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

Revision 1451, 53.5 kB (checked in by jalet, 20 years ago)

pkpgcounter : comments
pkprinters : when --add is used, existing printers are now skipped.

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