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

Revision 1582, 57.8 kB (checked in by jalet, 20 years ago)

Added code to handle the description field for printers

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