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

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

Performance improvement for user print quota entries search

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