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

Revision 1244, 41.2 kB (checked in by uid67467, 20 years ago)

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