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
Line 
1# PyKota
2# -*- coding: ISO-8859-15 -*-
3#
4# PyKota : Print Quotas for CUPS and LPRng
5#
6# (c) 2003-2004 Jerome Alet <alet@librelogiciel.com>
7# This program is free software; you can redistribute it and/or modify
8# it under the terms of the GNU General Public License as published by
9# the Free Software Foundation; either version 2 of the License, or
10# (at your option) any later version.
11#
12# This program is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15# GNU General Public License for more details.
16#
17# You should have received a copy of the GNU General Public License
18# along with this program; if not, write to the Free Software
19# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
20#
21# $Id$
22#
23#
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
31import os
32import types
33import time
34import md5
35from mx import DateTime
36
37from pykota.storage import PyKotaStorageError, BaseStorage, StorageObject, StorageUser, StorageGroup, StoragePrinter, StorageJob, StorageLastJob, StorageUserPQuota, StorageGroupPQuota
38
39try :
40    import ldap
41    import ldap.modlist
42    import ldap.cidict
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   
47class Storage(BaseStorage) :
48    def __init__(self, pykotatool, host, dbname, user, passwd) :
49        """Opens the LDAP connection."""
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) 
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()
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         
91           
92    def close(self) :   
93        """Closes the database connection."""
94        if not self.closed :
95            self.database.unbind_s()
96            self.closed = 1
97            self.tool.logdebug("Database closed.")
98       
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       
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       
116    def beginTransaction(self) :   
117        """Starts a transaction."""
118        self.tool.logdebug("Transaction begins... WARNING : No transactions in LDAP !")
119       
120    def commitTransaction(self) :   
121        """Commits a transaction."""
122        self.tool.logdebug("Transaction committed. WARNING : No transactions in LDAP !")
123       
124    def rollbackTransaction(self) :     
125        """Rollbacks a transaction."""
126        self.tool.logdebug("Transaction aborted. WARNING : No transaction in LDAP !")
127       
128    def doSearch(self, key, fields=None, base="", scope=ldap.SCOPE_SUBTREE, flushcache=0) :
129        """Does an LDAP search query."""
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)
161                result = [ (dn, ldap.cidict.cidict(attrs)) for (dn, attrs) in result ]
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
168           
169    def doAdd(self, dn, fields) :
170        """Adds an entry in the LDAP directory."""
171        fields = self.normalizeFields(ldap.cidict.cidict(fields))
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
191           
192    def doDelete(self, dn) :
193        """Deletes an entry from the LDAP directory."""
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
214           
215    def doModify(self, dn, fields, ignoreold=1, flushcache=0) :
216        """Modifies an entry in the LDAP directory."""
217        fields = ldap.cidict.cidict(fields)
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
229                    else :   
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 = []
250                for (mop, mtyp, mval) in entry :
251                    if mtyp and (mtyp.lower() != "createtimestamp") :
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
276           
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 = []
283        for (dn, record) in records :
284            attrval = record.get(attribute, [None])[0]
285            if attrval is None :
286                self.tool.printInfo("Object %s has no %s attribute !" % (dn, attribute), "error")
287            else :   
288                result.append(attrval)
289        return result       
290               
291    def getAllPrintersNames(self, printername=None) :   
292        """Extracts all printer names or only the printers' names matching the optional parameter."""
293        printernames = []
294        ldapfilter = "objectClass=pykotaPrinter"
295        if printername :
296            ldapfilter = "(&(%s)(pykotaPrinterName=%s))" % (ldapfilter, printername)
297        result = self.doSearch(ldapfilter, ["pykotaPrinterName"], base=self.info["printerbase"])
298        if result :
299            printernames = self.filterNames(result, "pykotaPrinterName")
300        return printernames
301       
302    def getAllUsersNames(self, username=None) :   
303        """Extracts all user names or only the users' names matching the optional parameter."""
304        usernames = []
305        ldapfilter = "objectClass=pykotaAccount"
306        if username :
307            ldapfilter = "(&(%s)(pykotaUserName=%s))" % (ldapfilter, username)
308        result = self.doSearch(ldapfilter, ["pykotaUserName"], base=self.info["userbase"])
309        if result :
310            usernames = self.filterNames(result, "pykotaUserName")
311        return usernames
312       
313    def getAllGroupsNames(self, groupname=None) :   
314        """Extracts all group names or only the groups' names matching the optional parameter."""
315        groupnames = []
316        ldapfilter = "objectClass=pykotaGroup"
317        if groupname :
318            ldapfilter = "(&(%s)(pykotaGroupName=%s))" % (ldapfilter, groupname)
319        result = self.doSearch(ldapfilter, ["pykotaGroupName"], base=self.info["groupbase"])
320        if result :
321            groupnames = self.filterNames(result, "pykotaGroupName")
322        return groupnames
323       
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       
329    def getUserFromBackend(self, username) :   
330        """Extracts user information given its name."""
331        user = StorageUser(self, username)
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"])
333        if result :
334            fields = result[0][1]
335            user.ident = result[0][0]
336            user.Name = fields.get("pykotaUserName", [username])[0] 
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])
340            result = self.doSearch("(&(objectClass=pykotaAccountBalance)(|(pykotaUserName=%s)(%s=%s)))" % (username, self.info["balancerdn"], username), ["pykotaBalance", "pykotaLifeTimePaid", "pykotaPayments"], base=self.info["balancebase"])
341            if not result :
342                raise PyKotaStorageError, _("No pykotaAccountBalance object found for user %s. Did you create LDAP entries manually ?") % username
343            else :
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       
360                user.Payments = []
361                for payment in fields.get("pykotaPayments", []) :
362                    (date, amount) = payment.split(" # ")
363                    user.Payments.append((date, amount))
364            user.Exists = 1
365        return user
366       
367    def getGroupFromBackend(self, groupname) :   
368        """Extracts group information given its name."""
369        group = StorageGroup(self, groupname)
370        result = self.doSearch("(&(objectClass=pykotaGroup)(|(pykotaGroupName=%s)(%s=%s)))" % (groupname, self.info["grouprdn"], groupname), ["pykotaGroupName", "pykotaLimitBy"], base=self.info["groupbase"])
371        if result :
372            fields = result[0][1]
373            group.ident = result[0][0]
374            group.Name = fields.get("pykotaGroupName", [groupname])[0] 
375            group.LimitBy = fields.get("pykotaLimitBy", ["quota"])[0]
376            group.AccountBalance = 0.0
377            group.LifeTimePaid = 0.0
378            for member in self.getGroupMembers(group) :
379                if member.Exists :
380                    group.AccountBalance += member.AccountBalance
381                    group.LifeTimePaid += member.LifeTimePaid
382            group.Exists = 1
383        return group
384       
385    def getPrinterFromBackend(self, printername) :       
386        """Extracts printer information given its name : returns first matching printer."""
387        printer = StoragePrinter(self, printername)
388        result = self.doSearch("(&(objectClass=pykotaPrinter)(|(pykotaPrinterName=%s)(%s=%s)))" % (printername, self.info["printerrdn"], printername), ["pykotaPrinterName", "pykotaPricePerPage", "pykotaPricePerJob", "uniqueMember", "description"], base=self.info["printerbase"])
389        if result :
390            fields = result[0][1]       # take only first matching printer, ignore the rest
391            printer.ident = result[0][0]
392            printer.Name = fields.get("pykotaPrinterName", [printername])[0] 
393            printer.PricePerJob = float(fields.get("pykotaPricePerJob", [0.0])[0])
394            printer.PricePerPage = float(fields.get("pykotaPricePerPage", [0.0])[0])
395            printer.uniqueMember = fields.get("uniqueMember", [])
396            printer.Description = self.databaseToUserCharset(fields.get("description", [""])[0]) 
397            printer.Exists = 1
398        return printer   
399       
400    def getUserPQuotaFromBackend(self, user, printer) :       
401        """Extracts a user print quota."""
402        userpquota = StorageUserPQuota(self, user, printer)
403        if printer.Exists and user.Exists :
404            if self.info["userquotabase"].lower() == "user" :
405                base = user.ident
406            else :   
407                base = self.info["userquotabase"]
408            result = self.doSearch("(&(objectClass=pykotaUserPQuota)(pykotaUserName=%s)(pykotaPrinterName=%s))" % (user.Name, printer.Name), ["pykotaPageCounter", "pykotaLifePageCounter", "pykotaSoftLimit", "pykotaHardLimit", "pykotaDateLimit", "pykotaWarnCount"], base=base)
409            if result :
410                fields = result[0][1]
411                userpquota.ident = result[0][0]
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])
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
435       
436    def getGroupPQuotaFromBackend(self, group, printer) :       
437        """Extracts a group print quota."""
438        grouppquota = StorageGroupPQuota(self, group, printer)
439        if group.Exists :
440            if self.info["groupquotabase"].lower() == "group" :
441                base = group.ident
442            else :   
443                base = self.info["groupquotabase"]
444            result = self.doSearch("(&(objectClass=pykotaGroupPQuota)(pykotaGroupName=%s)(pykotaPrinterName=%s))" % (group.Name, printer.Name), ["pykotaSoftLimit", "pykotaHardLimit", "pykotaDateLimit"], base=base)
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
468                usernamesfilter = "".join(["(pykotaUserName=%s)" % member.Name for member in self.getGroupMembers(group)])
469                if usernamesfilter :
470                    usernamesfilter = "(|%s)" % usernamesfilter
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)
476                if result :
477                    for userpquota in result :   
478                        grouppquota.PageCounter += int(userpquota[1].get("pykotaPageCounter", [0])[0] or 0)
479                        grouppquota.LifePageCounter += int(userpquota[1].get("pykotaLifePageCounter", [0])[0] or 0)
480                grouppquota.Exists = 1
481        return grouppquota
482       
483    def getPrinterLastJobFromBackend(self, printer) :       
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"])
487        if result :
488            lastjob.lastjobident = result[0][0]
489            lastjobident = result[0][1]["pykotaLastJobIdent"][0]
490            result = None
491            try :
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)
493            except PyKotaStorageError :   
494                pass # Last job entry exists, but job probably doesn't exist anymore.
495            if result :
496                fields = result[0][1]
497                lastjob.ident = result[0][0]
498                lastjob.JobId = fields.get("pykotaJobId")[0]
499                lastjob.UserName = fields.get("pykotaUserName")[0]
500                lastjob.PrinterPageCounter = int(fields.get("pykotaPrinterPageCounter", [0])[0])
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
509                lastjob.JobAction = fields.get("pykotaAction", [""])[0]
510                lastjob.JobFileName = self.databaseToUserCharset(fields.get("pykotaFileName", [""])[0]) 
511                lastjob.JobTitle = self.databaseToUserCharset(fields.get("pykotaTitle", [""])[0]) 
512                lastjob.JobCopies = int(fields.get("pykotaCopies", [0])[0])
513                lastjob.JobOptions = self.databaseToUserCharset(fields.get("pykotaOptions", [""])[0]) 
514                lastjob.JobHostName = fields.get("pykotaHostName", [""])[0]
515                lastjob.JobSizeBytes = fields.get("pykotaJobSizeBytes", [0L])[0]
516                lastjob.JobBillingCode = fields.get("pykotaMD5Sum", [None])[0]
517                lastjob.JobMD5Sum = fields.get("pykotaMD5Sum", [None])[0]
518                lastjob.JobPages = fields.get("pykotaPages", [""])[0]
519                date = fields.get("createTimestamp", ["19700101000000"])[0]
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
529       
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) :       
540        """Returns the user's groups list."""
541        groups = []
542        result = self.doSearch("(&(objectClass=pykotaGroup)(%s=%s))" % (self.info["groupmembers"], user.Name), [self.info["grouprdn"], "pykotaGroupName", "pykotaLimitBy"], base=self.info["groupbase"])
543        if result :
544            for (groupid, fields) in result :
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]
553                    else :   
554                        group.LimitBy = "quota"
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)
564        return groups       
565       
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       
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
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"])
583        if result :
584            for (printerid, fields) in result :
585                printername = fields.get("pykotaPrinterName", [""])[0] or fields.get(self.info["printerrdn"], [""])[0]
586                printer = StoragePrinter(self, printername)
587                printer.ident = printerid
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)
590                printer.uniqueMember = fields.get("uniqueMember", [])
591                printer.Description = self.databaseToUserCharset(fields.get("description", [""])[0]) 
592                printer.Exists = 1
593                printers.append(printer)
594                self.cacheEntry("PRINTERS", printer.Name, printer)
595        return printers       
596       
597    def getPrinterUsersAndQuotas(self, printer, names=["*"]) :       
598        """Returns the list of users who uses a given printer, along with their quotas."""
599        usersandquotas = []
600        if self.info["userquotabase"].lower() == "user" :
601           base = self.info["userbase"]
602        else :
603           base = self.info["userquotabase"]
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)
605        if result :
606            for (userquotaid, fields) in result :
607                user = self.getUser(fields.get("pykotaUserName")[0])
608                userpquota = StorageUserPQuota(self, user, printer)
609                userpquota.ident = userquotaid
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])
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)
634        usersandquotas.sort(lambda x, y : cmp(x[0].Name, y[0].Name))           
635        return usersandquotas
636               
637    def getPrinterGroupsAndQuotas(self, printer, names=["*"]) :       
638        """Returns the list of groups which uses a given printer, along with their quotas."""
639        groupsandquotas = []
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)
645        if result :
646            for (groupquotaid, fields) in result :
647                group = self.getGroup(fields.get("pykotaGroupName")[0])
648                grouppquota = self.getGroupPQuota(group, printer)
649                groupsandquotas.append((group, grouppquota))
650        groupsandquotas.sort(lambda x, y : cmp(x[0].Name, y[0].Name))           
651        return groupsandquotas
652       
653    def addPrinter(self, printername) :       
654        """Adds a printer to the quota storage, returns it."""
655        fields = { self.info["printerrdn"] : printername,
656                   "objectClass" : ["pykotaObject", "pykotaPrinter"],
657                   "cn" : printername,
658                   "pykotaPrinterName" : printername,
659                   "pykotaPricePerPage" : "0.0",
660                   "pykotaPricePerJob" : "0.0",
661                 } 
662        dn = "%s=%s,%s" % (self.info["printerrdn"], printername, self.info["printerbase"])
663        self.doAdd(dn, fields)
664        return self.getPrinter(printername)
665       
666    def addUser(self, user) :       
667        """Adds a user to the quota storage, returns it."""
668        newfields = {
669                       "pykotaUserName" : user.Name,
670                       "pykotaLimitBy" : (user.LimitBy or "quota"),
671                       "pykotaOverCharge" : str(user.OverCharge),
672                    }   
673                       
674        if user.Email :
675            newfields.update({self.info["usermail"]: user.Email})
676        mustadd = 1
677        if self.info["newuser"].lower() != 'below' :
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"])
683            if result :
684                (dn, fields) = result[0]
685                oc = fields.get("objectClass", fields.get("objectclass", []))
686                oc.extend(["pykotaAccount", "pykotaAccountBalance"])
687                fields.update(newfields)
688                fields.update({ "pykotaBalance" : str(user.AccountBalance or 0.0),
689                                "pykotaLifeTimePaid" : str(user.LifeTimePaid or 0.0), })   
690                self.doModify(dn, fields)
691                mustadd = 0
692            else :
693                message = _("Unable to find an existing objectClass %s entry with %s=%s to attach pykotaAccount objectClass") % (where, self.info["userrdn"], user.Name)
694                if action.lower() == "warn" :   
695                    self.tool.printInfo(_("%s. A new entry will be created instead.") % message, "warn")
696                else : # 'fail' or incorrect setting
697                    raise PyKotaStorageError, "%s. Action aborted. Please check your configuration." % message
698               
699        if mustadd :
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                         } 
712            fields.update(newfields)         
713            dn = "%s=%s,%s" % (self.info["userrdn"], user.Name, self.info["userbase"])
714            self.doAdd(dn, fields)
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           
725        return self.getUser(user.Name)
726       
727    def addGroup(self, group) :       
728        """Adds a group to the quota storage, returns it."""
729        newfields = { 
730                      "pykotaGroupName" : group.Name,
731                      "pykotaLimitBy" : (group.LimitBy or "quota"),
732                    } 
733        mustadd = 1
734        if self.info["newgroup"].lower() != 'below' :
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"])
740            if result :
741                (dn, fields) = result[0]
742                oc = fields.get("objectClass", fields.get("objectclass", []))
743                oc.extend(["pykotaGroup"])
744                fields.update(newfields)
745                self.doModify(dn, fields)
746                mustadd = 0
747            else :
748                message = _("Unable to find an existing entry to attach pykotaGroup objectclass %s") % group.Name
749                if action.lower() == "warn" :   
750                    self.tool.printInfo("%s. A new entry will be created instead." % message, "warn")
751                else : # 'fail' or incorrect setting
752                    raise PyKotaStorageError, "%s. Action aborted. Please check your configuration." % message
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)
762        return self.getGroup(group.Name)
763       
764    def addUserToGroup(self, user, group) :   
765        """Adds an user to a group."""
766        if user.Name not in [u.Name for u in self.getGroupMembers(group)] :
767            result = self.doSearch("objectClass=pykotaGroup", None, base=group.ident, scope=ldap.SCOPE_BASE)   
768            if result :
769                fields = result[0][1]
770                if not fields.has_key(self.info["groupmembers"]) :
771                    fields[self.info["groupmembers"]] = []
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."""
778        uuid = self.genUUID()
779        fields = { "cn" : uuid,
780                   "objectClass" : ["pykotaObject", "pykotaUserPQuota"],
781                   "pykotaUserName" : user.Name,
782                   "pykotaPrinterName" : printer.Name,
783                   "pykotaDateLimit" : "None",
784                   "pykotaPageCounter" : "0",
785                   "pykotaLifePageCounter" : "0",
786                   "pykotaWarnCount" : "0",
787                 } 
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"])
792        self.doAdd(dn, fields)
793        return self.getUserPQuota(user, printer)
794       
795    def addGroupPQuota(self, group, printer) :
796        """Initializes a group print quota on a printer."""
797        uuid = self.genUUID()
798        fields = { "cn" : uuid,
799                   "objectClass" : ["pykotaObject", "pykotaGroupPQuota"],
800                   "pykotaGroupName" : group.Name,
801                   "pykotaPrinterName" : printer.Name,
802                   "pykotaDateLimit" : "None",
803                 } 
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"])
808        self.doAdd(dn, fields)
809        return self.getGroupPQuota(group, printer)
810       
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)
818       
819    def writePrinterDescription(self, printer) :   
820        """Write the printer's description back into the storage."""
821        fields = {
822                   "description" : self.userCharsetToDatabase(str(printer.Description)), 
823                 }
824        self.doModify(printer.ident, fields)
825       
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       
833    def writeUserLimitBy(self, user, limitby) :   
834        """Sets the user's limiting factor."""
835        fields = {
836                   "pykotaLimitBy" : limitby,
837                 }
838        self.doModify(user.ident, fields)         
839       
840    def writeGroupLimitBy(self, group, limitby) :   
841        """Sets the group's limiting factor."""
842        fields = {
843                   "pykotaLimitBy" : limitby,
844                 }
845        self.doModify(group.ident, fields)         
846       
847    def writeUserPQuotaDateLimit(self, userpquota, datelimit) :   
848        """Sets the date limit permanently for a user print quota."""
849        fields = {
850                   "pykotaDateLimit" : datelimit,
851                 }
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."""
856        fields = {
857                   "pykotaDateLimit" : datelimit,
858                 }
859        return self.doModify(grouppquota.ident, fields)
860       
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       
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),
874                   "pykotaDateLimit" : None,
875                   "pykotaWarnCount" : "0",
876                 } 
877        return self.doModify(userpquota.ident, fields)         
878       
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                 }
884        return self.doModify(user.idbalance, fields, flushcache=1)         
885       
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) })
893        return self.doModify(user.idbalance, fields)         
894           
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       
906    def writeLastJobSize(self, lastjob, jobsize, jobprice) :       
907        """Sets the last job's size permanently."""
908        fields = {
909                   "pykotaJobSize" : str(jobsize),
910                   "pykotaJobPrice" : str(jobprice),
911                 }
912        self.doModify(lastjob.ident, fields)         
913       
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) :
915        """Adds a job in a printer's history."""
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
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"
925        fields = {
926                   "objectClass" : ["pykotaObject", "pykotaJob"],
927                   "cn" : uuid,
928                   "pykotaUserName" : user.Name,
929                   "pykotaPrinterName" : printer.Name,
930                   "pykotaJobId" : jobid,
931                   "pykotaPrinterPageCounter" : str(pagecounter),
932                   "pykotaAction" : action,
933                   "pykotaFileName" : ((filename is None) and "None") or self.userCharsetToDatabase(filename), 
934                   "pykotaTitle" : ((title is None) and "None") or self.userCharsetToDatabase(title), 
935                   "pykotaCopies" : str(copies), 
936                   "pykotaOptions" : ((options is None) and "None") or self.userCharsetToDatabase(options), 
937                   "pykotaHostName" : str(clienthost), 
938                   "pykotaJobSizeBytes" : str(jobsizebytes),
939                   "pykotaMD5Sum" : str(jobmd5sum),
940                 }
941        if (not self.disablehistory) or (not printer.LastJob.Exists) :
942            if jobsize is not None :         
943                fields.update({ "pykotaJobSize" : str(jobsize), "pykotaJobPrice" : str(jobprice) })
944            self.doAdd(dn, fields)
945        else :   
946            # here we explicitly want to reset jobsize to 'None' if needed
947            fields.update({ "pykotaJobSize" : str(jobsize), "pykotaJobPrice" : str(jobprice) })
948            self.doModify(dn, fields)
949           
950        if printer.LastJob.Exists :
951            fields = {
952                       "pykotaLastJobIdent" : uuid,
953                     }
954            self.doModify(printer.LastJob.lastjobident, fields)         
955        else :   
956            lastjuuid = self.genUUID()
957            lastjdn = "cn=%s,%s" % (lastjuuid, self.info["lastjobbase"])
958            fields = {
959                       "objectClass" : ["pykotaObject", "pykotaLastJob"],
960                       "cn" : lastjuuid,
961                       "pykotaPrinterName" : printer.Name,
962                       "pykotaLastJobIdent" : uuid,
963                     } 
964            self.doAdd(lastjdn, fields)         
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),
971                   "pykotaDateLimit" : "None",
972                   "pykotaWarnCount" : "0",
973                 }
974        self.doModify(userpquota.ident, fields)
975       
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       
990    def writeGroupPQuotaLimits(self, grouppquota, softlimit, hardlimit) :
991        """Sets soft and hard limits for a group quota on a specific printer."""
992        fields = { 
993                   "pykotaSoftLimit" : str(softlimit),
994                   "pykotaHardLimit" : str(hardlimit),
995                   "pykotaDateLimit" : "None",
996                 }
997        self.doModify(grouppquota.ident, fields)
998           
999    def writePrinterToGroup(self, pgroup, printer) :
1000        """Puts a printer into a printer group."""
1001        if printer.ident not in pgroup.uniqueMember :
1002            pgroup.uniqueMember.append(printer.ident)
1003            fields = {
1004                       "uniqueMember" : pgroup.uniqueMember
1005                     } 
1006            self.doModify(pgroup.ident, fields)         
1007           
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           
1020    def retrieveHistory(self, user=None, printer=None, datelimit=None, hostname=None, limit=100) :   
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)
1028        if hostname is not None :
1029            where.append("(pykotaHostName=%s)" % hostname)
1030        if where :   
1031            where = "(&%s)" % "".join([precond] + where)
1032        else :   
1033            where = precond
1034        jobs = []   
1035        result = self.doSearch(where, fields=["pykotaJobSizeBytes", "pykotaHostName", "pykotaUserName", "pykotaPrinterName", "pykotaJobId", "pykotaPrinterPageCounter", "pykotaAction", "pykotaJobSize", "pykotaJobPrice", "pykotaFileName", "pykotaTitle", "pykotaCopies", "pykotaOptions", "createTimestamp"], base=self.info["jobbase"])
1036        if result :
1037            for (ident, fields) in result :
1038                job = StorageJob(self)
1039                job.ident = ident
1040                job.JobId = fields.get("pykotaJobId")[0]
1041                job.PrinterPageCounter = int(fields.get("pykotaPrinterPageCounter", [0])[0] or 0)
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
1050                job.JobAction = fields.get("pykotaAction", [""])[0]
1051                job.JobFileName = self.databaseToUserCharset(fields.get("pykotaFileName", [""])[0]) 
1052                job.JobTitle = self.databaseToUserCharset(fields.get("pykotaTitle", [""])[0]) 
1053                job.JobCopies = int(fields.get("pykotaCopies", [0])[0])
1054                job.JobOptions = self.databaseToUserCharset(fields.get("pykotaOptions", [""])[0]) 
1055                job.JobHostName = fields.get("pykotaHostName", [""])[0]
1056                job.JobSizeBytes = fields.get("pykotaJobSizeBytes", [0L])[0]
1057                date = fields.get("createTimestamp", ["19700101000000"])[0]
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) :
1066                    job.UserName = fields.get("pykotaUserName")[0]
1067                    job.PrinterName = fields.get("pykotaPrinterName")[0]
1068                    job.Exists = 1
1069                    jobs.append(job)
1070            jobs.sort(lambda x, y : cmp(y.JobDate, x.JobDate))       
1071            if limit :   
1072                jobs = jobs[:int(limit)]
1073        return jobs
1074       
1075    def deleteUser(self, user) :   
1076        """Completely deletes an user from the Quota Storage."""
1077        todelete = []   
1078        result = self.doSearch("(&(objectClass=pykotaJob)(pykotaUserName=%s))" % user.Name, base=self.info["jobbase"])
1079        for (ident, fields) in result :
1080            todelete.append(ident)
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)
1086        for (ident, fields) in result :
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 :   
1098            self.doDelete(ident)
1099           
1100        result = self.doSearch("objectClass=pykotaAccount", None, base=user.ident, scope=ldap.SCOPE_BASE)   
1101        if result :
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]
1115            if fields.get("objectClass") or fields.get("objectclass") :
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."""
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)
1130        for (ident, fields) in result :
1131            self.doDelete(ident)
1132        result = self.doSearch("objectClass=pykotaGroup", None, base=group.ident, scope=ldap.SCOPE_BASE)   
1133        if result :
1134            fields = result[0][1]
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]
1147            if fields.get("objectClass") or fields.get("objectclass") :
1148                self.doModify(group.ident, fields, ignoreold=0)       
1149            else :   
1150                self.doDelete(group.ident)
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)
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)
1165        for (ident, fields) in result :
1166            self.doDelete(ident)
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)
1172        for (ident, fields) in result :
1173            self.doDelete(ident)
1174        for parent in self.getParentPrinters(printer) : 
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)         
1184        self.doDelete(printer.ident)   
1185       
1186    def extractPrinters(self, extractonly={}) :
1187        """Extracts all printer records."""
1188        pname = extractonly.get("printername")
1189        entries = [p for p in [self.getPrinter(name) for name in self.getAllPrintersNames(pname)] if p.Exists]
1190        if entries :
1191            result = [ ("dn", "printername", "priceperpage", "priceperjob", "description") ]
1192            for entry in entries :
1193                result.append((entry.ident, entry.Name, entry.PricePerPage, entry.PricePerJob, entry.Description))
1194            return result 
1195       
1196    def extractUsers(self, extractonly={}) :
1197        """Extracts all user records."""
1198        uname = extractonly.get("username")
1199        entries = [u for u in [self.getUser(name) for name in self.getAllUsersNames(uname)] if u.Exists]
1200        if entries :
1201            result = [ ("dn", "username", "balance", "lifetimepaid", "limitby", "email") ]
1202            for entry in entries :
1203                result.append((entry.ident, entry.Name, entry.AccountBalance, entry.LifeTimePaid, entry.LimitBy, entry.Email))
1204            return result 
1205       
1206    def extractGroups(self, extractonly={}) :
1207        """Extracts all group records."""
1208        gname = extractonly.get("groupname")
1209        entries = [g for g in [self.getGroup(name) for name in self.getAllGroupsNames(gname)] if g.Exists]
1210        if entries :
1211            result = [ ("dn", "groupname", "limitby", "balance", "lifetimepaid") ]
1212            for entry in entries :
1213                result.append((entry.ident, entry.Name, entry.LimitBy, entry.AccountBalance, entry.LifeTimePaid))
1214            return result 
1215       
1216    def extractPayments(self, extractonly={}) :
1217        """Extracts all payment records."""
1218        uname = extractonly.get("username")
1219        entries = [u for u in [self.getUser(name) for name in self.getAllUsersNames(uname)] if u.Exists]
1220        if entries :
1221            result = [ ("username", "amount", "date") ]
1222            for entry in entries :
1223                for (date, amount) in entry.Payments :
1224                    result.append((entry.Name, amount, date))
1225            return result       
1226       
1227    def extractUpquotas(self, extractonly={}) :
1228        """Extracts all userpquota records."""
1229        pname = extractonly.get("printername")
1230        entries = [p for p in [self.getPrinter(name) for name in self.getAllPrintersNames(pname)] if p.Exists]
1231        if entries :
1232            result = [ ("username", "printername", "dn", "userdn", "printerdn", "lifepagecounter", "pagecounter", "softlimit", "hardlimit", "datelimit") ]
1233            uname = extractonly.get("username")
1234            for entry in entries :
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))
1237            return result
1238       
1239    def extractGpquotas(self, extractonly={}) :
1240        """Extracts all grouppquota records."""
1241        pname = extractonly.get("printername")
1242        entries = [p for p in [self.getPrinter(name) for name in self.getAllPrintersNames(pname)] if p.Exists]
1243        if entries :
1244            result = [ ("groupname", "printername", "dn", "groupdn", "printerdn", "lifepagecounter", "pagecounter", "softlimit", "hardlimit", "datelimit") ]
1245            gname = extractonly.get("groupname")
1246            for entry in entries :
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))
1249            return result
1250       
1251    def extractUmembers(self, extractonly={}) :
1252        """Extracts all user groups members."""
1253        gname = extractonly.get("groupname")
1254        entries = [g for g in [self.getGroup(name) for name in self.getAllGroupsNames(gname)] if g.Exists]
1255        if entries :
1256            result = [ ("groupname", "username", "groupdn", "userdn") ]
1257            uname = extractonly.get("username")
1258            for entry in entries :
1259                for member in entry.Members :
1260                    if (uname is None) or (member.Name == uname) :
1261                        result.append((entry.Name, member.Name, entry.ident, member.ident))
1262            return result       
1263               
1264    def extractPmembers(self, extractonly={}) :
1265        """Extracts all printer groups members."""
1266        pname = extractonly.get("printername")
1267        entries = [p for p in [self.getPrinter(name) for name in self.getAllPrintersNames(pname)] if p.Exists]
1268        if entries :
1269            result = [ ("pgroupname", "printername", "pgroupdn", "printerdn") ]
1270            pgname = extractonly.get("pgroupname")
1271            for entry in entries :
1272                for parent in self.getParentPrinters(entry) :
1273                    if (pgname is None) or (parent.Name == pgname) :
1274                        result.append((parent.Name, entry.Name, parent.ident, entry.ident))
1275            return result       
1276       
1277    def extractHistory(self, extractonly={}) :
1278        """Extracts all jobhistory records."""
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)
1290        if entries :
1291            result = [ ("username", "printername", "dn", "jobid", "pagecounter", "jobsize", "action", "jobdate", "filename", "title", "copies", "options", "jobprice", "hostname", "jobsizebytes") ] 
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.