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

Revision 2042, 75.6 kB (checked in by jalet, 19 years ago)

Same fix for group print quota entries wrt LDAP performance

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