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

Revision 2937, 31.9 kB (checked in by jerome, 18 years ago)

pkusers now supports the --email command line option.

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