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

Revision 1204, 39.8 kB (checked in by jalet, 20 years ago)

Small fix for LDAP when pykotaOptions attribute wasn't present.

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