root / pykota / trunk / pykota / storage.py @ 3033

Revision 3033, 32.8 kB (checked in by jerome, 18 years ago)

Added lazy retrieval of a printer's coefficients.
Removed pykoef from setup script.
Added pksetup to setup script.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1# PyKota
2# -*- coding: ISO-8859-15 -*-
3#
4# PyKota : Print Quotas for CUPS and LPRng
5#
6# (c) 2003, 2004, 2005, 2006 Jerome Alet <alet@librelogiciel.com>
7# This program is free software; you can redistribute it and/or modify
8# it under the terms of the GNU General Public License as published by
9# the Free Software Foundation; either version 2 of the License, or
10# (at your option) any later version.
11#
12# This program is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15# GNU General Public License for more details.
16#
17# You should have received a copy of the GNU General Public License
18# along with this program; if not, write to the Free Software
19# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20#
21# $Id$
22#
23#
24
25import os
26import imp
27from mx import DateTime
28
29class PyKotaStorageError(Exception):
30    """An exception for database related stuff."""
31    def __init__(self, message = ""):
32        self.message = message
33        Exception.__init__(self, message)
34    def __repr__(self):
35        return self.message
36    __str__ = __repr__
37       
38class StorageObject :
39    """Object present in the database."""
40    def __init__(self, parent) :
41        "Initialize minimal data."""
42        self.parent = parent
43        self.ident = None
44        self.Description = None
45        self.isDirty = False
46        self.Exists = False
47       
48    def setDescription(self, description=None) :
49        """Sets the object's description."""
50        if description is not None :
51            self.Description = str(description)
52            self.isDirty = True   
53           
54    def save(self) :       
55        """Saves the object to the database."""
56        if self.isDirty :
57            getattr(self.parent, "save%s" % self.__class__.__name__[7:])(self)
58            self.isDirty = False
59       
60class StorageUser(StorageObject) :       
61    """User class."""
62    def __init__(self, parent, name) :
63        StorageObject.__init__(self, parent)
64        self.Name = name
65        self.LimitBy = None
66        self.AccountBalance = None
67        self.LifeTimePaid = None
68        self.Email = None
69        self.OverCharge = 1.0
70        self.Payments = [] # TODO : maybe handle this smartly for SQL, for now just don't retrieve them
71        self.PaymentsBacklog = []
72       
73    def consumeAccountBalance(self, amount) :     
74        """Consumes an amount of money from the user's account balance."""
75        self.parent.decreaseUserAccountBalance(self, amount)
76        self.AccountBalance = float(self.AccountBalance or 0.0) - amount
77       
78    def setAccountBalance(self, balance, lifetimepaid, comment="") :
79        """Sets the user's account balance in case he pays more money."""
80        diff = float(lifetimepaid or 0.0) - float(self.LifeTimePaid or 0.0)
81        self.AccountBalance = balance
82        self.LifeTimePaid = lifetimepaid
83        if diff :
84            self.PaymentsBacklog.append((diff, comment))
85        self.isDirty = True
86       
87    def save(self) :   
88        """Saves an user and flush its payments backlog."""
89        for (value, comment) in self.PaymentsBacklog :
90            self.parent.writeNewPayment(self, value, comment)
91        self.PaymentsBacklog = []   
92        StorageObject.save(self)   
93       
94    def setLimitBy(self, limitby) :   
95        """Sets the user's limiting factor."""
96        try :
97            limitby = limitby.lower()
98        except AttributeError :   
99            limitby = "quota"
100        if limitby in ["quota", "balance", \
101                       "noquota", "noprint", "nochange"] :
102            self.LimitBy = limitby
103            self.isDirty = True
104       
105    def setOverChargeFactor(self, factor) :   
106        """Sets the user's overcharging coefficient."""
107        self.OverCharge = factor
108        self.isDirty = True
109       
110    def setEmail(self, email) :   
111        """Sets the user's email address."""
112        self.Email = email
113        self.isDirty = True
114       
115    def delete(self) :   
116        """Deletes an user from the database."""
117        self.parent.deleteUser(self)
118        self.parent.flushEntry("USERS", self.Name)
119        if self.parent.usecache :
120            for (k, v) in self.parent.caches["USERPQUOTAS"].items() :
121                if v.User.Name == self.Name :
122                    self.parent.flushEntry("USERPQUOTAS", "%s@%s" % (v.User.Name, v.Printer.Name))
123        self.Exists = False
124        self.isDirty = False           
125       
126class StorageGroup(StorageObject) :       
127    """User class."""
128    def __init__(self, parent, name) :
129        StorageObject.__init__(self, parent)
130        self.Name = name
131        self.LimitBy = None
132        self.AccountBalance = None
133        self.LifeTimePaid = None
134       
135    def setLimitBy(self, limitby) :   
136        """Sets the user's limiting factor."""
137        try :
138            limitby = limitby.lower()
139        except AttributeError :   
140            limitby = "quota"
141        if limitby in ["quota", "balance", "noquota"] :
142            self.LimitBy = limitby
143            self.isDirty = True
144       
145    def addUserToGroup(self, user) :
146        """Adds an user to an users group."""
147        self.parent.addUserToGroup(user, self)
148       
149    def delUserFromGroup(self, user) :
150        """Removes an user from an users group."""
151        self.parent.delUserFromGroup(user, self)
152       
153    def delete(self) :   
154        """Deletes a group from the database."""
155        self.parent.deleteGroup(self)
156        self.parent.flushEntry("GROUPS", self.Name)
157        if self.parent.usecache :
158            for (k, v) in self.parent.caches["GROUPPQUOTAS"].items() :
159                if v.Group.Name == self.Name :
160                    self.parent.flushEntry("GROUPPQUOTAS", "%s@%s" % (v.Group.Name, v.Printer.Name))
161        self.Exists = False
162        self.isDirty = False           
163       
164class StoragePrinter(StorageObject) :
165    """Printer class."""
166    def __init__(self, parent, name) :
167        StorageObject.__init__(self, parent)
168        self.Name = name
169        self.PricePerPage = None
170        self.PricePerJob = None
171        self.MaxJobSize = None
172        self.PassThrough = None
173       
174    def __getattr__(self, name) :   
175        """Delays data retrieval until it's really needed."""
176        if name == "LastJob" : 
177            self.LastJob = self.parent.getPrinterLastJob(self)
178            self.parent.tool.logdebug("Lazy retrieval of last job for printer %s" % self.Name)
179            return self.LastJob
180        elif name == "Coefficients" :   
181            self.Coefficients = self.parent.tool.config.getPrinterCoefficients(self.Name)
182            self.parent.tool.logdebug("Lazy retrieval of coefficients for printer %s : %s" % (self.Name, self.Coefficients))
183            return self.Coefficients
184        else :
185            raise AttributeError, name
186           
187    def addJobToHistory(self, jobid, user, pagecounter, action, jobsize=None, jobprice=None, filename=None, title=None, copies=None, options=None, clienthost=None, jobsizebytes=None, jobmd5sum=None, jobpages=None, jobbilling=None, precomputedsize=None, precomputedprice=None) :
188        """Adds a job to the printer's history."""
189        self.parent.writeJobNew(self, user, jobid, pagecounter, action, jobsize, jobprice, filename, title, copies, options, clienthost, jobsizebytes, jobmd5sum, jobpages, jobbilling, precomputedsize, precomputedprice)
190        # TODO : update LastJob object ? Probably not needed.
191       
192    def addPrinterToGroup(self, printer) :   
193        """Adds a printer to a printer group."""
194        if (printer not in self.parent.getParentPrinters(self)) and (printer.ident != self.ident) :
195            self.parent.writePrinterToGroup(self, printer)
196            # TODO : reset cached value for printer parents, or add new parent to cached value
197           
198    def delPrinterFromGroup(self, printer) :   
199        """Deletes a printer from a printer group."""
200        self.parent.removePrinterFromGroup(self, printer)
201        # TODO : reset cached value for printer parents, or add new parent to cached value
202       
203    def setPrices(self, priceperpage = None, priceperjob = None) :   
204        """Sets the printer's prices."""
205        if priceperpage is None :
206            priceperpage = self.PricePerPage or 0.0
207        else :   
208            self.PricePerPage = float(priceperpage)
209        if priceperjob is None :   
210            priceperjob = self.PricePerJob or 0.0
211        else :   
212            self.PricePerJob = float(priceperjob)
213        self.isDirty = True   
214       
215    def setPassThrough(self, passthrough) :
216        """Sets the printer's passthrough mode."""
217        self.PassThrough = passthrough
218        self.isDirty = True
219       
220    def setMaxJobSize(self, maxjobsize) :
221        """Sets the printer's maximal job size."""
222        self.MaxJobSize = maxjobsize
223        self.isDirty = True
224       
225    def delete(self) :   
226        """Deletes a printer from the database."""
227        self.parent.deletePrinter(self)
228        self.parent.flushEntry("PRINTERS", self.Name)
229        if self.parent.usecache :
230            for (k, v) in self.parent.caches["USERPQUOTAS"].items() :
231                if v.Printer.Name == self.Name :
232                    self.parent.flushEntry("USERPQUOTAS", "%s@%s" % (v.User.Name, v.Printer.Name))
233            for (k, v) in self.parent.caches["GROUPPQUOTAS"].items() :
234                if v.Printer.Name == self.Name :
235                    self.parent.flushEntry("GROUPPQUOTAS", "%s@%s" % (v.Group.Name, v.Printer.Name))
236        self.Exists = False
237        self.isDirty = False           
238       
239class StorageUserPQuota(StorageObject) :
240    """User Print Quota class."""
241    def __init__(self, parent, user, printer) :
242        StorageObject.__init__(self, parent)
243        self.User = user
244        self.Printer = printer
245        self.PageCounter = None
246        self.LifePageCounter = None
247        self.SoftLimit = None
248        self.HardLimit = None
249        self.DateLimit = None
250        self.WarnCount = None
251        self.MaxJobSize = None
252       
253    def __getattr__(self, name) :   
254        """Delays data retrieval until it's really needed."""
255        if name == "ParentPrintersUserPQuota" : 
256            self.ParentPrintersUserPQuota = (self.User.Exists and self.Printer.Exists and self.parent.getParentPrintersUserPQuota(self)) or []
257            return self.ParentPrintersUserPQuota
258        else :
259            raise AttributeError, name
260       
261    def setDateLimit(self, datelimit) :   
262        """Sets the date limit for this quota."""
263        datelimit = DateTime.ISO.ParseDateTime(str(datelimit))
264        date = "%04i-%02i-%02i %02i:%02i:%02i" % (datelimit.year, datelimit.month, datelimit.day, datelimit.hour, datelimit.minute, datelimit.second)
265        self.parent.writeUserPQuotaDateLimit(self, date)
266        self.DateLimit = date
267       
268    def setLimits(self, softlimit, hardlimit) :   
269        """Sets the soft and hard limit for this quota."""
270        self.SoftLimit = softlimit
271        self.HardLimit = hardlimit
272        self.DateLimit = None
273        self.WarnCount = 0
274        self.isDirty = True
275       
276    def setUsage(self, used) :
277        """Sets the PageCounter and LifePageCounter to used, or if used is + or - prefixed, changes the values of {Life,}PageCounter by that amount."""
278        vused = int(used)
279        if used.startswith("+") or used.startswith("-") :
280            self.PageCounter += vused
281            self.LifePageCounter += vused
282        else :
283            self.PageCounter = self.LifePageCounter = vused
284        self.DateLimit = None
285        self.WarnCount = 0
286        self.isDirty = 1
287
288    def incDenyBannerCounter(self) :
289        """Increment the deny banner counter for this user quota."""
290        self.parent.increaseUserPQuotaWarnCount(self)
291        self.WarnCount = (self.WarnCount or 0) + 1
292       
293    def resetDenyBannerCounter(self) :
294        """Resets the deny banner counter for this user quota."""
295        self.parent.writeUserPQuotaWarnCount(self, 0)
296        self.WarnCount = 0
297       
298    def reset(self) :   
299        """Resets page counter to 0."""
300        self.PageCounter = 0
301        self.DateLimit = None
302        self.isDirty = True
303       
304    def hardreset(self) :   
305        """Resets actual and life time page counters to 0."""
306        self.PageCounter = self.LifePageCounter = 0
307        self.DateLimit = None
308        self.isDirty = True
309       
310    def computeJobPrice(self, jobsize) :   
311        """Computes the job price as the sum of all parent printers' prices + current printer's ones."""
312        totalprice = 0.0   
313        if jobsize :
314            if self.User.OverCharge != 0.0 :    # optimization, but TODO : beware of rounding errors
315                for upq in [ self ] + self.ParentPrintersUserPQuota :
316                    price = (float(upq.Printer.PricePerPage or 0.0) * jobsize) + float(upq.Printer.PricePerJob or 0.0)
317                    totalprice += price
318        if self.User.OverCharge != 1.0 : # TODO : beware of rounding errors
319            overcharged = totalprice * self.User.OverCharge       
320            self.parent.tool.logdebug("Overcharging %s by a factor of %s ===> User %s will be charged for %s units." % (totalprice, self.User.OverCharge, self.User.Name, overcharged))
321            return overcharged
322        else :   
323            return totalprice
324           
325    def increasePagesUsage(self, jobsize) :
326        """Increase the value of used pages and money."""
327        jobprice = self.computeJobPrice(jobsize)
328        if jobsize :
329            if jobprice :
330                self.User.consumeAccountBalance(jobprice)
331            for upq in [ self ] + self.ParentPrintersUserPQuota :
332                self.parent.increaseUserPQuotaPagesCounters(upq, jobsize)
333                upq.PageCounter = int(upq.PageCounter or 0) + jobsize
334                upq.LifePageCounter = int(upq.LifePageCounter or 0) + jobsize
335        return jobprice
336       
337    def delete(self) :   
338        """Deletes an user print quota entry from the database."""
339        self.parent.deleteUserPQuota(self)
340        if self.parent.usecache :
341            self.parent.flushEntry("USERPQUOTAS", "%s@%s" % (self.User.Name, self.Printer.Name))
342        self.Exists = False
343        self.isDirty = False
344       
345class StorageGroupPQuota(StorageObject) :
346    """Group Print Quota class."""
347    def __init__(self, parent, group, printer) :
348        StorageObject.__init__(self, parent)
349        self.Group = group
350        self.Printer = printer
351        self.PageCounter = None
352        self.LifePageCounter = None
353        self.SoftLimit = None
354        self.HardLimit = None
355        self.DateLimit = None
356        self.MaxJobSize = None
357       
358    def __getattr__(self, name) :   
359        """Delays data retrieval until it's really needed."""
360        if name == "ParentPrintersGroupPQuota" : 
361            self.ParentPrintersGroupPQuota = (self.Group.Exists and self.Printer.Exists and self.parent.getParentPrintersGroupPQuota(self)) or []
362            return self.ParentPrintersGroupPQuota
363        else :
364            raise AttributeError, name
365       
366    def reset(self) :   
367        """Resets page counter to 0."""
368        for user in self.parent.getGroupMembers(self.Group) :
369            uq = self.parent.getUserPQuota(user, self.Printer)
370            uq.reset()
371            uq.save()
372        self.PageCounter = 0
373        self.DateLimit = None
374        self.isDirty = True
375       
376    def hardreset(self) :   
377        """Resets actual and life time page counters to 0."""
378        for user in self.parent.getGroupMembers(self.Group) :
379            uq = self.parent.getUserPQuota(user, self.Printer)
380            uq.hardreset()
381            uq.save()
382        self.PageCounter = self.LifePageCounter = 0
383        self.DateLimit = None
384        self.isDirty = True
385       
386    def setDateLimit(self, datelimit) :   
387        """Sets the date limit for this quota."""
388        datelimit = DateTime.ISO.ParseDateTime(str(datelimit))
389        date = "%04i-%02i-%02i %02i:%02i:%02i" % (datelimit.year, \
390                                                  datelimit.month, \
391                                                  datelimit.day, \
392                                                  datelimit.hour, \
393                                                  datelimit.minute, \
394                                                  datelimit.second)
395        self.parent.writeGroupPQuotaDateLimit(self, date)
396        self.DateLimit = date
397       
398    def setLimits(self, softlimit, hardlimit) :   
399        """Sets the soft and hard limit for this quota."""
400        self.SoftLimit = softlimit
401        self.HardLimit = hardlimit
402        self.DateLimit = None
403        self.isDirty = True
404       
405    def delete(self) :   
406        """Deletes a group print quota entry from the database."""
407        self.parent.deleteGroupPQuota(self)
408        if self.parent.usecache :
409            self.parent.flushEntry("GROUPPQUOTAS", "%s@%s" % (self.Group.Name, self.Printer.Name))
410        self.Exists = False
411        self.isDirty = False
412       
413class StorageJob(StorageObject) :
414    """Printer's Job class."""
415    def __init__(self, parent) :
416        StorageObject.__init__(self, parent)
417        self.UserName = None
418        self.PrinterName = None
419        self.JobId = None
420        self.PrinterPageCounter = None
421        self.JobSizeBytes = None
422        self.JobSize = None
423        self.JobAction = None
424        self.JobDate = None
425        self.JobPrice = None
426        self.JobFileName = None
427        self.JobTitle = None
428        self.JobCopies = None
429        self.JobOptions = None
430        self.JobHostName = None
431        self.JobMD5Sum = None
432        self.JobPages = None
433        self.JobBillingCode = None
434        self.PrecomputedJobSize = None
435        self.PrecomputedJobPrice = None
436       
437    def __getattr__(self, name) :   
438        """Delays data retrieval until it's really needed."""
439        if name == "User" : 
440            self.User = self.parent.getUser(self.UserName)
441            return self.User
442        elif name == "Printer" :   
443            self.Printer = self.parent.getPrinter(self.PrinterName)
444            return self.Printer
445        else :
446            raise AttributeError, name
447       
448class StorageLastJob(StorageJob) :
449    """Printer's Last Job class."""
450    def __init__(self, parent, printer) :
451        StorageJob.__init__(self, parent)
452        self.PrinterName = printer.Name # not needed
453        self.Printer = printer
454       
455class StorageBillingCode(StorageObject) :
456    """Billing code class."""
457    def __init__(self, parent, name) :
458        StorageObject.__init__(self, parent)
459        self.BillingCode = name
460        self.PageCounter = None
461        self.Balance = None
462       
463    def delete(self) :   
464        """Deletes the billing code from the database."""
465        self.parent.deleteBillingCode(self)
466        self.parent.flushEntry("BILLINGCODES", self.BillingCode)
467        self.isDirty = False
468        self.Exists = False
469       
470    def reset(self, balance=0.0, pagecounter=0) :   
471        """Resets the pagecounter and balance for this billing code."""
472        self.Balance = balance
473        self.PageCounter = pagecounter
474        self.isDirty = True
475       
476    def consume(self, pages, price) :
477        """Consumes some pages and credits for this billing code."""
478        if pages :
479           self.parent.consumeBillingCode(self, pages, price)
480           self.PageCounter += pages
481           self.Balance -= price
482       
483class BaseStorage :
484    def __init__(self, pykotatool) :
485        """Opens the storage connection."""
486        self.closed = 1
487        self.tool = pykotatool
488        self.usecache = pykotatool.config.getCaching()
489        self.disablehistory = pykotatool.config.getDisableHistory()
490        self.privacy = pykotatool.config.getPrivacy()
491        if self.privacy :
492            pykotatool.logdebug("Jobs' title, filename and options will be hidden because of privacy concerns.")
493        if self.usecache :
494            self.tool.logdebug("Caching enabled.")
495            self.caches = { "USERS" : {}, \
496                            "GROUPS" : {}, \
497                            "PRINTERS" : {}, \
498                            "USERPQUOTAS" : {}, \
499                            "GROUPPQUOTAS" : {}, \
500                            "JOBS" : {}, \
501                            "LASTJOBS" : {}, \
502                            "BILLINGCODES" : {} }
503       
504    def close(self) :   
505        """Must be overriden in children classes."""
506        raise RuntimeError, "BaseStorage.close() must be overriden !"
507       
508    def __del__(self) :       
509        """Ensures that the database connection is closed."""
510        self.close()
511       
512    def getFromCache(self, cachetype, key) :
513        """Tries to extract something from the cache."""
514        if self.usecache :
515            entry = self.caches[cachetype].get(key)
516            if entry is not None :
517                self.tool.logdebug("Cache hit (%s->%s)" % (cachetype, key))
518            else :   
519                self.tool.logdebug("Cache miss (%s->%s)" % (cachetype, key))
520            return entry   
521           
522    def cacheEntry(self, cachetype, key, value) :       
523        """Puts an entry in the cache."""
524        if self.usecache and getattr(value, "Exists", 0) :
525            self.caches[cachetype][key] = value
526            self.tool.logdebug("Cache store (%s->%s)" % (cachetype, key))
527           
528    def flushEntry(self, cachetype, key) :       
529        """Removes an entry from the cache."""
530        if self.usecache :
531            try :
532                del self.caches[cachetype][key]
533            except KeyError :   
534                pass
535            else :   
536                self.tool.logdebug("Cache flush (%s->%s)" % (cachetype, key))
537           
538    def getUser(self, username) :       
539        """Returns the user from cache."""
540        user = self.getFromCache("USERS", username)
541        if user is None :
542            user = self.getUserFromBackend(username)
543            self.cacheEntry("USERS", username, user)
544        return user   
545       
546    def getGroup(self, groupname) :       
547        """Returns the group from cache."""
548        group = self.getFromCache("GROUPS", groupname)
549        if group is None :
550            group = self.getGroupFromBackend(groupname)
551            self.cacheEntry("GROUPS", groupname, group)
552        return group   
553       
554    def getPrinter(self, printername) :       
555        """Returns the printer from cache."""
556        printer = self.getFromCache("PRINTERS", printername)
557        if printer is None :
558            printer = self.getPrinterFromBackend(printername)
559            self.cacheEntry("PRINTERS", printername, printer)
560        return printer   
561       
562    def getUserPQuota(self, user, printer) :       
563        """Returns the user quota information from cache."""
564        useratprinter = "%s@%s" % (user.Name, printer.Name)
565        upquota = self.getFromCache("USERPQUOTAS", useratprinter)
566        if upquota is None :
567            upquota = self.getUserPQuotaFromBackend(user, printer)
568            self.cacheEntry("USERPQUOTAS", useratprinter, upquota)
569        return upquota   
570       
571    def getGroupPQuota(self, group, printer) :       
572        """Returns the group quota information from cache."""
573        groupatprinter = "%s@%s" % (group.Name, printer.Name)
574        gpquota = self.getFromCache("GROUPPQUOTAS", groupatprinter)
575        if gpquota is None :
576            gpquota = self.getGroupPQuotaFromBackend(group, printer)
577            self.cacheEntry("GROUPPQUOTAS", groupatprinter, gpquota)
578        return gpquota   
579       
580    def getPrinterLastJob(self, printer) :       
581        """Extracts last job information for a given printer from cache."""
582        lastjob = self.getFromCache("LASTJOBS", printer.Name)
583        if lastjob is None :
584            lastjob = self.getPrinterLastJobFromBackend(printer)
585            self.cacheEntry("LASTJOBS", printer.Name, lastjob)
586        return lastjob   
587       
588    def getBillingCode(self, label) :       
589        """Returns the user from cache."""
590        code = self.getFromCache("BILLINGCODES", label)
591        if code is None :
592            code = self.getBillingCodeFromBackend(label)
593            self.cacheEntry("BILLINGCODES", label, code)
594        return code
595       
596    def getParentPrinters(self, printer) :   
597        """Extracts parent printers information for a given printer from cache."""
598        if self.usecache :
599            if not hasattr(printer, "Parents") :
600                self.tool.logdebug("Cache miss (%s->Parents)" % printer.Name)
601                printer.Parents = self.getParentPrintersFromBackend(printer)
602                self.tool.logdebug("Cache store (%s->Parents)" % printer.Name)
603            else :
604                self.tool.logdebug("Cache hit (%s->Parents)" % printer.Name)
605        else :       
606            printer.Parents = self.getParentPrintersFromBackend(printer)
607        for parent in printer.Parents[:] :   
608            printer.Parents.extend(self.getParentPrinters(parent))
609        uniquedic = {}   
610        for parent in printer.Parents :
611            uniquedic[parent.Name] = parent
612        printer.Parents = uniquedic.values()   
613        return printer.Parents
614       
615    def getGroupMembers(self, group) :       
616        """Returns the group's members list from in-group cache."""
617        if self.usecache :
618            if not hasattr(group, "Members") :
619                self.tool.logdebug("Cache miss (%s->Members)" % group.Name)
620                group.Members = self.getGroupMembersFromBackend(group)
621                self.tool.logdebug("Cache store (%s->Members)" % group.Name)
622            else :
623                self.tool.logdebug("Cache hit (%s->Members)" % group.Name)
624        else :       
625            group.Members = self.getGroupMembersFromBackend(group)
626        return group.Members   
627       
628    def getUserGroups(self, user) :       
629        """Returns the user's groups list from in-user cache."""
630        if self.usecache :
631            if not hasattr(user, "Groups") :
632                self.tool.logdebug("Cache miss (%s->Groups)" % user.Name)
633                user.Groups = self.getUserGroupsFromBackend(user)
634                self.tool.logdebug("Cache store (%s->Groups)" % user.Name)
635            else :
636                self.tool.logdebug("Cache hit (%s->Groups)" % user.Name)
637        else :       
638            user.Groups = self.getUserGroupsFromBackend(user)
639        return user.Groups   
640       
641    def getParentPrintersUserPQuota(self, userpquota) :     
642        """Returns all user print quota on the printer and all its parents recursively."""
643        upquotas = [ ]
644        for printer in self.getParentPrinters(userpquota.Printer) :
645            upq = self.getUserPQuota(userpquota.User, printer)
646            if upq.Exists :
647                upquotas.append(upq)
648        return upquotas       
649       
650    def getParentPrintersGroupPQuota(self, grouppquota) :     
651        """Returns all group print quota on the printer and all its parents recursively."""
652        gpquotas = [ ]
653        for printer in self.getParentPrinters(grouppquota.Printer) :
654            gpq = self.getGroupPQuota(grouppquota.Group, printer)
655            if gpq.Exists :
656                gpquotas.append(gpq)
657        return gpquotas       
658       
659    def databaseToUserCharset(self, text) :
660        """Converts from database format (UTF-8) to user's charset."""
661        return self.tool.UTF8ToUserCharset(text)
662       
663    def userCharsetToDatabase(self, text) :
664        """Converts from user's charset to database format (UTF-8)."""
665        return self.tool.userCharsetToUTF8(text)
666       
667    def cleanDates(self, startdate, enddate) :   
668        """Clean the dates to create a correct filter."""
669        if startdate :   
670            startdate = startdate.strip().lower()
671        if enddate :   
672            enddate = enddate.strip().lower()
673        if (not startdate) and (not enddate) :   
674            return (None, None)
675           
676        now = DateTime.now()   
677        nameddates = ('yesterday', 'today', 'now', 'tomorrow')
678        datedict = { "start" : startdate, "end" : enddate }   
679        for limit in datedict.keys() :
680            dateval = datedict[limit]
681            if dateval :
682                for name in nameddates :
683                    if dateval.startswith(name) :
684                        try :
685                            offset = int(dateval[len(name):])
686                        except :   
687                            offset = 0
688                        dateval = dateval[:len(name)]   
689                        if limit == "start" :
690                            if dateval == "yesterday" :
691                                dateval = (now - 1 + offset).Format("%Y%m%d000000")
692                            elif dateval == "today" :
693                                dateval = (now + offset).Format("%Y%m%d000000")
694                            elif dateval == "now" :
695                                dateval = (now + offset).Format("%Y%m%d%H%M%S")
696                            else : # tomorrow
697                                dateval = (now + 1 + offset).Format("%Y%m%d000000")
698                        else :
699                            if dateval == "yesterday" :
700                                dateval = (now - 1 + offset).Format("%Y%m%d235959")
701                            elif dateval == "today" :
702                                dateval = (now + offset).Format("%Y%m%d235959")
703                            elif dateval == "now" :
704                                dateval = (now + offset).Format("%Y%m%d%H%M%S")
705                            else : # tomorrow
706                                dateval = (now + 1 + offset).Format("%Y%m%d235959")
707                        break
708                       
709                if not dateval.isdigit() :
710                    dateval = None
711                else :   
712                    lgdateval = len(dateval)
713                    if lgdateval == 4 :
714                        if limit == "start" : 
715                            dateval = "%s0101 00:00:00" % dateval
716                        else : 
717                            dateval = "%s1231 23:59:59" % dateval
718                    elif lgdateval == 6 :
719                        if limit == "start" : 
720                            dateval = "%s01 00:00:00" % dateval
721                        else : 
722                            mxdate = DateTime.ISO.ParseDateTime("%s01 00:00:00" % dateval)
723                            dateval = "%s%02i 23:59:59" % (dateval, mxdate.days_in_month)
724                    elif lgdateval == 8 :
725                        if limit == "start" : 
726                            dateval = "%s 00:00:00" % dateval
727                        else : 
728                            dateval = "%s 23:59:59" % dateval
729                    elif lgdateval == 10 :
730                        if limit == "start" : 
731                            dateval = "%s %s:00:00" % (dateval[:8], dateval[8:])
732                        else : 
733                            dateval = "%s %s:59:59" % (dateval[:8], dateval[8:])
734                    elif lgdateval == 12 :
735                        if limit == "start" : 
736                            dateval = "%s %s:%s:00" % (dateval[:8], dateval[8:10], dateval[10:])
737                        else : 
738                            dateval = "%s %s:%s:59" % (dateval[:8], dateval[8:10], dateval[10:])
739                    elif lgdateval == 14 :       
740                        dateval = "%s %s:%s:%s" % (dateval[:8], dateval[8:10], dateval[10:12], dateval[12:])
741                    else :   
742                        dateval = None
743                    try :   
744                        DateTime.ISO.ParseDateTime(dateval)
745                    except :   
746                        dateval = None
747                datedict[limit] = dateval   
748        (start, end) = (datedict["start"], datedict["end"])
749        if start and end and (start > end) :
750            (start, end) = (end, start)
751        try :   
752            if len(start) == 17 :
753                start = "%s-%s-%s %s" % (start[0:4], start[4:6], start[6:8], start[9:])
754        except TypeError :       
755            pass
756           
757        try :   
758            if len(end) == 17 :
759                end = "%s-%s-%s %s" % (end[0:4], end[4:6], end[6:8], end[9:])
760        except TypeError :       
761            pass
762           
763        return (start, end)   
764       
765def openConnection(pykotatool) :
766    """Returns a connection handle to the appropriate database."""
767    backendinfo = pykotatool.config.getStorageBackend()
768    backend = backendinfo["storagebackend"]
769    try :
770        storagebackend = imp.load_source("storagebackend", 
771                                         os.path.join(os.path.dirname(__file__),
772                                                      "storages",
773                                                      "%s.py" % backend.lower()))
774    except ImportError :
775        raise PyKotaStorageError, _("Unsupported quota storage backend %s") % backend
776    else :   
777        host = backendinfo["storageserver"]
778        database = backendinfo["storagename"]
779        admin = backendinfo["storageadmin"] or backendinfo["storageuser"]
780        adminpw = backendinfo["storageadminpw"] or backendinfo["storageuserpw"]
781        return storagebackend.Storage(pykotatool, host, database, admin, adminpw)
Note: See TracBrowser for help on using the browser.