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

Revision 1966, 70.4 kB (checked in by jalet, 19 years ago)

Now automates LDAP reconnections if the server dropped the connection due
to a timeout.

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