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

Revision 1274, 46.3 kB (checked in by jalet, 20 years ago)

Printing history added to CGI script.

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