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

Revision 2191, 66.9 kB (checked in by jerome, 19 years ago)

Hopefully final fix for LDAP attributes' names case (in)sensitivity

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