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

Revision 1874, 67.6 kB (checked in by jalet, 20 years ago)

Missing spaces

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