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

Revision 2452, 32.4 kB (checked in by jerome, 19 years ago)

Upgraded database schema.
Added -i | --ingroups command line option to repykota.
Added -C | --comment command line option to edpykota.
Added 'noquota', 'noprint', and 'nochange' as switches for edpykota's
-l | --limitby command line option.
Severity : entirely new features, in need of testers :-)

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