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

Revision 1968, 70.8 kB (checked in by jalet, 19 years ago)

TLS is now supported with the LDAP backend

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