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

Revision 2696, 33.7 kB (checked in by jerome, 18 years ago)

Fixed a small problem with printer's description.

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