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

Revision 2706, 33.6 kB (checked in by jerome, 18 years ago)

pkusers now mostly works. Removing an user from a group with
LDAP is not yet done though. Also no test was done with
LDAP yet.
filldb now really creates users (it uses pkusers instead
of edpykota)

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