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

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

Did some work to prepare the integration of MaxJobSize? and PassThrough?
mode for printers.

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