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

Revision 1332, 48.3 kB (checked in by jalet, 20 years ago)

pkprinters can now remove printers from printers groups.

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