root / pykota / trunk / pykota / storages / ldapstorage.py @ 1790

Revision 1790, 67.1 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.83  2004/10/07 21:14:28  jalet
25# Hopefully final fix for data encoding to and from the database
26#
27# Revision 1.82  2004/10/05 09:59:20  jalet
28# Restore compatibility with Python 2.1
29#
30# Revision 1.81  2004/10/04 11:27:57  jalet
31# Finished LDAP support for dumpykota.
32#
33# Revision 1.80  2004/10/03 19:57:57  jalet
34# Dump of payments should work with LDAP backend now.
35#
36# Revision 1.79  2004/10/03 19:52:59  jalet
37# More work done on LDAP and dumpykota
38#
39# Revision 1.78  2004/10/02 05:48:56  jalet
40# Should now correctly deal with charsets both when storing into databases and when
41# retrieving datas. Works with both PostgreSQL and LDAP.
42#
43# Revision 1.77  2004/09/28 14:29:00  jalet
44# dumpykota for LDAP backend is almost there.
45#
46# Revision 1.76  2004/09/28 09:11:56  jalet
47# Fix for accented chars in print job's title, filename, and options
48#
49# Revision 1.75  2004/09/24 20:21:50  jalet
50# Fixed pykotaAccountBalance object location during creation
51#
52# Revision 1.74  2004/09/02 10:09:30  jalet
53# Fixed bug in LDAP user deletion code which didn't correctly delete the user's
54# pykotaLastJob entries.
55#
56# Revision 1.73  2004/07/17 20:37:27  jalet
57# Missing file... Am I really stupid ?
58#
59# Revision 1.72  2004/07/01 19:56:43  jalet
60# Better dispatching of error messages
61#
62# Revision 1.71  2004/07/01 17:45:49  jalet
63# Added code to handle the description field for printers
64#
65# Revision 1.70  2004/06/10 20:50:25  jalet
66# Better log message
67#
68# Revision 1.69  2004/06/05 22:18:04  jalet
69# Now catches some exceptions earlier.
70# storage.py and ldapstorage.py : removed old comments
71#
72# Revision 1.68  2004/06/05 22:03:50  jalet
73# Payments history is now stored in database
74#
75# Revision 1.67  2004/06/03 23:14:10  jalet
76# Now stores the job's size in bytes in the database.
77# Preliminary work on payments storage : database schemas are OK now,
78# but no code to store payments yet.
79# Removed schema picture, not relevant anymore.
80#
81# Revision 1.66  2004/05/28 20:56:45  jalet
82# Extended syntax for LDAP specific newuser and newgroup directives. Untested.
83#
84# Revision 1.65  2004/05/27 12:52:12  jalet
85# More useful error message in case of misconfiguration of an LDAP  search base
86# in pykota.conf
87#
88# Revision 1.64  2004/05/26 14:50:01  jalet
89# First try at saving the job-originating-hostname in the database
90#
91# Revision 1.63  2004/05/06 12:37:46  jalet
92# pkpgcounter : comments
93# pkprinters : when --add is used, existing printers are now skipped.
94#
95# Revision 1.62  2004/03/05 14:31:58  jalet
96# Improvement on strange history entries
97#
98# Revision 1.61  2004/03/05 13:19:53  jalet
99# Code safer wrt entries created in other tools
100#
101# Revision 1.60  2004/03/02 14:39:02  jalet
102# Final fix for printers searching
103#
104# Revision 1.59  2004/03/02 14:35:46  jalet
105# Missing test when searching printer objects when these objects were manually
106# created and don't contain the pykotaPrinterName attribute
107#
108# Revision 1.58  2004/02/27 09:30:33  jalet
109# datelimit wasn't reset when modifying soft and hard limits with the LDAP backend
110#
111# Revision 1.57  2004/02/26 14:18:07  jalet
112# Should fix the remaining bugs wrt printers groups and users groups.
113#
114# Revision 1.56  2004/02/25 16:52:39  jalet
115# Small fix wrt empty user groups
116#
117# Revision 1.55  2004/02/23 22:53:21  jalet
118# Don't retrieve data when it's not needed, to avoid database queries
119#
120# Revision 1.54  2004/02/20 16:38:39  jalet
121# ldapcache directive marked as experimental
122#
123# Revision 1.53  2004/02/20 14:42:21  jalet
124# Experimental ldapcache directive added
125#
126# Revision 1.52  2004/02/17 23:41:48  jalet
127# Preliminary work on low-level LDAP specific cache.
128#
129# Revision 1.51  2004/02/04 13:24:41  jalet
130# pkprinters can now remove printers from printers groups.
131#
132# Revision 1.50  2004/02/04 11:17:00  jalet
133# pkprinters command line tool added.
134#
135# Revision 1.49  2004/01/29 22:35:45  jalet
136# Small fix from Matt.
137#
138# Revision 1.48  2004/01/12 14:35:02  jalet
139# Printing history added to CGI script.
140#
141# Revision 1.47  2004/01/10 09:44:02  jalet
142# Fixed potential accuracy problem if a user printed on several printers at
143# the very same time.
144#
145# Revision 1.46  2004/01/08 16:33:27  jalet
146# Additionnal check to not create a circular printers group.
147#
148# Revision 1.45  2004/01/08 16:24:49  jalet
149# edpykota now supports adding printers to printer groups.
150#
151# Revision 1.44  2004/01/08 14:10:33  jalet
152# Copyright year changed.
153#
154# Revision 1.43  2004/01/06 14:24:59  jalet
155# Printer groups should be cached now, if caching is enabled.
156#
157# Revision 1.42  2003/12/29 14:12:48  uid67467
158# Tries to workaround possible integrity violations when retrieving printer groups
159#
160# Revision 1.41  2003/12/27 16:49:25  uid67467
161# Should be ok now.
162#
163# Revision 1.40  2003/11/29 22:02:14  jalet
164# Don't try to retrieve the user print quota information if current printer
165# doesn't exist.
166#
167# Revision 1.39  2003/11/26 23:35:32  jalet
168# Added a bit of code to support the setting of the user's email address
169# which was ignored during writes for now.
170#
171# Revision 1.38  2003/11/24 09:54:06  jalet
172# Small fix for LDAP when pykotaOptions attribute wasn't present.
173#
174# Revision 1.37  2003/11/23 19:01:37  jalet
175# Job price added to history
176#
177# Revision 1.36  2003/11/21 14:28:46  jalet
178# More complete job history.
179#
180# Revision 1.35  2003/11/12 13:06:37  jalet
181# Bug fix wrt no user/group name command line argument to edpykota
182#
183# Revision 1.34  2003/10/24 08:37:55  jalet
184# More complete messages in case of LDAP failure.
185# LDAP database connection is now unbound on exit too.
186#
187# Revision 1.33  2003/10/08 07:01:20  jalet
188# Job history can be disabled.
189# Some typos in README.
190# More messages in setup script.
191#
192# Revision 1.32  2003/10/07 14:23:25  jalet
193# More work on cache
194#
195# Revision 1.31  2003/10/07 09:07:30  jalet
196# Character encoding added to please latest version of Python
197#
198# Revision 1.30  2003/10/06 14:42:36  jalet
199# LDAP group access will be slower when cache is disabled, but at least code
200# is consistent with the rest of the caching mechanis, but at least code
201# is consistent with the rest of the caching mechanism
202#
203# Revision 1.29  2003/10/06 13:12:28  jalet
204# More work on caching
205#
206# Revision 1.28  2003/10/03 12:27:02  jalet
207# Several optimizations, especially with LDAP backend
208#
209# Revision 1.27  2003/10/03 08:57:55  jalet
210# Caching mechanism now caches all that's cacheable.
211#
212# Revision 1.26  2003/10/02 20:23:18  jalet
213# Storage caching mechanism added.
214#
215# Revision 1.25  2003/08/20 15:56:24  jalet
216# Better user and group deletion
217#
218# Revision 1.24  2003/07/29 20:55:17  jalet
219# 1.14 is out !
220#
221# Revision 1.23  2003/07/29 19:52:32  jalet
222# Forgot to read the email field from LDAP
223#
224# Revision 1.22  2003/07/29 09:54:03  jalet
225# Added configurable LDAP mail attribute support
226#
227# Revision 1.21  2003/07/28 09:11:12  jalet
228# PyKota now tries to add its attributes intelligently in existing LDAP
229# directories.
230#
231# Revision 1.20  2003/07/25 10:41:30  jalet
232# Better documentation.
233# pykotme now displays the current user's account balance.
234# Some test changed in ldap module.
235#
236# Revision 1.19  2003/07/14 14:18:16  jalet
237# Wrong documentation strings
238#
239# Revision 1.18  2003/07/11 14:23:13  jalet
240# When adding an user only adds one object containing both the user and
241# its account balance instead of two objects.
242#
243# Revision 1.17  2003/07/07 12:51:07  jalet
244# Small fix
245#
246# Revision 1.16  2003/07/07 12:11:13  jalet
247# Small fix
248#
249# Revision 1.15  2003/07/07 11:49:24  jalet
250# Lots of small fixes with the help of PyChecker
251#
252# Revision 1.14  2003/07/07 08:33:18  jalet
253# Bug fix due to a typo in LDAP code
254#
255# Revision 1.13  2003/07/05 07:46:50  jalet
256# The previous bug fix was incomplete.
257#
258# Revision 1.12  2003/06/30 13:54:21  jalet
259# Sorts by user / group name
260#
261# Revision 1.11  2003/06/25 14:10:01  jalet
262# Hey, it may work (edpykota --reset excepted) !
263#
264# Revision 1.10  2003/06/16 21:55:15  jalet
265# More work on LDAP, again. Problem detected.
266#
267# Revision 1.9  2003/06/16 11:59:09  jalet
268# More work on LDAP
269#
270# Revision 1.8  2003/06/15 22:26:52  jalet
271# More work on LDAP
272#
273# Revision 1.7  2003/06/14 22:44:21  jalet
274# More work on LDAP storage backend.
275#
276# Revision 1.6  2003/06/13 19:07:57  jalet
277# Two big bugs fixed, time to release something ;-)
278#
279# Revision 1.5  2003/06/10 16:37:54  jalet
280# Deletion of the second user which is not needed anymore.
281# Added a debug configuration field in /etc/pykota.conf
282# All queries can now be sent to the logger in debug mode, this will
283# greatly help improve performance when time for this will come.
284#
285# Revision 1.4  2003/06/10 10:45:32  jalet
286# Not implemented methods now raise an exception when called.
287#
288# Revision 1.3  2003/06/06 20:49:15  jalet
289# Very latest schema. UNTESTED.
290#
291# Revision 1.2  2003/06/06 14:21:08  jalet
292# New LDAP schema.
293# Small bug fixes.
294#
295# Revision 1.1  2003/06/05 11:19:13  jalet
296# More good work on LDAP storage.
297#
298#
299#
300
301#
302# My IANA assigned number, for
303# "Conseil Internet & Logiciels Libres, J�me Alet"
304# is 16868. Use this as a base to create the LDAP schema.
305#
306
307import os
308import types
309import time
310import md5
311from mx import DateTime
312
313from pykota.storage import PyKotaStorageError,BaseStorage,StorageObject,StorageUser,StorageGroup,StoragePrinter,StorageJob,StorageLastJob,StorageUserPQuota,StorageGroupPQuota
314
315try :
316    import ldap
317    import ldap.modlist
318except ImportError :   
319    import sys
320    # TODO : to translate or not to translate ?
321    raise PyKotaStorageError, "This python version (%s) doesn't seem to have the python-ldap module installed correctly." % sys.version.split()[0]
322   
323class Storage(BaseStorage) :
324    def __init__(self, pykotatool, host, dbname, user, passwd) :
325        """Opens the LDAP connection."""
326        BaseStorage.__init__(self, pykotatool)
327        self.info = pykotatool.config.getLDAPInfo()
328        try :
329            self.database = ldap.initialize(host) 
330            self.database.simple_bind_s(user, passwd)
331            self.basedn = dbname
332        except ldap.SERVER_DOWN :   
333            raise PyKotaStorageError, "LDAP backend for PyKota seems to be down !" # TODO : translate
334        except ldap.LDAPError :   
335            raise PyKotaStorageError, "Unable to connect to LDAP server %s as %s." % (host, user) # TODO : translate
336        else :   
337            self.useldapcache = pykotatool.config.getLDAPCache()
338            if self.useldapcache :
339                self.tool.logdebug("Low-Level LDAP Caching enabled.")
340                self.ldapcache = {} # low-level cache specific to LDAP backend
341            self.closed = 0
342            self.tool.logdebug("Database opened (host=%s, dbname=%s, user=%s)" % (host, dbname, user))
343           
344    def close(self) :   
345        """Closes the database connection."""
346        if not self.closed :
347            self.database.unbind_s()
348            self.closed = 1
349            self.tool.logdebug("Database closed.")
350       
351    def genUUID(self) :   
352        """Generates an unique identifier.
353       
354           TODO : this one is not unique accross several print servers, but should be sufficient for testing.
355        """
356        return md5.md5("%s" % time.time()).hexdigest()
357       
358    def normalizeFields(self, fields) :   
359        """Ensure all items are lists."""
360        for (k, v) in fields.items() :
361            if type(v) not in (types.TupleType, types.ListType) :
362                if not v :
363                    del fields[k]
364                else :   
365                    fields[k] = [ v ]
366        return fields       
367       
368    def beginTransaction(self) :   
369        """Starts a transaction."""
370        self.tool.logdebug("Transaction begins... WARNING : No transactions in LDAP !")
371       
372    def commitTransaction(self) :   
373        """Commits a transaction."""
374        self.tool.logdebug("Transaction committed. WARNING : No transactions in LDAP !")
375       
376    def rollbackTransaction(self) :     
377        """Rollbacks a transaction."""
378        self.tool.logdebug("Transaction aborted. WARNING : No transaction in LDAP !")
379       
380    def doSearch(self, key, fields=None, base="", scope=ldap.SCOPE_SUBTREE, flushcache=0) :
381        """Does an LDAP search query."""
382        try :
383            base = base or self.basedn
384            if self.useldapcache :
385                # Here we overwrite the fields the app want, to try and
386                # retrieve ALL user defined attributes ("*")
387                # + the createTimestamp attribute, needed by job history
388                #
389                # This may not work with all LDAP servers
390                # but works at least in OpenLDAP (2.1.25)
391                # and iPlanet Directory Server (5.1 SP3)
392                fields = ["*", "createTimestamp"]         
393               
394            if self.useldapcache and (not flushcache) and (scope == ldap.SCOPE_BASE) and self.ldapcache.has_key(base) :
395                entry = self.ldapcache[base]
396                self.tool.logdebug("LDAP cache hit %s => %s" % (base, entry))
397                result = [(base, entry)]
398            else :
399                self.tool.logdebug("QUERY : Filter : %s, BaseDN : %s, Scope : %s, Attributes : %s" % (key, base, scope, fields))
400                result = self.database.search_s(base, scope, key, fields)
401        except ldap.NO_SUCH_OBJECT, msg :       
402            raise PyKotaStorageError, (_("Search base %s doesn't seem to exist. Probable misconfiguration. Please double check /etc/pykota/pykota.conf : %s") % (base, msg))
403        except ldap.LDAPError, msg :   
404            raise PyKotaStorageError, (_("Search for %s(%s) from %s(scope=%s) returned no answer.") % (key, fields, base, scope)) + " : %s" % str(msg)
405        else :     
406            self.tool.logdebug("QUERY : Result : %s" % result)
407            if self.useldapcache :
408                for (dn, attributes) in result :
409                    self.tool.logdebug("LDAP cache store %s => %s" % (dn, attributes))
410                    self.ldapcache[dn] = attributes
411            return result
412           
413    def doAdd(self, dn, fields) :
414        """Adds an entry in the LDAP directory."""
415        # TODO : store into LDAP specific cache
416        fields = self.normalizeFields(fields)
417        try :
418            self.tool.logdebug("QUERY : ADD(%s, %s)" % (dn, str(fields)))
419            entry = ldap.modlist.addModlist(fields)
420            self.tool.logdebug("%s" % entry)
421            self.database.add_s(dn, entry)
422        except ldap.LDAPError, msg :
423            raise PyKotaStorageError, (_("Problem adding LDAP entry (%s, %s)") % (dn, str(fields))) + " : %s" % str(msg)
424        else :
425            if self.useldapcache :
426                self.tool.logdebug("LDAP cache add %s => %s" % (dn, fields))
427                self.ldapcache[dn] = fields
428            return dn
429           
430    def doDelete(self, dn) :
431        """Deletes an entry from the LDAP directory."""
432        # TODO : delete from LDAP specific cache
433        try :
434            self.tool.logdebug("QUERY : Delete(%s)" % dn)
435            self.database.delete_s(dn)
436        except ldap.LDAPError, msg :
437            raise PyKotaStorageError, (_("Problem deleting LDAP entry (%s)") % dn) + " : %s" % str(msg)
438        else :   
439            if self.useldapcache :
440                try :
441                    self.tool.logdebug("LDAP cache del %s" % dn)
442                    del self.ldapcache[dn]
443                except KeyError :   
444                    pass
445           
446    def doModify(self, dn, fields, ignoreold=1, flushcache=0) :
447        """Modifies an entry in the LDAP directory."""
448        try :
449            # TODO : take care of, and update LDAP specific cache
450            if self.useldapcache and not flushcache :
451                if self.ldapcache.has_key(dn) :
452                    old = self.ldapcache[dn]
453                    self.tool.logdebug("LDAP cache hit %s => %s" % (dn, old))
454                    oldentry = {}
455                    for (k, v) in old.items() :
456                        if k != "createTimestamp" :
457                            oldentry[k] = v
458                else :   
459                    self.tool.logdebug("LDAP cache miss %s" % dn)
460                    oldentry = self.doSearch("objectClass=*", base=dn, scope=ldap.SCOPE_BASE)[0][1]
461            else :       
462                oldentry = self.doSearch("objectClass=*", base=dn, scope=ldap.SCOPE_BASE, flushcache=flushcache)[0][1]
463            for (k, v) in fields.items() :
464                if type(v) == type({}) :
465                    try :
466                        oldvalue = v["convert"](oldentry.get(k, [0])[0])
467                    except ValueError :   
468                        self.tool.logdebug("Error converting %s with %s(%s)" % (oldentry.get(k), k, v))
469                        oldvalue = 0
470                    if v["operator"] == '+' :
471                        newvalue = oldvalue + v["value"]
472                    else :   
473                        newvalue = oldvalue - v["value"]
474                    fields[k] = str(newvalue)
475            fields = self.normalizeFields(fields)
476            self.tool.logdebug("QUERY : Modify(%s, %s ==> %s)" % (dn, oldentry, fields))
477            entry = ldap.modlist.modifyModlist(oldentry, fields, ignore_oldexistent=ignoreold)
478            modentry = []
479            for (mop, mtyp, mval) in entry :
480                if mtyp != "createTimestamp" :
481                    modentry.append((mop, mtyp, mval))
482            self.tool.logdebug("MODIFY : %s ==> %s ==> %s" % (fields, entry, modentry))
483            if modentry :
484                self.database.modify_s(dn, modentry)
485        except ldap.LDAPError, msg :
486            raise PyKotaStorageError, (_("Problem modifying LDAP entry (%s, %s)") % (dn, fields)) + " : %s" % str(msg)
487        else :
488            if self.useldapcache :
489                cachedentry = self.ldapcache[dn]
490                for (mop, mtyp, mval) in entry :
491                    if mop in (ldap.MOD_ADD, ldap.MOD_REPLACE) :
492                        cachedentry[mtyp] = mval
493                    else :
494                        try :
495                            del cachedentry[mtyp]
496                        except KeyError :   
497                            pass
498                self.tool.logdebug("LDAP cache update %s => %s" % (dn, cachedentry))
499            return dn
500           
501    def getAllPrintersNames(self) :   
502        """Extracts all printer names."""
503        printernames = []
504        result = self.doSearch("objectClass=pykotaPrinter", ["pykotaPrinterName"], base=self.info["printerbase"])
505        if result :
506            printernames = [record[1]["pykotaPrinterName"][0] for record in result]
507        return printernames
508       
509    def getAllUsersNames(self) :   
510        """Extracts all user names."""
511        usernames = []
512        result = self.doSearch("objectClass=pykotaAccount", ["pykotaUserName"], base=self.info["userbase"])
513        if result :
514            usernames = [record[1]["pykotaUserName"][0] for record in result]
515        return usernames
516       
517    def getAllGroupsNames(self) :   
518        """Extracts all group names."""
519        groupnames = []
520        result = self.doSearch("objectClass=pykotaGroup", ["pykotaGroupName"], base=self.info["groupbase"])
521        if result :
522            groupnames = [record[1]["pykotaGroupName"][0] for record in result]
523        return groupnames
524       
525    def getUserFromBackend(self, username) :   
526        """Extracts user information given its name."""
527        user = StorageUser(self, username)
528        result = self.doSearch("(&(objectClass=pykotaAccount)(|(pykotaUserName=%s)(%s=%s)))" % (username, self.info["userrdn"], username), ["pykotaUserName", "pykotaLimitBy", self.info["usermail"]], base=self.info["userbase"])
529        if result :
530            fields = result[0][1]
531            user.ident = result[0][0]
532            user.Name = fields.get("pykotaUserName", [username])[0] 
533            user.Email = fields.get(self.info["usermail"])
534            if user.Email is not None :
535                user.Email = user.Email[0]
536            user.LimitBy = fields.get("pykotaLimitBy")
537            if user.LimitBy is not None :
538                user.LimitBy = user.LimitBy[0]
539            result = self.doSearch("(&(objectClass=pykotaAccountBalance)(|(pykotaUserName=%s)(%s=%s)))" % (username, self.info["balancerdn"], username), ["pykotaBalance", "pykotaLifeTimePaid", "pykotaPayments"], base=self.info["balancebase"])
540            if not result :
541                raise PyKotaStorageError, _("No pykotaAccountBalance object found for user %s. Did you create LDAP entries manually ?") % username
542            else :
543                fields = result[0][1]
544                user.idbalance = result[0][0]
545                user.AccountBalance = fields.get("pykotaBalance")
546                if user.AccountBalance is not None :
547                    if user.AccountBalance[0].upper() == "NONE" :
548                        user.AccountBalance = None
549                    else :   
550                        user.AccountBalance = float(user.AccountBalance[0])
551                user.AccountBalance = user.AccountBalance or 0.0       
552                user.LifeTimePaid = fields.get("pykotaLifeTimePaid")
553                if user.LifeTimePaid is not None :
554                    if user.LifeTimePaid[0].upper() == "NONE" :
555                        user.LifeTimePaid = None
556                    else :   
557                        user.LifeTimePaid = float(user.LifeTimePaid[0])
558                user.LifeTimePaid = user.LifeTimePaid or 0.0       
559                user.Payments = []
560                for payment in fields.get("pykotaPayments", []) :
561                    (date, amount) = payment.split(" # ")
562                    user.Payments.append((date, amount))
563            user.Exists = 1
564        return user
565       
566    def getGroupFromBackend(self, groupname) :   
567        """Extracts group information given its name."""
568        group = StorageGroup(self, groupname)
569        result = self.doSearch("(&(objectClass=pykotaGroup)(|(pykotaGroupName=%s)(%s=%s)))" % (groupname, self.info["grouprdn"], groupname), ["pykotaGroupName", "pykotaLimitBy"], base=self.info["groupbase"])
570        if result :
571            fields = result[0][1]
572            group.ident = result[0][0]
573            group.Name = fields.get("pykotaGroupName", [groupname])[0] 
574            group.LimitBy = fields.get("pykotaLimitBy")
575            if group.LimitBy is not None :
576                group.LimitBy = group.LimitBy[0]
577            group.AccountBalance = 0.0
578            group.LifeTimePaid = 0.0
579            for member in self.getGroupMembers(group) :
580                if member.Exists :
581                    group.AccountBalance += member.AccountBalance
582                    group.LifeTimePaid += member.LifeTimePaid
583            group.Exists = 1
584        return group
585       
586    def getPrinterFromBackend(self, printername) :       
587        """Extracts printer information given its name : returns first matching printer."""
588        printer = StoragePrinter(self, printername)
589        result = self.doSearch("(&(objectClass=pykotaPrinter)(|(pykotaPrinterName=%s)(%s=%s)))" % (printername, self.info["printerrdn"], printername), ["pykotaPrinterName", "pykotaPricePerPage", "pykotaPricePerJob", "uniqueMember", "description"], base=self.info["printerbase"])
590        if result :
591            fields = result[0][1]       # take only first matching printer, ignore the rest
592            printer.ident = result[0][0]
593            printer.Name = fields.get("pykotaPrinterName", [printername])[0] 
594            printer.PricePerJob = float(fields.get("pykotaPricePerJob", [0.0])[0] or 0.0)
595            printer.PricePerPage = float(fields.get("pykotaPricePerPage", [0.0])[0] or 0.0)
596            printer.uniqueMember = fields.get("uniqueMember", [])
597            printer.Description = self.databaseToUserCharset(fields.get("description", [""])[0]) 
598            printer.Exists = 1
599        return printer   
600       
601    def getUserPQuotaFromBackend(self, user, printer) :       
602        """Extracts a user print quota."""
603        userpquota = StorageUserPQuota(self, user, printer)
604        if printer.Exists and user.Exists :
605            result = self.doSearch("(&(objectClass=pykotaUserPQuota)(pykotaUserName=%s)(pykotaPrinterName=%s))" % (user.Name, printer.Name), ["pykotaPageCounter", "pykotaLifePageCounter", "pykotaSoftLimit", "pykotaHardLimit", "pykotaDateLimit"], base=self.info["userquotabase"])
606            if result :
607                fields = result[0][1]
608                userpquota.ident = result[0][0]
609                userpquota.PageCounter = int(fields.get("pykotaPageCounter", [0])[0] or 0)
610                userpquota.LifePageCounter = int(fields.get("pykotaLifePageCounter", [0])[0] or 0)
611                userpquota.SoftLimit = fields.get("pykotaSoftLimit")
612                if userpquota.SoftLimit is not None :
613                    if userpquota.SoftLimit[0].upper() == "NONE" :
614                        userpquota.SoftLimit = None
615                    else :   
616                        userpquota.SoftLimit = int(userpquota.SoftLimit[0])
617                userpquota.HardLimit = fields.get("pykotaHardLimit")
618                if userpquota.HardLimit is not None :
619                    if userpquota.HardLimit[0].upper() == "NONE" :
620                        userpquota.HardLimit = None
621                    elif userpquota.HardLimit is not None :   
622                        userpquota.HardLimit = int(userpquota.HardLimit[0])
623                userpquota.DateLimit = fields.get("pykotaDateLimit")
624                if userpquota.DateLimit is not None :
625                    if userpquota.DateLimit[0].upper() == "NONE" : 
626                        userpquota.DateLimit = None
627                    else :   
628                        userpquota.DateLimit = userpquota.DateLimit[0]
629                userpquota.Exists = 1
630        return userpquota
631       
632    def getGroupPQuotaFromBackend(self, group, printer) :       
633        """Extracts a group print quota."""
634        grouppquota = StorageGroupPQuota(self, group, printer)
635        if group.Exists :
636            result = self.doSearch("(&(objectClass=pykotaGroupPQuota)(pykotaGroupName=%s)(pykotaPrinterName=%s))" % (group.Name, printer.Name), ["pykotaSoftLimit", "pykotaHardLimit", "pykotaDateLimit"], base=self.info["groupquotabase"])
637            if result :
638                fields = result[0][1]
639                grouppquota.ident = result[0][0]
640                grouppquota.SoftLimit = fields.get("pykotaSoftLimit")
641                if grouppquota.SoftLimit is not None :
642                    if grouppquota.SoftLimit[0].upper() == "NONE" :
643                        grouppquota.SoftLimit = None
644                    else :   
645                        grouppquota.SoftLimit = int(grouppquota.SoftLimit[0])
646                grouppquota.HardLimit = fields.get("pykotaHardLimit")
647                if grouppquota.HardLimit is not None :
648                    if grouppquota.HardLimit[0].upper() == "NONE" :
649                        grouppquota.HardLimit = None
650                    else :   
651                        grouppquota.HardLimit = int(grouppquota.HardLimit[0])
652                grouppquota.DateLimit = fields.get("pykotaDateLimit")
653                if grouppquota.DateLimit is not None :
654                    if grouppquota.DateLimit[0].upper() == "NONE" : 
655                        grouppquota.DateLimit = None
656                    else :   
657                        grouppquota.DateLimit = grouppquota.DateLimit[0]
658                grouppquota.PageCounter = 0
659                grouppquota.LifePageCounter = 0
660                usernamesfilter = "".join(["(pykotaUserName=%s)" % member.Name for member in self.getGroupMembers(group)])
661                if usernamesfilter :
662                    usernamesfilter = "(|%s)" % usernamesfilter
663                result = self.doSearch("(&(objectClass=pykotaUserPQuota)(pykotaPrinterName=%s)%s)" % (printer.Name, usernamesfilter), ["pykotaPageCounter", "pykotaLifePageCounter"], base=self.info["userquotabase"])
664                if result :
665                    for userpquota in result :   
666                        grouppquota.PageCounter += int(userpquota[1].get("pykotaPageCounter", [0])[0] or 0)
667                        grouppquota.LifePageCounter += int(userpquota[1].get("pykotaLifePageCounter", [0])[0] or 0)
668                grouppquota.Exists = 1
669        return grouppquota
670       
671    def getPrinterLastJobFromBackend(self, printer) :       
672        """Extracts a printer's last job information."""
673        lastjob = StorageLastJob(self, printer)
674        result = self.doSearch("(&(objectClass=pykotaLastjob)(|(pykotaPrinterName=%s)(%s=%s)))" % (printer.Name, self.info["printerrdn"], printer.Name), ["pykotaLastJobIdent"], base=self.info["lastjobbase"])
675        if result :
676            lastjob.lastjobident = result[0][0]
677            lastjobident = result[0][1]["pykotaLastJobIdent"][0]
678            result = None
679            try :
680                result = self.doSearch("objectClass=pykotaJob", ["pykotaJobSizeBytes", "pykotaHostName", "pykotaUserName", "pykotaJobId", "pykotaPrinterPageCounter", "pykotaJobSize", "pykotaAction", "pykotaJobPrice", "pykotaFileName", "pykotaTitle", "pykotaCopies", "pykotaOptions", "createTimestamp"], base="cn=%s,%s" % (lastjobident, self.info["jobbase"]), scope=ldap.SCOPE_BASE)
681            except PyKotaStorageError :   
682                pass # Last job entry exists, but job probably doesn't exist anymore.
683            if result :
684                fields = result[0][1]
685                lastjob.ident = result[0][0]
686                lastjob.JobId = fields.get("pykotaJobId")[0]
687                lastjob.UserName = fields.get("pykotaUserName")[0]
688                lastjob.PrinterPageCounter = int(fields.get("pykotaPrinterPageCounter", [0])[0] or 0)
689                try :
690                    lastjob.JobSize = int(fields.get("pykotaJobSize", [0])[0])
691                except ValueError :   
692                    lastjob.JobSize = None
693                try :   
694                    lastjob.JobPrice = float(fields.get("pykotaJobPrice", [0.0])[0])
695                except ValueError :   
696                    lastjob.JobPrice = None
697                lastjob.JobAction = fields.get("pykotaAction", [""])[0]
698                lastjob.JobFileName = self.databaseToUserCharset(fields.get("pykotaFileName", [""])[0]) 
699                lastjob.JobTitle = self.databaseToUserCharset(fields.get("pykotaTitle", [""])[0]) 
700                lastjob.JobCopies = int(fields.get("pykotaCopies", [0])[0])
701                lastjob.JobOptions = self.databaseToUserCharset(fields.get("pykotaOptions", [""])[0]) 
702                lastjob.JobHostName = fields.get("pykotaHostName", [""])[0]
703                lastjob.JobSizeBytes = fields.get("pykotaJobSizeBytes", [0L])[0]
704                date = fields.get("createTimestamp", ["19700101000000"])[0]
705                year = int(date[:4])
706                month = int(date[4:6])
707                day = int(date[6:8])
708                hour = int(date[8:10])
709                minute = int(date[10:12])
710                second = int(date[12:14])
711                lastjob.JobDate = "%04i-%02i-%02i %02i:%02i:%02i" % (year, month, day, hour, minute, second)
712                lastjob.Exists = 1
713        return lastjob
714       
715    def getGroupMembersFromBackend(self, group) :       
716        """Returns the group's members list."""
717        groupmembers = []
718        result = self.doSearch("(&(objectClass=pykotaGroup)(|(pykotaGroupName=%s)(%s=%s)))" % (group.Name, self.info["grouprdn"], group.Name), [self.info["groupmembers"]], base=self.info["groupbase"])
719        if result :
720            for username in result[0][1].get(self.info["groupmembers"], []) :
721                groupmembers.append(self.getUser(username))
722        return groupmembers       
723       
724    def getUserGroupsFromBackend(self, user) :       
725        """Returns the user's groups list."""
726        groups = []
727        result = self.doSearch("(&(objectClass=pykotaGroup)(%s=%s))" % (self.info["groupmembers"], user.Name), [self.info["grouprdn"], "pykotaGroupName", "pykotaLimitBy"], base=self.info["groupbase"])
728        if result :
729            for (groupid, fields) in result :
730                groupname = (fields.get("pykotaGroupName", [None]) or fields.get(self.info["grouprdn"], [None]))[0]
731                group = self.getFromCache("GROUPS", groupname)
732                if group is None :
733                    group = StorageGroup(self, groupname)
734                    group.ident = groupid
735                    group.LimitBy = fields.get("pykotaLimitBy")
736                    if group.LimitBy is not None :
737                        group.LimitBy = group.LimitBy[0]
738                    group.AccountBalance = 0.0
739                    group.LifeTimePaid = 0.0
740                    for member in self.getGroupMembers(group) :
741                        if member.Exists :
742                            group.AccountBalance += member.AccountBalance
743                            group.LifeTimePaid += member.LifeTimePaid
744                    group.Exists = 1
745                    self.cacheEntry("GROUPS", group.Name, group)
746                groups.append(group)
747        return groups       
748       
749    def getParentPrintersFromBackend(self, printer) :   
750        """Get all the printer groups this printer is a member of."""
751        pgroups = []
752        result = self.doSearch("(&(objectClass=pykotaPrinter)(uniqueMember=%s))" % printer.ident, ["pykotaPrinterName"], base=self.info["printerbase"])
753        if result :
754            for (printerid, fields) in result :
755                if printerid != printer.ident : # In case of integrity violation.
756                    parentprinter = self.getPrinter(fields.get("pykotaPrinterName")[0])
757                    if parentprinter.Exists :
758                        pgroups.append(parentprinter)
759        return pgroups
760       
761    def getMatchingPrinters(self, printerpattern) :
762        """Returns the list of all printers for which name matches a certain pattern."""
763        printers = []
764        # see comment at the same place in pgstorage.py
765        result = self.doSearch("(&(objectClass=pykotaPrinter)(|%s))" % "".join(["(pykotaPrinterName=%s)(%s=%s)" % (pname, self.info["printerrdn"], pname) for pname in printerpattern.split(",")]), ["pykotaPrinterName", "pykotaPricePerPage", "pykotaPricePerJob", "uniqueMember", "description"], base=self.info["printerbase"])
766        if result :
767            for (printerid, fields) in result :
768                printername = fields.get("pykotaPrinterName", [""])[0] or fields.get(self.info["printerrdn"], [""])[0]
769                printer = StoragePrinter(self, printername)
770                printer.ident = printerid
771                printer.PricePerJob = float(fields.get("pykotaPricePerJob", [0.0])[0] or 0.0)
772                printer.PricePerPage = float(fields.get("pykotaPricePerPage", [0.0])[0] or 0.0)
773                printer.uniqueMember = fields.get("uniqueMember", [])
774                printer.Description = self.databaseToUserCharset(fields.get("description", [""])[0]) 
775                printer.Exists = 1
776                printers.append(printer)
777                self.cacheEntry("PRINTERS", printer.Name, printer)
778        return printers       
779       
780    def getPrinterUsersAndQuotas(self, printer, names=["*"]) :       
781        """Returns the list of users who uses a given printer, along with their quotas."""
782        usersandquotas = []
783        result = self.doSearch("(&(objectClass=pykotaUserPQuota)(pykotaPrinterName=%s)(|%s))" % (printer.Name, "".join(["(pykotaUserName=%s)" % uname for uname in names])), ["pykotaUserName", "pykotaPageCounter", "pykotaLifePageCounter", "pykotaSoftLimit", "pykotaHardLimit", "pykotaDateLimit"], base=self.info["userquotabase"])
784        if result :
785            for (userquotaid, fields) in result :
786                user = self.getUser(fields.get("pykotaUserName")[0])
787                userpquota = StorageUserPQuota(self, user, printer)
788                userpquota.ident = userquotaid
789                userpquota.PageCounter = int(fields.get("pykotaPageCounter", [0])[0] or 0)
790                userpquota.LifePageCounter = int(fields.get("pykotaLifePageCounter", [0])[0] or 0)
791                userpquota.SoftLimit = fields.get("pykotaSoftLimit")
792                if userpquota.SoftLimit is not None :
793                    if userpquota.SoftLimit[0].upper() == "NONE" :
794                        userpquota.SoftLimit = None
795                    else :   
796                        userpquota.SoftLimit = int(userpquota.SoftLimit[0])
797                userpquota.HardLimit = fields.get("pykotaHardLimit")
798                if userpquota.HardLimit is not None :
799                    if userpquota.HardLimit[0].upper() == "NONE" :
800                        userpquota.HardLimit = None
801                    elif userpquota.HardLimit is not None :   
802                        userpquota.HardLimit = int(userpquota.HardLimit[0])
803                userpquota.DateLimit = fields.get("pykotaDateLimit")
804                if userpquota.DateLimit is not None :
805                    if userpquota.DateLimit[0].upper() == "NONE" : 
806                        userpquota.DateLimit = None
807                    else :   
808                        userpquota.DateLimit = userpquota.DateLimit[0]
809                userpquota.Exists = 1
810                usersandquotas.append((user, userpquota))
811                self.cacheEntry("USERPQUOTAS", "%s@%s" % (user.Name, printer.Name), userpquota)
812        usersandquotas.sort(lambda x, y : cmp(x[0].Name, y[0].Name))           
813        return usersandquotas
814               
815    def getPrinterGroupsAndQuotas(self, printer, names=["*"]) :       
816        """Returns the list of groups which uses a given printer, along with their quotas."""
817        groupsandquotas = []
818        result = self.doSearch("(&(objectClass=pykotaGroupPQuota)(pykotaPrinterName=%s)(|%s))" % (printer.Name, "".join(["(pykotaGroupName=%s)" % gname for gname in names])), ["pykotaGroupName"], base=self.info["groupquotabase"])
819        if result :
820            for (groupquotaid, fields) in result :
821                group = self.getGroup(fields.get("pykotaGroupName")[0])
822                grouppquota = self.getGroupPQuota(group, printer)
823                groupsandquotas.append((group, grouppquota))
824        groupsandquotas.sort(lambda x, y : cmp(x[0].Name, y[0].Name))           
825        return groupsandquotas
826       
827    def addPrinter(self, printername) :       
828        """Adds a printer to the quota storage, returns it."""
829        fields = { self.info["printerrdn"] : printername,
830                   "objectClass" : ["pykotaObject", "pykotaPrinter"],
831                   "cn" : printername,
832                   "pykotaPrinterName" : printername,
833                   "pykotaPricePerPage" : "0.0",
834                   "pykotaPricePerJob" : "0.0",
835                 } 
836        dn = "%s=%s,%s" % (self.info["printerrdn"], printername, self.info["printerbase"])
837        self.doAdd(dn, fields)
838        return self.getPrinter(printername)
839       
840    def addUser(self, user) :       
841        """Adds a user to the quota storage, returns it."""
842        newfields = {
843                       "pykotaUserName" : user.Name,
844                       "pykotaLimitBy" : (user.LimitBy or "quota"),
845                    }   
846                       
847        if user.Email :
848            newfields.update({self.info["usermail"]: user.Email})
849        mustadd = 1
850        if self.info["newuser"].lower() != 'below' :
851            try :
852                (where, action) = [s.strip() for s in self.info["newuser"].split(",")]
853            except ValueError :
854                (where, action) = (self.info["newuser"].strip(), "fail")
855            result = self.doSearch("(&(objectClass=%s)(%s=%s))" % (where, self.info["userrdn"], user.Name), None, base=self.info["userbase"])
856            if result :
857                (dn, fields) = result[0]
858                fields["objectClass"].extend(["pykotaAccount", "pykotaAccountBalance"])
859                fields.update(newfields)
860                fields.update({ "pykotaBalance" : str(user.AccountBalance or 0.0),
861                                "pykotaLifeTimePaid" : str(user.LifeTimePaid or 0.0), })   
862                self.doModify(dn, fields)
863                mustadd = 0
864            else :
865                message = _("Unable to find an existing objectClass %s entry with %s=%s to attach pykotaAccount objectClass") % (where, self.info["userrdn"], user.Name)
866                if action.lower() == "warn" :   
867                    self.tool.printInfo("%s. A new entry will be created instead." % message, "warn")
868                else : # 'fail' or incorrect setting
869                    raise PyKotaStorageError, "%s. Action aborted. Please check your configuration." % message
870               
871        if mustadd :
872            if self.info["userbase"] == self.info["balancebase"] :           
873                fields = { self.info["userrdn"] : user.Name,
874                           "objectClass" : ["pykotaObject", "pykotaAccount", "pykotaAccountBalance"],
875                           "cn" : user.Name,
876                           "pykotaBalance" : str(user.AccountBalance or 0.0),
877                           "pykotaLifeTimePaid" : str(user.LifeTimePaid or 0.0), 
878                         } 
879            else :             
880                fields = { self.info["userrdn"] : user.Name,
881                           "objectClass" : ["pykotaObject", "pykotaAccount"],
882                           "cn" : user.Name,
883                         } 
884            fields.update(newfields)         
885            dn = "%s=%s,%s" % (self.info["userrdn"], user.Name, self.info["userbase"])
886            self.doAdd(dn, fields)
887            if self.info["userbase"] != self.info["balancebase"] :           
888                fields = { self.info["balancerdn"] : user.Name,
889                           "objectClass" : ["pykotaObject", "pykotaAccountBalance"],
890                           "cn" : user.Name,
891                           "pykotaBalance" : str(user.AccountBalance or 0.0),
892                           "pykotaLifeTimePaid" : str(user.LifeTimePaid or 0.0), 
893                         } 
894                dn = "%s=%s,%s" % (self.info["balancerdn"], user.Name, self.info["balancebase"])
895                self.doAdd(dn, fields)
896           
897        return self.getUser(user.Name)
898       
899    def addGroup(self, group) :       
900        """Adds a group to the quota storage, returns it."""
901        newfields = { 
902                      "pykotaGroupName" : group.Name,
903                      "pykotaLimitBY" : (group.LimitBy or "quota"),
904                    } 
905        mustadd = 1
906        if self.info["newgroup"].lower() != 'below' :
907            try :
908                (where, action) = [s.strip() for s in self.info["newgroup"].split(",")]
909            except ValueError :
910                (where, action) = (self.info["newgroup"].strip(), "fail")
911            result = self.doSearch("(&(objectClass=%s)(%s=%s))" % (where, self.info["grouprdn"], group.Name), None, base=self.info["groupbase"])
912            if result :
913                (dn, fields) = result[0]
914                fields["objectClass"].extend(["pykotaGroup"])
915                fields.update(newfields)
916                self.doModify(dn, fields)
917                mustadd = 0
918            else :
919                message = _("Unable to find an existing entry to attach pykotaGroup objectclass %s") % group.Name
920                if action.lower() == "warn" :   
921                    self.tool.printInfo("%s. A new entry will be created instead." % message, "warn")
922                else : # 'fail' or incorrect setting
923                    raise PyKotaStorageError, "%s. Action aborted. Please check your configuration." % message
924               
925        if mustadd :
926            fields = { self.info["grouprdn"] : group.Name,
927                       "objectClass" : ["pykotaObject", "pykotaGroup"],
928                       "cn" : group.Name,
929                     } 
930            fields.update(newfields)         
931            dn = "%s=%s,%s" % (self.info["grouprdn"], group.Name, self.info["groupbase"])
932            self.doAdd(dn, fields)
933        return self.getGroup(group.Name)
934       
935    def addUserToGroup(self, user, group) :   
936        """Adds an user to a group."""
937        if user.Name not in [u.Name for u in self.getGroupMembers(group)] :
938            result = self.doSearch("objectClass=pykotaGroup", None, base=group.ident, scope=ldap.SCOPE_BASE)   
939            if result :
940                fields = result[0][1]
941                if not fields.has_key(self.info["groupmembers"]) :
942                    fields[self.info["groupmembers"]] = []
943                fields[self.info["groupmembers"]].append(user.Name)
944                self.doModify(group.ident, fields)
945                group.Members.append(user)
946               
947    def addUserPQuota(self, user, printer) :
948        """Initializes a user print quota on a printer."""
949        uuid = self.genUUID()
950        fields = { "cn" : uuid,
951                   "objectClass" : ["pykotaObject", "pykotaUserPQuota"],
952                   "pykotaUserName" : user.Name,
953                   "pykotaPrinterName" : printer.Name,
954                   "pykotaDateLimit" : "None",
955                   "pykotaPageCounter" : "0",
956                   "pykotaLifePageCounter" : "0",
957                 } 
958        dn = "cn=%s,%s" % (uuid, self.info["userquotabase"])
959        self.doAdd(dn, fields)
960        return self.getUserPQuota(user, printer)
961       
962    def addGroupPQuota(self, group, printer) :
963        """Initializes a group print quota on a printer."""
964        uuid = self.genUUID()
965        fields = { "cn" : uuid,
966                   "objectClass" : ["pykotaObject", "pykotaGroupPQuota"],
967                   "pykotaGroupName" : group.Name,
968                   "pykotaPrinterName" : printer.Name,
969                   "pykotaDateLimit" : "None",
970                 } 
971        dn = "cn=%s,%s" % (uuid, self.info["groupquotabase"])
972        self.doAdd(dn, fields)
973        return self.getGroupPQuota(group, printer)
974       
975    def writePrinterPrices(self, printer) :   
976        """Write the printer's prices back into the storage."""
977        fields = {
978                   "pykotaPricePerPage" : str(printer.PricePerPage),
979                   "pykotaPricePerJob" : str(printer.PricePerJob),
980                 }
981        self.doModify(printer.ident, fields)
982       
983    def writePrinterDescription(self, printer) :   
984        """Write the printer's description back into the storage."""
985        fields = {
986                   "description" : self.userCharsetToDatabase(str(printer.Description)), 
987                 }
988        self.doModify(printer.ident, fields)
989       
990    def writeUserLimitBy(self, user, limitby) :   
991        """Sets the user's limiting factor."""
992        fields = {
993                   "pykotaLimitBy" : limitby,
994                 }
995        self.doModify(user.ident, fields)         
996       
997    def writeGroupLimitBy(self, group, limitby) :   
998        """Sets the group's limiting factor."""
999        fields = {
1000                   "pykotaLimitBy" : limitby,
1001                 }
1002        self.doModify(group.ident, fields)         
1003       
1004    def writeUserPQuotaDateLimit(self, userpquota, datelimit) :   
1005        """Sets the date limit permanently for a user print quota."""
1006        fields = {
1007                   "pykotaDateLimit" : datelimit,
1008                 }
1009        return self.doModify(userpquota.ident, fields)
1010           
1011    def writeGroupPQuotaDateLimit(self, grouppquota, datelimit) :   
1012        """Sets the date limit permanently for a group print quota."""
1013        fields = {
1014                   "pykotaDateLimit" : datelimit,
1015                 }
1016        return self.doModify(grouppquota.ident, fields)
1017       
1018    def increaseUserPQuotaPagesCounters(self, userpquota, nbpages) :   
1019        """Increase page counters for a user print quota."""
1020        fields = {
1021                   "pykotaPageCounter" : { "operator" : "+", "value" : nbpages, "convert" : int },
1022                   "pykotaLifePageCounter" : { "operator" : "+", "value" : nbpages, "convert" : int },
1023                 }
1024        return self.doModify(userpquota.ident, fields)         
1025       
1026    def writeUserPQuotaPagesCounters(self, userpquota, newpagecounter, newlifepagecounter) :   
1027        """Sets the new page counters permanently for a user print quota."""
1028        fields = {
1029                   "pykotaPageCounter" : str(newpagecounter),
1030                   "pykotaLifePageCounter" : str(newlifepagecounter),
1031                 } 
1032        return self.doModify(userpquota.ident, fields)         
1033       
1034    def decreaseUserAccountBalance(self, user, amount) :   
1035        """Decreases user's account balance from an amount."""
1036        fields = {
1037                   "pykotaBalance" : { "operator" : "-", "value" : amount, "convert" : float },
1038                 }
1039        return self.doModify(user.idbalance, fields, flushcache=1)         
1040       
1041    def writeUserAccountBalance(self, user, newbalance, newlifetimepaid=None) :   
1042        """Sets the new account balance and eventually new lifetime paid."""
1043        fields = {
1044                   "pykotaBalance" : str(newbalance),
1045                 }
1046        if newlifetimepaid is not None :
1047            fields.update({ "pykotaLifeTimePaid" : str(newlifetimepaid) })
1048        return self.doModify(user.idbalance, fields)         
1049           
1050    def writeNewPayment(self, user, amount) :       
1051        """Adds a new payment to the payments history."""
1052        payments = []
1053        for payment in user.Payments :
1054            payments.append("%s # %s" % (payment[0], str(payment[1])))
1055        payments.append("%s # %s" % (str(DateTime.now()), str(amount)))
1056        fields = {
1057                   "pykotaPayments" : payments,
1058                 }
1059        return self.doModify(user.idbalance, fields)         
1060       
1061    def writeLastJobSize(self, lastjob, jobsize, jobprice) :       
1062        """Sets the last job's size permanently."""
1063        fields = {
1064                   "pykotaJobSize" : str(jobsize),
1065                   "pykotaJobPrice" : str(jobprice),
1066                 }
1067        self.doModify(lastjob.ident, fields)         
1068       
1069    def writeJobNew(self, printer, user, jobid, pagecounter, action, jobsize=None, jobprice=None, filename=None, title=None, copies=None, options=None, clienthost=None, jobsizebytes=None) :
1070        """Adds a job in a printer's history."""
1071        if (not self.disablehistory) or (not printer.LastJob.Exists) :
1072            uuid = self.genUUID()
1073            dn = "cn=%s,%s" % (uuid, self.info["jobbase"])
1074        else :   
1075            uuid = printer.LastJob.ident[3:].split(",")[0]
1076            dn = printer.LastJob.ident
1077        fields = {
1078                   "objectClass" : ["pykotaObject", "pykotaJob"],
1079                   "cn" : uuid,
1080                   "pykotaUserName" : user.Name,
1081                   "pykotaPrinterName" : printer.Name,
1082                   "pykotaJobId" : jobid,
1083                   "pykotaPrinterPageCounter" : str(pagecounter),
1084                   "pykotaAction" : action,
1085                   "pykotaFileName" : ((filename is None) and "None") or self.userCharsetToDatabase(filename), 
1086                   "pykotaTitle" : ((title is None) and "None") or self.userCharsetToDatabase(title), 
1087                   "pykotaCopies" : str(copies), 
1088                   "pykotaOptions" : ((options is None) and "None") or self.userCharsetToDatabase(options), 
1089                   "pykotaHostName" : str(clienthost), 
1090                   "pykotaJobSizeBytes" : str(jobsizebytes),
1091                 }
1092        if (not self.disablehistory) or (not printer.LastJob.Exists) :
1093            if jobsize is not None :         
1094                fields.update({ "pykotaJobSize" : str(jobsize), "pykotaJobPrice" : str(jobprice) })
1095            self.doAdd(dn, fields)
1096        else :   
1097            # here we explicitly want to reset jobsize to 'None' if needed
1098            fields.update({ "pykotaJobSize" : str(jobsize), "pykotaJobPrice" : str(jobprice) })
1099            self.doModify(dn, fields)
1100           
1101        if printer.LastJob.Exists :
1102            fields = {
1103                       "pykotaLastJobIdent" : uuid,
1104                     }
1105            self.doModify(printer.LastJob.lastjobident, fields)         
1106        else :   
1107            lastjuuid = self.genUUID()
1108            lastjdn = "cn=%s,%s" % (lastjuuid, self.info["lastjobbase"])
1109            fields = {
1110                       "objectClass" : ["pykotaObject", "pykotaLastJob"],
1111                       "cn" : lastjuuid,
1112                       "pykotaPrinterName" : printer.Name,
1113                       "pykotaLastJobIdent" : uuid,
1114                     } 
1115            self.doAdd(lastjdn, fields)         
1116           
1117    def writeUserPQuotaLimits(self, userpquota, softlimit, hardlimit) :
1118        """Sets soft and hard limits for a user quota."""
1119        fields = { 
1120                   "pykotaSoftLimit" : str(softlimit),
1121                   "pykotaHardLimit" : str(hardlimit),
1122                   "pykotaDateLimit" : "None",
1123                 }
1124        self.doModify(userpquota.ident, fields)
1125       
1126    def writeGroupPQuotaLimits(self, grouppquota, softlimit, hardlimit) :
1127        """Sets soft and hard limits for a group quota on a specific printer."""
1128        fields = { 
1129                   "pykotaSoftLimit" : str(softlimit),
1130                   "pykotaHardLimit" : str(hardlimit),
1131                   "pykotaDateLimit" : "None",
1132                 }
1133        self.doModify(grouppquota.ident, fields)
1134           
1135    def writePrinterToGroup(self, pgroup, printer) :
1136        """Puts a printer into a printer group."""
1137        if printer.ident not in pgroup.uniqueMember :
1138            pgroup.uniqueMember.append(printer.ident)
1139            fields = {
1140                       "uniqueMember" : pgroup.uniqueMember
1141                     } 
1142            self.doModify(pgroup.ident, fields)         
1143           
1144    def removePrinterFromGroup(self, pgroup, printer) :
1145        """Removes a printer from a printer group."""
1146        try :
1147            pgroup.uniqueMember.remove(printer.ident)
1148        except ValueError :   
1149            pass
1150        else :   
1151            fields = {
1152                       "uniqueMember" : pgroup.uniqueMember,
1153                     } 
1154            self.doModify(pgroup.ident, fields)         
1155           
1156    def retrieveHistory(self, user=None, printer=None, datelimit=None, hostname=None, limit=100) :   
1157        """Retrieves all print jobs for user on printer (or all) before date, limited to first 100 results."""
1158        precond = "(objectClass=pykotaJob)"
1159        where = []
1160        if (user is not None) and user.Exists :
1161            where.append("(pykotaUserName=%s)" % user.Name)
1162        if (printer is not None) and printer.Exists :
1163            where.append("(pykotaPrinterName=%s)" % printer.Name)
1164        if hostname is not None :
1165            where.append("(pykotaHostName=%s)" % hostname)
1166        if where :   
1167            where = "(&%s)" % "".join([precond] + where)
1168        else :   
1169            where = precond
1170        jobs = []   
1171        result = self.doSearch(where, fields=["pykotaJobSizeBytes", "pykotaHostName", "pykotaUserName", "pykotaPrinterName", "pykotaJobId", "pykotaPrinterPageCounter", "pykotaAction", "pykotaJobSize", "pykotaJobPrice", "pykotaFileName", "pykotaTitle", "pykotaCopies", "pykotaOptions", "createTimestamp"], base=self.info["jobbase"])
1172        if result :
1173            for (ident, fields) in result :
1174                job = StorageJob(self)
1175                job.ident = ident
1176                job.JobId = fields.get("pykotaJobId")[0]
1177                job.PrinterPageCounter = int(fields.get("pykotaPrinterPageCounter", [0])[0] or 0)
1178                try :
1179                    job.JobSize = int(fields.get("pykotaJobSize", [0])[0])
1180                except ValueError :   
1181                    job.JobSize = None
1182                try :   
1183                    job.JobPrice = float(fields.get("pykotaJobPrice", [0.0])[0])
1184                except ValueError :
1185                    job.JobPrice = None
1186                job.JobAction = fields.get("pykotaAction", [""])[0]
1187                job.JobFileName = self.databaseToUserCharset(fields.get("pykotaFileName", [""])[0]) 
1188                job.JobTitle = self.databaseToUserCharset(fields.get("pykotaTitle", [""])[0]) 
1189                job.JobCopies = int(fields.get("pykotaCopies", [0])[0])
1190                job.JobOptions = self.databaseToUserCharset(fields.get("pykotaOptions", [""])[0]) 
1191                job.JobHostName = fields.get("pykotaHostName", [""])[0]
1192                job.JobSizeBytes = fields.get("pykotaJobSizeBytes", [0L])[0]
1193                date = fields.get("createTimestamp", ["19700101000000"])[0]
1194                year = int(date[:4])
1195                month = int(date[4:6])
1196                day = int(date[6:8])
1197                hour = int(date[8:10])
1198                minute = int(date[10:12])
1199                second = int(date[12:14])
1200                job.JobDate = "%04i-%02i-%02i %02i:%02i:%02i" % (year, month, day, hour, minute, second)
1201                if (datelimit is None) or (job.JobDate <= datelimit) :
1202                    job.UserName = fields.get("pykotaUserName")[0]
1203                    job.PrinterName = fields.get("pykotaPrinterName")[0]
1204                    job.Exists = 1
1205                    jobs.append(job)
1206            jobs.sort(lambda x,y : cmp(y.JobDate, x.JobDate))       
1207            if limit :   
1208                jobs = jobs[:int(limit)]
1209        return jobs
1210       
1211    def deleteUser(self, user) :   
1212        """Completely deletes an user from the Quota Storage."""
1213        todelete = []   
1214        result = self.doSearch("(&(objectClass=pykotaJob)(pykotaUserName=%s))" % user.Name, base=self.info["jobbase"])
1215        for (ident, fields) in result :
1216            todelete.append(ident)
1217           
1218        result = self.doSearch("(&(objectClass=pykotaUserPQuota)(pykotaUserName=%s))" % user.Name, ["pykotaPrinterName", "pykotaUserName"], base=self.info["userquotabase"])
1219        for (ident, fields) in result :
1220            # ensure the user print quota entry will be deleted
1221            todelete.append(ident)
1222           
1223            # if last job of current printer was printed by the user
1224            # to delete, we also need to delete the printer's last job entry.
1225            printername = fields["pykotaPrinterName"][0]
1226            printer = self.getPrinter(printername)
1227            if printer.LastJob.UserName == user.Name :
1228                todelete.append(printer.LastJob.lastjobident)
1229           
1230        for ident in todelete :   
1231            self.doDelete(ident)
1232           
1233        result = self.doSearch("objectClass=pykotaAccount", None, base=user.ident, scope=ldap.SCOPE_BASE)   
1234        if result :
1235            fields = result[0][1]
1236            for k in fields.keys() :
1237                if k.startswith("pykota") :
1238                    del fields[k]
1239                elif k.lower() == "objectclass" :   
1240                    todelete = []
1241                    for i in range(len(fields[k])) :
1242                        if fields[k][i].startswith("pykota") : 
1243                            todelete.append(i)
1244                    todelete.sort()       
1245                    todelete.reverse()
1246                    for i in todelete :
1247                        del fields[k][i]
1248            if fields.get("objectClass") or fields.get("objectclass") :
1249                self.doModify(user.ident, fields, ignoreold=0)       
1250            else :   
1251                self.doDelete(user.ident)
1252        result = self.doSearch("(&(objectClass=pykotaAccountBalance)(pykotaUserName=%s))" % user.Name, ["pykotaUserName"], base=self.info["balancebase"])
1253        for (ident, fields) in result :
1254            self.doDelete(ident)
1255       
1256    def deleteGroup(self, group) :   
1257        """Completely deletes a group from the Quota Storage."""
1258        result = self.doSearch("(&(objectClass=pykotaGroupPQuota)(pykotaGroupName=%s))" % group.Name, ["pykotaGroupName"], base=self.info["groupquotabase"])
1259        for (ident, fields) in result :
1260            self.doDelete(ident)
1261        result = self.doSearch("objectClass=pykotaGroup", None, base=group.ident, scope=ldap.SCOPE_BASE)   
1262        if result :
1263            fields = result[0][1]
1264            for k in fields.keys() :
1265                if k.startswith("pykota") :
1266                    del fields[k]
1267                elif k.lower() == "objectclass" :   
1268                    todelete = []
1269                    for i in range(len(fields[k])) :
1270                        if fields[k][i].startswith("pykota") : 
1271                            todelete.append(i)
1272                    todelete.sort()       
1273                    todelete.reverse()
1274                    for i in todelete :
1275                        del fields[k][i]
1276            if fields.get("objectClass") or fields.get("objectclass") :
1277                self.doModify(group.ident, fields, ignoreold=0)       
1278            else :   
1279                self.doDelete(group.ident)
1280               
1281    def deletePrinter(self, printer) :   
1282        """Completely deletes an user from the Quota Storage."""
1283        result = self.doSearch("(&(objectClass=pykotaLastJob)(pykotaPrinterName=%s))" % printer.Name, base=self.info["lastjobbase"])
1284        for (ident, fields) in result :
1285            self.doDelete(ident)
1286        result = self.doSearch("(&(objectClass=pykotaJob)(pykotaPrinterName=%s))" % printer.Name, base=self.info["jobbase"])
1287        for (ident, fields) in result :
1288            self.doDelete(ident)
1289        result = self.doSearch("(&(objectClass=pykotaGroupPQuota)(pykotaPrinterName=%s))" % printer.Name, base=self.info["groupquotabase"])
1290        for (ident, fields) in result :
1291            self.doDelete(ident)
1292        result = self.doSearch("(&(objectClass=pykotaUserPQuota)(pykotaPrinterName=%s))" % printer.Name, base=self.info["userquotabase"])
1293        for (ident, fields) in result :
1294            self.doDelete(ident)
1295        for parent in self.getParentPrinters(printer) : 
1296            try :
1297                parent.uniqueMember.remove(printer.ident)
1298            except ValueError :   
1299                pass
1300            else :   
1301                fields = {
1302                           "uniqueMember" : parent.uniqueMember,
1303                         } 
1304                self.doModify(parent.ident, fields)         
1305        self.doDelete(printer.ident)   
1306       
1307    def extractPrinters(self) :
1308        """Extracts all printer records."""
1309        entries = [p for p in [self.getPrinter(name) for name in self.getAllPrintersNames()] if p.Exists]
1310        if entries :
1311            result = [ ("dn", "pykotaPrinterName", "pykotaPricePerPage", "pykotaPricePerPage", "description") ]
1312            for entry in entries :
1313                result.append((entry.ident, entry.Name, entry.PricePerPage, entry.PricePerJob, entry.Description))
1314            return result 
1315       
1316    def extractUsers(self) :
1317        """Extracts all user records."""
1318        entries = [u for u in [self.getUser(name) for name in self.getAllUsersNames()] if u.Exists]
1319        if entries :
1320            result = [ ("dn", "pykotaUserName", self.info["usermail"], "pykotaBalance", "pykotaLifeTimePaid", "pykotaLimitBy") ]
1321            for entry in entries :
1322                result.append((entry.ident, entry.Name, entry.Email, entry.AccountBalance, entry.LifeTimePaid, entry.LimitBy))
1323            return result 
1324       
1325    def extractGroups(self) :
1326        """Extracts all group records."""
1327        entries = [g for g in [self.getGroup(name) for name in self.getAllGroupsNames()] if g.Exists]
1328        if entries :
1329            result = [ ("dn", "pykotaGroupName", "pykotaBalance", "pykotaLifeTimePaid", "pykotaLimitBy") ]
1330            for entry in entries :
1331                result.append((entry.ident, entry.Name, entry.AccountBalance, entry.LifeTimePaid, entry.LimitBy))
1332            return result 
1333       
1334    def extractPayments(self) :
1335        """Extracts all payment records."""
1336        entries = [u for u in [self.getUser(name) for name in self.getAllUsersNames()] if u.Exists]
1337        if entries :
1338            result = [ ("pykotaUserName", "date", "amount") ]
1339            for entry in entries :
1340                for (date, amount) in entry.Payments :
1341                    result.append((entry.Name, date, amount))
1342            return result       
1343       
1344    def extractUpquotas(self) :
1345        """Extracts all userpquota records."""
1346        entries = [p for p in [self.getPrinter(name) for name in self.getAllPrintersNames()] if p.Exists]
1347        if entries :
1348            result = [ ("pykotaUserName", "pykotaPrinterName", "dn", "userdn", "printerdn", "pykotaLifePageCounter", "pykotaPageCounter", "pykotaSoftLimit", "pykotaHardLimit", "pykotaDateLimit") ]
1349            for entry in entries :
1350                for (user, userpquota) in self.getPrinterUsersAndQuotas(entry) :
1351                    result.append((user.Name, entry.Name, userpquota.ident, user.ident, entry.ident, userpquota.LifePageCounter, userpquota.PageCounter, userpquota.SoftLimit, userpquota.HardLimit, userpquota.DateLimit))
1352            return result
1353       
1354    def extractGpquotas(self) :
1355        """Extracts all grouppquota records."""
1356        entries = [p for p in [self.getPrinter(name) for name in self.getAllPrintersNames()] if p.Exists]
1357        if entries :
1358            result = [ ("pykotaGroupName", "pykotaPrinterName", "dn", "groupdn", "printerdn", "pykotaLifePageCounter", "pykotaPageCounter", "pykotaSoftLimit", "pykotaHardLimit", "pykotaDateLimit") ]
1359            for entry in entries :
1360                for (group, grouppquota) in self.getPrinterGroupsAndQuotas(entry) :
1361                    result.append((group.Name, entry.Name, grouppquota.ident, group.ident, entry.ident, grouppquota.LifePageCounter, grouppquota.PageCounter, grouppquota.SoftLimit, grouppquota.HardLimit, grouppquota.DateLimit))
1362            return result
1363       
1364    def extractUmembers(self) :
1365        """Extracts all user groups members."""
1366        entries = [g for g in [self.getGroup(name) for name in self.getAllGroupsNames()] if g.Exists]
1367        if entries :
1368            result = [ ("pykotaGroupName", "pykotaUserName", "groupdn", "userdn") ]
1369            for entry in entries :
1370                for member in entry.Members :
1371                    result.append((entry.Name, member.Name, entry.ident, member.ident))
1372            return result       
1373               
1374    def extractPmembers(self) :
1375        """Extracts all printer groups members."""
1376        entries = [p for p in [self.getPrinter(name) for name in self.getAllPrintersNames()] if p.Exists]
1377        if entries :
1378            result = [ ("pykotaPGroupName", "pykotaPrinterName", "pgroupdn", "printerdn") ]
1379            for entry in entries :
1380                for parent in self.getParentPrinters(entry) :
1381                    result.append((parent.Name, entry.Name, parent.ident, entry.ident))
1382            return result       
1383       
1384    def extractHistory(self) :
1385        """Extracts all jobhistory records."""
1386        entries = self.retrieveHistory(limit=None)
1387        if entries :
1388            result = [ ("pykotaUserName", "pykotaPrinterName", "dn", "pykotaJobId", "pykotaPrinterPageCounter", "pykotaJobSize", "pykotaAction", "createTimeStamp", "pykotaFileName", "pykotaTitle", "pykotaCopies", "pykotaOptions", "pykotaJobPrice", "pykotaHostName", "pykotaJobSizeBytes") ] 
1389            for entry in entries :
1390                result.append((entry.UserName, entry.PrinterName, entry.ident, entry.JobId, entry.PrinterPageCounter, entry.JobSize, entry.JobAction, entry.JobDate, entry.JobFileName, entry.JobTitle, entry.JobCopies, entry.JobOptions, entry.JobPrice, entry.JobHostName, entry.JobSizeBytes)) 
1391            return result   
Note: See TracBrowser for help on using the browser.