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

Revision 1875, 68.0 kB (checked in by jalet, 20 years ago)

For URGENT legal reasons (Italy), a new "privacy" directive was added to pykota.conf
to hide print jobs' title, filename, and options.

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