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

Revision 1791, 28.2 kB (checked in by jalet, 20 years ago)

Added ugly workaround for strange locale problem

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