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

Revision 1768, 67.1 kB (checked in by jalet, 20 years ago)

Finished LDAP support for dumpykota.

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