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

Revision 1330, 47.7 kB (checked in by jalet, 20 years ago)

pkprinters command line tool added.

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