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

Revision 1522, 57.1 kB (checked in by jalet, 20 years ago)

Payments history is now stored in database

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