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

Revision 1742, 60.2 kB (checked in by jalet, 20 years ago)

Fixed pykotaAccountBalance object location during creation

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