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

Revision 2699, 33.4 kB (checked in by jerome, 18 years ago)

Preliminary work on pkusers. Don't use it right now !

  • 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           
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       
70    def consumeAccountBalance(self, amount) :     
71        """Consumes an amount of money from the user's account balance."""
72        self.parent.decreaseUserAccountBalance(self, amount)
73        self.AccountBalance = float(self.AccountBalance or 0.0) - amount
74       
75    def setAccountBalance(self, balance, lifetimepaid, comment="") :
76        """Sets the user's account balance in case he pays more money."""
77        diff = float(lifetimepaid or 0.0) - float(self.LifeTimePaid or 0.0)
78        self.parent.beginTransaction()
79        try :
80            self.parent.writeUserAccountBalance(self, balance, lifetimepaid)
81            self.parent.writeNewPayment(self, diff, comment)
82        except PyKotaStorageError, msg :   
83            self.parent.rollbackTransaction()
84            raise PyKotaStorageError, msg
85        else :   
86            self.parent.commitTransaction()
87            self.AccountBalance = balance
88            self.LifeTimePaid = lifetimepaid
89       
90    def setLimitBy(self, limitby) :   
91        """Sets the user's limiting factor."""
92        try :
93            limitby = limitby.lower()
94        except AttributeError :   
95            limitby = "quota"
96        if limitby in ["quota", "balance", \
97                       "noquota", "noprint", "nochange"] :
98            self.parent.writeUserLimitBy(self, limitby)
99            self.LimitBy = limitby
100       
101    def setOverChargeFactor(self, factor) :   
102        """Sets the user's overcharging coefficient."""
103        self.parent.writeUserOverCharge(self, factor)
104        self.OverCharge = factor
105       
106    def delete(self) :   
107        """Deletes an user from the Quota Storage."""
108        self.parent.beginTransaction()
109        try :
110            self.parent.deleteUser(self)
111        except PyKotaStorageError, msg :   
112            self.parent.rollbackTransaction()
113            raise PyKotaStorageError, msg
114        else :   
115            self.parent.commitTransaction()
116            self.parent.flushEntry("USERS", self.Name)
117            if self.parent.usecache :
118                for (k, v) in self.parent.caches["USERPQUOTAS"].items() :
119                    if v.User.Name == self.Name :
120                        self.parent.flushEntry("USERPQUOTAS", "%s@%s" % (v.User.Name, v.Printer.Name))
121            self.Exists = 0
122       
123class StorageGroup(StorageObject) :       
124    """User class."""
125    def __init__(self, parent, name) :
126        StorageObject.__init__(self, parent)
127        self.Name = name
128        self.LimitBy = None
129        self.AccountBalance = None
130        self.LifeTimePaid = None
131       
132    def setLimitBy(self, limitby) :   
133        """Sets the user's limiting factor."""
134        try :
135            limitby = limitby.lower()
136        except AttributeError :   
137            limitby = "quota"
138        if limitby in ["quota", "balance", "noquota"] :
139            self.parent.writeGroupLimitBy(self, limitby)
140            self.LimitBy = limitby
141       
142    def delete(self) :   
143        """Deletes a group from the Quota Storage."""
144        self.parent.beginTransaction()
145        try :
146            self.parent.deleteGroup(self)
147        except PyKotaStorageError, msg :   
148            self.parent.rollbackTransaction()
149            raise PyKotaStorageError, msg
150        else :   
151            self.parent.commitTransaction()
152            self.parent.flushEntry("GROUPS", self.Name)
153            if self.parent.usecache :
154                for (k, v) in self.parent.caches["GROUPPQUOTAS"].items() :
155                    if v.Group.Name == self.Name :
156                        self.parent.flushEntry("GROUPPQUOTAS", "%s@%s" % (v.Group.Name, v.Printer.Name))
157            self.Exists = 0
158       
159class StoragePrinter(StorageObject) :
160    """Printer class."""
161    def __init__(self, parent, name) :
162        StorageObject.__init__(self, parent)
163        self.Name = name
164        self.PricePerPage = None
165        self.PricePerJob = None
166        self.MaxJobSize = None
167        self.PassThrough = None
168        self.Coefficients = None
169       
170    def __getattr__(self, name) :   
171        """Delays data retrieval until it's really needed."""
172        if name == "LastJob" : 
173            self.LastJob = self.parent.getPrinterLastJob(self)
174            return self.LastJob
175        else :
176            raise AttributeError, name
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 consume(self, pages, price) :
479        """Consumes some pages and credits for this billing code."""
480        if pages :
481           self.parent.consumeBillingCode(self, pages, price)
482           self.PageCounter += pages
483           self.Balance -= price
484       
485class BaseStorage :
486    def __init__(self, pykotatool) :
487        """Opens the storage connection."""
488        self.closed = 1
489        self.tool = pykotatool
490        self.usecache = pykotatool.config.getCaching()
491        self.disablehistory = pykotatool.config.getDisableHistory()
492        self.privacy = pykotatool.config.getPrivacy()
493        if self.privacy :
494            pykotatool.logdebug("Jobs' title, filename and options will be hidden because of privacy concerns.")
495        if self.usecache :
496            self.tool.logdebug("Caching enabled.")
497            self.caches = { "USERS" : {}, \
498                            "GROUPS" : {}, \
499                            "PRINTERS" : {}, \
500                            "USERPQUOTAS" : {}, \
501                            "GROUPPQUOTAS" : {}, \
502                            "JOBS" : {}, \
503                            "LASTJOBS" : {}, \
504                            "BILLINGCODES" : {} }
505       
506    def close(self) :   
507        """Must be overriden in children classes."""
508        raise RuntimeError, "BaseStorage.close() must be overriden !"
509       
510    def __del__(self) :       
511        """Ensures that the database connection is closed."""
512        self.close()
513       
514    def getFromCache(self, cachetype, key) :
515        """Tries to extract something from the cache."""
516        if self.usecache :
517            entry = self.caches[cachetype].get(key)
518            if entry is not None :
519                self.tool.logdebug("Cache hit (%s->%s)" % (cachetype, key))
520            else :   
521                self.tool.logdebug("Cache miss (%s->%s)" % (cachetype, key))
522            return entry   
523           
524    def cacheEntry(self, cachetype, key, value) :       
525        """Puts an entry in the cache."""
526        if self.usecache and getattr(value, "Exists", 0) :
527            self.caches[cachetype][key] = value
528            self.tool.logdebug("Cache store (%s->%s)" % (cachetype, key))
529           
530    def flushEntry(self, cachetype, key) :       
531        """Removes an entry from the cache."""
532        if self.usecache :
533            try :
534                del self.caches[cachetype][key]
535            except KeyError :   
536                pass
537            else :   
538                self.tool.logdebug("Cache flush (%s->%s)" % (cachetype, key))
539           
540    def getUser(self, username) :       
541        """Returns the user from cache."""
542        user = self.getFromCache("USERS", username)
543        if user is None :
544            user = self.getUserFromBackend(username)
545            self.cacheEntry("USERS", username, user)
546        return user   
547       
548    def getGroup(self, groupname) :       
549        """Returns the group from cache."""
550        group = self.getFromCache("GROUPS", groupname)
551        if group is None :
552            group = self.getGroupFromBackend(groupname)
553            self.cacheEntry("GROUPS", groupname, group)
554        return group   
555       
556    def getPrinter(self, printername) :       
557        """Returns the printer from cache."""
558        printer = self.getFromCache("PRINTERS", printername)
559        if printer is None :
560            printer = self.getPrinterFromBackend(printername)
561            self.cacheEntry("PRINTERS", printername, printer)
562        return printer   
563       
564    def getUserPQuota(self, user, printer) :       
565        """Returns the user quota information from cache."""
566        useratprinter = "%s@%s" % (user.Name, printer.Name)
567        upquota = self.getFromCache("USERPQUOTAS", useratprinter)
568        if upquota is None :
569            upquota = self.getUserPQuotaFromBackend(user, printer)
570            self.cacheEntry("USERPQUOTAS", useratprinter, upquota)
571        return upquota   
572       
573    def getGroupPQuota(self, group, printer) :       
574        """Returns the group quota information from cache."""
575        groupatprinter = "%s@%s" % (group.Name, printer.Name)
576        gpquota = self.getFromCache("GROUPPQUOTAS", groupatprinter)
577        if gpquota is None :
578            gpquota = self.getGroupPQuotaFromBackend(group, printer)
579            self.cacheEntry("GROUPPQUOTAS", groupatprinter, gpquota)
580        return gpquota   
581       
582    def getPrinterLastJob(self, printer) :       
583        """Extracts last job information for a given printer from cache."""
584        lastjob = self.getFromCache("LASTJOBS", printer.Name)
585        if lastjob is None :
586            lastjob = self.getPrinterLastJobFromBackend(printer)
587            self.cacheEntry("LASTJOBS", printer.Name, lastjob)
588        return lastjob   
589       
590    def getBillingCode(self, label) :       
591        """Returns the user from cache."""
592        code = self.getFromCache("BILLINGCODES", label)
593        if code is None :
594            code = self.getBillingCodeFromBackend(label)
595            self.cacheEntry("BILLINGCODES", label, code)
596        return code
597       
598    def getParentPrinters(self, printer) :   
599        """Extracts parent printers information for a given printer from cache."""
600        if self.usecache :
601            if not hasattr(printer, "Parents") :
602                self.tool.logdebug("Cache miss (%s->Parents)" % printer.Name)
603                printer.Parents = self.getParentPrintersFromBackend(printer)
604                self.tool.logdebug("Cache store (%s->Parents)" % printer.Name)
605            else :
606                self.tool.logdebug("Cache hit (%s->Parents)" % printer.Name)
607        else :       
608            printer.Parents = self.getParentPrintersFromBackend(printer)
609        for parent in printer.Parents[:] :   
610            printer.Parents.extend(self.getParentPrinters(parent))
611        uniquedic = {}   
612        for parent in printer.Parents :
613            uniquedic[parent.Name] = parent
614        printer.Parents = uniquedic.values()   
615        return printer.Parents
616       
617    def getGroupMembers(self, group) :       
618        """Returns the group's members list from in-group cache."""
619        if self.usecache :
620            if not hasattr(group, "Members") :
621                self.tool.logdebug("Cache miss (%s->Members)" % group.Name)
622                group.Members = self.getGroupMembersFromBackend(group)
623                self.tool.logdebug("Cache store (%s->Members)" % group.Name)
624            else :
625                self.tool.logdebug("Cache hit (%s->Members)" % group.Name)
626        else :       
627            group.Members = self.getGroupMembersFromBackend(group)
628        return group.Members   
629       
630    def getUserGroups(self, user) :       
631        """Returns the user's groups list from in-user cache."""
632        if self.usecache :
633            if not hasattr(user, "Groups") :
634                self.tool.logdebug("Cache miss (%s->Groups)" % user.Name)
635                user.Groups = self.getUserGroupsFromBackend(user)
636                self.tool.logdebug("Cache store (%s->Groups)" % user.Name)
637            else :
638                self.tool.logdebug("Cache hit (%s->Groups)" % user.Name)
639        else :       
640            user.Groups = self.getUserGroupsFromBackend(user)
641        return user.Groups   
642       
643    def getParentPrintersUserPQuota(self, userpquota) :     
644        """Returns all user print quota on the printer and all its parents recursively."""
645        upquotas = [ ]
646        for printer in self.getParentPrinters(userpquota.Printer) :
647            upq = self.getUserPQuota(userpquota.User, printer)
648            if upq.Exists :
649                upquotas.append(upq)
650        return upquotas       
651       
652    def getParentPrintersGroupPQuota(self, grouppquota) :     
653        """Returns all group print quota on the printer and all its parents recursively."""
654        gpquotas = [ ]
655        for printer in self.getParentPrinters(grouppquota.Printer) :
656            gpq = self.getGroupPQuota(grouppquota.Group, printer)
657            if gpq.Exists :
658                gpquotas.append(gpq)
659        return gpquotas       
660       
661    def databaseToUserCharset(self, text) :
662        """Converts from database format (UTF-8) to user's charset."""
663        if text is not None :
664            try :
665                return unicode(text, "UTF-8").encode(self.tool.getCharset()) 
666            except UnicodeError :   
667                try :
668                    # Incorrect locale settings ?
669                    return unicode(text, "UTF-8").encode("ISO-8859-15") 
670                except UnicodeError :   
671                    pass
672        return text
673       
674    def userCharsetToDatabase(self, text) :
675        """Converts from user's charset to database format (UTF-8)."""
676        if text is not None :
677            try :
678                return unicode(text, self.tool.getCharset()).encode("UTF-8") 
679            except UnicodeError :   
680                try :
681                    # Incorrect locale settings ?
682                    return unicode(text, "ISO-8859-15").encode("UTF-8") 
683                except UnicodeError :   
684                    pass
685        return text
686       
687    def cleanDates(self, startdate, enddate) :   
688        """Clean the dates to create a correct filter."""
689        if startdate :   
690            startdate = startdate.strip().lower()
691        if enddate :   
692            enddate = enddate.strip().lower()
693        if (not startdate) and (not enddate) :   
694            return (None, None)
695           
696        now = DateTime.now()   
697        nameddates = ('yesterday', 'today', 'now', 'tomorrow')
698        datedict = { "start" : startdate, "end" : enddate }   
699        for limit in datedict.keys() :
700            dateval = datedict[limit]
701            if dateval :
702                for name in nameddates :
703                    if dateval.startswith(name) :
704                        try :
705                            offset = int(dateval[len(name):])
706                        except :   
707                            offset = 0
708                        dateval = dateval[:len(name)]   
709                        if limit == "start" :
710                            if dateval == "yesterday" :
711                                dateval = (now - 1 + offset).Format("%Y%m%d000000")
712                            elif dateval == "today" :
713                                dateval = (now + offset).Format("%Y%m%d000000")
714                            elif dateval == "now" :
715                                dateval = (now + offset).Format("%Y%m%d%H%M%S")
716                            else : # tomorrow
717                                dateval = (now + 1 + offset).Format("%Y%m%d000000")
718                        else :
719                            if dateval == "yesterday" :
720                                dateval = (now - 1 + offset).Format("%Y%m%d235959")
721                            elif dateval == "today" :
722                                dateval = (now + offset).Format("%Y%m%d235959")
723                            elif dateval == "now" :
724                                dateval = (now + offset).Format("%Y%m%d%H%M%S")
725                            else : # tomorrow
726                                dateval = (now + 1 + offset).Format("%Y%m%d235959")
727                        break
728                       
729                if not dateval.isdigit() :
730                    dateval = None
731                else :   
732                    lgdateval = len(dateval)
733                    if lgdateval == 4 :
734                        if limit == "start" : 
735                            dateval = "%s0101 00:00:00" % dateval
736                        else : 
737                            dateval = "%s1231 23:59:59" % dateval
738                    elif lgdateval == 6 :
739                        if limit == "start" : 
740                            dateval = "%s01 00:00:00" % dateval
741                        else : 
742                            mxdate = DateTime.ISO.ParseDateTime("%s01 00:00:00" % dateval)
743                            dateval = "%s%02i 23:59:59" % (dateval, mxdate.days_in_month)
744                    elif lgdateval == 8 :
745                        if limit == "start" : 
746                            dateval = "%s 00:00:00" % dateval
747                        else : 
748                            dateval = "%s 23:59:59" % dateval
749                    elif lgdateval == 10 :
750                        if limit == "start" : 
751                            dateval = "%s %s:00:00" % (dateval[:8], dateval[8:])
752                        else : 
753                            dateval = "%s %s:59:59" % (dateval[:8], dateval[8:])
754                    elif lgdateval == 12 :
755                        if limit == "start" : 
756                            dateval = "%s %s:%s:00" % (dateval[:8], dateval[8:10], dateval[10:])
757                        else : 
758                            dateval = "%s %s:%s:59" % (dateval[:8], dateval[8:10], dateval[10:])
759                    elif lgdateval == 14 :       
760                        dateval = "%s %s:%s:%s" % (dateval[:8], dateval[8:10], dateval[10:12], dateval[12:])
761                    else :   
762                        dateval = None
763                    try :   
764                        DateTime.ISO.ParseDateTime(dateval)
765                    except :   
766                        dateval = None
767                datedict[limit] = dateval   
768        (start, end) = (datedict["start"], datedict["end"])
769        if start and end and (start > end) :
770            (start, end) = (end, start)
771        return (start, end)   
772       
773def openConnection(pykotatool) :
774    """Returns a connection handle to the appropriate Quota Storage Database."""
775    backendinfo = pykotatool.config.getStorageBackend()
776    backend = backendinfo["storagebackend"]
777    try :
778        exec "from pykota.storages import %s as storagebackend" % backend.lower()
779    except ImportError :
780        raise PyKotaStorageError, _("Unsupported quota storage backend %s") % backend
781    else :   
782        host = backendinfo["storageserver"]
783        database = backendinfo["storagename"]
784        admin = backendinfo["storageadmin"] or backendinfo["storageuser"]
785        adminpw = backendinfo["storageadminpw"] or backendinfo["storageuserpw"]
786        return storagebackend.Storage(pykotatool, host, database, admin, adminpw)
Note: See TracBrowser for help on using the browser.