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

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

Completely untested modification stuff...

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