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

Revision 2188, 66.7 kB (checked in by jerome, 19 years ago)

Fixes some case related problems with LDAP

  • 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#
[1257]6# (c) 2003-2004 Jerome Alet <alet@librelogiciel.com>
[1016]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#
[2107]23#
[1016]24
25#
26# My IANA assigned number, for
27# "Conseil Internet & Logiciels Libres, J�me Alet"
28# is 16868. Use this as a base to create the LDAP schema.
29#
30
[1750]31import os
[1240]32import types
[1030]33import time
34import md5
[1522]35from mx import DateTime
[1016]36
[1874]37from pykota.storage import PyKotaStorageError, BaseStorage, StorageObject, StorageUser, StorageGroup, StoragePrinter, StorageJob, StorageLastJob, StorageUserPQuota, StorageGroupPQuota
[1016]38
39try :
40    import ldap
[1356]41    import ldap.modlist
[1016]42except ImportError :   
43    import sys
44    raise PyKotaStorageError, "This python version (%s) doesn't seem to have the python-ldap module installed correctly." % sys.version.split()[0]
45   
[1130]46class Storage(BaseStorage) :
[1021]47    def __init__(self, pykotatool, host, dbname, user, passwd) :
[1016]48        """Opens the LDAP connection."""
[1966]49        self.savedtool = pykotatool
50        self.savedhost = host
51        self.saveddbname = dbname
52        self.saveduser = user
53        self.savedpasswd = passwd
54        self.secondStageInit()
55       
56    def secondStageInit(self) :   
57        """Second stage initialisation."""
58        BaseStorage.__init__(self, self.savedtool)
59        self.info = self.tool.config.getLDAPInfo()
60        message = ""
61        for tryit in range(3) :
62            try :
63                self.database = ldap.initialize(self.savedhost) 
[1968]64                if self.info["ldaptls"] :
65                    # we want TLS
66                    ldap.set_option(ldap.OPT_X_TLS_CACERTFILE, self.info["cacert"])
67                    self.database.set_option(ldap.OPT_X_TLS, ldap.OPT_X_TLS_DEMAND)
68                    self.database.start_tls_s()
[1966]69                self.database.simple_bind_s(self.saveduser, self.savedpasswd)
70                self.basedn = self.saveddbname
71            except ldap.SERVER_DOWN :   
72                message = "LDAP backend for PyKota seems to be down !"
73                self.tool.printInfo("%s" % message, "error")
74                self.tool.printInfo("Trying again in 2 seconds...", "warn")
75                time.sleep(2)
76            except ldap.LDAPError :   
77                message = "Unable to connect to LDAP server %s as %s." % (self.savedhost, self.saveduser)
78                self.tool.printInfo("%s" % message, "error")
79                self.tool.printInfo("Trying again in 2 seconds...", "warn")
80                time.sleep(2)
81            else :   
82                self.useldapcache = self.tool.config.getLDAPCache()
83                if self.useldapcache :
84                    self.tool.logdebug("Low-Level LDAP Caching enabled.")
85                    self.ldapcache = {} # low-level cache specific to LDAP backend
86                self.closed = 0
87                self.tool.logdebug("Database opened (host=%s, dbname=%s, user=%s)" % (self.savedhost, self.saveddbname, self.saveduser))
88                return # All is fine here.
89        raise PyKotaStorageError, message         
[1016]90           
[1113]91    def close(self) :   
[1016]92        """Closes the database connection."""
93        if not self.closed :
[1170]94            self.database.unbind_s()
[1016]95            self.closed = 1
[1130]96            self.tool.logdebug("Database closed.")
[1016]97       
[1030]98    def genUUID(self) :   
99        """Generates an unique identifier.
100       
101           TODO : this one is not unique accross several print servers, but should be sufficient for testing.
102        """
103        return md5.md5("%s" % time.time()).hexdigest()
104       
[1240]105    def normalizeFields(self, fields) :   
106        """Ensure all items are lists."""
107        for (k, v) in fields.items() :
108            if type(v) not in (types.TupleType, types.ListType) :
109                if not v :
110                    del fields[k]
111                else :   
112                    fields[k] = [ v ]
113        return fields       
114       
[1041]115    def beginTransaction(self) :   
116        """Starts a transaction."""
[1130]117        self.tool.logdebug("Transaction begins... WARNING : No transactions in LDAP !")
[1041]118       
119    def commitTransaction(self) :   
120        """Commits a transaction."""
[1130]121        self.tool.logdebug("Transaction committed. WARNING : No transactions in LDAP !")
[1041]122       
123    def rollbackTransaction(self) :     
124        """Rollbacks a transaction."""
[1130]125        self.tool.logdebug("Transaction aborted. WARNING : No transaction in LDAP !")
[1041]126       
[1356]127    def doSearch(self, key, fields=None, base="", scope=ldap.SCOPE_SUBTREE, flushcache=0) :
[1016]128        """Does an LDAP search query."""
[1966]129        message = ""
130        for tryit in range(3) :
131            try :
132                base = base or self.basedn
133                if self.useldapcache :
134                    # Here we overwrite the fields the app want, to try and
135                    # retrieve ALL user defined attributes ("*")
136                    # + the createTimestamp attribute, needed by job history
137                    #
138                    # This may not work with all LDAP servers
139                    # but works at least in OpenLDAP (2.1.25)
140                    # and iPlanet Directory Server (5.1 SP3)
141                    fields = ["*", "createTimestamp"]         
142                   
143                if self.useldapcache and (not flushcache) and (scope == ldap.SCOPE_BASE) and self.ldapcache.has_key(base) :
144                    entry = self.ldapcache[base]
145                    self.tool.logdebug("LDAP cache hit %s => %s" % (base, entry))
146                    result = [(base, entry)]
147                else :
148                    self.tool.logdebug("QUERY : Filter : %s, BaseDN : %s, Scope : %s, Attributes : %s" % (key, base, scope, fields))
149                    result = self.database.search_s(base, scope, key, fields)
150            except ldap.NO_SUCH_OBJECT, msg :       
151                raise PyKotaStorageError, (_("Search base %s doesn't seem to exist. Probable misconfiguration. Please double check /etc/pykota/pykota.conf : %s") % (base, msg))
152            except ldap.LDAPError, msg :   
153                message = (_("Search for %s(%s) from %s(scope=%s) returned no answer.") % (key, fields, base, scope)) + " : %s" % str(msg)
154                self.tool.printInfo("LDAP error : %s" % message, "error")
155                self.tool.printInfo("LDAP connection will be closed and reopened.", "warn")
156                self.close()
157                self.secondStageInit()
158            else :     
159                self.tool.logdebug("QUERY : Result : %s" % result)
160                if self.useldapcache :
161                    for (dn, attributes) in result :
162                        self.tool.logdebug("LDAP cache store %s => %s" % (dn, attributes))
163                        self.ldapcache[dn] = attributes
164                return result
165        raise PyKotaStorageError, message
[1030]166           
167    def doAdd(self, dn, fields) :
168        """Adds an entry in the LDAP directory."""
[1240]169        fields = self.normalizeFields(fields)
[1966]170        message = ""
171        for tryit in range(3) :
172            try :
173                self.tool.logdebug("QUERY : ADD(%s, %s)" % (dn, str(fields)))
174                entry = ldap.modlist.addModlist(fields)
175                self.tool.logdebug("%s" % entry)
176                self.database.add_s(dn, entry)
177            except ldap.LDAPError, msg :
178                message = (_("Problem adding LDAP entry (%s, %s)") % (dn, str(fields))) + " : %s" % str(msg)
179                self.tool.printInfo("LDAP error : %s" % message, "error")
180                self.tool.printInfo("LDAP connection will be closed and reopened.", "warn")
181                self.close()
182                self.secondStageInit()
183            else :
184                if self.useldapcache :
185                    self.tool.logdebug("LDAP cache add %s => %s" % (dn, fields))
186                    self.ldapcache[dn] = fields
187                return dn
188        raise PyKotaStorageError, message
[1030]189           
[1041]190    def doDelete(self, dn) :
191        """Deletes an entry from the LDAP directory."""
[1966]192        message = ""
193        for tryit in range(3) :
194            try :
195                self.tool.logdebug("QUERY : Delete(%s)" % dn)
196                self.database.delete_s(dn)
197            except ldap.LDAPError, msg :
198                message = (_("Problem deleting LDAP entry (%s)") % dn) + " : %s" % str(msg)
199                self.tool.printInfo("LDAP error : %s" % message, "error")
200                self.tool.printInfo("LDAP connection will be closed and reopened.", "warn")
201                self.close()
202                self.secondStageInit()
203            else :   
204                if self.useldapcache :
205                    try :
206                        self.tool.logdebug("LDAP cache del %s" % dn)
207                        del self.ldapcache[dn]
208                    except KeyError :   
209                        pass
210                return       
211        raise PyKotaStorageError, message
[1041]212           
[1356]213    def doModify(self, dn, fields, ignoreold=1, flushcache=0) :
[1030]214        """Modifies an entry in the LDAP directory."""
[1966]215        for tryit in range(3) :
216            try :
217                # TODO : take care of, and update LDAP specific cache
218                if self.useldapcache and not flushcache :
219                    if self.ldapcache.has_key(dn) :
220                        old = self.ldapcache[dn]
221                        self.tool.logdebug("LDAP cache hit %s => %s" % (dn, old))
222                        oldentry = {}
223                        for (k, v) in old.items() :
224                            if k != "createTimestamp" :
225                                oldentry[k] = v
[1269]226                    else :   
[1966]227                        self.tool.logdebug("LDAP cache miss %s" % dn)
228                        oldentry = self.doSearch("objectClass=*", base=dn, scope=ldap.SCOPE_BASE)[0][1]
229                else :       
230                    oldentry = self.doSearch("objectClass=*", base=dn, scope=ldap.SCOPE_BASE, flushcache=flushcache)[0][1]
231                for (k, v) in fields.items() :
232                    if type(v) == type({}) :
233                        try :
234                            oldvalue = v["convert"](oldentry.get(k, [0])[0])
235                        except ValueError :   
236                            self.tool.logdebug("Error converting %s with %s(%s)" % (oldentry.get(k), k, v))
237                            oldvalue = 0
238                        if v["operator"] == '+' :
239                            newvalue = oldvalue + v["value"]
240                        else :   
241                            newvalue = oldvalue - v["value"]
242                        fields[k] = str(newvalue)
243                fields = self.normalizeFields(fields)
244                self.tool.logdebug("QUERY : Modify(%s, %s ==> %s)" % (dn, oldentry, fields))
245                entry = ldap.modlist.modifyModlist(oldentry, fields, ignore_oldexistent=ignoreold)
246                modentry = []
[1356]247                for (mop, mtyp, mval) in entry :
[1966]248                    if mtyp != "createTimestamp" :
249                        modentry.append((mop, mtyp, mval))
250                self.tool.logdebug("MODIFY : %s ==> %s ==> %s" % (fields, entry, modentry))
251                if modentry :
252                    self.database.modify_s(dn, modentry)
253            except ldap.LDAPError, msg :
254                message = (_("Problem modifying LDAP entry (%s, %s)") % (dn, fields)) + " : %s" % str(msg)
255                self.tool.printInfo("LDAP error : %s" % message, "error")
256                self.tool.printInfo("LDAP connection will be closed and reopened.", "warn")
257                self.close()
258                self.secondStageInit()
259            else :
260                if self.useldapcache :
261                    cachedentry = self.ldapcache[dn]
262                    for (mop, mtyp, mval) in entry :
263                        if mop in (ldap.MOD_ADD, ldap.MOD_REPLACE) :
264                            cachedentry[mtyp] = mval
265                        else :
266                            try :
267                                del cachedentry[mtyp]
268                            except KeyError :   
269                                pass
270                    self.tool.logdebug("LDAP cache update %s => %s" % (dn, cachedentry))
271                return dn
272        raise PyKotaStorageError, message
[1016]273           
[2107]274    def filterNames(self, records, attribute) :       
275        """Returns a list of 'attribute' from a list of records.
276       
277           Logs any missing attribute.
278        """   
279        result = []
280        for record in records :
281            attrval = record[1].get(attribute, [None])[0]
282            if attrval is None :
283                self.tool.printInfo("Object %s has no %s attribute !" % (record[0], attribute), "error")
284            else :   
285                result.append(attrval)
286        return result       
287               
[1993]288    def getAllPrintersNames(self, printername=None) :   
289        """Extracts all printer names or only the printers' names matching the optional parameter."""
[1754]290        printernames = []
[1993]291        ldapfilter = "objectClass=pykotaPrinter"
292        if printername :
[2039]293            ldapfilter = "(&(%s)(pykotaPrinterName=%s))" % (ldapfilter, printername)
[1993]294        result = self.doSearch(ldapfilter, ["pykotaPrinterName"], base=self.info["printerbase"])
[1754]295        if result :
[2107]296            printernames = self.filterNames(result, "pykotaPrinterName")
[1754]297        return printernames
298       
[1993]299    def getAllUsersNames(self, username=None) :   
300        """Extracts all user names or only the users' names matching the optional parameter."""
[1179]301        usernames = []
[1993]302        ldapfilter = "objectClass=pykotaAccount"
303        if username :
[2039]304            ldapfilter = "(&(%s)(pykotaUserName=%s))" % (ldapfilter, username)
[1993]305        result = self.doSearch(ldapfilter, ["pykotaUserName"], base=self.info["userbase"])
[1179]306        if result :
[2107]307            usernames = self.filterNames(result, "pykotaUserName")
[1179]308        return usernames
309       
[1993]310    def getAllGroupsNames(self, groupname=None) :   
311        """Extracts all group names or only the groups' names matching the optional parameter."""
[1179]312        groupnames = []
[1993]313        ldapfilter = "objectClass=pykotaGroup"
314        if groupname :
[2039]315            ldapfilter = "(&(%s)(pykotaGroupName=%s))" % (ldapfilter, groupname)
[1993]316        result = self.doSearch(ldapfilter, ["pykotaGroupName"], base=self.info["groupbase"])
[1179]317        if result :
[2107]318            groupnames = self.filterNames(result, "pykotaGroupName")
[1179]319        return groupnames
320       
[1806]321    def getUserNbJobsFromHistory(self, user) :
322        """Returns the number of jobs the user has in history."""
323        result = self.doSearch("(&(pykotaUserName=%s)(objectClass=pykotaJob))" % user.Name, None, base=self.info["jobbase"])
324        return len(result)
325       
[1130]326    def getUserFromBackend(self, username) :   
[1041]327        """Extracts user information given its name."""
328        user = StorageUser(self, username)
[2054]329        result = self.doSearch("(&(objectClass=pykotaAccount)(|(pykotaUserName=%s)(%s=%s)))" % (username, self.info["userrdn"], username), ["pykotaUserName", "pykotaLimitBy", self.info["usermail"], "pykotaOverCharge"], base=self.info["userbase"])
[1016]330        if result :
[1041]331            fields = result[0][1]
332            user.ident = result[0][0]
[1451]333            user.Name = fields.get("pykotaUserName", [username])[0] 
[2054]334            user.Email = fields.get(self.info["usermail"], [None])[0]
335            user.LimitBy = fields.get("pykotaLimitBy", ["quota"])[0]
336            user.OverCharge = float(fields.get("pykotaOverCharge", [1.0])[0])
[1522]337            result = self.doSearch("(&(objectClass=pykotaAccountBalance)(|(pykotaUserName=%s)(%s=%s)))" % (username, self.info["balancerdn"], username), ["pykotaBalance", "pykotaLifeTimePaid", "pykotaPayments"], base=self.info["balancebase"])
[1742]338            if not result :
339                raise PyKotaStorageError, _("No pykotaAccountBalance object found for user %s. Did you create LDAP entries manually ?") % username
340            else :
[1041]341                fields = result[0][1]
342                user.idbalance = result[0][0]
343                user.AccountBalance = fields.get("pykotaBalance")
344                if user.AccountBalance is not None :
345                    if user.AccountBalance[0].upper() == "NONE" :
346                        user.AccountBalance = None
347                    else :   
348                        user.AccountBalance = float(user.AccountBalance[0])
349                user.AccountBalance = user.AccountBalance or 0.0       
350                user.LifeTimePaid = fields.get("pykotaLifeTimePaid")
351                if user.LifeTimePaid is not None :
352                    if user.LifeTimePaid[0].upper() == "NONE" :
353                        user.LifeTimePaid = None
354                    else :   
355                        user.LifeTimePaid = float(user.LifeTimePaid[0])
356                user.LifeTimePaid = user.LifeTimePaid or 0.0       
[1522]357                user.Payments = []
358                for payment in fields.get("pykotaPayments", []) :
359                    (date, amount) = payment.split(" # ")
360                    user.Payments.append((date, amount))
[1041]361            user.Exists = 1
362        return user
363       
[1130]364    def getGroupFromBackend(self, groupname) :   
[1041]365        """Extracts group information given its name."""
366        group = StorageGroup(self, groupname)
[1451]367        result = self.doSearch("(&(objectClass=pykotaGroup)(|(pykotaGroupName=%s)(%s=%s)))" % (groupname, self.info["grouprdn"], groupname), ["pykotaGroupName", "pykotaLimitBy"], base=self.info["groupbase"])
[1030]368        if result :
[1041]369            fields = result[0][1]
370            group.ident = result[0][0]
[1451]371            group.Name = fields.get("pykotaGroupName", [groupname])[0] 
[2054]372            group.LimitBy = fields.get("pykotaLimitBy", ["quota"])[0]
[1041]373            group.AccountBalance = 0.0
374            group.LifeTimePaid = 0.0
[1137]375            for member in self.getGroupMembers(group) :
[1075]376                if member.Exists :
377                    group.AccountBalance += member.AccountBalance
378                    group.LifeTimePaid += member.LifeTimePaid
[1041]379            group.Exists = 1
380        return group
381       
[1130]382    def getPrinterFromBackend(self, printername) :       
[1451]383        """Extracts printer information given its name : returns first matching printer."""
[1041]384        printer = StoragePrinter(self, printername)
[1582]385        result = self.doSearch("(&(objectClass=pykotaPrinter)(|(pykotaPrinterName=%s)(%s=%s)))" % (printername, self.info["printerrdn"], printername), ["pykotaPrinterName", "pykotaPricePerPage", "pykotaPricePerJob", "uniqueMember", "description"], base=self.info["printerbase"])
[1016]386        if result :
[1451]387            fields = result[0][1]       # take only first matching printer, ignore the rest
[1041]388            printer.ident = result[0][0]
[1451]389            printer.Name = fields.get("pykotaPrinterName", [printername])[0] 
[2054]390            printer.PricePerJob = float(fields.get("pykotaPricePerJob", [0.0])[0])
391            printer.PricePerPage = float(fields.get("pykotaPricePerPage", [0.0])[0])
[1258]392            printer.uniqueMember = fields.get("uniqueMember", [])
[1790]393            printer.Description = self.databaseToUserCharset(fields.get("description", [""])[0]) 
[1041]394            printer.Exists = 1
395        return printer   
396       
[1130]397    def getUserPQuotaFromBackend(self, user, printer) :       
[1041]398        """Extracts a user print quota."""
399        userpquota = StorageUserPQuota(self, user, printer)
[1228]400        if printer.Exists and user.Exists :
[1969]401            if self.info["userquotabase"].lower() == "user" :
[1998]402                base = user.ident
[1969]403            else :   
[1998]404                base = self.info["userquotabase"]
[2054]405            result = self.doSearch("(&(objectClass=pykotaUserPQuota)(pykotaUserName=%s)(pykotaPrinterName=%s))" % (user.Name, printer.Name), ["pykotaPageCounter", "pykotaLifePageCounter", "pykotaSoftLimit", "pykotaHardLimit", "pykotaDateLimit", "pykotaWarnCount"], base=base)
[1017]406            if result :
[1041]407                fields = result[0][1]
408                userpquota.ident = result[0][0]
[2054]409                userpquota.PageCounter = int(fields.get("pykotaPageCounter", [0])[0])
410                userpquota.LifePageCounter = int(fields.get("pykotaLifePageCounter", [0])[0])
411                userpquota.WarnCount = int(fields.get("pykotaWarnCount", [0])[0])
[1041]412                userpquota.SoftLimit = fields.get("pykotaSoftLimit")
413                if userpquota.SoftLimit is not None :
414                    if userpquota.SoftLimit[0].upper() == "NONE" :
415                        userpquota.SoftLimit = None
416                    else :   
417                        userpquota.SoftLimit = int(userpquota.SoftLimit[0])
418                userpquota.HardLimit = fields.get("pykotaHardLimit")
419                if userpquota.HardLimit is not None :
420                    if userpquota.HardLimit[0].upper() == "NONE" :
421                        userpquota.HardLimit = None
422                    elif userpquota.HardLimit is not None :   
423                        userpquota.HardLimit = int(userpquota.HardLimit[0])
424                userpquota.DateLimit = fields.get("pykotaDateLimit")
425                if userpquota.DateLimit is not None :
426                    if userpquota.DateLimit[0].upper() == "NONE" : 
427                        userpquota.DateLimit = None
428                    else :   
429                        userpquota.DateLimit = userpquota.DateLimit[0]
430                userpquota.Exists = 1
431        return userpquota
[1016]432       
[1130]433    def getGroupPQuotaFromBackend(self, group, printer) :       
[1041]434        """Extracts a group print quota."""
435        grouppquota = StorageGroupPQuota(self, group, printer)
436        if group.Exists :
[1969]437            if self.info["groupquotabase"].lower() == "group" :
[1998]438                base = group.ident
[1969]439            else :   
[1998]440                base = self.info["groupquotabase"]
441            result = self.doSearch("(&(objectClass=pykotaGroupPQuota)(pykotaGroupName=%s)(pykotaPrinterName=%s))" % (group.Name, printer.Name), ["pykotaSoftLimit", "pykotaHardLimit", "pykotaDateLimit"], base=base)
[1041]442            if result :
443                fields = result[0][1]
444                grouppquota.ident = result[0][0]
445                grouppquota.SoftLimit = fields.get("pykotaSoftLimit")
446                if grouppquota.SoftLimit is not None :
447                    if grouppquota.SoftLimit[0].upper() == "NONE" :
448                        grouppquota.SoftLimit = None
449                    else :   
450                        grouppquota.SoftLimit = int(grouppquota.SoftLimit[0])
451                grouppquota.HardLimit = fields.get("pykotaHardLimit")
452                if grouppquota.HardLimit is not None :
453                    if grouppquota.HardLimit[0].upper() == "NONE" :
454                        grouppquota.HardLimit = None
455                    else :   
456                        grouppquota.HardLimit = int(grouppquota.HardLimit[0])
457                grouppquota.DateLimit = fields.get("pykotaDateLimit")
458                if grouppquota.DateLimit is not None :
459                    if grouppquota.DateLimit[0].upper() == "NONE" : 
460                        grouppquota.DateLimit = None
461                    else :   
462                        grouppquota.DateLimit = grouppquota.DateLimit[0]
463                grouppquota.PageCounter = 0
464                grouppquota.LifePageCounter = 0
[1141]465                usernamesfilter = "".join(["(pykotaUserName=%s)" % member.Name for member in self.getGroupMembers(group)])
[1361]466                if usernamesfilter :
467                    usernamesfilter = "(|%s)" % usernamesfilter
[1998]468                if self.info["userquotabase"].lower() == "user" :
469                    base = self.info["userbase"]
470                else :
471                    base = self.info["userquotabase"]
472                result = self.doSearch("(&(objectClass=pykotaUserPQuota)(pykotaPrinterName=%s)%s)" % (printer.Name, usernamesfilter), ["pykotaPageCounter", "pykotaLifePageCounter"], base=base)
[1041]473                if result :
474                    for userpquota in result :   
[1392]475                        grouppquota.PageCounter += int(userpquota[1].get("pykotaPageCounter", [0])[0] or 0)
476                        grouppquota.LifePageCounter += int(userpquota[1].get("pykotaLifePageCounter", [0])[0] or 0)
[1041]477                grouppquota.Exists = 1
478        return grouppquota
479       
[1130]480    def getPrinterLastJobFromBackend(self, printer) :       
[1041]481        """Extracts a printer's last job information."""
482        lastjob = StorageLastJob(self, printer)
483        result = self.doSearch("(&(objectClass=pykotaLastjob)(|(pykotaPrinterName=%s)(%s=%s)))" % (printer.Name, self.info["printerrdn"], printer.Name), ["pykotaLastJobIdent"], base=self.info["lastjobbase"])
[1016]484        if result :
[1041]485            lastjob.lastjobident = result[0][0]
486            lastjobident = result[0][1]["pykotaLastJobIdent"][0]
[1692]487            result = None
488            try :
[2054]489                result = self.doSearch("objectClass=pykotaJob", ["pykotaJobSizeBytes", "pykotaHostName", "pykotaUserName", "pykotaJobId", "pykotaPrinterPageCounter", "pykotaJobSize", "pykotaAction", "pykotaJobPrice", "pykotaFileName", "pykotaTitle", "pykotaCopies", "pykotaOptions", "pykotaBillingCode", "pykotaPages", "pykotaMD5Sum", "createTimestamp"], base="cn=%s,%s" % (lastjobident, self.info["jobbase"]), scope=ldap.SCOPE_BASE)
[1692]490            except PyKotaStorageError :   
491                pass # Last job entry exists, but job probably doesn't exist anymore.
[1017]492            if result :
[1041]493                fields = result[0][1]
494                lastjob.ident = result[0][0]
495                lastjob.JobId = fields.get("pykotaJobId")[0]
[1358]496                lastjob.UserName = fields.get("pykotaUserName")[0]
[2054]497                lastjob.PrinterPageCounter = int(fields.get("pykotaPrinterPageCounter", [0])[0])
[1601]498                try :
499                    lastjob.JobSize = int(fields.get("pykotaJobSize", [0])[0])
500                except ValueError :   
501                    lastjob.JobSize = None
502                try :   
503                    lastjob.JobPrice = float(fields.get("pykotaJobPrice", [0.0])[0])
504                except ValueError :   
505                    lastjob.JobPrice = None
[1393]506                lastjob.JobAction = fields.get("pykotaAction", [""])[0]
[1790]507                lastjob.JobFileName = self.databaseToUserCharset(fields.get("pykotaFileName", [""])[0]) 
508                lastjob.JobTitle = self.databaseToUserCharset(fields.get("pykotaTitle", [""])[0]) 
[1203]509                lastjob.JobCopies = int(fields.get("pykotaCopies", [0])[0])
[1790]510                lastjob.JobOptions = self.databaseToUserCharset(fields.get("pykotaOptions", [""])[0]) 
[1502]511                lastjob.JobHostName = fields.get("pykotaHostName", [""])[0]
[1520]512                lastjob.JobSizeBytes = fields.get("pykotaJobSizeBytes", [0L])[0]
[2054]513                lastjob.JobBillingCode = fields.get("pykotaMD5Sum", [None])[0]
514                lastjob.JobMD5Sum = fields.get("pykotaMD5Sum", [None])[0]
515                lastjob.JobPages = fields.get("pykotaPages", [""])[0]
[1392]516                date = fields.get("createTimestamp", ["19700101000000"])[0]
[1041]517                year = int(date[:4])
518                month = int(date[4:6])
519                day = int(date[6:8])
520                hour = int(date[8:10])
521                minute = int(date[10:12])
522                second = int(date[12:14])
523                lastjob.JobDate = "%04i-%02i-%02i %02i:%02i:%02i" % (year, month, day, hour, minute, second)
524                lastjob.Exists = 1
525        return lastjob
[1016]526       
[1137]527    def getGroupMembersFromBackend(self, group) :       
528        """Returns the group's members list."""
529        groupmembers = []
530        result = self.doSearch("(&(objectClass=pykotaGroup)(|(pykotaGroupName=%s)(%s=%s)))" % (group.Name, self.info["grouprdn"], group.Name), [self.info["groupmembers"]], base=self.info["groupbase"])
531        if result :
532            for username in result[0][1].get(self.info["groupmembers"], []) :
533                groupmembers.append(self.getUser(username))
534        return groupmembers       
535       
536    def getUserGroupsFromBackend(self, user) :       
[1130]537        """Returns the user's groups list."""
538        groups = []
[1147]539        result = self.doSearch("(&(objectClass=pykotaGroup)(%s=%s))" % (self.info["groupmembers"], user.Name), [self.info["grouprdn"], "pykotaGroupName", "pykotaLimitBy"], base=self.info["groupbase"])
[1130]540        if result :
541            for (groupid, fields) in result :
[1147]542                groupname = (fields.get("pykotaGroupName", [None]) or fields.get(self.info["grouprdn"], [None]))[0]
543                group = self.getFromCache("GROUPS", groupname)
544                if group is None :
545                    group = StorageGroup(self, groupname)
546                    group.ident = groupid
547                    group.LimitBy = fields.get("pykotaLimitBy")
548                    if group.LimitBy is not None :
549                        group.LimitBy = group.LimitBy[0]
[2000]550                    else :   
551                        group.LimitBy = "quota"
[1147]552                    group.AccountBalance = 0.0
553                    group.LifeTimePaid = 0.0
554                    for member in self.getGroupMembers(group) :
555                        if member.Exists :
556                            group.AccountBalance += member.AccountBalance
557                            group.LifeTimePaid += member.LifeTimePaid
558                    group.Exists = 1
559                    self.cacheEntry("GROUPS", group.Name, group)
560                groups.append(group)
[1130]561        return groups       
562       
[1249]563    def getParentPrintersFromBackend(self, printer) :   
564        """Get all the printer groups this printer is a member of."""
565        pgroups = []
566        result = self.doSearch("(&(objectClass=pykotaPrinter)(uniqueMember=%s))" % printer.ident, ["pykotaPrinterName"], base=self.info["printerbase"])
567        if result :
568            for (printerid, fields) in result :
569                if printerid != printer.ident : # In case of integrity violation.
570                    parentprinter = self.getPrinter(fields.get("pykotaPrinterName")[0])
571                    if parentprinter.Exists :
572                        pgroups.append(parentprinter)
573        return pgroups
574       
[1041]575    def getMatchingPrinters(self, printerpattern) :
576        """Returns the list of all printers for which name matches a certain pattern."""
577        printers = []
578        # see comment at the same place in pgstorage.py
[1582]579        result = self.doSearch("(&(objectClass=pykotaPrinter)(|%s))" % "".join(["(pykotaPrinterName=%s)(%s=%s)" % (pname, self.info["printerrdn"], pname) for pname in printerpattern.split(",")]), ["pykotaPrinterName", "pykotaPricePerPage", "pykotaPricePerJob", "uniqueMember", "description"], base=self.info["printerbase"])
[1016]580        if result :
[1041]581            for (printerid, fields) in result :
[1380]582                printername = fields.get("pykotaPrinterName", [""])[0] or fields.get(self.info["printerrdn"], [""])[0]
[1133]583                printer = StoragePrinter(self, printername)
584                printer.ident = printerid
[1392]585                printer.PricePerJob = float(fields.get("pykotaPricePerJob", [0.0])[0] or 0.0)
586                printer.PricePerPage = float(fields.get("pykotaPricePerPage", [0.0])[0] or 0.0)
[1258]587                printer.uniqueMember = fields.get("uniqueMember", [])
[1790]588                printer.Description = self.databaseToUserCharset(fields.get("description", [""])[0]) 
[1133]589                printer.Exists = 1
590                printers.append(printer)
591                self.cacheEntry("PRINTERS", printer.Name, printer)
[1041]592        return printers       
[1016]593       
[1133]594    def getPrinterUsersAndQuotas(self, printer, names=["*"]) :       
[1041]595        """Returns the list of users who uses a given printer, along with their quotas."""
596        usersandquotas = []
[1998]597        if self.info["userquotabase"].lower() == "user" :
598           base = self.info["userbase"]
599        else :
600           base = self.info["userquotabase"]
[2054]601        result = self.doSearch("(&(objectClass=pykotaUserPQuota)(pykotaPrinterName=%s)(|%s))" % (printer.Name, "".join(["(pykotaUserName=%s)" % uname for uname in names])), ["pykotaUserName", "pykotaPageCounter", "pykotaLifePageCounter", "pykotaSoftLimit", "pykotaHardLimit", "pykotaDateLimit", "pykotaWarnCount"], base=base)
[1041]602        if result :
603            for (userquotaid, fields) in result :
[1133]604                user = self.getUser(fields.get("pykotaUserName")[0])
605                userpquota = StorageUserPQuota(self, user, printer)
606                userpquota.ident = userquotaid
[2054]607                userpquota.PageCounter = int(fields.get("pykotaPageCounter", [0])[0])
608                userpquota.LifePageCounter = int(fields.get("pykotaLifePageCounter", [0])[0])
609                userpquota.WarnCount = int(fields.get("pykotaWarnCount", [0])[0])
[1133]610                userpquota.SoftLimit = fields.get("pykotaSoftLimit")
611                if userpquota.SoftLimit is not None :
612                    if userpquota.SoftLimit[0].upper() == "NONE" :
613                        userpquota.SoftLimit = None
614                    else :   
615                        userpquota.SoftLimit = int(userpquota.SoftLimit[0])
616                userpquota.HardLimit = fields.get("pykotaHardLimit")
617                if userpquota.HardLimit is not None :
618                    if userpquota.HardLimit[0].upper() == "NONE" :
619                        userpquota.HardLimit = None
620                    elif userpquota.HardLimit is not None :   
621                        userpquota.HardLimit = int(userpquota.HardLimit[0])
622                userpquota.DateLimit = fields.get("pykotaDateLimit")
623                if userpquota.DateLimit is not None :
624                    if userpquota.DateLimit[0].upper() == "NONE" : 
625                        userpquota.DateLimit = None
626                    else :   
627                        userpquota.DateLimit = userpquota.DateLimit[0]
628                userpquota.Exists = 1
629                usersandquotas.append((user, userpquota))
630                self.cacheEntry("USERPQUOTAS", "%s@%s" % (user.Name, printer.Name), userpquota)
[1051]631        usersandquotas.sort(lambda x, y : cmp(x[0].Name, y[0].Name))           
[1041]632        return usersandquotas
633               
[1133]634    def getPrinterGroupsAndQuotas(self, printer, names=["*"]) :       
[1041]635        """Returns the list of groups which uses a given printer, along with their quotas."""
636        groupsandquotas = []
[1998]637        if self.info["groupquotabase"].lower() == "group" :
638           base = self.info["groupbase"]
639        else :
640           base = self.info["groupquotabase"]
641        result = self.doSearch("(&(objectClass=pykotaGroupPQuota)(pykotaPrinterName=%s)(|%s))" % (printer.Name, "".join(["(pykotaGroupName=%s)" % gname for gname in names])), ["pykotaGroupName"], base=base)
[1041]642        if result :
643            for (groupquotaid, fields) in result :
644                group = self.getGroup(fields.get("pykotaGroupName")[0])
[1133]645                grouppquota = self.getGroupPQuota(group, printer)
646                groupsandquotas.append((group, grouppquota))
[1051]647        groupsandquotas.sort(lambda x, y : cmp(x[0].Name, y[0].Name))           
[1041]648        return groupsandquotas
[1016]649       
650    def addPrinter(self, printername) :       
[1041]651        """Adds a printer to the quota storage, returns it."""
[1030]652        fields = { self.info["printerrdn"] : printername,
653                   "objectClass" : ["pykotaObject", "pykotaPrinter"],
[1041]654                   "cn" : printername,
[1030]655                   "pykotaPrinterName" : printername,
656                   "pykotaPricePerPage" : "0.0",
657                   "pykotaPricePerJob" : "0.0",
658                 } 
659        dn = "%s=%s,%s" % (self.info["printerrdn"], printername, self.info["printerbase"])
[1041]660        self.doAdd(dn, fields)
661        return self.getPrinter(printername)
[1016]662       
[1041]663    def addUser(self, user) :       
664        """Adds a user to the quota storage, returns it."""
[1105]665        newfields = {
666                       "pykotaUserName" : user.Name,
[1742]667                       "pykotaLimitBy" : (user.LimitBy or "quota"),
[2054]668                       "pykotaOverCharge" : str(user.OverCharge),
[1105]669                    }   
[1742]670                       
[1224]671        if user.Email :
672            newfields.update({self.info["usermail"]: user.Email})
[1105]673        mustadd = 1
674        if self.info["newuser"].lower() != 'below' :
[1510]675            try :
676                (where, action) = [s.strip() for s in self.info["newuser"].split(",")]
677            except ValueError :
678                (where, action) = (self.info["newuser"].strip(), "fail")
679            result = self.doSearch("(&(objectClass=%s)(%s=%s))" % (where, self.info["userrdn"], user.Name), None, base=self.info["userbase"])
[1105]680            if result :
681                (dn, fields) = result[0]
[2188]682                oc = fields.get("objectClass", fields.get("objectclass", []))
683                oc.extend(["pykotaAccount", "pykotaAccountBalance"])
[1105]684                fields.update(newfields)
[1742]685                fields.update({ "pykotaBalance" : str(user.AccountBalance or 0.0),
686                                "pykotaLifeTimePaid" : str(user.LifeTimePaid or 0.0), })   
[1105]687                self.doModify(dn, fields)
688                mustadd = 0
[1510]689            else :
[1534]690                message = _("Unable to find an existing objectClass %s entry with %s=%s to attach pykotaAccount objectClass") % (where, self.info["userrdn"], user.Name)
[1510]691                if action.lower() == "warn" :   
[1584]692                    self.tool.printInfo("%s. A new entry will be created instead." % message, "warn")
[1510]693                else : # 'fail' or incorrect setting
694                    raise PyKotaStorageError, "%s. Action aborted. Please check your configuration." % message
[1105]695               
696        if mustadd :
[1742]697            if self.info["userbase"] == self.info["balancebase"] :           
698                fields = { self.info["userrdn"] : user.Name,
699                           "objectClass" : ["pykotaObject", "pykotaAccount", "pykotaAccountBalance"],
700                           "cn" : user.Name,
701                           "pykotaBalance" : str(user.AccountBalance or 0.0),
702                           "pykotaLifeTimePaid" : str(user.LifeTimePaid or 0.0), 
703                         } 
704            else :             
705                fields = { self.info["userrdn"] : user.Name,
706                           "objectClass" : ["pykotaObject", "pykotaAccount"],
707                           "cn" : user.Name,
708                         } 
[1105]709            fields.update(newfields)         
710            dn = "%s=%s,%s" % (self.info["userrdn"], user.Name, self.info["userbase"])
711            self.doAdd(dn, fields)
[1742]712            if self.info["userbase"] != self.info["balancebase"] :           
713                fields = { self.info["balancerdn"] : user.Name,
714                           "objectClass" : ["pykotaObject", "pykotaAccountBalance"],
715                           "cn" : user.Name,
716                           "pykotaBalance" : str(user.AccountBalance or 0.0),
717                           "pykotaLifeTimePaid" : str(user.LifeTimePaid or 0.0), 
718                         } 
719                dn = "%s=%s,%s" % (self.info["balancerdn"], user.Name, self.info["balancebase"])
720                self.doAdd(dn, fields)
721           
[1041]722        return self.getUser(user.Name)
[1016]723       
[1041]724    def addGroup(self, group) :       
725        """Adds a group to the quota storage, returns it."""
[1105]726        newfields = { 
727                      "pykotaGroupName" : group.Name,
[2054]728                      "pykotaLimitBy" : (group.LimitBy or "quota"),
[1105]729                    } 
730        mustadd = 1
731        if self.info["newgroup"].lower() != 'below' :
[1510]732            try :
733                (where, action) = [s.strip() for s in self.info["newgroup"].split(",")]
734            except ValueError :
735                (where, action) = (self.info["newgroup"].strip(), "fail")
736            result = self.doSearch("(&(objectClass=%s)(%s=%s))" % (where, self.info["grouprdn"], group.Name), None, base=self.info["groupbase"])
[1105]737            if result :
738                (dn, fields) = result[0]
[2188]739                oc = fields.get("objectClass", fields.get("objectclass", []))
740                oc.extend(["pykotaGroup"])
[1105]741                fields.update(newfields)
742                self.doModify(dn, fields)
743                mustadd = 0
[1510]744            else :
745                message = _("Unable to find an existing entry to attach pykotaGroup objectclass %s") % group.Name
746                if action.lower() == "warn" :   
[1584]747                    self.tool.printInfo("%s. A new entry will be created instead." % message, "warn")
[1510]748                else : # 'fail' or incorrect setting
749                    raise PyKotaStorageError, "%s. Action aborted. Please check your configuration." % message
[1105]750               
751        if mustadd :
752            fields = { self.info["grouprdn"] : group.Name,
753                       "objectClass" : ["pykotaObject", "pykotaGroup"],
754                       "cn" : group.Name,
755                     } 
756            fields.update(newfields)         
757            dn = "%s=%s,%s" % (self.info["grouprdn"], group.Name, self.info["groupbase"])
758            self.doAdd(dn, fields)
[1041]759        return self.getGroup(group.Name)
[1016]760       
[1041]761    def addUserToGroup(self, user, group) :   
762        """Adds an user to a group."""
[1141]763        if user.Name not in [u.Name for u in self.getGroupMembers(group)] :
[1041]764            result = self.doSearch("objectClass=pykotaGroup", None, base=group.ident, scope=ldap.SCOPE_BASE)   
765            if result :
766                fields = result[0][1]
[1070]767                if not fields.has_key(self.info["groupmembers"]) :
768                    fields[self.info["groupmembers"]] = []
[1041]769                fields[self.info["groupmembers"]].append(user.Name)
770                self.doModify(group.ident, fields)
771                group.Members.append(user)
772               
773    def addUserPQuota(self, user, printer) :
774        """Initializes a user print quota on a printer."""
[1030]775        uuid = self.genUUID()
[1041]776        fields = { "cn" : uuid,
777                   "objectClass" : ["pykotaObject", "pykotaUserPQuota"],
778                   "pykotaUserName" : user.Name,
779                   "pykotaPrinterName" : printer.Name,
780                   "pykotaDateLimit" : "None",
[1030]781                   "pykotaPageCounter" : "0",
782                   "pykotaLifePageCounter" : "0",
[2054]783                   "pykotaWarnCount" : "0",
[1030]784                 } 
[1969]785        if self.info["userquotabase"].lower() == "user" :
786            dn = "cn=%s,%s" % (uuid, user.ident)
787        else :   
788            dn = "cn=%s,%s" % (uuid, self.info["userquotabase"])
[1031]789        self.doAdd(dn, fields)
[1041]790        return self.getUserPQuota(user, printer)
[1016]791       
[1041]792    def addGroupPQuota(self, group, printer) :
793        """Initializes a group print quota on a printer."""
[1030]794        uuid = self.genUUID()
[1041]795        fields = { "cn" : uuid,
796                   "objectClass" : ["pykotaObject", "pykotaGroupPQuota"],
797                   "pykotaGroupName" : group.Name,
798                   "pykotaPrinterName" : printer.Name,
[1030]799                   "pykotaDateLimit" : "None",
800                 } 
[1969]801        if self.info["groupquotabase"].lower() == "group" :
802            dn = "cn=%s,%s" % (uuid, group.ident)
803        else :   
804            dn = "cn=%s,%s" % (uuid, self.info["groupquotabase"])
[1031]805        self.doAdd(dn, fields)
[1041]806        return self.getGroupPQuota(group, printer)
[1016]807       
[1041]808    def writePrinterPrices(self, printer) :   
809        """Write the printer's prices back into the storage."""
810        fields = {
811                   "pykotaPricePerPage" : str(printer.PricePerPage),
812                   "pykotaPricePerJob" : str(printer.PricePerJob),
813                 }
814        self.doModify(printer.ident, fields)
[1016]815       
[1582]816    def writePrinterDescription(self, printer) :   
817        """Write the printer's description back into the storage."""
818        fields = {
[1790]819                   "description" : self.userCharsetToDatabase(str(printer.Description)), 
[1582]820                 }
821        self.doModify(printer.ident, fields)
822       
[2054]823    def writeUserOverCharge(self, user, factor) :
824        """Sets the user's overcharging coefficient."""
825        fields = {
826                   "pykotaOverCharge" : str(factor),
827                 }
828        self.doModify(user.ident, fields)
829       
[1041]830    def writeUserLimitBy(self, user, limitby) :   
831        """Sets the user's limiting factor."""
[1031]832        fields = {
[1041]833                   "pykotaLimitBy" : limitby,
[1031]834                 }
[1041]835        self.doModify(user.ident, fields)         
[1016]836       
[1041]837    def writeGroupLimitBy(self, group, limitby) :   
838        """Sets the group's limiting factor."""
[1031]839        fields = {
[1041]840                   "pykotaLimitBy" : limitby,
[1031]841                 }
[1041]842        self.doModify(group.ident, fields)         
[1016]843       
[1041]844    def writeUserPQuotaDateLimit(self, userpquota, datelimit) :   
845        """Sets the date limit permanently for a user print quota."""
[1031]846        fields = {
[1240]847                   "pykotaDateLimit" : datelimit,
[1031]848                 }
[1041]849        return self.doModify(userpquota.ident, fields)
850           
851    def writeGroupPQuotaDateLimit(self, grouppquota, datelimit) :   
852        """Sets the date limit permanently for a group print quota."""
[1031]853        fields = {
[1240]854                   "pykotaDateLimit" : datelimit,
[1031]855                 }
[1041]856        return self.doModify(grouppquota.ident, fields)
[1016]857       
[1269]858    def increaseUserPQuotaPagesCounters(self, userpquota, nbpages) :   
859        """Increase page counters for a user print quota."""
860        fields = {
861                   "pykotaPageCounter" : { "operator" : "+", "value" : nbpages, "convert" : int },
862                   "pykotaLifePageCounter" : { "operator" : "+", "value" : nbpages, "convert" : int },
863                 }
864        return self.doModify(userpquota.ident, fields)         
865       
[1041]866    def writeUserPQuotaPagesCounters(self, userpquota, newpagecounter, newlifepagecounter) :   
867        """Sets the new page counters permanently for a user print quota."""
868        fields = {
869                   "pykotaPageCounter" : str(newpagecounter),
870                   "pykotaLifePageCounter" : str(newlifepagecounter),
[2030]871                   "pykotaDateLimit" : None,
[2054]872                   "pykotaWarnCount" : "0",
[1041]873                 } 
874        return self.doModify(userpquota.ident, fields)         
875       
[1269]876    def decreaseUserAccountBalance(self, user, amount) :   
877        """Decreases user's account balance from an amount."""
878        fields = {
879                   "pykotaBalance" : { "operator" : "-", "value" : amount, "convert" : float },
880                 }
[1356]881        return self.doModify(user.idbalance, fields, flushcache=1)         
[1269]882       
[1041]883    def writeUserAccountBalance(self, user, newbalance, newlifetimepaid=None) :   
884        """Sets the new account balance and eventually new lifetime paid."""
885        fields = {
886                   "pykotaBalance" : str(newbalance),
887                 }
888        if newlifetimepaid is not None :
889            fields.update({ "pykotaLifeTimePaid" : str(newlifetimepaid) })
[1357]890        return self.doModify(user.idbalance, fields)         
[1041]891           
[1522]892    def writeNewPayment(self, user, amount) :       
893        """Adds a new payment to the payments history."""
894        payments = []
895        for payment in user.Payments :
896            payments.append("%s # %s" % (payment[0], str(payment[1])))
897        payments.append("%s # %s" % (str(DateTime.now()), str(amount)))
898        fields = {
899                   "pykotaPayments" : payments,
900                 }
901        return self.doModify(user.idbalance, fields)         
902       
[1203]903    def writeLastJobSize(self, lastjob, jobsize, jobprice) :       
[1041]904        """Sets the last job's size permanently."""
905        fields = {
906                   "pykotaJobSize" : str(jobsize),
[1203]907                   "pykotaJobPrice" : str(jobprice),
[1041]908                 }
909        self.doModify(lastjob.ident, fields)         
910       
[2057]911    def writeJobNew(self, printer, user, jobid, pagecounter, action, jobsize=None, jobprice=None, filename=None, title=None, copies=None, options=None, clienthost=None, jobsizebytes=None, jobmd5sum=None) :
[1041]912        """Adds a job in a printer's history."""
[1149]913        if (not self.disablehistory) or (not printer.LastJob.Exists) :
914            uuid = self.genUUID()
915            dn = "cn=%s,%s" % (uuid, self.info["jobbase"])
916        else :   
917            uuid = printer.LastJob.ident[3:].split(",")[0]
918            dn = printer.LastJob.ident
[1875]919        if self.privacy :   
920            # For legal reasons, we want to hide the title, filename and options
921            title = filename = options = "Hidden because of privacy concerns"
[1032]922        fields = {
923                   "objectClass" : ["pykotaObject", "pykotaJob"],
924                   "cn" : uuid,
[1041]925                   "pykotaUserName" : user.Name,
926                   "pykotaPrinterName" : printer.Name,
[1032]927                   "pykotaJobId" : jobid,
928                   "pykotaPrinterPageCounter" : str(pagecounter),
929                   "pykotaAction" : action,
[1790]930                   "pykotaFileName" : ((filename is None) and "None") or self.userCharsetToDatabase(filename), 
931                   "pykotaTitle" : ((title is None) and "None") or self.userCharsetToDatabase(title), 
[1200]932                   "pykotaCopies" : str(copies), 
[1790]933                   "pykotaOptions" : ((options is None) and "None") or self.userCharsetToDatabase(options), 
[1502]934                   "pykotaHostName" : str(clienthost), 
[1520]935                   "pykotaJobSizeBytes" : str(jobsizebytes),
[2057]936                   "pykotaMD5Sum" : str(jobmd5sum),
[1032]937                 }
[1149]938        if (not self.disablehistory) or (not printer.LastJob.Exists) :
939            if jobsize is not None :         
[1203]940                fields.update({ "pykotaJobSize" : str(jobsize), "pykotaJobPrice" : str(jobprice) })
[1149]941            self.doAdd(dn, fields)
942        else :   
943            # here we explicitly want to reset jobsize to 'None' if needed
[1203]944            fields.update({ "pykotaJobSize" : str(jobsize), "pykotaJobPrice" : str(jobprice) })
[1149]945            self.doModify(dn, fields)
946           
[1041]947        if printer.LastJob.Exists :
[1032]948            fields = {
949                       "pykotaLastJobIdent" : uuid,
950                     }
[1041]951            self.doModify(printer.LastJob.lastjobident, fields)         
[1032]952        else :   
953            lastjuuid = self.genUUID()
[1067]954            lastjdn = "cn=%s,%s" % (lastjuuid, self.info["lastjobbase"])
[1032]955            fields = {
956                       "objectClass" : ["pykotaObject", "pykotaLastJob"],
957                       "cn" : lastjuuid,
[1041]958                       "pykotaPrinterName" : printer.Name,
[1032]959                       "pykotaLastJobIdent" : uuid,
960                     } 
961            self.doAdd(lastjdn, fields)         
[1041]962           
963    def writeUserPQuotaLimits(self, userpquota, softlimit, hardlimit) :
964        """Sets soft and hard limits for a user quota."""
965        fields = { 
966                   "pykotaSoftLimit" : str(softlimit),
967                   "pykotaHardLimit" : str(hardlimit),
[1367]968                   "pykotaDateLimit" : "None",
[2054]969                   "pykotaWarnCount" : "0",
[1041]970                 }
971        self.doModify(userpquota.ident, fields)
972       
[2054]973    def writeUserPQuotaWarnCount(self, userpquota, warncount) :
974        """Sets the warn counter value for a user quota."""
975        fields = { 
976                   "pykotaWarnCount" : str(warncount or 0),
977                 }
978        self.doModify(userpquota.ident, fields)
979       
980    def increaseUserPQuotaWarnCount(self, userpquota) :
981        """Increases the warn counter value for a user quota."""
982        fields = {
983                   "pykotaWarnCount" : { "operator" : "+", "value" : 1, "convert" : int },
984                 }
985        return self.doModify(userpquota.ident, fields)         
986       
[1041]987    def writeGroupPQuotaLimits(self, grouppquota, softlimit, hardlimit) :
[1084]988        """Sets soft and hard limits for a group quota on a specific printer."""
[1041]989        fields = { 
990                   "pykotaSoftLimit" : str(softlimit),
991                   "pykotaHardLimit" : str(hardlimit),
[1367]992                   "pykotaDateLimit" : "None",
[1041]993                 }
994        self.doModify(grouppquota.ident, fields)
995           
[1258]996    def writePrinterToGroup(self, pgroup, printer) :
997        """Puts a printer into a printer group."""
[1259]998        if printer.ident not in pgroup.uniqueMember :
[1269]999            pgroup.uniqueMember.append(printer.ident)
[1258]1000            fields = {
[1269]1001                       "uniqueMember" : pgroup.uniqueMember
[1258]1002                     } 
1003            self.doModify(pgroup.ident, fields)         
[1274]1004           
[1332]1005    def removePrinterFromGroup(self, pgroup, printer) :
1006        """Removes a printer from a printer group."""
1007        try :
1008            pgroup.uniqueMember.remove(printer.ident)
1009        except ValueError :   
1010            pass
1011        else :   
1012            fields = {
1013                       "uniqueMember" : pgroup.uniqueMember,
1014                     } 
1015            self.doModify(pgroup.ident, fields)         
1016           
[1502]1017    def retrieveHistory(self, user=None, printer=None, datelimit=None, hostname=None, limit=100) :   
[1274]1018        """Retrieves all print jobs for user on printer (or all) before date, limited to first 100 results."""
1019        precond = "(objectClass=pykotaJob)"
1020        where = []
1021        if (user is not None) and user.Exists :
1022            where.append("(pykotaUserName=%s)" % user.Name)
1023        if (printer is not None) and printer.Exists :
1024            where.append("(pykotaPrinterName=%s)" % printer.Name)
[1502]1025        if hostname is not None :
1026            where.append("(pykotaHostName=%s)" % hostname)
[1274]1027        if where :   
1028            where = "(&%s)" % "".join([precond] + where)
1029        else :   
1030            where = precond
1031        jobs = []   
[1520]1032        result = self.doSearch(where, fields=["pykotaJobSizeBytes", "pykotaHostName", "pykotaUserName", "pykotaPrinterName", "pykotaJobId", "pykotaPrinterPageCounter", "pykotaAction", "pykotaJobSize", "pykotaJobPrice", "pykotaFileName", "pykotaTitle", "pykotaCopies", "pykotaOptions", "createTimestamp"], base=self.info["jobbase"])
[1274]1033        if result :
1034            for (ident, fields) in result :
1035                job = StorageJob(self)
1036                job.ident = ident
1037                job.JobId = fields.get("pykotaJobId")[0]
[1392]1038                job.PrinterPageCounter = int(fields.get("pykotaPrinterPageCounter", [0])[0] or 0)
[1601]1039                try :
1040                    job.JobSize = int(fields.get("pykotaJobSize", [0])[0])
1041                except ValueError :   
1042                    job.JobSize = None
1043                try :   
1044                    job.JobPrice = float(fields.get("pykotaJobPrice", [0.0])[0])
1045                except ValueError :
1046                    job.JobPrice = None
[1392]1047                job.JobAction = fields.get("pykotaAction", [""])[0]
[1790]1048                job.JobFileName = self.databaseToUserCharset(fields.get("pykotaFileName", [""])[0]) 
1049                job.JobTitle = self.databaseToUserCharset(fields.get("pykotaTitle", [""])[0]) 
[1274]1050                job.JobCopies = int(fields.get("pykotaCopies", [0])[0])
[1790]1051                job.JobOptions = self.databaseToUserCharset(fields.get("pykotaOptions", [""])[0]) 
[1502]1052                job.JobHostName = fields.get("pykotaHostName", [""])[0]
[1520]1053                job.JobSizeBytes = fields.get("pykotaJobSizeBytes", [0L])[0]
[1392]1054                date = fields.get("createTimestamp", ["19700101000000"])[0]
[1274]1055                year = int(date[:4])
1056                month = int(date[4:6])
1057                day = int(date[6:8])
1058                hour = int(date[8:10])
1059                minute = int(date[10:12])
1060                second = int(date[12:14])
1061                job.JobDate = "%04i-%02i-%02i %02i:%02i:%02i" % (year, month, day, hour, minute, second)
1062                if (datelimit is None) or (job.JobDate <= datelimit) :
[1358]1063                    job.UserName = fields.get("pykotaUserName")[0]
1064                    job.PrinterName = fields.get("pykotaPrinterName")[0]
[1274]1065                    job.Exists = 1
1066                    jobs.append(job)
[1874]1067            jobs.sort(lambda x, y : cmp(y.JobDate, x.JobDate))       
[1274]1068            if limit :   
1069                jobs = jobs[:int(limit)]
1070        return jobs
[1258]1071       
[1041]1072    def deleteUser(self, user) :   
1073        """Completely deletes an user from the Quota Storage."""
[1692]1074        todelete = []   
[1041]1075        result = self.doSearch("(&(objectClass=pykotaJob)(pykotaUserName=%s))" % user.Name, base=self.info["jobbase"])
1076        for (ident, fields) in result :
[1692]1077            todelete.append(ident)
[1998]1078        if self.info["userquotabase"].lower() == "user" :
1079            base = self.info["userbase"]
1080        else :
1081            base = self.info["userquotabase"]
1082        result = self.doSearch("(&(objectClass=pykotaUserPQuota)(pykotaUserName=%s))" % user.Name, ["pykotaPrinterName", "pykotaUserName"], base=base)
[1041]1083        for (ident, fields) in result :
[1692]1084            # ensure the user print quota entry will be deleted
1085            todelete.append(ident)
1086           
1087            # if last job of current printer was printed by the user
1088            # to delete, we also need to delete the printer's last job entry.
1089            printername = fields["pykotaPrinterName"][0]
1090            printer = self.getPrinter(printername)
1091            if printer.LastJob.UserName == user.Name :
1092                todelete.append(printer.LastJob.lastjobident)
1093           
1094        for ident in todelete :   
[1041]1095            self.doDelete(ident)
[1692]1096           
[1041]1097        result = self.doSearch("objectClass=pykotaAccount", None, base=user.ident, scope=ldap.SCOPE_BASE)   
[1032]1098        if result :
[1041]1099            fields = result[0][1]
1100            for k in fields.keys() :
1101                if k.startswith("pykota") :
1102                    del fields[k]
1103                elif k.lower() == "objectclass" :   
1104                    todelete = []
1105                    for i in range(len(fields[k])) :
1106                        if fields[k][i].startswith("pykota") : 
1107                            todelete.append(i)
1108                    todelete.sort()       
1109                    todelete.reverse()
1110                    for i in todelete :
1111                        del fields[k][i]
[1119]1112            if fields.get("objectClass") or fields.get("objectclass") :
[1041]1113                self.doModify(user.ident, fields, ignoreold=0)       
1114            else :   
1115                self.doDelete(user.ident)
1116        result = self.doSearch("(&(objectClass=pykotaAccountBalance)(pykotaUserName=%s))" % user.Name, ["pykotaUserName"], base=self.info["balancebase"])
1117        for (ident, fields) in result :
1118            self.doDelete(ident)
1119       
1120    def deleteGroup(self, group) :   
1121        """Completely deletes a group from the Quota Storage."""
[1998]1122        if self.info["groupquotabase"].lower() == "group" :
1123            base = self.info["groupbase"]
1124        else :
1125            base = self.info["groupquotabase"]
1126        result = self.doSearch("(&(objectClass=pykotaGroupPQuota)(pykotaGroupName=%s))" % group.Name, ["pykotaGroupName"], base=base)
[1041]1127        for (ident, fields) in result :
1128            self.doDelete(ident)
1129        result = self.doSearch("objectClass=pykotaGroup", None, base=group.ident, scope=ldap.SCOPE_BASE)   
[1016]1130        if result :
[1027]1131            fields = result[0][1]
[1041]1132            for k in fields.keys() :
1133                if k.startswith("pykota") :
1134                    del fields[k]
1135                elif k.lower() == "objectclass" :   
1136                    todelete = []
1137                    for i in range(len(fields[k])) :
1138                        if fields[k][i].startswith("pykota") : 
1139                            todelete.append(i)
1140                    todelete.sort()       
1141                    todelete.reverse()
1142                    for i in todelete :
1143                        del fields[k][i]
[1119]1144            if fields.get("objectClass") or fields.get("objectclass") :
[1041]1145                self.doModify(group.ident, fields, ignoreold=0)       
1146            else :   
1147                self.doDelete(group.ident)
[1330]1148               
1149    def deletePrinter(self, printer) :   
1150        """Completely deletes an user from the Quota Storage."""
1151        result = self.doSearch("(&(objectClass=pykotaLastJob)(pykotaPrinterName=%s))" % printer.Name, base=self.info["lastjobbase"])
1152        for (ident, fields) in result :
1153            self.doDelete(ident)
1154        result = self.doSearch("(&(objectClass=pykotaJob)(pykotaPrinterName=%s))" % printer.Name, base=self.info["jobbase"])
1155        for (ident, fields) in result :
1156            self.doDelete(ident)
[1998]1157        if self.info["groupquotabase"].lower() == "group" :
1158            base = self.info["groupbase"]
1159        else :
1160            base = self.info["groupquotabase"]
1161        result = self.doSearch("(&(objectClass=pykotaGroupPQuota)(pykotaPrinterName=%s))" % printer.Name, base=base)
[1330]1162        for (ident, fields) in result :
1163            self.doDelete(ident)
[1998]1164        if self.info["userquotabase"].lower() == "user" :
1165            base = self.info["userbase"]
1166        else :
1167            base = self.info["userquotabase"]
1168        result = self.doSearch("(&(objectClass=pykotaUserPQuota)(pykotaPrinterName=%s))" % printer.Name, base=base)
[1330]1169        for (ident, fields) in result :
1170            self.doDelete(ident)
1171        for parent in self.getParentPrinters(printer) : 
[1332]1172            try :
1173                parent.uniqueMember.remove(printer.ident)
1174            except ValueError :   
1175                pass
1176            else :   
1177                fields = {
1178                           "uniqueMember" : parent.uniqueMember,
1179                         } 
1180                self.doModify(parent.ident, fields)         
[1330]1181        self.doDelete(printer.ident)   
[1754]1182       
[1990]1183    def extractPrinters(self, extractonly={}) :
[1754]1184        """Extracts all printer records."""
[1993]1185        pname = extractonly.get("printername")
1186        entries = [p for p in [self.getPrinter(name) for name in self.getAllPrintersNames(pname)] if p.Exists]
[1754]1187        if entries :
[1995]1188            result = [ ("dn", "printername", "priceperpage", "priceperjob", "description") ]
[1754]1189            for entry in entries :
1190                result.append((entry.ident, entry.Name, entry.PricePerPage, entry.PricePerJob, entry.Description))
1191            return result 
1192       
[1990]1193    def extractUsers(self, extractonly={}) :
[1754]1194        """Extracts all user records."""
[1993]1195        uname = extractonly.get("username")
1196        entries = [u for u in [self.getUser(name) for name in self.getAllUsersNames(uname)] if u.Exists]
[1754]1197        if entries :
[1995]1198            result = [ ("dn", "username", "balance", "lifetimepaid", "limitby", "email") ]
[1754]1199            for entry in entries :
[1995]1200                result.append((entry.ident, entry.Name, entry.AccountBalance, entry.LifeTimePaid, entry.LimitBy, entry.Email))
[1754]1201            return result 
1202       
[1990]1203    def extractGroups(self, extractonly={}) :
[1754]1204        """Extracts all group records."""
[1993]1205        gname = extractonly.get("groupname")
1206        entries = [g for g in [self.getGroup(name) for name in self.getAllGroupsNames(gname)] if g.Exists]
[1754]1207        if entries :
[1995]1208            result = [ ("dn", "groupname", "limitby", "balance", "lifetimepaid") ]
[1754]1209            for entry in entries :
[1995]1210                result.append((entry.ident, entry.Name, entry.LimitBy, entry.AccountBalance, entry.LifeTimePaid))
[1754]1211            return result 
1212       
[1990]1213    def extractPayments(self, extractonly={}) :
[1754]1214        """Extracts all payment records."""
[1993]1215        uname = extractonly.get("username")
1216        entries = [u for u in [self.getUser(name) for name in self.getAllUsersNames(uname)] if u.Exists]
[1765]1217        if entries :
[1995]1218            result = [ ("username", "amount", "date") ]
[1765]1219            for entry in entries :
1220                for (date, amount) in entry.Payments :
[1995]1221                    result.append((entry.Name, amount, date))
[1765]1222            return result       
[1754]1223       
[1990]1224    def extractUpquotas(self, extractonly={}) :
[1754]1225        """Extracts all userpquota records."""
[1993]1226        pname = extractonly.get("printername")
1227        entries = [p for p in [self.getPrinter(name) for name in self.getAllPrintersNames(pname)] if p.Exists]
[1754]1228        if entries :
[1995]1229            result = [ ("username", "printername", "dn", "userdn", "printerdn", "lifepagecounter", "pagecounter", "softlimit", "hardlimit", "datelimit") ]
[2040]1230            uname = extractonly.get("username")
[1764]1231            for entry in entries :
[2041]1232                for (user, userpquota) in self.getPrinterUsersAndQuotas(entry, names=[uname or "*"]) :
1233                    result.append((user.Name, entry.Name, userpquota.ident, user.ident, entry.ident, userpquota.LifePageCounter, userpquota.PageCounter, userpquota.SoftLimit, userpquota.HardLimit, userpquota.DateLimit))
[1768]1234            return result
[1754]1235       
[1990]1236    def extractGpquotas(self, extractonly={}) :
[1754]1237        """Extracts all grouppquota records."""
[1993]1238        pname = extractonly.get("printername")
1239        entries = [p for p in [self.getPrinter(name) for name in self.getAllPrintersNames(pname)] if p.Exists]
[1754]1240        if entries :
[1995]1241            result = [ ("groupname", "printername", "dn", "groupdn", "printerdn", "lifepagecounter", "pagecounter", "softlimit", "hardlimit", "datelimit") ]
[1993]1242            gname = extractonly.get("groupname")
[1764]1243            for entry in entries :
[2042]1244                for (group, grouppquota) in self.getPrinterGroupsAndQuotas(entry, names=[gname or "*"]) :
1245                    result.append((group.Name, entry.Name, grouppquota.ident, group.ident, entry.ident, grouppquota.LifePageCounter, grouppquota.PageCounter, grouppquota.SoftLimit, grouppquota.HardLimit, grouppquota.DateLimit))
[1768]1246            return result
[1754]1247       
[1990]1248    def extractUmembers(self, extractonly={}) :
[1754]1249        """Extracts all user groups members."""
[1993]1250        gname = extractonly.get("groupname")
1251        entries = [g for g in [self.getGroup(name) for name in self.getAllGroupsNames(gname)] if g.Exists]
[1754]1252        if entries :
[1995]1253            result = [ ("groupname", "username", "groupdn", "userdn") ]
[1993]1254            uname = extractonly.get("username")
[1754]1255            for entry in entries :
1256                for member in entry.Members :
[1993]1257                    if (uname is None) or (member.Name == uname) :
1258                        result.append((entry.Name, member.Name, entry.ident, member.ident))
[1754]1259            return result       
1260               
[1990]1261    def extractPmembers(self, extractonly={}) :
[1754]1262        """Extracts all printer groups members."""
[1993]1263        pname = extractonly.get("printername")
1264        entries = [p for p in [self.getPrinter(name) for name in self.getAllPrintersNames(pname)] if p.Exists]
[1754]1265        if entries :
[1995]1266            result = [ ("pgroupname", "printername", "pgroupdn", "printerdn") ]
[1993]1267            pgname = extractonly.get("pgroupname")
[1754]1268            for entry in entries :
1269                for parent in self.getParentPrinters(entry) :
[1993]1270                    if (pgname is None) or (parent.Name == pgname) :
1271                        result.append((parent.Name, entry.Name, parent.ident, entry.ident))
[1754]1272            return result       
1273       
[1990]1274    def extractHistory(self, extractonly={}) :
[1754]1275        """Extracts all jobhistory records."""
[1993]1276        uname = extractonly.get("username")
1277        if uname :
1278            user = self.getUser(uname)
1279        else :   
1280            user = None
1281        pname = extractonly.get("printername")
1282        if pname :
1283            printer = self.getPrinter(pname)
1284        else :   
1285            printer = None
1286        entries = self.retrieveHistory(user, printer, limit=None)
[1754]1287        if entries :
[1995]1288            result = [ ("username", "printername", "dn", "jobid", "pagecounter", "jobsize", "action", "jobdate", "filename", "title", "copies", "options", "jobprice", "hostname", "jobsizebytes") ] 
[1754]1289            for entry in entries :
1290                result.append((entry.UserName, entry.PrinterName, entry.ident, entry.JobId, entry.PrinterPageCounter, entry.JobSize, entry.JobAction, entry.JobDate, entry.JobFileName, entry.JobTitle, entry.JobCopies, entry.JobOptions, entry.JobPrice, entry.JobHostName, entry.JobSizeBytes)) 
1291            return result   
Note: See TracBrowser for help on using the browser.