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

Revision 1990, 72.2 kB (checked in by jalet, 19 years ago)

Prepared dumpykota to accept the new --filter command line option. Some
additionnal work needs to be done in the backends though.

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