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

Revision 1258, 42.1 kB (checked in by jalet, 20 years ago)

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