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

Revision 1601, 58.4 kB (checked in by jalet, 20 years ago)

Missing file... Am I really stupid ?

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