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

Revision 1224, 40.0 kB (checked in by jalet, 20 years ago)

Added a bit of code to support the setting of the user's email address
which was ignored during writes for now.

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