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

Revision 1998, 74.9 kB (checked in by jalet, 19 years ago)

Fixed recently introduced bugs due to extended userquotabase and groupquotabase
directives.

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