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

Revision 3260, 36.4 kB (checked in by jerome, 16 years ago)

Changed license to GNU GPL v3 or later.
Changed Python source encoding from ISO-8859-15 to UTF-8 (only ASCII
was used anyway).

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