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

Revision 2106, 77.4 kB (checked in by jalet, 19 years ago)

Improved robustness

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