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

Revision 1506, 54.4 kB (checked in by jalet, 20 years ago)

More useful error message in case of misconfiguration of an LDAP search base
in pykota.conf

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