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

Revision 1875, 28.5 kB (checked in by jalet, 20 years ago)

For URGENT legal reasons (Italy), a new "privacy" directive was added to pykota.conf
to hide print jobs' title, filename, and options.

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