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

Revision 2057, 77.3 kB (checked in by jalet, 19 years ago)

Added the md5sum to the history

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