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

Revision 1520, 56.3 kB (checked in by jalet, 20 years ago)

Now stores the job's size in bytes in the database.
Preliminary work on payments storage : database schemas are OK now,
but no code to store payments yet.
Removed schema picture, not relevant anymore.

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