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

Revision 1754, 64.9 kB (checked in by jalet, 20 years ago)

dumpykota for LDAP backend is almost there.

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