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

Revision 2697, 33.6 kB (checked in by jerome, 18 years ago)

Add the description attribute on creation

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