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
RevLine 
[1016]1# PyKota
[1144]2# -*- coding: ISO-8859-15 -*-
[1016]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$
[1224]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#
[1204]28# Revision 1.38  2003/11/24 09:54:06  jalet
29# Small fix for LDAP when pykotaOptions attribute wasn't present.
30#
[1203]31# Revision 1.37  2003/11/23 19:01:37  jalet
32# Job price added to history
33#
[1200]34# Revision 1.36  2003/11/21 14:28:46  jalet
35# More complete job history.
36#
[1179]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#
[1170]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#
[1149]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#
[1147]49# Revision 1.32  2003/10/07 14:23:25  jalet
50# More work on cache
51#
[1144]52# Revision 1.31  2003/10/07 09:07:30  jalet
53# Character encoding added to please latest version of Python
54#
[1141]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#
[1137]60# Revision 1.29  2003/10/06 13:12:28  jalet
61# More work on caching
62#
[1133]63# Revision 1.28  2003/10/03 12:27:02  jalet
64# Several optimizations, especially with LDAP backend
65#
[1131]66# Revision 1.27  2003/10/03 08:57:55  jalet
67# Caching mechanism now caches all that's cacheable.
68#
[1130]69# Revision 1.26  2003/10/02 20:23:18  jalet
70# Storage caching mechanism added.
71#
[1119]72# Revision 1.25  2003/08/20 15:56:24  jalet
73# Better user and group deletion
74#
[1113]75# Revision 1.24  2003/07/29 20:55:17  jalet
76# 1.14 is out !
77#
[1112]78# Revision 1.23  2003/07/29 19:52:32  jalet
79# Forgot to read the email field from LDAP
80#
[1111]81# Revision 1.22  2003/07/29 09:54:03  jalet
82# Added configurable LDAP mail attribute support
83#
[1105]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#
[1099]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#
[1084]93# Revision 1.19  2003/07/14 14:18:16  jalet
94# Wrong documentation strings
95#
[1081]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#
[1075]100# Revision 1.17  2003/07/07 12:51:07  jalet
101# Small fix
102#
[1070]103# Revision 1.16  2003/07/07 12:11:13  jalet
104# Small fix
105#
[1068]106# Revision 1.15  2003/07/07 11:49:24  jalet
107# Lots of small fixes with the help of PyChecker
108#
[1067]109# Revision 1.14  2003/07/07 08:33:18  jalet
110# Bug fix due to a typo in LDAP code
111#
[1062]112# Revision 1.13  2003/07/05 07:46:50  jalet
113# The previous bug fix was incomplete.
114#
[1051]115# Revision 1.12  2003/06/30 13:54:21  jalet
116# Sorts by user / group name
117#
[1041]118# Revision 1.11  2003/06/25 14:10:01  jalet
119# Hey, it may work (edpykota --reset excepted) !
120#
[1032]121# Revision 1.10  2003/06/16 21:55:15  jalet
122# More work on LDAP, again. Problem detected.
123#
[1031]124# Revision 1.9  2003/06/16 11:59:09  jalet
125# More work on LDAP
126#
[1030]127# Revision 1.8  2003/06/15 22:26:52  jalet
128# More work on LDAP
129#
[1029]130# Revision 1.7  2003/06/14 22:44:21  jalet
131# More work on LDAP storage backend.
132#
[1027]133# Revision 1.6  2003/06/13 19:07:57  jalet
134# Two big bugs fixed, time to release something ;-)
135#
[1021]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#
[1020]142# Revision 1.4  2003/06/10 10:45:32  jalet
143# Not implemented methods now raise an exception when called.
144#
[1018]145# Revision 1.3  2003/06/06 20:49:15  jalet
146# Very latest schema. UNTESTED.
147#
[1017]148# Revision 1.2  2003/06/06 14:21:08  jalet
149# New LDAP schema.
150# Small bug fixes.
151#
[1016]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
[1030]164import time
165import md5
[1016]166
[1130]167from pykota.storage import PyKotaStorageError,BaseStorage,StorageObject,StorageUser,StorageGroup,StoragePrinter,StorageLastJob,StorageUserPQuota,StorageGroupPQuota
[1016]168
169try :
170    import ldap
[1030]171    from ldap import modlist
[1016]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   
[1130]177class Storage(BaseStorage) :
[1021]178    def __init__(self, pykotatool, host, dbname, user, passwd) :
[1016]179        """Opens the LDAP connection."""
180        # raise PyKotaStorageError, "Sorry, the LDAP backend for PyKota is not yet implemented !"
[1130]181        BaseStorage.__init__(self, pykotatool)
[1029]182        self.info = pykotatool.config.getLDAPInfo()
[1016]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
[1031]189        except ldap.LDAPError :   
190            raise PyKotaStorageError, "Unable to connect to LDAP server %s as %s." % (host, user) # TODO : translate
[1016]191        else :   
192            self.closed = 0
[1130]193            self.tool.logdebug("Database opened (host=%s, dbname=%s, user=%s)" % (host, dbname, user))
[1016]194           
[1113]195    def close(self) :   
[1016]196        """Closes the database connection."""
197        if not self.closed :
[1170]198            self.database.unbind_s()
[1016]199            self.closed = 1
[1130]200            self.tool.logdebug("Database closed.")
[1016]201       
[1030]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       
[1041]209    def beginTransaction(self) :   
210        """Starts a transaction."""
[1130]211        self.tool.logdebug("Transaction begins... WARNING : No transactions in LDAP !")
[1041]212       
213    def commitTransaction(self) :   
214        """Commits a transaction."""
[1130]215        self.tool.logdebug("Transaction committed. WARNING : No transactions in LDAP !")
[1041]216       
217    def rollbackTransaction(self) :     
218        """Rollbacks a transaction."""
[1130]219        self.tool.logdebug("Transaction aborted. WARNING : No transaction in LDAP !")
[1041]220       
[1030]221    def doSearch(self, key, fields=None, base="", scope=ldap.SCOPE_SUBTREE) :
[1016]222        """Does an LDAP search query."""
223        try :
[1030]224            base = base or self.basedn
[1130]225            self.tool.logdebug("QUERY : Filter : %s, BaseDN : %s, Scope : %s, Attributes : %s" % (key, base, scope, fields))
[1017]226            result = self.database.search_s(base or self.basedn, scope, key, fields)
[1170]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)
[1016]229        else :     
[1130]230            self.tool.logdebug("QUERY : Result : %s" % result)
[1016]231            return result
[1030]232           
233    def doAdd(self, dn, fields) :
234        """Adds an entry in the LDAP directory."""
235        try :
[1130]236            self.tool.logdebug("QUERY : ADD(%s, %s)" % (dn, str(fields)))
[1030]237            self.database.add_s(dn, modlist.addModlist(fields))
[1170]238        except ldap.LDAPError, msg :
239            raise PyKotaStorageError, (_("Problem adding LDAP entry (%s, %s)") % (dn, str(fields))) + " : %s" % str(msg)
[1030]240        else :
241            return dn
242           
[1041]243    def doDelete(self, dn) :
244        """Deletes an entry from the LDAP directory."""
245        try :
[1130]246            self.tool.logdebug("QUERY : Delete(%s)" % dn)
[1041]247            self.database.delete_s(dn)
[1170]248        except ldap.LDAPError, msg :
249            raise PyKotaStorageError, (_("Problem deleting LDAP entry (%s)") % dn) + " : %s" % str(msg)
[1041]250           
251    def doModify(self, dn, fields, ignoreold=1) :
[1030]252        """Modifies an entry in the LDAP directory."""
253        try :
254            oldentry = self.doSearch("objectClass=*", base=dn, scope=ldap.SCOPE_BASE)
[1130]255            self.tool.logdebug("QUERY : Modify(%s, %s ==> %s)" % (dn, oldentry[0][1], fields))
[1041]256            self.database.modify_s(dn, modlist.modifyModlist(oldentry[0][1], fields, ignore_oldexistent=ignoreold))
[1170]257        except ldap.LDAPError, msg :
258            raise PyKotaStorageError, (_("Problem modifying LDAP entry (%s, %s)") % (dn, fields)) + " : %s" % str(msg)
[1030]259        else :
260            return dn
[1016]261           
[1179]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       
[1130]278    def getUserFromBackend(self, username) :   
[1041]279        """Extracts user information given its name."""
280        user = StorageUser(self, username)
[1112]281        result = self.doSearch("(&(objectClass=pykotaAccount)(|(pykotaUserName=%s)(%s=%s)))" % (username, self.info["userrdn"], username), ["pykotaLimitBy", self.info["usermail"]], base=self.info["userbase"])
[1016]282        if result :
[1041]283            fields = result[0][1]
284            user.ident = result[0][0]
[1111]285            user.Email = fields.get(self.info["usermail"])
286            if user.Email is not None :
287                user.Email = user.Email[0]
[1062]288            user.LimitBy = fields.get("pykotaLimitBy")
289            if user.LimitBy is not None :
290                user.LimitBy = user.LimitBy[0]
[1041]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       
[1130]312    def getGroupFromBackend(self, groupname) :   
[1041]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"])
[1030]316        if result :
[1041]317            fields = result[0][1]
318            group.ident = result[0][0]
[1062]319            group.LimitBy = fields.get("pykotaLimitBy")
320            if group.LimitBy is not None :
321                group.LimitBy = group.LimitBy[0]
[1041]322            group.AccountBalance = 0.0
323            group.LifeTimePaid = 0.0
[1137]324            for member in self.getGroupMembers(group) :
[1075]325                if member.Exists :
326                    group.AccountBalance += member.AccountBalance
327                    group.LifeTimePaid += member.LifeTimePaid
[1041]328            group.Exists = 1
329        return group
330       
[1130]331    def getPrinterFromBackend(self, printername) :       
[1041]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"])
[1016]335        if result :
[1041]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       
[1130]344    def getUserPQuotaFromBackend(self, user, printer) :       
[1041]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"])
[1017]349            if result :
[1041]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
[1016]374       
[1130]375    def getGroupPQuotaFromBackend(self, group, printer) :       
[1041]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
[1141]403                usernamesfilter = "".join(["(pykotaUserName=%s)" % member.Name for member in self.getGroupMembers(group)])
[1041]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       
[1130]412    def getPrinterLastJobFromBackend(self, printer) :       
[1041]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"])
[1016]416        if result :
[1041]417            lastjob.lastjobident = result[0][0]
418            lastjobident = result[0][1]["pykotaLastJobIdent"][0]
[1203]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)
[1017]420            if result :
[1041]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])
[1203]427                lastjob.JobPrice = float(fields.get("pykotaJobPrice", [0.0])[0])
[1041]428                lastjob.JobAction = fields.get("pykotaAction")[0]
[1204]429                lastjob.JobFileName = fields.get("pykotaFileName", [""])[0]
430                lastjob.JobTitle = fields.get("pykotaTitle", [""])[0]
[1203]431                lastjob.JobCopies = int(fields.get("pykotaCopies", [0])[0])
[1204]432                lastjob.JobOptions = fields.get("pykotaOptions", [""])[0]
[1041]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
[1016]443       
[1137]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) :       
[1130]454        """Returns the user's groups list."""
455        groups = []
[1147]456        result = self.doSearch("(&(objectClass=pykotaGroup)(%s=%s))" % (self.info["groupmembers"], user.Name), [self.info["grouprdn"], "pykotaGroupName", "pykotaLimitBy"], base=self.info["groupbase"])
[1130]457        if result :
458            for (groupid, fields) in result :
[1147]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)
[1130]476        return groups       
477       
[1041]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
[1133]482        result = self.doSearch("(&(objectClass=pykotaPrinter)(|%s))" % "".join(["(pykotaPrinterName=%s)" % pname for pname in printerpattern.split(",")]), ["pykotaPrinterName", "pykotaPricePerPage", "pykotaPricePerJob"], base=self.info["printerbase"])
[1016]483        if result :
[1041]484            for (printerid, fields) in result :
485                printername = fields["pykotaPrinterName"][0]
[1133]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)
[1041]494        return printers       
[1016]495       
[1133]496    def getPrinterUsersAndQuotas(self, printer, names=["*"]) :       
[1041]497        """Returns the list of users who uses a given printer, along with their quotas."""
498        usersandquotas = []
[1133]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"])
[1041]500        if result :
501            for (userquotaid, fields) in result :
[1133]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)
[1051]528        usersandquotas.sort(lambda x, y : cmp(x[0].Name, y[0].Name))           
[1041]529        return usersandquotas
530               
[1133]531    def getPrinterGroupsAndQuotas(self, printer, names=["*"]) :       
[1041]532        """Returns the list of groups which uses a given printer, along with their quotas."""
533        groupsandquotas = []
[1133]534        result = self.doSearch("(&(objectClass=pykotaGroupPQuota)(pykotaPrinterName=%s)(|%s))" % (printer.Name, "".join(["(pykotaGroupName=%s)" % gname for gname in names])), ["pykotaGroupName"], base=self.info["groupquotabase"])
[1041]535        if result :
536            for (groupquotaid, fields) in result :
537                group = self.getGroup(fields.get("pykotaGroupName")[0])
[1133]538                grouppquota = self.getGroupPQuota(group, printer)
539                groupsandquotas.append((group, grouppquota))
[1051]540        groupsandquotas.sort(lambda x, y : cmp(x[0].Name, y[0].Name))           
[1041]541        return groupsandquotas
[1016]542       
543    def addPrinter(self, printername) :       
[1041]544        """Adds a printer to the quota storage, returns it."""
[1030]545        fields = { self.info["printerrdn"] : printername,
546                   "objectClass" : ["pykotaObject", "pykotaPrinter"],
[1041]547                   "cn" : printername,
[1030]548                   "pykotaPrinterName" : printername,
549                   "pykotaPricePerPage" : "0.0",
550                   "pykotaPricePerJob" : "0.0",
551                 } 
552        dn = "%s=%s,%s" % (self.info["printerrdn"], printername, self.info["printerbase"])
[1041]553        self.doAdd(dn, fields)
554        return self.getPrinter(printername)
[1016]555       
[1041]556    def addUser(self, user) :       
557        """Adds a user to the quota storage, returns it."""
[1105]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                    }   
[1224]564        if user.Email :
565            newfields.update({self.info["usermail"]: user.Email})
[1105]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)
[1041]584        return self.getUser(user.Name)
[1016]585       
[1041]586    def addGroup(self, group) :       
587        """Adds a group to the quota storage, returns it."""
[1105]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)
[1041]610        return self.getGroup(group.Name)
[1016]611       
[1041]612    def addUserToGroup(self, user, group) :   
613        """Adds an user to a group."""
[1141]614        if user.Name not in [u.Name for u in self.getGroupMembers(group)] :
[1041]615            result = self.doSearch("objectClass=pykotaGroup", None, base=group.ident, scope=ldap.SCOPE_BASE)   
616            if result :
617                fields = result[0][1]
[1070]618                if not fields.has_key(self.info["groupmembers"]) :
619                    fields[self.info["groupmembers"]] = []
[1041]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."""
[1030]626        uuid = self.genUUID()
[1041]627        fields = { "cn" : uuid,
628                   "objectClass" : ["pykotaObject", "pykotaUserPQuota"],
629                   "pykotaUserName" : user.Name,
630                   "pykotaPrinterName" : printer.Name,
631                   "pykotaDateLimit" : "None",
[1030]632                   "pykotaPageCounter" : "0",
633                   "pykotaLifePageCounter" : "0",
634                 } 
635        dn = "cn=%s,%s" % (uuid, self.info["userquotabase"])
[1031]636        self.doAdd(dn, fields)
[1041]637        return self.getUserPQuota(user, printer)
[1016]638       
[1041]639    def addGroupPQuota(self, group, printer) :
640        """Initializes a group print quota on a printer."""
[1030]641        uuid = self.genUUID()
[1041]642        fields = { "cn" : uuid,
643                   "objectClass" : ["pykotaObject", "pykotaGroupPQuota"],
644                   "pykotaGroupName" : group.Name,
645                   "pykotaPrinterName" : printer.Name,
[1030]646                   "pykotaDateLimit" : "None",
647                 } 
648        dn = "cn=%s,%s" % (uuid, self.info["groupquotabase"])
[1031]649        self.doAdd(dn, fields)
[1041]650        return self.getGroupPQuota(group, printer)
[1016]651       
[1041]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)
[1016]659       
[1041]660    def writeUserLimitBy(self, user, limitby) :   
661        """Sets the user's limiting factor."""
[1031]662        fields = {
[1041]663                   "pykotaLimitBy" : limitby,
[1031]664                 }
[1041]665        self.doModify(user.ident, fields)         
[1016]666       
[1041]667    def writeGroupLimitBy(self, group, limitby) :   
668        """Sets the group's limiting factor."""
[1031]669        fields = {
[1041]670                   "pykotaLimitBy" : limitby,
[1031]671                 }
[1041]672        self.doModify(group.ident, fields)         
[1016]673       
[1041]674    def writeUserPQuotaDateLimit(self, userpquota, datelimit) :   
675        """Sets the date limit permanently for a user print quota."""
[1031]676        fields = {
677                   "pykotaDateLimit" : "%04i-%02i-%02i %02i:%02i:%02i" % (datelimit.year, datelimit.month, datelimit.day, datelimit.hour, datelimit.minute, datelimit.second),
678                 }
[1041]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."""
[1031]683        fields = {
684                   "pykotaDateLimit" : "%04i-%02i-%02i %02i:%02i:%02i" % (datelimit.year, datelimit.month, datelimit.day, datelimit.hour, datelimit.minute, datelimit.second),
685                 }
[1041]686        return self.doModify(grouppquota.ident, fields)
[1016]687       
[1041]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           
[1203]705    def writeLastJobSize(self, lastjob, jobsize, jobprice) :       
[1041]706        """Sets the last job's size permanently."""
707        fields = {
708                   "pykotaJobSize" : str(jobsize),
[1203]709                   "pykotaJobPrice" : str(jobprice),
[1041]710                 }
711        self.doModify(lastjob.ident, fields)         
712       
[1203]713    def writeJobNew(self, printer, user, jobid, pagecounter, action, jobsize=None, jobprice=None, filename=None, title=None, copies=None, options=None) :
[1041]714        """Adds a job in a printer's history."""
[1149]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
[1032]721        fields = {
722                   "objectClass" : ["pykotaObject", "pykotaJob"],
723                   "cn" : uuid,
[1041]724                   "pykotaUserName" : user.Name,
725                   "pykotaPrinterName" : printer.Name,
[1032]726                   "pykotaJobId" : jobid,
727                   "pykotaPrinterPageCounter" : str(pagecounter),
728                   "pykotaAction" : action,
[1200]729                   "pykotaFileName" : str(filename), 
730                   "pykotaTitle" : str(title), 
731                   "pykotaCopies" : str(copies), 
732                   "pykotaOptions" : str(options), 
[1032]733                 }
[1149]734        if (not self.disablehistory) or (not printer.LastJob.Exists) :
735            if jobsize is not None :         
[1203]736                fields.update({ "pykotaJobSize" : str(jobsize), "pykotaJobPrice" : str(jobprice) })
[1149]737            self.doAdd(dn, fields)
738        else :   
739            # here we explicitly want to reset jobsize to 'None' if needed
[1203]740            fields.update({ "pykotaJobSize" : str(jobsize), "pykotaJobPrice" : str(jobprice) })
[1149]741            self.doModify(dn, fields)
742           
[1041]743        if printer.LastJob.Exists :
[1032]744            fields = {
745                       "pykotaLastJobIdent" : uuid,
746                     }
[1041]747            self.doModify(printer.LastJob.lastjobident, fields)         
[1032]748        else :   
749            lastjuuid = self.genUUID()
[1067]750            lastjdn = "cn=%s,%s" % (lastjuuid, self.info["lastjobbase"])
[1032]751            fields = {
752                       "objectClass" : ["pykotaObject", "pykotaLastJob"],
753                       "cn" : lastjuuid,
[1041]754                       "pykotaPrinterName" : printer.Name,
[1032]755                       "pykotaLastJobIdent" : uuid,
756                     } 
757            self.doAdd(lastjdn, fields)         
[1041]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) :
[1084]768        """Sets soft and hard limits for a group quota on a specific printer."""
[1041]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)   
[1032]790        if result :
[1041]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]
[1119]804            if fields.get("objectClass") or fields.get("objectclass") :
[1041]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)   
[1016]818        if result :
[1027]819            fields = result[0][1]
[1041]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]
[1119]832            if fields.get("objectClass") or fields.get("objectclass") :
[1041]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.