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

Revision 1967, 29.3 kB (checked in by jalet, 19 years ago)

Integrated the patch by Wilson Roberto Afonso and Matt Hyclak to allow
edpykota to accept the -U | --used value command line option.

  • 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
20#
21# $Id$
22#
23# $Log$
24# Revision 1.66  2004/12/02 21:24:50  jalet
25# Integrated the patch by Wilson Roberto Afonso and Matt Hyclak to allow
26# edpykota to accept the -U | --used value command line option.
27#
28# Revision 1.65  2004/10/25 14:12:25  jalet
29# For URGENT legal reasons (Italy), a new "privacy" directive was added to pykota.conf
30# to hide print jobs' title, filename, and options.
31#
32# Revision 1.64  2004/10/08 20:19:18  jalet
33# Added ugly workaround for strange locale problem
34#
35# Revision 1.63  2004/10/07 21:14:28  jalet
36# Hopefully final fix for data encoding to and from the database
37#
38# Revision 1.62  2004/09/28 17:45:31  jalet
39# Added the --hardreset command line option to edpykota
40#
41# Revision 1.61  2004/09/24 21:19:48  jalet
42# Did a pass of PyChecker
43#
44# Revision 1.60  2004/09/24 20:21:50  jalet
45# Fixed pykotaAccountBalance object location during creation
46#
47# Revision 1.59  2004/09/10 21:32:52  jalet
48# Small fixes for incomplete entry intialization
49#
50# Revision 1.58  2004/09/02 10:09:30  jalet
51# Fixed bug in LDAP user deletion code which didn't correctly delete the user's
52# pykotaLastJob entries.
53#
54# Revision 1.57  2004/07/22 22:41:48  jalet
55# Hardware accounting for LPRng should be OK now. UNTESTED.
56#
57# Revision 1.56  2004/07/01 17:45:49  jalet
58# Added code to handle the description field for printers
59#
60# Revision 1.55  2004/06/05 22:18:04  jalet
61# Now catches some exceptions earlier.
62# storage.py and ldapstorage.py : removed old comments
63#
64# Revision 1.54  2004/06/05 22:03:49  jalet
65# Payments history is now stored in database
66#
67# Revision 1.53  2004/06/03 23:14:10  jalet
68# Now stores the job's size in bytes in the database.
69# Preliminary work on payments storage : database schemas are OK now,
70# but no code to store payments yet.
71# Removed schema picture, not relevant anymore.
72#
73# Revision 1.52  2004/05/26 14:49:57  jalet
74# First try at saving the job-originating-hostname in the database
75#
76# Revision 1.51  2004/03/24 15:15:24  jalet
77# Began integration of Henrik Janhagen's work on quota-then-balance
78# and balance-then-quota
79#
80# Revision 1.50  2004/03/09 08:05:27  jalet
81# Small fix : only keeps existing quota entries when searching parents
82#
83# Revision 1.49  2004/03/01 15:06:51  jalet
84# Pre and Post hooks should now work in the pykota filter too.
85# The pykota filter doesn't check the last user's quota anymore
86# when delayed hardware accounting is used : this will be checked
87# anyway the next time the last user will print
88#
89# Revision 1.48  2004/02/27 13:50:12  jalet
90# Hopefully the final fix for groups (users and printers)
91#
92# Revision 1.47  2004/02/27 09:30:33  jalet
93# datelimit wasn't reset when modifying soft and hard limits with the LDAP backend
94#
95# Revision 1.46  2004/02/26 14:18:07  jalet
96# Should fix the remaining bugs wrt printers groups and users groups.
97#
98# Revision 1.45  2004/02/26 10:40:40  jalet
99# Fixed nested printer groups accounting.
100#
101# Revision 1.44  2004/02/25 19:09:24  jalet
102# Fix for LDAP problem when job price was 0.
103#
104# Revision 1.43  2004/02/25 12:36:34  jalet
105# Avoids a database query even if caching was disabled.
106#
107# Revision 1.42  2004/02/23 22:53:21  jalet
108# Don't retrieve data when it's not needed, to avoid database queries
109#
110# Revision 1.41  2004/02/04 17:12:33  jalet
111# Removing a printer from a printers group should work now.
112#
113# Revision 1.40  2004/02/04 13:24:41  jalet
114# pkprinters can now remove printers from printers groups.
115#
116# Revision 1.39  2004/02/04 11:16:59  jalet
117# pkprinters command line tool added.
118#
119# Revision 1.38  2004/01/12 22:43:40  jalet
120# New formula to compute a job's price
121#
122# Revision 1.37  2004/01/12 14:35:01  jalet
123# Printing history added to CGI script.
124#
125# Revision 1.36  2004/01/10 09:44:02  jalet
126# Fixed potential accuracy problem if a user printed on several printers at
127# the very same time.
128#
129# Revision 1.35  2004/01/08 16:33:27  jalet
130# Additionnal check to not create a circular printers group.
131#
132# Revision 1.34  2004/01/08 16:24:49  jalet
133# edpykota now supports adding printers to printer groups.
134#
135# Revision 1.33  2004/01/08 14:10:32  jalet
136# Copyright year changed.
137#
138# Revision 1.32  2004/01/06 16:02:57  jalet
139# This time printer groups caching works.
140#
141# Revision 1.31  2004/01/06 15:51:24  jalet
142# Fixed caching of printer groups
143#
144# Revision 1.30  2004/01/06 14:24:59  jalet
145# Printer groups should be cached now, if caching is enabled.
146#
147# Revision 1.29  2003/12/27 16:49:25  uid67467
148# Should be ok now.
149#
150# Revision 1.28  2003/11/25 23:46:40  jalet
151# Don't try to verify if module name is valid, Python does this better than us.
152#
153# Revision 1.27  2003/11/23 19:01:36  jalet
154# Job price added to history
155#
156# Revision 1.26  2003/11/21 14:28:45  jalet
157# More complete job history.
158#
159# Revision 1.25  2003/10/08 21:12:27  jalet
160# Do not cache anymore entries which don't exist.
161#
162# Revision 1.24  2003/10/07 22:06:05  jalet
163# Preliminary code to disable job history
164#
165# Revision 1.23  2003/10/07 09:07:28  jalet
166# Character encoding added to please latest version of Python
167#
168# Revision 1.22  2003/10/06 13:12:27  jalet
169# More work on caching
170#
171# Revision 1.21  2003/10/03 09:02:20  jalet
172# Logs cache store actions too
173#
174# Revision 1.20  2003/10/02 20:23:18  jalet
175# Storage caching mechanism added.
176#
177# Revision 1.19  2003/07/16 21:53:07  jalet
178# Really big modifications wrt new configuration file's location and content.
179#
180# Revision 1.18  2003/07/07 08:33:18  jalet
181# Bug fix due to a typo in LDAP code
182#
183# Revision 1.17  2003/07/05 07:46:50  jalet
184# The previous bug fix was incomplete.
185#
186# Revision 1.16  2003/06/25 19:52:31  jalet
187# Should be ready for testing :-)
188#
189# Revision 1.15  2003/06/25 14:10:58  jalet
190# Exception raising for now.
191#
192# Revision 1.14  2003/06/25 14:10:01  jalet
193# Hey, it may work (edpykota --reset excepted) !
194#
195# Revision 1.13  2003/06/10 16:37:54  jalet
196# Deletion of the second user which is not needed anymore.
197# Added a debug configuration field in /etc/pykota.conf
198# All queries can now be sent to the logger in debug mode, this will
199# greatly help improve performance when time for this will come.
200#
201# Revision 1.12  2003/04/23 22:13:57  jalet
202# Preliminary support for LPRng added BUT STILL UNTESTED.
203#
204# Revision 1.11  2003/04/10 21:47:20  jalet
205# Job history added. Upgrade script neutralized for now !
206#
207# Revision 1.10  2003/03/29 13:45:27  jalet
208# GPL paragraphs were incorrectly (from memory) copied into the sources.
209# Two README files were added.
210# Upgrade script for PostgreSQL pre 1.01 schema was added.
211#
212# Revision 1.9  2003/02/17 22:55:01  jalet
213# More options can now be set per printer or globally :
214#
215#       admin
216#       adminmail
217#       gracedelay
218#       requester
219#
220# the printer option has priority when both are defined.
221#
222# Revision 1.8  2003/02/17 22:05:50  jalet
223# Storage backend now supports admin and user passwords (untested)
224#
225# Revision 1.7  2003/02/10 12:07:31  jalet
226# Now repykota should output the recorded total page number for each printer too.
227#
228# Revision 1.6  2003/02/09 13:05:43  jalet
229# Internationalization continues...
230#
231# Revision 1.5  2003/02/08 22:39:46  jalet
232# --reset command line option added
233#
234# Revision 1.4  2003/02/08 09:59:59  jalet
235# Added preliminary base class for all storages
236#
237# Revision 1.3  2003/02/05 22:10:29  jalet
238# Typos
239#
240# Revision 1.2  2003/02/05 22:02:22  jalet
241# __import__ statement didn't work as expected
242#
243# Revision 1.1  2003/02/05 21:28:17  jalet
244# Initial import into CVS
245#
246#
247#
248
249class PyKotaStorageError(Exception):
250    """An exception for Quota Storage related stuff."""
251    def __init__(self, message = ""):
252        self.message = message
253        Exception.__init__(self, message)
254    def __repr__(self):
255        return self.message
256    __str__ = __repr__
257       
258class StorageObject :
259    """Object present in the Quota Storage."""
260    def __init__(self, parent) :
261        "Initialize minimal data."""
262        self.parent = parent
263        self.ident = None
264        self.Exists = 0
265       
266class StorageUser(StorageObject) :       
267    """User class."""
268    def __init__(self, parent, name) :
269        StorageObject.__init__(self, parent)
270        self.Name = name
271        self.LimitBy = None
272        self.AccountBalance = None
273        self.LifeTimePaid = None
274        self.Email = None
275        self.Payments = [] # TODO : maybe handle this smartly for SQL, for now just don't retrieve them
276       
277    def consumeAccountBalance(self, amount) :     
278        """Consumes an amount of money from the user's account balance."""
279        self.parent.decreaseUserAccountBalance(self, amount)
280        self.AccountBalance = float(self.AccountBalance or 0.0) - amount
281       
282    def setAccountBalance(self, balance, lifetimepaid) :   
283        """Sets the user's account balance in case he pays more money."""
284        diff = float(lifetimepaid or 0.0) - float(self.LifeTimePaid or 0.0)
285        self.parent.beginTransaction()
286        try :
287            self.parent.writeUserAccountBalance(self, balance, lifetimepaid)
288            self.parent.writeNewPayment(self, diff)
289        except PyKotaStorageError, msg :   
290            self.parent.rollbackTransaction()
291            raise PyKotaStorageError, msg
292        else :   
293            self.parent.commitTransaction()
294            self.AccountBalance = balance
295            self.LifeTimePaid = lifetimepaid
296       
297    def setLimitBy(self, limitby) :   
298        """Sets the user's limiting factor."""
299        try :
300            limitby = limitby.lower()
301        except AttributeError :   
302            limitby = "quota"
303        if limitby in ["quota", "balance", "quota-then-balance", "balance-then-quota"] :
304            self.parent.writeUserLimitBy(self, limitby)
305            self.LimitBy = limitby
306       
307    def delete(self) :   
308        """Deletes an user from the Quota Storage."""
309        self.parent.beginTransaction()
310        try :
311            self.parent.deleteUser(self)
312        except PyKotaStorageError, msg :   
313            self.parent.rollbackTransaction()
314            raise PyKotaStorageError, msg
315        else :   
316            self.parent.commitTransaction()
317       
318class StorageGroup(StorageObject) :       
319    """User class."""
320    def __init__(self, parent, name) :
321        StorageObject.__init__(self, parent)
322        self.Name = name
323        self.LimitBy = None
324        self.AccountBalance = None
325        self.LifeTimePaid = None
326       
327    def setLimitBy(self, limitby) :   
328        """Sets the user's limiting factor."""
329        try :
330            limitby = limitby.lower()
331        except AttributeError :   
332            limitby = "quota"
333        if limitby in ["quota", "balance"] :
334            self.parent.writeGroupLimitBy(self, limitby)
335            self.LimitBy = limitby
336       
337    def delete(self) :   
338        """Deletes a group from the Quota Storage."""
339        self.parent.beginTransaction()
340        try :
341            self.parent.deleteGroup(self)
342        except PyKotaStorageError, msg :   
343            self.parent.rollbackTransaction()
344            raise PyKotaStorageError, msg
345        else :   
346            self.parent.commitTransaction()
347       
348class StoragePrinter(StorageObject) :
349    """Printer class."""
350    def __init__(self, parent, name) :
351        StorageObject.__init__(self, parent)
352        self.Name = name
353        self.PricePerPage = None
354        self.PricePerJob = None
355        self.Description = None
356       
357    def __getattr__(self, name) :   
358        """Delays data retrieval until it's really needed."""
359        if name == "LastJob" : 
360            self.LastJob = self.parent.getPrinterLastJob(self)
361            return self.LastJob
362        else :
363            raise AttributeError, name
364           
365    def addJobToHistory(self, jobid, user, pagecounter, action, jobsize=None, jobprice=None, filename=None, title=None, copies=None, options=None, clienthost=None, jobsizebytes=None) :
366        """Adds a job to the printer's history."""
367        self.parent.writeJobNew(self, user, jobid, pagecounter, action, jobsize, jobprice, filename, title, copies, options, clienthost, jobsizebytes)
368        # TODO : update LastJob object ? Probably not needed.
369       
370    def addPrinterToGroup(self, printer) :   
371        """Adds a printer to a printer group."""
372        if (printer not in self.parent.getParentPrinters(self)) and (printer.ident != self.ident) :
373            self.parent.writePrinterToGroup(self, printer)
374            # TODO : reset cached value for printer parents, or add new parent to cached value
375           
376    def delPrinterFromGroup(self, printer) :   
377        """Deletes a printer from a printer group."""
378        self.parent.removePrinterFromGroup(self, printer)
379        # TODO : reset cached value for printer parents, or add new parent to cached value
380       
381    def setPrices(self, priceperpage = None, priceperjob = None) :   
382        """Sets the printer's prices."""
383        if priceperpage is None :
384            priceperpage = self.PricePerPage or 0.0
385        else :   
386            self.PricePerPage = float(priceperpage)
387        if priceperjob is None :   
388            priceperjob = self.PricePerJob or 0.0
389        else :   
390            self.PricePerJob = float(priceperjob)
391        self.parent.writePrinterPrices(self)
392       
393    def setDescription(self, description = None) :   
394        """Sets the printer's prices."""
395        if description is None :
396            description = self.Description
397        else :   
398            self.Description = str(description)
399        self.parent.writePrinterDescription(self)
400       
401    def delete(self) :   
402        """Deletes a printer from the Quota Storage."""
403        self.parent.beginTransaction()
404        try :
405            self.parent.deletePrinter(self)
406        except PyKotaStorageError, msg :   
407            self.parent.rollbackTransaction()
408            raise PyKotaStorageError, msg
409        else :   
410            self.parent.commitTransaction()
411       
412class StorageUserPQuota(StorageObject) :
413    """User Print Quota class."""
414    def __init__(self, parent, user, printer) :
415        StorageObject.__init__(self, parent)
416        self.User = user
417        self.Printer = printer
418        self.PageCounter = None
419        self.LifePageCounter = None
420        self.SoftLimit = None
421        self.HardLimit = None
422        self.DateLimit = None
423       
424    def __getattr__(self, name) :   
425        """Delays data retrieval until it's really needed."""
426        if name == "ParentPrintersUserPQuota" : 
427            self.ParentPrintersUserPQuota = (self.User.Exists and self.Printer.Exists and self.parent.getParentPrintersUserPQuota(self)) or []
428            return self.ParentPrintersUserPQuota
429        else :
430            raise AttributeError, name
431       
432    def setDateLimit(self, datelimit) :   
433        """Sets the date limit for this quota."""
434        date = "%04i-%02i-%02i %02i:%02i:%02i" % (datelimit.year, datelimit.month, datelimit.day, datelimit.hour, datelimit.minute, datelimit.second)
435        self.parent.writeUserPQuotaDateLimit(self, date)
436        self.DateLimit = date
437       
438    def setLimits(self, softlimit, hardlimit) :   
439        """Sets the soft and hard limit for this quota."""
440        self.parent.writeUserPQuotaLimits(self, softlimit, hardlimit)
441        self.SoftLimit = softlimit
442        self.HardLimit = hardlimit
443        self.DateLimit = None
444       
445    def setUsage(self, used) :
446        """Sets the PageCounter and LifePageCounter to used, or if used is + or - prefixed, changes the values of {Life,}PageCounter by that amount."""
447        vused = int(used)
448        if used.startswith("+") or used.startswith("-") :
449           self.parent.increaseUserPQuotaPagesCounters(self, vused)
450           self.PageCounter += vused
451           self.LifePageCounter += vused
452        else :
453           self.parent.writeUserPQuotaPagesCounters(self, vused, vused)
454           self.PageCounter = self.LifePageCounter = vused
455
456    def reset(self) :   
457        """Resets page counter to 0."""
458        self.parent.writeUserPQuotaPagesCounters(self, 0, int(self.LifePageCounter or 0))
459        self.PageCounter = 0
460       
461    def hardreset(self) :   
462        """Resets actual and life time page counters to 0."""
463        self.parent.writeUserPQuotaPagesCounters(self, 0, 0)
464        self.PageCounter = self.LifePageCounter = 0
465       
466    def computeJobPrice(self, jobsize) :   
467        """Computes the job price as the sum of all parent printers' prices + current printer's ones."""
468        totalprice = 0.0   
469        if jobsize :
470            for upq in [ self ] + self.ParentPrintersUserPQuota :
471                price = (float(upq.Printer.PricePerPage or 0.0) * jobsize) + float(upq.Printer.PricePerJob or 0.0)
472                totalprice += price
473        return totalprice   
474           
475    def increasePagesUsage(self, jobsize) :
476        """Increase the value of used pages and money."""
477        jobprice = self.computeJobPrice(jobsize)
478        if jobsize :
479            self.parent.beginTransaction()
480            try :
481                if jobprice :
482                    self.User.consumeAccountBalance(jobprice)
483                for upq in [ self ] + self.ParentPrintersUserPQuota :
484                    self.parent.increaseUserPQuotaPagesCounters(upq, jobsize)
485                    upq.PageCounter = int(upq.PageCounter or 0) + jobsize
486                    upq.LifePageCounter = int(upq.LifePageCounter or 0) + jobsize
487            except PyKotaStorageError, msg :   
488                self.parent.rollbackTransaction()
489                raise PyKotaStorageError, msg
490            else :   
491                self.parent.commitTransaction()
492        return jobprice
493       
494class StorageGroupPQuota(StorageObject) :
495    """Group Print Quota class."""
496    def __init__(self, parent, group, printer) :
497        StorageObject.__init__(self, parent)
498        self.Group = group
499        self.Printer = printer
500        self.PageCounter = None
501        self.LifePageCounter = None
502        self.SoftLimit = None
503        self.HardLimit = None
504        self.DateLimit = None
505       
506    def __getattr__(self, name) :   
507        """Delays data retrieval until it's really needed."""
508        if name == "ParentPrintersGroupPQuota" : 
509            self.ParentPrintersGroupPQuota = (self.Group.Exists and self.Printer.Exists and self.parent.getParentPrintersGroupPQuota(self)) or []
510            return self.ParentPrintersGroupPQuota
511        else :
512            raise AttributeError, name
513       
514    def setDateLimit(self, datelimit) :   
515        """Sets the date limit for this quota."""
516        date = "%04i-%02i-%02i %02i:%02i:%02i" % (datelimit.year, datelimit.month, datelimit.day, datelimit.hour, datelimit.minute, datelimit.second)
517        self.parent.writeGroupPQuotaDateLimit(self, date)
518        self.DateLimit = date
519       
520    def setLimits(self, softlimit, hardlimit) :   
521        """Sets the soft and hard limit for this quota."""
522        self.parent.writeGroupPQuotaLimits(self, softlimit, hardlimit)
523        self.SoftLimit = softlimit
524        self.HardLimit = hardlimit
525        self.DateLimit = None
526       
527class StorageJob(StorageObject) :
528    """Printer's Job class."""
529    def __init__(self, parent) :
530        StorageObject.__init__(self, parent)
531        self.UserName = None
532        self.PrinterName = None
533        self.JobId = None
534        self.PrinterPageCounter = None
535        self.JobSizeBytes = None
536        self.JobSize = None
537        self.JobAction = None
538        self.JobDate = None
539        self.JobPrice = None
540        self.JobFileName = None
541        self.JobTitle = None
542        self.JobCopies = None
543        self.JobOptions = None
544        self.JobHostName = None
545       
546    def __getattr__(self, name) :   
547        """Delays data retrieval until it's really needed."""
548        if name == "User" : 
549            self.User = self.parent.getUser(self.UserName)
550            return self.User
551        elif name == "Printer" :   
552            self.Printer = self.parent.getPrinter(self.PrinterName)
553            return self.Printer
554        else :
555            raise AttributeError, name
556       
557class StorageLastJob(StorageJob) :
558    """Printer's Last Job class."""
559    def __init__(self, parent, printer) :
560        StorageJob.__init__(self, parent)
561        self.PrinterName = printer.Name # not needed
562        self.Printer = printer
563       
564class BaseStorage :
565    def __init__(self, pykotatool) :
566        """Opens the storage connection."""
567        self.closed = 1
568        self.tool = pykotatool
569        self.usecache = pykotatool.config.getCaching()
570        self.disablehistory = pykotatool.config.getDisableHistory()
571        self.privacy = pykotatool.config.getPrivacy()
572        if self.privacy :
573            pykotatool.logdebug("Jobs' title, filename and options will be hidden because of privacy concerns.")
574        if self.usecache :
575            self.tool.logdebug("Caching enabled.")
576            self.caches = { "USERS" : {}, "GROUPS" : {}, "PRINTERS" : {}, "USERPQUOTAS" : {}, "GROUPPQUOTAS" : {}, "JOBS" : {}, "LASTJOBS" : {} }
577       
578    def close(self) :   
579        """Must be overriden in children classes."""
580        raise RuntimeError, "BaseStorage.close() must be overriden !"
581       
582    def __del__(self) :       
583        """Ensures that the database connection is closed."""
584        self.close()
585       
586    def getFromCache(self, cachetype, key) :
587        """Tries to extract something from the cache."""
588        if self.usecache :
589            entry = self.caches[cachetype].get(key)
590            if entry is not None :
591                self.tool.logdebug("Cache hit (%s->%s)" % (cachetype, key))
592            else :   
593                self.tool.logdebug("Cache miss (%s->%s)" % (cachetype, key))
594            return entry   
595           
596    def cacheEntry(self, cachetype, key, value) :       
597        """Puts an entry in the cache."""
598        if self.usecache and getattr(value, "Exists", 0) :
599            self.caches[cachetype][key] = value
600            self.tool.logdebug("Cache store (%s->%s)" % (cachetype, key))
601           
602    def getUser(self, username) :       
603        """Returns the user from cache."""
604        user = self.getFromCache("USERS", username)
605        if user is None :
606            user = self.getUserFromBackend(username)
607            self.cacheEntry("USERS", username, user)
608        return user   
609       
610    def getGroup(self, groupname) :       
611        """Returns the group from cache."""
612        group = self.getFromCache("GROUPS", groupname)
613        if group is None :
614            group = self.getGroupFromBackend(groupname)
615            self.cacheEntry("GROUPS", groupname, group)
616        return group   
617       
618    def getPrinter(self, printername) :       
619        """Returns the printer from cache."""
620        printer = self.getFromCache("PRINTERS", printername)
621        if printer is None :
622            printer = self.getPrinterFromBackend(printername)
623            self.cacheEntry("PRINTERS", printername, printer)
624        return printer   
625       
626    def getUserPQuota(self, user, printer) :       
627        """Returns the user quota information from cache."""
628        useratprinter = "%s@%s" % (user.Name, printer.Name)
629        upquota = self.getFromCache("USERPQUOTAS", useratprinter)
630        if upquota is None :
631            upquota = self.getUserPQuotaFromBackend(user, printer)
632            self.cacheEntry("USERPQUOTAS", useratprinter, upquota)
633        return upquota   
634       
635    def getGroupPQuota(self, group, printer) :       
636        """Returns the group quota information from cache."""
637        groupatprinter = "%s@%s" % (group.Name, printer.Name)
638        gpquota = self.getFromCache("GROUPPQUOTAS", groupatprinter)
639        if gpquota is None :
640            gpquota = self.getGroupPQuotaFromBackend(group, printer)
641            self.cacheEntry("GROUPPQUOTAS", groupatprinter, gpquota)
642        return gpquota   
643       
644    def getPrinterLastJob(self, printer) :       
645        """Extracts last job information for a given printer from cache."""
646        lastjob = self.getFromCache("LASTJOBS", printer.Name)
647        if lastjob is None :
648            lastjob = self.getPrinterLastJobFromBackend(printer)
649            self.cacheEntry("LASTJOBS", printer.Name, lastjob)
650        return lastjob   
651       
652    def getParentPrinters(self, printer) :   
653        """Extracts parent printers information for a given printer from cache."""
654        if self.usecache :
655            if not hasattr(printer, "Parents") :
656                self.tool.logdebug("Cache miss (%s->Parents)" % printer.Name)
657                printer.Parents = self.getParentPrintersFromBackend(printer)
658                self.tool.logdebug("Cache store (%s->Parents)" % printer.Name)
659            else :
660                self.tool.logdebug("Cache hit (%s->Parents)" % printer.Name)
661        else :       
662            printer.Parents = self.getParentPrintersFromBackend(printer)
663        for parent in printer.Parents[:] :   
664            printer.Parents.extend(self.getParentPrinters(parent))
665        uniquedic = {}   
666        for parent in printer.Parents :
667            uniquedic[parent.Name] = parent
668        printer.Parents = uniquedic.values()   
669        return printer.Parents
670       
671    def getGroupMembers(self, group) :       
672        """Returns the group's members list from in-group cache."""
673        if self.usecache :
674            if not hasattr(group, "Members") :
675                self.tool.logdebug("Cache miss (%s->Members)" % group.Name)
676                group.Members = self.getGroupMembersFromBackend(group)
677                self.tool.logdebug("Cache store (%s->Members)" % group.Name)
678            else :
679                self.tool.logdebug("Cache hit (%s->Members)" % group.Name)
680        else :       
681            group.Members = self.getGroupMembersFromBackend(group)
682        return group.Members   
683       
684    def getUserGroups(self, user) :       
685        """Returns the user's groups list from in-user cache."""
686        if self.usecache :
687            if not hasattr(user, "Groups") :
688                self.tool.logdebug("Cache miss (%s->Groups)" % user.Name)
689                user.Groups = self.getUserGroupsFromBackend(user)
690                self.tool.logdebug("Cache store (%s->Groups)" % user.Name)
691            else :
692                self.tool.logdebug("Cache hit (%s->Groups)" % user.Name)
693        else :       
694            user.Groups = self.getUserGroupsFromBackend(user)
695        return user.Groups   
696       
697    def getParentPrintersUserPQuota(self, userpquota) :     
698        """Returns all user print quota on the printer and all its parents recursively."""
699        upquotas = [ ]
700        for printer in self.getParentPrinters(userpquota.Printer) :
701            upq = self.getUserPQuota(userpquota.User, printer)
702            if upq.Exists :
703                upquotas.append(upq)
704        return upquotas       
705       
706    def getParentPrintersGroupPQuota(self, grouppquota) :     
707        """Returns all group print quota on the printer and all its parents recursively."""
708        gpquotas = [ ]
709        for printer in self.getParentPrinters(grouppquota.Printer) :
710            gpq = self.getGroupPQuota(grouppquota.Group, printer)
711            if gpq.Exists :
712                gpquotas.append(gpq)
713        return gpquotas       
714       
715    def databaseToUserCharset(self, text) :
716        """Converts from database format (UTF-8) to user's charset."""
717        if text is not None :
718            try :
719                return unicode(text, "UTF-8").encode(self.tool.getCharset()) 
720            except UnicodeError :   
721                try :
722                    # Incorrect locale settings ?
723                    return unicode(text, "UTF-8").encode("ISO-8859-15") 
724                except UnicodeError :   
725                    pass
726        return text
727       
728    def userCharsetToDatabase(self, text) :
729        """Converts from user's charset to database format (UTF-8)."""
730        if text is not None :
731            try :
732                return unicode(text, self.tool.getCharset()).encode("UTF-8") 
733            except UnicodeError :   
734                try :
735                    # Incorrect locale settings ?
736                    return unicode(text, "ISO-8859-15").encode("UTF-8") 
737                except UnicodeError :   
738                    pass
739        return text
740       
741def openConnection(pykotatool) :
742    """Returns a connection handle to the appropriate Quota Storage Database."""
743    backendinfo = pykotatool.config.getStorageBackend()
744    backend = backendinfo["storagebackend"]
745    try :
746        exec "from pykota.storages import %s as storagebackend" % backend.lower()
747    except ImportError :
748        raise PyKotaStorageError, _("Unsupported quota storage backend %s") % backend
749    else :   
750        host = backendinfo["storageserver"]
751        database = backendinfo["storagename"]
752        admin = backendinfo["storageadmin"] or backendinfo["storageuser"]
753        adminpw = backendinfo["storageadminpw"] or backendinfo["storageuserpw"]
754        return storagebackend.Storage(pykotatool, host, database, admin, adminpw)
Note: See TracBrowser for help on using the browser.