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

Revision 1765, 66.2 kB (checked in by jalet, 20 years ago)

Dump of payments should work with LDAP backend now.

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