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

Revision 2030, 75.4 kB (checked in by jalet, 19 years ago)

Big bug fix wrt the datelimit attribute

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