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

Revision 2773, 34.0 kB (checked in by jerome, 18 years ago)

pkusers is now optimized like pkprinters, pkbcodes and edpykota.

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