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

Revision 1790, 27.7 kB (checked in by jalet, 20 years ago)

Hopefully final fix for data encoding to and from the database

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