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

Revision 1764, 65.8 kB (checked in by jalet, 20 years ago)

More work done on LDAP and dumpykota

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