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

Revision 2455, 32.7 kB (checked in by jerome, 19 years ago)

Added the precomputed job's size and price to the history.

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