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

Revision 2953, 97.0 kB (checked in by jerome, 18 years ago)

Fixed date formatting problems with MySQL.

  • 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, 2005, 2006 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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 sys
32import types
33import time
34import md5
35import base64
36import random
37
38from mx import DateTime
39
40from pykota.storage import PyKotaStorageError, BaseStorage, \
41                           StorageUser, StorageGroup, StoragePrinter, \
42                           StorageJob, StorageLastJob, StorageUserPQuota, \
43                           StorageGroupPQuota, StorageBillingCode
44
45try :
46    import ldap
47    import ldap.modlist
48except ImportError :   
49    raise PyKotaStorageError, "This python version (%s) doesn't seem to have the python-ldap module installed correctly." % sys.version.split()[0]
50else :   
51    try :
52        from ldap.cidict import cidict
53    except ImportError :   
54        import UserDict
55        sys.stderr.write("ERROR: PyKota requires a newer version of python-ldap. Workaround activated. Please upgrade python-ldap !\n")
56        class cidict(UserDict.UserDict) :
57            pass # Fake it all, and don't care for case insensitivity : users who need it will have to upgrade.
58   
59class Storage(BaseStorage) :
60    def __init__(self, pykotatool, host, dbname, user, passwd) :
61        """Opens the LDAP connection."""
62        self.savedtool = pykotatool
63        self.savedhost = host
64        self.saveddbname = dbname
65        self.saveduser = user
66        self.savedpasswd = passwd
67        self.secondStageInit()
68       
69    def secondStageInit(self) :   
70        """Second stage initialisation."""
71        BaseStorage.__init__(self, self.savedtool)
72        self.info = self.tool.config.getLDAPInfo()
73        message = ""
74        for tryit in range(3) :
75            try :
76                self.tool.logdebug("Trying to open database (host=%s, dbname=%s, user=%s)..." % (self.savedhost, self.saveddbname, self.saveduser))
77                self.database = ldap.initialize(self.savedhost) 
78                if self.info["ldaptls"] :
79                    # we want TLS
80                    ldap.set_option(ldap.OPT_X_TLS_CACERTFILE, self.info["cacert"])
81                    self.database.set_option(ldap.OPT_X_TLS, ldap.OPT_X_TLS_DEMAND)
82                    self.database.start_tls_s()
83                self.database.simple_bind_s(self.saveduser, self.savedpasswd)
84                self.basedn = self.saveddbname
85            except ldap.SERVER_DOWN :   
86                message = "LDAP backend for PyKota seems to be down !"
87                self.tool.printInfo("%s" % message, "error")
88                self.tool.printInfo("Trying again in 2 seconds...", "warn")
89                time.sleep(2)
90            except ldap.LDAPError :   
91                message = "Unable to connect to LDAP server %s as %s." % (self.savedhost, self.saveduser)
92                self.tool.printInfo("%s" % message, "error")
93                self.tool.printInfo("Trying again in 2 seconds...", "warn")
94                time.sleep(2)
95            else :   
96                self.useldapcache = self.tool.config.getLDAPCache()
97                if self.useldapcache :
98                    self.tool.logdebug("Low-Level LDAP Caching enabled.")
99                    self.ldapcache = {} # low-level cache specific to LDAP backend
100                self.closed = 0
101                self.tool.logdebug("Database opened (host=%s, dbname=%s, user=%s)" % (self.savedhost, self.saveddbname, self.saveduser))
102                return # All is fine here.
103        raise PyKotaStorageError, message         
104           
105    def close(self) :   
106        """Closes the database connection."""
107        if not self.closed :
108            self.database.unbind_s()
109            self.closed = 1
110            self.tool.logdebug("Database closed.")
111       
112    def genUUID(self) :   
113        """Generates an unique identifier.
114       
115           TODO : this one is not unique accross several print servers, but should be sufficient for testing.
116        """
117        return md5.md5("%s-%s" % (time.time(), random.random())).hexdigest()
118       
119    def normalizeFields(self, fields) :   
120        """Ensure all items are lists."""
121        for (k, v) in fields.items() :
122            if type(v) not in (types.TupleType, types.ListType) :
123                if not v :
124                    del fields[k]
125                else :   
126                    fields[k] = [ v ]
127        return fields       
128       
129    def beginTransaction(self) :   
130        """Starts a transaction."""
131        self.tool.logdebug("Transaction begins... WARNING : No transactions in LDAP !")
132       
133    def commitTransaction(self) :   
134        """Commits a transaction."""
135        self.tool.logdebug("Transaction committed. WARNING : No transactions in LDAP !")
136       
137    def rollbackTransaction(self) :     
138        """Rollbacks a transaction."""
139        self.tool.logdebug("Transaction aborted. WARNING : No transaction in LDAP !")
140       
141    def doSearch(self, key, fields=None, base="", scope=ldap.SCOPE_SUBTREE, flushcache=0) :
142        """Does an LDAP search query."""
143        message = ""
144        for tryit in range(3) :
145            try :
146                base = base or self.basedn
147                if self.useldapcache :
148                    # Here we overwrite the fields the app want, to try and
149                    # retrieve ALL user defined attributes ("*")
150                    # + the createTimestamp attribute, needed by job history
151                    #
152                    # This may not work with all LDAP servers
153                    # but works at least in OpenLDAP (2.1.25)
154                    # and iPlanet Directory Server (5.1 SP3)
155                    fields = ["*", "createTimestamp"]         
156                   
157                if self.useldapcache and (not flushcache) and (scope == ldap.SCOPE_BASE) and self.ldapcache.has_key(base) :
158                    entry = self.ldapcache[base]
159                    self.tool.logdebug("LDAP cache hit %s => %s" % (base, entry))
160                    result = [(base, entry)]
161                else :
162                    self.tool.logdebug("QUERY : Filter : %s, BaseDN : %s, Scope : %s, Attributes : %s" % (key, base, scope, fields))
163                    result = self.database.search_s(base, scope, key, fields)
164            except ldap.NO_SUCH_OBJECT, msg :       
165                raise PyKotaStorageError, (_("Search base %s doesn't seem to exist. Probable misconfiguration. Please double check /etc/pykota/pykota.conf : %s") % (base, msg))
166            except ldap.LDAPError, msg :   
167                message = (_("Search for %s(%s) from %s(scope=%s) returned no answer.") % (key, fields, base, scope)) + " : %s" % str(msg)
168                self.tool.printInfo("LDAP error : %s" % message, "error")
169                self.tool.printInfo("LDAP connection will be closed and reopened.", "warn")
170                self.close()
171                self.secondStageInit()
172            else :     
173                self.tool.logdebug("QUERY : Result : %s" % result)
174                result = [ (dn, cidict(attrs)) for (dn, attrs) in result ]
175                if self.useldapcache :
176                    for (dn, attributes) in result :
177                        self.tool.logdebug("LDAP cache store %s => %s" % (dn, attributes))
178                        self.ldapcache[dn] = attributes
179                return result
180        raise PyKotaStorageError, message
181           
182    def doAdd(self, dn, fields) :
183        """Adds an entry in the LDAP directory."""
184        fields = self.normalizeFields(cidict(fields))
185        message = ""
186        for tryit in range(3) :
187            try :
188                self.tool.logdebug("QUERY : ADD(%s, %s)" % (dn, str(fields)))
189                entry = ldap.modlist.addModlist(fields)
190                self.tool.logdebug("%s" % entry)
191                self.database.add_s(dn, entry)
192            except ldap.ALREADY_EXISTS, msg :       
193                raise PyKotaStorageError, "Entry %s already exists : %s" % (dn, str(msg))
194            except ldap.LDAPError, msg :
195                message = (_("Problem adding LDAP entry (%s, %s)") % (dn, str(fields))) + " : %s" % str(msg)
196                self.tool.printInfo("LDAP error : %s" % message, "error")
197                self.tool.printInfo("LDAP connection will be closed and reopened.", "warn")
198                self.close()
199                self.secondStageInit()
200            else :
201                if self.useldapcache :
202                    self.tool.logdebug("LDAP cache add %s => %s" % (dn, fields))
203                    self.ldapcache[dn] = fields
204                return dn
205        raise PyKotaStorageError, message
206           
207    def doDelete(self, dn) :
208        """Deletes an entry from the LDAP directory."""
209        message = ""
210        for tryit in range(3) :
211            try :
212                self.tool.logdebug("QUERY : Delete(%s)" % dn)
213                self.database.delete_s(dn)
214            except ldap.NO_SUCH_OBJECT :   
215                self.tool.printInfo("Entry %s was already missing before we deleted it. This **MAY** be normal." % dn, "info")
216            except ldap.LDAPError, msg :
217                message = (_("Problem deleting LDAP entry (%s)") % dn) + " : %s" % str(msg)
218                self.tool.printInfo("LDAP error : %s" % message, "error")
219                self.tool.printInfo("LDAP connection will be closed and reopened.", "warn")
220                self.close()
221                self.secondStageInit()
222            else :   
223                if self.useldapcache :
224                    try :
225                        self.tool.logdebug("LDAP cache del %s" % dn)
226                        del self.ldapcache[dn]
227                    except KeyError :   
228                        pass
229                return       
230        raise PyKotaStorageError, message
231           
232    def doModify(self, dn, fields, ignoreold=1, flushcache=0) :
233        """Modifies an entry in the LDAP directory."""
234        fields = cidict(fields)
235        for tryit in range(3) :
236            try :
237                # TODO : take care of, and update LDAP specific cache
238                if self.useldapcache and not flushcache :
239                    if self.ldapcache.has_key(dn) :
240                        old = self.ldapcache[dn]
241                        self.tool.logdebug("LDAP cache hit %s => %s" % (dn, old))
242                        oldentry = {}
243                        for (k, v) in old.items() :
244                            if k != "createTimestamp" :
245                                oldentry[k] = v
246                    else :   
247                        self.tool.logdebug("LDAP cache miss %s" % dn)
248                        oldentry = self.doSearch("objectClass=*", base=dn, scope=ldap.SCOPE_BASE)[0][1]
249                else :       
250                    oldentry = self.doSearch("objectClass=*", base=dn, scope=ldap.SCOPE_BASE, flushcache=flushcache)[0][1]
251                for (k, v) in fields.items() :
252                    if type(v) == type({}) :
253                        try :
254                            oldvalue = v["convert"](oldentry.get(k, [0])[0])
255                        except ValueError :   
256                            self.tool.logdebug("Error converting %s with %s(%s)" % (oldentry.get(k), k, v))
257                            oldvalue = 0
258                        if v["operator"] == '+' :
259                            newvalue = oldvalue + v["value"]
260                        else :   
261                            newvalue = oldvalue - v["value"]
262                        fields[k] = str(newvalue)
263                fields = self.normalizeFields(fields)
264                self.tool.logdebug("QUERY : Modify(%s, %s ==> %s)" % (dn, oldentry, fields))
265                entry = ldap.modlist.modifyModlist(oldentry, fields, ignore_oldexistent=ignoreold)
266                modentry = []
267                for (mop, mtyp, mval) in entry :
268                    if mtyp and (mtyp.lower() != "createtimestamp") :
269                        modentry.append((mop, mtyp, mval))
270                self.tool.logdebug("MODIFY : %s ==> %s ==> %s" % (fields, entry, modentry))
271                if modentry :
272                    self.database.modify_s(dn, modentry)
273            except ldap.LDAPError, msg :
274                message = (_("Problem modifying LDAP entry (%s, %s)") % (dn, fields)) + " : %s" % str(msg)
275                self.tool.printInfo("LDAP error : %s" % message, "error")
276                self.tool.printInfo("LDAP connection will be closed and reopened.", "warn")
277                self.close()
278                self.secondStageInit()
279            else :
280                if self.useldapcache :
281                    cachedentry = self.ldapcache[dn]
282                    for (mop, mtyp, mval) in entry :
283                        if mop in (ldap.MOD_ADD, ldap.MOD_REPLACE) :
284                            cachedentry[mtyp] = mval
285                        else :
286                            try :
287                                del cachedentry[mtyp]
288                            except KeyError :   
289                                pass
290                    self.tool.logdebug("LDAP cache update %s => %s" % (dn, cachedentry))
291                return dn
292        raise PyKotaStorageError, message
293           
294    def filterNames(self, records, attribute, patterns=None) :
295        """Returns a list of 'attribute' from a list of records.
296       
297           Logs any missing attribute.
298        """   
299        result = []
300        for (dn, record) in records :
301            attrval = record.get(attribute, [None])[0]
302            if attrval is None :
303                self.tool.printInfo("Object %s has no %s attribute !" % (dn, attribute), "error")
304            else :
305                attrval = self.databaseToUserCharset(attrval)
306                if patterns :
307                    if (not isinstance(patterns, type([]))) and (not isinstance(patterns, type(()))) :
308                        patterns = [ patterns ]
309                    if self.tool.matchString(attrval, patterns) :   
310                        result.append(attrval)
311                else :   
312                    result.append(attrval)
313        return result       
314               
315    def getAllBillingCodes(self, billingcode=None) :   
316        """Extracts all billing codes or only the billing codes matching the optional parameter."""
317        ldapfilter = "objectClass=pykotaBilling"
318        result = self.doSearch(ldapfilter, ["pykotaBillingCode"], base=self.info["billingcodebase"])
319        if result :
320            return [self.databaseToUserCharset(bc) for bc in self.filterNames(result, "pykotaBillingCode", billingcode)]
321        else :   
322            return []
323       
324    def getAllPrintersNames(self, printername=None) :   
325        """Extracts all printer names or only the printers' names matching the optional parameter."""
326        ldapfilter = "objectClass=pykotaPrinter"
327        result = self.doSearch(ldapfilter, ["pykotaPrinterName"], base=self.info["printerbase"])
328        if result :
329            return self.filterNames(result, "pykotaPrinterName", printername)
330        else :   
331            return []
332       
333    def getAllUsersNames(self, username=None) :   
334        """Extracts all user names or only the users' names matching the optional parameter."""
335        ldapfilter = "objectClass=pykotaAccount"
336        result = self.doSearch(ldapfilter, ["pykotaUserName"], base=self.info["userbase"])
337        if result :
338            return self.filterNames(result, "pykotaUserName", username)
339        else :   
340            return []
341       
342    def getAllGroupsNames(self, groupname=None) :   
343        """Extracts all group names or only the groups' names matching the optional parameter."""
344        ldapfilter = "objectClass=pykotaGroup"
345        result = self.doSearch(ldapfilter, ["pykotaGroupName"], base=self.info["groupbase"])
346        if result :
347            return self.filterNames(result, "pykotaGroupName", groupname)
348        else :   
349            return []
350       
351    def getUserNbJobsFromHistory(self, user) :
352        """Returns the number of jobs the user has in history."""
353        result = self.doSearch("(&(pykotaUserName=%s)(objectClass=pykotaJob))" % self.userCharsetToDatabase(user.Name), None, base=self.info["jobbase"])
354        return len(result)
355       
356    def getUserFromBackend(self, username) :   
357        """Extracts user information given its name."""
358        user = StorageUser(self, username)
359        username = self.userCharsetToDatabase(username)
360        result = self.doSearch("(&(objectClass=pykotaAccount)(|(pykotaUserName=%s)(%s=%s)))" % (username, self.info["userrdn"], username), ["pykotaUserName", "pykotaLimitBy", self.info["usermail"], "pykotaOverCharge", "description"], base=self.info["userbase"])
361        if result :
362            fields = result[0][1]
363            user.ident = result[0][0]
364            user.Description = self.databaseToUserCharset(fields.get("description", [None])[0])
365            user.Email = fields.get(self.info["usermail"], [None])[0]
366            user.LimitBy = fields.get("pykotaLimitBy", ["quota"])[0]
367            user.OverCharge = float(fields.get("pykotaOverCharge", [1.0])[0])
368            result = self.doSearch("(&(objectClass=pykotaAccountBalance)(|(pykotaUserName=%s)(%s=%s)))" % (username, self.info["balancerdn"], username), ["pykotaBalance", "pykotaLifeTimePaid", "pykotaPayments"], base=self.info["balancebase"])
369            if not result :
370                raise PyKotaStorageError, _("No pykotaAccountBalance object found for user %s. Did you create LDAP entries manually ?") % username
371            else :
372                fields = result[0][1]
373                user.idbalance = result[0][0]
374                user.AccountBalance = fields.get("pykotaBalance")
375                if user.AccountBalance is not None :
376                    if user.AccountBalance[0].upper() == "NONE" :
377                        user.AccountBalance = None
378                    else :   
379                        user.AccountBalance = float(user.AccountBalance[0])
380                user.AccountBalance = user.AccountBalance or 0.0       
381                user.LifeTimePaid = fields.get("pykotaLifeTimePaid")
382                if user.LifeTimePaid is not None :
383                    if user.LifeTimePaid[0].upper() == "NONE" :
384                        user.LifeTimePaid = None
385                    else :   
386                        user.LifeTimePaid = float(user.LifeTimePaid[0])
387                user.LifeTimePaid = user.LifeTimePaid or 0.0       
388                user.Payments = []
389                for payment in fields.get("pykotaPayments", []) :
390                    try :
391                        (date, amount, description) = payment.split(" # ")
392                    except ValueError :
393                        # Payment with no description (old Payment)
394                        (date, amount) = payment.split(" # ")
395                        description = ""
396                    else :   
397                        description = self.databaseToUserCharset(base64.decodestring(description))
398                    user.Payments.append((date, float(amount), description))
399            user.Exists = True
400        return user
401       
402    def getGroupFromBackend(self, groupname) :   
403        """Extracts group information given its name."""
404        group = StorageGroup(self, groupname)
405        groupname = self.userCharsetToDatabase(groupname)
406        result = self.doSearch("(&(objectClass=pykotaGroup)(|(pykotaGroupName=%s)(%s=%s)))" % (groupname, self.info["grouprdn"], groupname), ["pykotaGroupName", "pykotaLimitBy", "description"], base=self.info["groupbase"])
407        if result :
408            fields = result[0][1]
409            group.ident = result[0][0]
410            group.Name = fields.get("pykotaGroupName", [self.databaseToUserCharset(groupname)])[0] 
411            group.Description = self.databaseToUserCharset(fields.get("description", [None])[0])
412            group.LimitBy = fields.get("pykotaLimitBy", ["quota"])[0]
413            group.AccountBalance = 0.0
414            group.LifeTimePaid = 0.0
415            for member in self.getGroupMembers(group) :
416                if member.Exists :
417                    group.AccountBalance += member.AccountBalance
418                    group.LifeTimePaid += member.LifeTimePaid
419            group.Exists = True
420        return group
421       
422    def getPrinterFromBackend(self, printername) :       
423        """Extracts printer information given its name : returns first matching printer."""
424        printer = StoragePrinter(self, printername)
425        printername = self.userCharsetToDatabase(printername)
426        result = self.doSearch("(&(objectClass=pykotaPrinter)(|(pykotaPrinterName=%s)(%s=%s)))" \
427                      % (printername, self.info["printerrdn"], printername), \
428                        ["pykotaPrinterName", "pykotaPricePerPage", \
429                         "pykotaPricePerJob", "pykotaMaxJobSize", \
430                         "pykotaPassThrough", "uniqueMember", "description"], \
431                      base=self.info["printerbase"])
432        if result :
433            fields = result[0][1]       # take only first matching printer, ignore the rest
434            printer.ident = result[0][0]
435            printer.Name = fields.get("pykotaPrinterName", [self.databaseToUserCharset(printername)])[0] 
436            printer.PricePerJob = float(fields.get("pykotaPricePerJob", [0.0])[0])
437            printer.PricePerPage = float(fields.get("pykotaPricePerPage", [0.0])[0])
438            printer.MaxJobSize = int(fields.get("pykotaMaxJobSize", [0])[0])
439            printer.PassThrough = fields.get("pykotaPassThrough", [None])[0]
440            if printer.PassThrough in (1, "1", "t", "true", "TRUE", "True") :
441                printer.PassThrough = 1
442            else :
443                printer.PassThrough = 0
444            printer.uniqueMember = fields.get("uniqueMember", [])
445            printer.Description = self.databaseToUserCharset(fields.get("description", [""])[0]) 
446            printer.Exists = True
447        return printer   
448       
449    def getUserPQuotaFromBackend(self, user, printer) :       
450        """Extracts a user print quota."""
451        userpquota = StorageUserPQuota(self, user, printer)
452        if printer.Exists and user.Exists :
453            if self.info["userquotabase"].lower() == "user" :
454                base = user.ident
455            else :   
456                base = self.info["userquotabase"]
457            result = self.doSearch("(&(objectClass=pykotaUserPQuota)(pykotaUserName=%s)(pykotaPrinterName=%s))" % \
458                                      (self.userCharsetToDatabase(user.Name), self.userCharsetToDatabase(printer.Name)), \
459                                      ["pykotaPageCounter", "pykotaLifePageCounter", "pykotaSoftLimit", "pykotaHardLimit", "pykotaDateLimit", "pykotaWarnCount", "pykotaMaxJobSize"], \
460                                      base=base)
461            if result :
462                fields = result[0][1]
463                userpquota.ident = result[0][0]
464                userpquota.PageCounter = int(fields.get("pykotaPageCounter", [0])[0])
465                userpquota.LifePageCounter = int(fields.get("pykotaLifePageCounter", [0])[0])
466                userpquota.WarnCount = int(fields.get("pykotaWarnCount", [0])[0])
467                userpquota.SoftLimit = fields.get("pykotaSoftLimit")
468                if userpquota.SoftLimit is not None :
469                    if userpquota.SoftLimit[0].upper() == "NONE" :
470                        userpquota.SoftLimit = None
471                    else :   
472                        userpquota.SoftLimit = int(userpquota.SoftLimit[0])
473                userpquota.HardLimit = fields.get("pykotaHardLimit")
474                if userpquota.HardLimit is not None :
475                    if userpquota.HardLimit[0].upper() == "NONE" :
476                        userpquota.HardLimit = None
477                    elif userpquota.HardLimit is not None :   
478                        userpquota.HardLimit = int(userpquota.HardLimit[0])
479                userpquota.DateLimit = fields.get("pykotaDateLimit")
480                if userpquota.DateLimit is not None :
481                    if userpquota.DateLimit[0].upper() == "NONE" : 
482                        userpquota.DateLimit = None
483                    else :   
484                        userpquota.DateLimit = userpquota.DateLimit[0]
485                userpquota.MaxJobSize = fields.get("pykotaMaxJobSize")
486                if userpquota.MaxJobSize is not None :
487                    if userpquota.MaxJobSize[0].upper() == "NONE" :
488                        userpquota.MaxJobSize = None
489                    else :   
490                        userpquota.MaxJobSize = int(userpquota.MaxJobSize[0])
491                userpquota.Exists = True
492        return userpquota
493       
494    def getGroupPQuotaFromBackend(self, group, printer) :       
495        """Extracts a group print quota."""
496        grouppquota = StorageGroupPQuota(self, group, printer)
497        if group.Exists :
498            if self.info["groupquotabase"].lower() == "group" :
499                base = group.ident
500            else :   
501                base = self.info["groupquotabase"]
502            result = self.doSearch("(&(objectClass=pykotaGroupPQuota)(pykotaGroupName=%s)(pykotaPrinterName=%s))" % \
503                                      (self.userCharsetToDatabase(group.Name), self.userCharsetToDatabase(printer.Name)), \
504                                      ["pykotaSoftLimit", "pykotaHardLimit", "pykotaDateLimit", "pykotaMaxJobSize"], \
505                                      base=base)
506            if result :
507                fields = result[0][1]
508                grouppquota.ident = result[0][0]
509                grouppquota.SoftLimit = fields.get("pykotaSoftLimit")
510                if grouppquota.SoftLimit is not None :
511                    if grouppquota.SoftLimit[0].upper() == "NONE" :
512                        grouppquota.SoftLimit = None
513                    else :   
514                        grouppquota.SoftLimit = int(grouppquota.SoftLimit[0])
515                grouppquota.HardLimit = fields.get("pykotaHardLimit")
516                if grouppquota.HardLimit is not None :
517                    if grouppquota.HardLimit[0].upper() == "NONE" :
518                        grouppquota.HardLimit = None
519                    else :   
520                        grouppquota.HardLimit = int(grouppquota.HardLimit[0])
521                grouppquota.DateLimit = fields.get("pykotaDateLimit")
522                if grouppquota.DateLimit is not None :
523                    if grouppquota.DateLimit[0].upper() == "NONE" : 
524                        grouppquota.DateLimit = None
525                    else :   
526                        grouppquota.DateLimit = grouppquota.DateLimit[0]
527                grouppquota.MaxJobSize = fields.get("pykotaMaxJobSize")
528                if grouppquota.MaxJobSize is not None :
529                    if grouppquota.MaxJobSize[0].upper() == "NONE" :
530                        grouppquota.MaxJobSize = None
531                    else :   
532                        grouppquota.MaxJobSize = int(grouppquota.MaxJobSize[0])
533                grouppquota.PageCounter = 0
534                grouppquota.LifePageCounter = 0
535                usernamesfilter = "".join(["(pykotaUserName=%s)" % self.userCharsetToDatabase(member.Name) for member in self.getGroupMembers(group)])
536                if usernamesfilter :
537                    usernamesfilter = "(|%s)" % usernamesfilter
538                if self.info["userquotabase"].lower() == "user" :
539                    base = self.info["userbase"]
540                else :
541                    base = self.info["userquotabase"]
542                result = self.doSearch("(&(objectClass=pykotaUserPQuota)(pykotaPrinterName=%s)%s)" % \
543                                          (self.userCharsetToDatabase(printer.Name), usernamesfilter), \
544                                          ["pykotaPageCounter", "pykotaLifePageCounter"], base=base)
545                if result :
546                    for userpquota in result :   
547                        grouppquota.PageCounter += int(userpquota[1].get("pykotaPageCounter", [0])[0] or 0)
548                        grouppquota.LifePageCounter += int(userpquota[1].get("pykotaLifePageCounter", [0])[0] or 0)
549                grouppquota.Exists = True
550        return grouppquota
551       
552    def getPrinterLastJobFromBackend(self, printer) :       
553        """Extracts a printer's last job information."""
554        lastjob = StorageLastJob(self, printer)
555        pname = self.userCharsetToDatabase(printer.Name)
556        result = self.doSearch("(&(objectClass=pykotaLastjob)(|(pykotaPrinterName=%s)(%s=%s)))" % \
557                                  (pname, self.info["printerrdn"], pname), \
558                                  ["pykotaLastJobIdent"], \
559                                  base=self.info["lastjobbase"])
560        if result :
561            lastjob.lastjobident = result[0][0]
562            lastjobident = result[0][1]["pykotaLastJobIdent"][0]
563            result = None
564            try :
565                result = self.doSearch("objectClass=pykotaJob", [ "pykotaJobSizeBytes", 
566                                                                  "pykotaHostName", 
567                                                                  "pykotaUserName", 
568                                                                  "pykotaPrinterName", 
569                                                                  "pykotaJobId", 
570                                                                  "pykotaPrinterPageCounter", 
571                                                                  "pykotaJobSize", 
572                                                                  "pykotaAction", 
573                                                                  "pykotaJobPrice", 
574                                                                  "pykotaFileName", 
575                                                                  "pykotaTitle", 
576                                                                  "pykotaCopies", 
577                                                                  "pykotaOptions", 
578                                                                  "pykotaBillingCode", 
579                                                                  "pykotaPages", 
580                                                                  "pykotaMD5Sum", 
581                                                                  "pykotaPrecomputedJobSize",
582                                                                  "pykotaPrecomputedJobPrice",
583                                                                  "createTimestamp" ], 
584                                                                base="cn=%s,%s" % (lastjobident, self.info["jobbase"]), scope=ldap.SCOPE_BASE)
585            except PyKotaStorageError :   
586                pass # Last job entry exists, but job probably doesn't exist anymore.
587            if result :
588                fields = result[0][1]
589                lastjob.ident = result[0][0]
590                lastjob.JobId = fields.get("pykotaJobId")[0]
591                lastjob.UserName = self.databaseToUserCharset(fields.get("pykotaUserName")[0])
592                lastjob.PrinterPageCounter = int(fields.get("pykotaPrinterPageCounter", [0])[0])
593                try :
594                    lastjob.JobSize = int(fields.get("pykotaJobSize", [0])[0])
595                except ValueError :   
596                    lastjob.JobSize = None
597                try :   
598                    lastjob.JobPrice = float(fields.get("pykotaJobPrice", [0.0])[0])
599                except ValueError :   
600                    lastjob.JobPrice = None
601                lastjob.JobAction = fields.get("pykotaAction", [""])[0]
602                lastjob.JobFileName = self.databaseToUserCharset(fields.get("pykotaFileName", [""])[0]) 
603                lastjob.JobTitle = self.databaseToUserCharset(fields.get("pykotaTitle", [""])[0]) 
604                lastjob.JobCopies = int(fields.get("pykotaCopies", [0])[0])
605                lastjob.JobOptions = self.databaseToUserCharset(fields.get("pykotaOptions", [""])[0]) 
606                lastjob.JobHostName = fields.get("pykotaHostName", [""])[0]
607                lastjob.JobSizeBytes = fields.get("pykotaJobSizeBytes", [0L])[0]
608                lastjob.JobBillingCode = self.databaseToUserCharset(fields.get("pykotaBillingCode", [None])[0])
609                lastjob.JobMD5Sum = fields.get("pykotaMD5Sum", [None])[0]
610                lastjob.JobPages = fields.get("pykotaPages", [""])[0]
611                try :
612                    lastjob.PrecomputedJobSize = int(fields.get("pykotaPrecomputedJobSize", [0])[0])
613                except ValueError :   
614                    lastjob.PrecomputedJobSize = None
615                try :   
616                    lastjob.PrecomputedJobPrice = float(fields.get("pykotaPrecomputedJobPrice", [0.0])[0])
617                except ValueError :   
618                    lastjob.PrecomputedJobPrice = None
619                if lastjob.JobTitle == lastjob.JobFileName == lastjob.JobOptions == "hidden" :
620                    (lastjob.JobTitle, lastjob.JobFileName, lastjob.JobOptions) = (_("Hidden because of privacy concerns"),) * 3
621                date = fields.get("createTimestamp", ["19700101000000Z"])[0] # It's in UTC !
622                mxtime = DateTime.strptime(date[:14], "%Y%m%d%H%M%S").localtime()
623                lastjob.JobDate = mxtime.strftime("%Y-%m-%d %H:%M:%S")
624                lastjob.Exists = True
625        return lastjob
626       
627    def getGroupMembersFromBackend(self, group) :       
628        """Returns the group's members list."""
629        groupmembers = []
630        gname = self.userCharsetToDatabase(group.Name)
631        result = self.doSearch("(&(objectClass=pykotaGroup)(|(pykotaGroupName=%s)(%s=%s)))" % \
632                                  (gname, self.info["grouprdn"], gname), \
633                                  [self.info["groupmembers"]], \
634                                  base=self.info["groupbase"])
635        if result :
636            for username in result[0][1].get(self.info["groupmembers"], []) :
637                groupmembers.append(self.getUser(self.databaseToUserCharset(username)))
638        return groupmembers       
639       
640    def getUserGroupsFromBackend(self, user) :       
641        """Returns the user's groups list."""
642        groups = []
643        uname = self.userCharsetToDatabase(user.Name)
644        result = self.doSearch("(&(objectClass=pykotaGroup)(%s=%s))" % \
645                                  (self.info["groupmembers"], uname), \
646                                  [self.info["grouprdn"], "pykotaGroupName", "pykotaLimitBy"], \
647                                  base=self.info["groupbase"])
648        if result :
649            for (groupid, fields) in result :
650                groupname = self.databaseToUserCharset((fields.get("pykotaGroupName", [None]) or fields.get(self.info["grouprdn"], [None]))[0])
651                group = self.getFromCache("GROUPS", groupname)
652                if group is None :
653                    group = StorageGroup(self, groupname)
654                    group.ident = groupid
655                    group.LimitBy = fields.get("pykotaLimitBy")
656                    if group.LimitBy is not None :
657                        group.LimitBy = group.LimitBy[0]
658                    else :   
659                        group.LimitBy = "quota"
660                    group.AccountBalance = 0.0
661                    group.LifeTimePaid = 0.0
662                    for member in self.getGroupMembers(group) :
663                        if member.Exists :
664                            group.AccountBalance += member.AccountBalance
665                            group.LifeTimePaid += member.LifeTimePaid
666                    group.Exists = True
667                    self.cacheEntry("GROUPS", group.Name, group)
668                groups.append(group)
669        return groups       
670       
671    def getParentPrintersFromBackend(self, printer) :   
672        """Get all the printer groups this printer is a member of."""
673        pgroups = []
674        result = self.doSearch("(&(objectClass=pykotaPrinter)(uniqueMember=%s))" % \
675                                  printer.ident, \
676                                  ["pykotaPrinterName"], \
677                                  base=self.info["printerbase"])
678        if result :
679            for (printerid, fields) in result :
680                if printerid != printer.ident : # In case of integrity violation.
681                    parentprinter = self.getPrinter(self.databaseToUserCharset(fields.get("pykotaPrinterName")[0]))
682                    if parentprinter.Exists :
683                        pgroups.append(parentprinter)
684        return pgroups
685       
686    def getMatchingPrinters(self, printerpattern) :
687        """Returns the list of all printers for which name matches a certain pattern."""
688        printers = []
689        # see comment at the same place in pgstorage.py
690        result = self.doSearch("objectClass=pykotaPrinter", \
691                                  ["pykotaPrinterName", "pykotaPricePerPage", "pykotaPricePerJob", "pykotaMaxJobSize", "pykotaPassThrough", "uniqueMember", "description"], \
692                                  base=self.info["printerbase"])
693        if result :
694            patterns = printerpattern.split(",")
695            try :
696                patdict = {}.fromkeys(patterns)
697            except AttributeError :   
698                # Python v2.2 or earlier
699                patdict = {}
700                for p in patterns :
701                    patdict[p] = None
702            for (printerid, fields) in result :
703                printername = self.databaseToUserCharset(fields.get("pykotaPrinterName", [""])[0] or fields.get(self.info["printerrdn"], [""])[0])
704                if patdict.has_key(printername) or self.tool.matchString(printername, patterns) :
705                    printer = StoragePrinter(self, printername)
706                    printer.ident = printerid
707                    printer.PricePerJob = float(fields.get("pykotaPricePerJob", [0.0])[0] or 0.0)
708                    printer.PricePerPage = float(fields.get("pykotaPricePerPage", [0.0])[0] or 0.0)
709                    printer.MaxJobSize = int(fields.get("pykotaMaxJobSize", [0])[0])
710                    printer.PassThrough = fields.get("pykotaPassThrough", [None])[0]
711                    if printer.PassThrough in (1, "1", "t", "true", "TRUE", "True") :
712                        printer.PassThrough = 1
713                    else :
714                        printer.PassThrough = 0
715                    printer.uniqueMember = fields.get("uniqueMember", [])
716                    printer.Description = self.databaseToUserCharset(fields.get("description", [""])[0]) 
717                    printer.Exists = True
718                    printers.append(printer)
719                    self.cacheEntry("PRINTERS", printer.Name, printer)
720        return printers       
721       
722    def getMatchingUsers(self, userpattern) :
723        """Returns the list of all users for which name matches a certain pattern."""
724        users = []
725        # see comment at the same place in pgstorage.py
726        result = self.doSearch("objectClass=pykotaAccount", \
727                                  ["pykotaUserName", "pykotaLimitBy", self.info["usermail"], "pykotaOverCharge", "description"], \
728                                  base=self.info["userbase"])
729        if result :
730            patterns = userpattern.split(",")
731            try :
732                patdict = {}.fromkeys(patterns)
733            except AttributeError :   
734                # Python v2.2 or earlier
735                patdict = {}
736                for p in patterns :
737                    patdict[p] = None
738            for (userid, fields) in result :
739                username = self.databaseToUserCharset(fields.get("pykotaUserName", [""])[0] or fields.get(self.info["userrdn"], [""])[0])
740                if patdict.has_key(username) or self.tool.matchString(username, patterns) :
741                    user = StorageUser(self, username)
742                    user.ident = userid
743                    user.Email = fields.get(self.info["usermail"], [None])[0]
744                    user.LimitBy = fields.get("pykotaLimitBy", ["quota"])[0]
745                    user.OverCharge = float(fields.get("pykotaOverCharge", [1.0])[0])
746                    user.Description = self.databaseToUserCharset(fields.get("description", [""])[0]) 
747                    uname = self.userCharsetToDatabase(username)
748                    result = self.doSearch("(&(objectClass=pykotaAccountBalance)(|(pykotaUserName=%s)(%s=%s)))" % \
749                                              (uname, self.info["balancerdn"], uname), \
750                                              ["pykotaBalance", "pykotaLifeTimePaid", "pykotaPayments"], \
751                                              base=self.info["balancebase"])
752                    if not result :
753                        raise PyKotaStorageError, _("No pykotaAccountBalance object found for user %s. Did you create LDAP entries manually ?") % username
754                    else :
755                        fields = result[0][1]
756                        user.idbalance = result[0][0]
757                        user.AccountBalance = fields.get("pykotaBalance")
758                        if user.AccountBalance is not None :
759                            if user.AccountBalance[0].upper() == "NONE" :
760                                user.AccountBalance = None
761                            else :   
762                                user.AccountBalance = float(user.AccountBalance[0])
763                        user.AccountBalance = user.AccountBalance or 0.0       
764                        user.LifeTimePaid = fields.get("pykotaLifeTimePaid")
765                        if user.LifeTimePaid is not None :
766                            if user.LifeTimePaid[0].upper() == "NONE" :
767                                user.LifeTimePaid = None
768                            else :   
769                                user.LifeTimePaid = float(user.LifeTimePaid[0])
770                        user.LifeTimePaid = user.LifeTimePaid or 0.0       
771                        user.Payments = []
772                        for payment in fields.get("pykotaPayments", []) :
773                            try :
774                                (date, amount, description) = payment.split(" # ")
775                            except ValueError :
776                                # Payment with no description (old Payment)
777                                (date, amount) = payment.split(" # ")
778                                description = ""
779                            else :   
780                                description = self.databaseToUserCharset(base64.decodestring(description))
781                            user.Payments.append((date, float(amount), description))
782                    user.Exists = True
783                    users.append(user)
784                    self.cacheEntry("USERS", user.Name, user)
785        return users       
786       
787    def getMatchingGroups(self, grouppattern) :
788        """Returns the list of all groups for which name matches a certain pattern."""
789        groups = []
790        # see comment at the same place in pgstorage.py
791        result = self.doSearch("objectClass=pykotaGroup", \
792                                  ["pykotaGroupName", "pykotaLimitBy", "description"], \
793                                  base=self.info["groupbase"])
794        if result :
795            patterns = grouppattern.split(",")
796            try :
797                patdict = {}.fromkeys(patterns)
798            except AttributeError :   
799                # Python v2.2 or earlier
800                patdict = {}
801                for p in patterns :
802                    patdict[p] = None
803            for (groupid, fields) in result :
804                groupname = self.databaseToUserCharset(fields.get("pykotaGroupName", [""])[0] or fields.get(self.info["grouprdn"], [""])[0])
805                if patdict.has_key(groupname) or self.tool.matchString(groupname, patterns) :
806                    group = StorageGroup(self, groupname)
807                    group.ident = groupid
808                    group.Name = fields.get("pykotaGroupName", [self.databaseToUserCharset(groupname)])[0] 
809                    group.LimitBy = fields.get("pykotaLimitBy", ["quota"])[0]
810                    group.Description = self.databaseToUserCharset(fields.get("description", [""])[0]) 
811                    group.AccountBalance = 0.0
812                    group.LifeTimePaid = 0.0
813                    for member in self.getGroupMembers(group) :
814                        if member.Exists :
815                            group.AccountBalance += member.AccountBalance
816                            group.LifeTimePaid += member.LifeTimePaid
817                    group.Exists = True
818                    groups.append(group)
819                    self.cacheEntry("GROUPS", group.Name, group)
820        return groups
821       
822    def getPrinterUsersAndQuotas(self, printer, names=["*"]) :       
823        """Returns the list of users who uses a given printer, along with their quotas."""
824        usersandquotas = []
825        pname = self.userCharsetToDatabase(printer.Name)
826        names = [self.userCharsetToDatabase(n) for n in names]
827        if self.info["userquotabase"].lower() == "user" :
828            base = self.info["userbase"]
829        else :
830            base = self.info["userquotabase"]
831        result = self.doSearch("(&(objectClass=pykotaUserPQuota)(pykotaPrinterName=%s)(|%s))" % \
832                                  (pname, "".join(["(pykotaUserName=%s)" % uname for uname in names])), \
833                                  ["pykotaUserName", "pykotaPageCounter", "pykotaLifePageCounter", "pykotaSoftLimit", "pykotaHardLimit", "pykotaDateLimit", "pykotaWarnCount"], \
834                                  base=base)
835        if result :
836            for (userquotaid, fields) in result :
837                user = self.getUser(self.databaseToUserCharset(fields.get("pykotaUserName")[0]))
838                userpquota = StorageUserPQuota(self, user, printer)
839                userpquota.ident = userquotaid
840                userpquota.PageCounter = int(fields.get("pykotaPageCounter", [0])[0])
841                userpquota.LifePageCounter = int(fields.get("pykotaLifePageCounter", [0])[0])
842                userpquota.WarnCount = int(fields.get("pykotaWarnCount", [0])[0])
843                userpquota.SoftLimit = fields.get("pykotaSoftLimit")
844                if userpquota.SoftLimit is not None :
845                    if userpquota.SoftLimit[0].upper() == "NONE" :
846                        userpquota.SoftLimit = None
847                    else :   
848                        userpquota.SoftLimit = int(userpquota.SoftLimit[0])
849                userpquota.HardLimit = fields.get("pykotaHardLimit")
850                if userpquota.HardLimit is not None :
851                    if userpquota.HardLimit[0].upper() == "NONE" :
852                        userpquota.HardLimit = None
853                    elif userpquota.HardLimit is not None :   
854                        userpquota.HardLimit = int(userpquota.HardLimit[0])
855                userpquota.DateLimit = fields.get("pykotaDateLimit")
856                if userpquota.DateLimit is not None :
857                    if userpquota.DateLimit[0].upper() == "NONE" : 
858                        userpquota.DateLimit = None
859                    else :   
860                        userpquota.DateLimit = userpquota.DateLimit[0]
861                userpquota.Exists = True
862                usersandquotas.append((user, userpquota))
863                self.cacheEntry("USERPQUOTAS", "%s@%s" % (user.Name, printer.Name), userpquota)
864        usersandquotas.sort(lambda x, y : cmp(x[0].Name, y[0].Name))           
865        return usersandquotas
866               
867    def getPrinterGroupsAndQuotas(self, printer, names=["*"]) :       
868        """Returns the list of groups which uses a given printer, along with their quotas."""
869        groupsandquotas = []
870        pname = self.userCharsetToDatabase(printer.Name)
871        names = [self.userCharsetToDatabase(n) for n in names]
872        if self.info["groupquotabase"].lower() == "group" :
873            base = self.info["groupbase"]
874        else :
875            base = self.info["groupquotabase"]
876        result = self.doSearch("(&(objectClass=pykotaGroupPQuota)(pykotaPrinterName=%s)(|%s))" % \
877                                  (pname, "".join(["(pykotaGroupName=%s)" % gname for gname in names])), \
878                                  ["pykotaGroupName"], \
879                                  base=base)
880        if result :
881            for (groupquotaid, fields) in result :
882                group = self.getGroup(self.databaseToUserCharset(fields.get("pykotaGroupName")[0]))
883                grouppquota = self.getGroupPQuota(group, printer)
884                groupsandquotas.append((group, grouppquota))
885        groupsandquotas.sort(lambda x, y : cmp(x[0].Name, y[0].Name))           
886        return groupsandquotas
887       
888    def addPrinter(self, printer) :
889        """Adds a printer to the quota storage, returns the old value if it already exists."""
890        oldentry = self.getPrinter(printer.Name)
891        if oldentry.Exists :
892            return oldentry # we return the existing entry
893        printername = self.userCharsetToDatabase(printer.Name)
894        fields = { self.info["printerrdn"] : printername,
895                   "objectClass" : ["pykotaObject", "pykotaPrinter"],
896                   "cn" : printername,
897                   "pykotaPrinterName" : printername,
898                   "pykotaPassThrough" : (printer.PassThrough and "t") or "f",
899                   "pykotaMaxJobSize" : str(printer.MaxJobSize or 0),
900                   "description" : self.userCharsetToDatabase(printer.Description or ""),
901                   "pykotaPricePerPage" : str(printer.PricePerPage or 0.0),
902                   "pykotaPricePerJob" : str(printer.PricePerJob or 0.0),
903                 } 
904        dn = "%s=%s,%s" % (self.info["printerrdn"], printername, self.info["printerbase"])
905        self.doAdd(dn, fields)
906        printer.isDirty = False
907        return None # the entry created doesn't need further modification
908       
909    def addUser(self, user) :       
910        """Adds a user to the quota storage, returns the old value if it already exists."""
911        oldentry = self.getUser(user.Name)
912        if oldentry.Exists :
913            return oldentry # we return the existing entry
914        uname = self.userCharsetToDatabase(user.Name)
915        newfields = {
916                       "pykotaUserName" : uname,
917                       "pykotaLimitBy" : (user.LimitBy or "quota"),
918                       "pykotaOverCharge" : str(user.OverCharge),
919                       "description" : self.userCharsetToDatabase(user.Description or ""),
920                       self.info["usermail"] : user.Email or "",
921                    }   
922                       
923        mustadd = 1
924        if self.info["newuser"].lower() != 'below' :
925            try :
926                (where, action) = [s.strip() for s in self.info["newuser"].split(",")]
927            except ValueError :
928                (where, action) = (self.info["newuser"].strip(), "fail")
929            result = self.doSearch("(&(objectClass=%s)(%s=%s))" % \
930                                      (where, self.info["userrdn"], uname), \
931                                      None, \
932                                      base=self.info["userbase"])
933            if result :
934                (dn, fields) = result[0]
935                oc = fields.get("objectClass", fields.get("objectclass", []))
936                oc.extend(["pykotaAccount", "pykotaAccountBalance"])
937                fields.update(newfields)
938                fields.update({ "pykotaBalance" : str(user.AccountBalance or 0.0),
939                                "pykotaLifeTimePaid" : str(user.LifeTimePaid or 0.0), })   
940                self.doModify(dn, fields)
941                mustadd = 0
942            else :
943                message = _("Unable to find an existing objectClass %s entry with %s=%s to attach pykotaAccount objectClass") % (where, self.info["userrdn"], user.Name)
944                if action.lower() == "warn" :   
945                    self.tool.printInfo(_("%s. A new entry will be created instead.") % message, "warn")
946                else : # 'fail' or incorrect setting
947                    raise PyKotaStorageError, "%s. Action aborted. Please check your configuration." % message
948               
949        if mustadd :
950            if self.info["userbase"] == self.info["balancebase"] :           
951                fields = { self.info["userrdn"] : uname,
952                           "objectClass" : ["pykotaObject", "pykotaAccount", "pykotaAccountBalance"],
953                           "cn" : uname,
954                           "pykotaBalance" : str(user.AccountBalance or 0.0),
955                           "pykotaLifeTimePaid" : str(user.LifeTimePaid or 0.0), 
956                         } 
957            else :             
958                fields = { self.info["userrdn"] : uname,
959                           "objectClass" : ["pykotaObject", "pykotaAccount"],
960                           "cn" : uname,
961                         } 
962            fields.update(newfields)         
963            dn = "%s=%s,%s" % (self.info["userrdn"], uname, self.info["userbase"])
964            self.doAdd(dn, fields)
965            if self.info["userbase"] != self.info["balancebase"] :           
966                fields = { self.info["balancerdn"] : uname,
967                           "objectClass" : ["pykotaObject", "pykotaAccountBalance"],
968                           "cn" : uname,
969                           "pykotaBalance" : str(user.AccountBalance or 0.0),
970                           "pykotaLifeTimePaid" : str(user.LifeTimePaid or 0.0), 
971                         } 
972                dn = "%s=%s,%s" % (self.info["balancerdn"], uname, self.info["balancebase"])
973                self.doAdd(dn, fields)
974        user.idbalance = dn
975        if user.PaymentsBacklog :
976            for (value, comment) in user.PaymentsBacklog :
977                self.writeNewPayment(user, value, comment)
978            user.PaymentsBacklog = []
979        user.isDirty = False
980        return None # the entry created doesn't need further modification
981       
982    def addGroup(self, group) :       
983        """Adds a group to the quota storage, returns the old value if it already exists."""
984        oldentry = self.getGroup(group.Name)
985        if oldentry.Exists :
986            return oldentry # we return the existing entry
987        gname = self.userCharsetToDatabase(group.Name)
988        newfields = { 
989                      "pykotaGroupName" : gname,
990                      "pykotaLimitBy" : (group.LimitBy or "quota"),
991                      "description" : self.userCharsetToDatabase(group.Description or "")
992                    } 
993        mustadd = 1
994        if self.info["newgroup"].lower() != 'below' :
995            try :
996                (where, action) = [s.strip() for s in self.info["newgroup"].split(",")]
997            except ValueError :
998                (where, action) = (self.info["newgroup"].strip(), "fail")
999            result = self.doSearch("(&(objectClass=%s)(%s=%s))" % \
1000                                      (where, self.info["grouprdn"], gname), \
1001                                      None, \
1002                                      base=self.info["groupbase"])
1003            if result :
1004                (dn, fields) = result[0]
1005                oc = fields.get("objectClass", fields.get("objectclass", []))
1006                oc.extend(["pykotaGroup"])
1007                fields.update(newfields)
1008                self.doModify(dn, fields)
1009                mustadd = 0
1010            else :
1011                message = _("Unable to find an existing entry to attach pykotaGroup objectclass %s") % group.Name
1012                if action.lower() == "warn" :   
1013                    self.tool.printInfo("%s. A new entry will be created instead." % message, "warn")
1014                else : # 'fail' or incorrect setting
1015                    raise PyKotaStorageError, "%s. Action aborted. Please check your configuration." % message
1016               
1017        if mustadd :
1018            fields = { self.info["grouprdn"] : gname,
1019                       "objectClass" : ["pykotaObject", "pykotaGroup"],
1020                       "cn" : gname,
1021                     } 
1022            fields.update(newfields)         
1023            dn = "%s=%s,%s" % (self.info["grouprdn"], gname, self.info["groupbase"])
1024            self.doAdd(dn, fields)
1025        group.isDirty = False
1026        return None # the entry created doesn't need further modification
1027       
1028    def addUserToGroup(self, user, group) :   
1029        """Adds an user to a group."""
1030        if user.Name not in [u.Name for u in self.getGroupMembers(group)] :
1031            result = self.doSearch("objectClass=pykotaGroup", None, base=group.ident, scope=ldap.SCOPE_BASE)   
1032            if result :
1033                fields = result[0][1]
1034                if not fields.has_key(self.info["groupmembers"]) :
1035                    fields[self.info["groupmembers"]] = []
1036                fields[self.info["groupmembers"]].append(self.userCharsetToDatabase(user.Name))
1037                self.doModify(group.ident, fields)
1038                group.Members.append(user)
1039               
1040    def delUserFromGroup(self, user, group) :   
1041        """Removes an user from a group."""
1042        if user.Name in [u.Name for u in self.getGroupMembers(group)] :
1043            result = self.doSearch("objectClass=pykotaGroup", None, base=group.ident, scope=ldap.SCOPE_BASE)
1044            if result :
1045                fields = result[0][1]
1046                if not fields.has_key(self.info["groupmembers"]) :
1047                    fields[self.info["groupmembers"]] = []
1048                try :   
1049                    fields[self.info["groupmembers"]].remove(self.userCharsetToDatabase(user.Name))
1050                except ValueError :
1051                    pass # TODO : Strange, shouldn't it be there ?
1052                else :
1053                    self.doModify(group.ident, fields)
1054                    group.Members.remove(user)
1055               
1056    def addUserPQuota(self, upq) :
1057        """Initializes a user print quota on a printer."""
1058        # first check if an entry already exists
1059        oldentry = self.getUserPQuota(upq.User, upq.Printer)
1060        if oldentry.Exists :
1061            return oldentry # we return the existing entry
1062        uuid = self.genUUID()
1063        uname = self.userCharsetToDatabase(upq.User.Name)
1064        pname = self.userCharsetToDatabase(upq.Printer.Name)
1065        fields = { "cn" : uuid,
1066                   "objectClass" : ["pykotaObject", "pykotaUserPQuota"],
1067                   "pykotaUserName" : uname,
1068                   "pykotaPrinterName" : pname,
1069                   "pykotaSoftLimit" : str(upq.SoftLimit),
1070                   "pykotaHardLimit" : str(upq.HardLimit),
1071                   "pykotaDateLimit" : str(upq.DateLimit),
1072                   "pykotaPageCounter" : str(upq.PageCounter or 0),
1073                   "pykotaLifePageCounter" : str(upq.LifePageCounter or 0),
1074                   "pykotaWarnCount" : str(upq.WarnCount or 0),
1075                   "pykotaMaxJobSize" : str(upq.MaxJobSize or 0),
1076                 } 
1077        if self.info["userquotabase"].lower() == "user" :
1078            dn = "cn=%s,%s" % (uuid, upq.User.ident)
1079        else :   
1080            dn = "cn=%s,%s" % (uuid, self.info["userquotabase"])
1081        self.doAdd(dn, fields)
1082        upq.isDirty = False
1083        return None # the entry created doesn't need further modification
1084       
1085    def addGroupPQuota(self, gpq) :
1086        """Initializes a group print quota on a printer."""
1087        oldentry = self.getGroupPQuota(gpq.Group, gpq.Printer)
1088        if oldentry.Exists :
1089            return oldentry # we return the existing entry
1090        uuid = self.genUUID()
1091        gname = self.userCharsetToDatabase(gpq.Group.Name)
1092        pname = self.userCharsetToDatabase(gpq.Printer.Name)
1093        fields = { "cn" : uuid,
1094                   "objectClass" : ["pykotaObject", "pykotaGroupPQuota"],
1095                   "pykotaGroupName" : gname,
1096                   "pykotaPrinterName" : pname,
1097                   "pykotaDateLimit" : "None",
1098                 } 
1099        if self.info["groupquotabase"].lower() == "group" :
1100            dn = "cn=%s,%s" % (uuid, gpq.Group.ident)
1101        else :   
1102            dn = "cn=%s,%s" % (uuid, self.info["groupquotabase"])
1103        self.doAdd(dn, fields)
1104        gpq.isDirty = False
1105        return None # the entry created doesn't need further modification
1106       
1107    def savePrinter(self, printer) :   
1108        """Saves the printer to the database in a single operation."""
1109        fields = {
1110                   "pykotaPassThrough" : (printer.PassThrough and "t") or "f",
1111                   "pykotaMaxJobSize" : str(printer.MaxJobSize or 0),
1112                   "description" : self.userCharsetToDatabase(printer.Description or ""),
1113                   "pykotaPricePerPage" : str(printer.PricePerPage or 0.0),
1114                   "pykotaPricePerJob" : str(printer.PricePerJob or 0.0),
1115                 }
1116        self.doModify(printer.ident, fields)
1117       
1118    def saveUser(self, user) :
1119        """Saves the user to the database in a single operation."""
1120        newfields = {
1121                       "pykotaLimitBy" : (user.LimitBy or "quota"),
1122                       "pykotaOverCharge" : str(user.OverCharge),
1123                       "description" : self.userCharsetToDatabase(user.Description or ""), 
1124                       self.info["usermail"] : user.Email or "",
1125                    }   
1126        self.doModify(user.ident, newfields)
1127       
1128        newfields = { "pykotaBalance" : str(user.AccountBalance or 0.0),
1129                      "pykotaLifeTimePaid" : str(user.LifeTimePaid or 0.0), 
1130                    }
1131        self.doModify(user.idbalance, newfields)
1132       
1133    def saveGroup(self, group) :
1134        """Saves the group to the database in a single operation."""
1135        newfields = {
1136                       "pykotaLimitBy" : (group.LimitBy or "quota"),
1137                       "description" : self.userCharsetToDatabase(group.Description or ""), 
1138                    }   
1139        self.doModify(group.ident, newfields)
1140       
1141    def writeUserPQuotaDateLimit(self, userpquota, datelimit) :   
1142        """Sets the date limit permanently for a user print quota."""
1143        fields = {
1144                   "pykotaDateLimit" : str(datelimit),
1145                 }
1146        return self.doModify(userpquota.ident, fields)
1147           
1148    def writeGroupPQuotaDateLimit(self, grouppquota, datelimit) :   
1149        """Sets the date limit permanently for a group print quota."""
1150        fields = {
1151                   "pykotaDateLimit" : str(datelimit),
1152                 }
1153        return self.doModify(grouppquota.ident, fields)
1154       
1155    def increaseUserPQuotaPagesCounters(self, userpquota, nbpages) :   
1156        """Increase page counters for a user print quota."""
1157        fields = {
1158                   "pykotaPageCounter" : { "operator" : "+", "value" : nbpages, "convert" : int },
1159                   "pykotaLifePageCounter" : { "operator" : "+", "value" : nbpages, "convert" : int },
1160                 }
1161        return self.doModify(userpquota.ident, fields)         
1162       
1163    def decreaseUserAccountBalance(self, user, amount) :   
1164        """Decreases user's account balance from an amount."""
1165        fields = {
1166                   "pykotaBalance" : { "operator" : "-", "value" : amount, "convert" : float },
1167                 }
1168        return self.doModify(user.idbalance, fields, flushcache=1)         
1169       
1170    def writeNewPayment(self, user, amount, comment="") :
1171        """Adds a new payment to the payments history."""
1172        payments = []
1173        for payment in user.Payments :
1174            payments.append("%s # %s # %s" % (payment[0], str(payment[1]), base64.encodestring(self.userCharsetToDatabase(payment[2])).strip()))
1175        payments.append("%s # %s # %s" % (str(DateTime.now()), str(amount), base64.encodestring(self.userCharsetToDatabase(comment)).strip()))
1176        fields = {
1177                   "pykotaPayments" : payments,
1178                 }
1179        return self.doModify(user.idbalance, fields)         
1180       
1181    def writeLastJobSize(self, lastjob, jobsize, jobprice) :       
1182        """Sets the last job's size permanently."""
1183        fields = {
1184                   "pykotaJobSize" : str(jobsize),
1185                   "pykotaJobPrice" : str(jobprice),
1186                 }
1187        self.doModify(lastjob.ident, fields)         
1188       
1189    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, jobpages=None, jobbilling=None, precomputedsize=None, precomputedprice=None) :
1190        """Adds a job in a printer's history."""
1191        uname = self.userCharsetToDatabase(user.Name)
1192        pname = self.userCharsetToDatabase(printer.Name)
1193        if (not self.disablehistory) or (not printer.LastJob.Exists) :
1194            uuid = self.genUUID()
1195            dn = "cn=%s,%s" % (uuid, self.info["jobbase"])
1196        else :   
1197            uuid = printer.LastJob.ident[3:].split(",")[0]
1198            dn = printer.LastJob.ident
1199        if self.privacy :   
1200            # For legal reasons, we want to hide the title, filename and options
1201            title = filename = options = "hidden"
1202        fields = {
1203                   "objectClass" : ["pykotaObject", "pykotaJob"],
1204                   "cn" : uuid,
1205                   "pykotaUserName" : uname,
1206                   "pykotaPrinterName" : pname,
1207                   "pykotaJobId" : jobid,
1208                   "pykotaPrinterPageCounter" : str(pagecounter),
1209                   "pykotaAction" : action,
1210                   "pykotaFileName" : ((filename is None) and "None") or self.userCharsetToDatabase(filename), 
1211                   "pykotaTitle" : ((title is None) and "None") or self.userCharsetToDatabase(title), 
1212                   "pykotaCopies" : str(copies), 
1213                   "pykotaOptions" : ((options is None) and "None") or self.userCharsetToDatabase(options), 
1214                   "pykotaHostName" : str(clienthost), 
1215                   "pykotaJobSizeBytes" : str(jobsizebytes),
1216                   "pykotaMD5Sum" : str(jobmd5sum),
1217                   "pykotaPages" : jobpages,            # don't add this attribute if it is not set, so no string conversion
1218                   "pykotaBillingCode" : self.userCharsetToDatabase(jobbilling), # don't add this attribute if it is not set, so no string conversion
1219                   "pykotaPrecomputedJobSize" : str(precomputedsize),
1220                   "pykotaPrecomputedJobPrice" : str(precomputedprice),
1221                 }
1222        if (not self.disablehistory) or (not printer.LastJob.Exists) :
1223            if jobsize is not None :         
1224                fields.update({ "pykotaJobSize" : str(jobsize), "pykotaJobPrice" : str(jobprice) })
1225            self.doAdd(dn, fields)
1226        else :   
1227            # here we explicitly want to reset jobsize to 'None' if needed
1228            fields.update({ "pykotaJobSize" : str(jobsize), "pykotaJobPrice" : str(jobprice) })
1229            self.doModify(dn, fields)
1230           
1231        if printer.LastJob.Exists :
1232            fields = {
1233                       "pykotaLastJobIdent" : uuid,
1234                     }
1235            self.doModify(printer.LastJob.lastjobident, fields)         
1236        else :   
1237            lastjuuid = self.genUUID()
1238            lastjdn = "cn=%s,%s" % (lastjuuid, self.info["lastjobbase"])
1239            fields = {
1240                       "objectClass" : ["pykotaObject", "pykotaLastJob"],
1241                       "cn" : lastjuuid,
1242                       "pykotaPrinterName" : pname,
1243                       "pykotaLastJobIdent" : uuid,
1244                     } 
1245            self.doAdd(lastjdn, fields)         
1246           
1247    def saveUserPQuota(self, userpquota) :
1248        """Saves an user print quota entry."""
1249        fields = { 
1250                   "pykotaSoftLimit" : str(userpquota.SoftLimit),
1251                   "pykotaHardLimit" : str(userpquota.HardLimit),
1252                   "pykotaDateLimit" : str(userpquota.DateLimit),
1253                   "pykotaWarnCount" : str(userpquota.WarnCount or 0),
1254                   "pykotaPageCounter" : str(userpquota.PageCounter or 0),
1255                   "pykotaLifePageCounter" : str(userpquota.LifePageCounter or 0),
1256                   "pykotaMaxJobSize" : str(userpquota.MaxJobSize or 0),
1257                 }
1258        self.doModify(userpquota.ident, fields)
1259       
1260    def writeUserPQuotaWarnCount(self, userpquota, warncount) :
1261        """Sets the warn counter value for a user quota."""
1262        fields = { 
1263                   "pykotaWarnCount" : str(warncount or 0),
1264                 }
1265        self.doModify(userpquota.ident, fields)
1266       
1267    def increaseUserPQuotaWarnCount(self, userpquota) :
1268        """Increases the warn counter value for a user quota."""
1269        fields = {
1270                   "pykotaWarnCount" : { "operator" : "+", "value" : 1, "convert" : int },
1271                 }
1272        return self.doModify(userpquota.ident, fields)         
1273       
1274    def saveGroupPQuota(self, grouppquota) :
1275        """Saves a group print quota entry."""
1276        fields = { 
1277                   "pykotaSoftLimit" : str(grouppquota.SoftLimit),
1278                   "pykotaHardLimit" : str(grouppquota.HardLimit),
1279                   "pykotaDateLimit" : str(grouppquota.DateLimit),
1280                   "pykotaMaxJobSize" : str(grouppquota.MaxJobSize or 0),
1281                 }
1282        self.doModify(grouppquota.ident, fields)
1283           
1284    def writePrinterToGroup(self, pgroup, printer) :
1285        """Puts a printer into a printer group."""
1286        if printer.ident not in pgroup.uniqueMember :
1287            pgroup.uniqueMember.append(printer.ident)
1288            fields = {
1289                       "uniqueMember" : pgroup.uniqueMember
1290                     } 
1291            self.doModify(pgroup.ident, fields)         
1292           
1293    def removePrinterFromGroup(self, pgroup, printer) :
1294        """Removes a printer from a printer group."""
1295        try :
1296            pgroup.uniqueMember.remove(printer.ident)
1297        except ValueError :   
1298            pass
1299        else :   
1300            fields = {
1301                       "uniqueMember" : pgroup.uniqueMember,
1302                     } 
1303            self.doModify(pgroup.ident, fields)         
1304           
1305    def retrieveHistory(self, user=None, printer=None, hostname=None, billingcode=None, limit=100, start=None, end=None) :
1306        """Retrieves all print jobs for user on printer (or all) between start and end date, limited to first 100 results."""
1307        precond = "(objectClass=pykotaJob)"
1308        where = []
1309        if user is not None :
1310            where.append("(pykotaUserName=%s)" % self.userCharsetToDatabase(user.Name))
1311        if printer is not None :
1312            where.append("(pykotaPrinterName=%s)" % self.userCharsetToDatabase(printer.Name))
1313        if hostname is not None :
1314            where.append("(pykotaHostName=%s)" % hostname)
1315        if billingcode is not None :
1316            where.append("(pykotaBillingCode=%s)" % self.userCharsetToDatabase(billingcode))
1317        if where :   
1318            where = "(&%s)" % "".join([precond] + where)
1319        else :   
1320            where = precond
1321        jobs = []   
1322        result = self.doSearch(where, fields=[ "pykotaJobSizeBytes", 
1323                                               "pykotaHostName", 
1324                                               "pykotaUserName", 
1325                                               "pykotaPrinterName", 
1326                                               "pykotaJobId", 
1327                                               "pykotaPrinterPageCounter", 
1328                                               "pykotaAction", 
1329                                               "pykotaJobSize", 
1330                                               "pykotaJobPrice", 
1331                                               "pykotaFileName", 
1332                                               "pykotaTitle", 
1333                                               "pykotaCopies", 
1334                                               "pykotaOptions", 
1335                                               "pykotaBillingCode", 
1336                                               "pykotaPages", 
1337                                               "pykotaMD5Sum", 
1338                                               "pykotaPrecomputedJobSize",
1339                                               "pykotaPrecomputedJobPrice",
1340                                               "createTimestamp" ], 
1341                                      base=self.info["jobbase"])
1342        if result :
1343            for (ident, fields) in result :
1344                job = StorageJob(self)
1345                job.ident = ident
1346                job.JobId = fields.get("pykotaJobId")[0]
1347                job.PrinterPageCounter = int(fields.get("pykotaPrinterPageCounter", [0])[0] or 0)
1348                try :
1349                    job.JobSize = int(fields.get("pykotaJobSize", [0])[0])
1350                except ValueError :   
1351                    job.JobSize = None
1352                try :   
1353                    job.JobPrice = float(fields.get("pykotaJobPrice", [0.0])[0])
1354                except ValueError :
1355                    job.JobPrice = None
1356                job.JobAction = fields.get("pykotaAction", [""])[0]
1357                job.JobFileName = self.databaseToUserCharset(fields.get("pykotaFileName", [""])[0]) 
1358                job.JobTitle = self.databaseToUserCharset(fields.get("pykotaTitle", [""])[0]) 
1359                job.JobCopies = int(fields.get("pykotaCopies", [0])[0])
1360                job.JobOptions = self.databaseToUserCharset(fields.get("pykotaOptions", [""])[0]) 
1361                job.JobHostName = fields.get("pykotaHostName", [""])[0]
1362                job.JobSizeBytes = fields.get("pykotaJobSizeBytes", [0L])[0]
1363                job.JobBillingCode = self.databaseToUserCharset(fields.get("pykotaBillingCode", [None])[0])
1364                job.JobMD5Sum = fields.get("pykotaMD5Sum", [None])[0]
1365                job.JobPages = fields.get("pykotaPages", [""])[0]
1366                try :
1367                    job.PrecomputedJobSize = int(fields.get("pykotaPrecomputedJobSize", [0])[0])
1368                except ValueError :   
1369                    job.PrecomputedJobSize = None
1370                try :   
1371                    job.PrecomputedJobPrice = float(fields.get("pykotaPrecomputedJobPrice", [0.0])[0])
1372                except ValueError :
1373                    job.PrecomputedJobPrice = None
1374                if job.JobTitle == job.JobFileName == job.JobOptions == "hidden" :
1375                    (job.JobTitle, job.JobFileName, job.JobOptions) = (_("Hidden because of privacy concerns"),) * 3
1376                date = fields.get("createTimestamp", ["19700101000000Z"])[0] # It's in UTC !
1377                mxtime = DateTime.strptime(date[:14], "%Y%m%d%H%M%S").localtime()
1378                job.JobDate = mxtime.strftime("%Y-%m-%d %H:%M:%S")
1379                if ((start is None) and (end is None)) or \
1380                   ((start is None) and (job.JobDate <= end)) or \
1381                   ((end is None) and (job.JobDate >= start)) or \
1382                   ((job.JobDate >= start) and (job.JobDate <= end)) :
1383                    job.UserName = self.databaseToUserCharset(fields.get("pykotaUserName")[0])
1384                    job.PrinterName = self.databaseToUserCharset(fields.get("pykotaPrinterName")[0])
1385                    job.Exists = True
1386                    jobs.append(job)
1387            jobs.sort(lambda x, y : cmp(y.JobDate, x.JobDate))       
1388            if limit :   
1389                jobs = jobs[:int(limit)]
1390        return jobs
1391       
1392    def deleteUser(self, user) :   
1393        """Completely deletes an user from the Quota Storage."""
1394        uname = self.userCharsetToDatabase(user.Name)
1395        todelete = []   
1396        result = self.doSearch("(&(objectClass=pykotaJob)(pykotaUserName=%s))" % uname, base=self.info["jobbase"])
1397        for (ident, fields) in result :
1398            todelete.append(ident)
1399        if self.info["userquotabase"].lower() == "user" :
1400            base = self.info["userbase"]
1401        else :
1402            base = self.info["userquotabase"]
1403        result = self.doSearch("(&(objectClass=pykotaUserPQuota)(pykotaUserName=%s))" % uname, \
1404                                  ["pykotaPrinterName", "pykotaUserName"], \
1405                                  base=base)
1406        for (ident, fields) in result :
1407            # ensure the user print quota entry will be deleted
1408            todelete.append(ident)
1409           
1410            # if last job of current printer was printed by the user
1411            # to delete, we also need to delete the printer's last job entry.
1412            printer = self.getPrinter(self.databaseToUserCharset(fields["pykotaPrinterName"][0]))
1413            if printer.LastJob.UserName == user.Name :
1414                todelete.append(printer.LastJob.lastjobident)
1415           
1416        for ident in todelete :   
1417            self.doDelete(ident)
1418           
1419        result = self.doSearch("objectClass=pykotaAccount", None, base=user.ident, scope=ldap.SCOPE_BASE)   
1420        if result :
1421            fields = result[0][1]
1422            for k in fields.keys() :
1423                if k.startswith("pykota") :
1424                    del fields[k]
1425                elif k.lower() == "objectclass" :   
1426                    todelete = []
1427                    for i in range(len(fields[k])) :
1428                        if fields[k][i].startswith("pykota") : 
1429                            todelete.append(i)
1430                    todelete.sort()       
1431                    todelete.reverse()
1432                    for i in todelete :
1433                        del fields[k][i]
1434            if fields.get("objectClass") or fields.get("objectclass") :
1435                self.doModify(user.ident, fields, ignoreold=0)       
1436            else :   
1437                self.doDelete(user.ident)
1438        result = self.doSearch("(&(objectClass=pykotaAccountBalance)(pykotaUserName=%s))" % \
1439                                   uname, \
1440                                   ["pykotaUserName"], \
1441                                   base=self.info["balancebase"])
1442        for (ident, fields) in result :
1443            self.doDelete(ident)
1444       
1445    def deleteGroup(self, group) :   
1446        """Completely deletes a group from the Quota Storage."""
1447        gname = self.userCharsetToDatabase(group.Name)
1448        if self.info["groupquotabase"].lower() == "group" :
1449            base = self.info["groupbase"]
1450        else :
1451            base = self.info["groupquotabase"]
1452        result = self.doSearch("(&(objectClass=pykotaGroupPQuota)(pykotaGroupName=%s))" % \
1453                                  gname, \
1454                                  ["pykotaGroupName"], \
1455                                  base=base)
1456        for (ident, fields) in result :
1457            self.doDelete(ident)
1458        result = self.doSearch("objectClass=pykotaGroup", None, base=group.ident, scope=ldap.SCOPE_BASE)   
1459        if result :
1460            fields = result[0][1]
1461            for k in fields.keys() :
1462                if k.startswith("pykota") :
1463                    del fields[k]
1464                elif k.lower() == "objectclass" :   
1465                    todelete = []
1466                    for i in range(len(fields[k])) :
1467                        if fields[k][i].startswith("pykota") : 
1468                            todelete.append(i)
1469                    todelete.sort()       
1470                    todelete.reverse()
1471                    for i in todelete :
1472                        del fields[k][i]
1473            if fields.get("objectClass") or fields.get("objectclass") :
1474                self.doModify(group.ident, fields, ignoreold=0)       
1475            else :   
1476                self.doDelete(group.ident)
1477               
1478    def deleteManyBillingCodes(self, billingcodes) :
1479        """Deletes many billing codes."""
1480        for bcode in billingcodes :
1481            bcode.delete()
1482       
1483    def deleteManyUsers(self, users) :       
1484        """Deletes many users."""
1485        for user in users :
1486            user.delete()
1487           
1488    def deleteManyGroups(self, groups) :       
1489        """Deletes many groups."""
1490        for group in groups :
1491            group.delete()
1492       
1493    def deleteManyPrinters(self, printers) :       
1494        """Deletes many printers."""
1495        for printer in printers :
1496            printer.delete()
1497       
1498    def deleteManyUserPQuotas(self, printers, users) :       
1499        """Deletes many user print quota entries."""
1500        # TODO : grab all with a single (possibly VERY huge) filter if possible (might depend on the LDAP server !)
1501        for printer in printers :
1502            for user in users :
1503                upq = self.getUserPQuota(user, printer)
1504                if upq.Exists :
1505                    upq.delete()
1506           
1507    def deleteManyGroupPQuotas(self, printers, groups) :
1508        """Deletes many group print quota entries."""
1509        # TODO : grab all with a single (possibly VERY huge) filter if possible (might depend on the LDAP server !)
1510        for printer in printers :
1511            for group in groups :
1512                gpq = self.getGroupPQuota(group, printer)
1513                if gpq.Exists :
1514                    gpq.delete()
1515               
1516    def deleteUserPQuota(self, upquota) :   
1517        """Completely deletes an user print quota entry from the database."""
1518        uname = self.userCharsetToDatabase(upquota.User.Name)
1519        pname = self.userCharsetToDatabase(upquota.Printer.Name)
1520        result = self.doSearch("(&(objectClass=pykotaJob)(pykotaUserName=%s)(pykotaPrinterName=%s))" \
1521                                   % (uname, pname), \
1522                                   base=self.info["jobbase"])
1523        for (ident, fields) in result :
1524            self.doDelete(ident)
1525        if upquota.Printer.LastJob.UserName == upquota.User.Name :
1526            self.doDelete(upquota.Printer.LastJob.lastjobident)
1527        self.doDelete(upquota.ident)
1528       
1529    def deleteGroupPQuota(self, gpquota) :   
1530        """Completely deletes a group print quota entry from the database."""
1531        self.doDelete(gpquota.ident)
1532               
1533    def deletePrinter(self, printer) :   
1534        """Completely deletes a printer from the Quota Storage."""
1535        pname = self.userCharsetToDatabase(printer.Name)
1536        result = self.doSearch("(&(objectClass=pykotaLastJob)(pykotaPrinterName=%s))" % pname, base=self.info["lastjobbase"])
1537        for (ident, fields) in result :
1538            self.doDelete(ident)
1539        result = self.doSearch("(&(objectClass=pykotaJob)(pykotaPrinterName=%s))" % pname, base=self.info["jobbase"])
1540        for (ident, fields) in result :
1541            self.doDelete(ident)
1542        if self.info["groupquotabase"].lower() == "group" :
1543            base = self.info["groupbase"]
1544        else :
1545            base = self.info["groupquotabase"]
1546        result = self.doSearch("(&(objectClass=pykotaGroupPQuota)(pykotaPrinterName=%s))" % pname, base=base)
1547        for (ident, fields) in result :
1548            self.doDelete(ident)
1549        if self.info["userquotabase"].lower() == "user" :
1550            base = self.info["userbase"]
1551        else :
1552            base = self.info["userquotabase"]
1553        result = self.doSearch("(&(objectClass=pykotaUserPQuota)(pykotaPrinterName=%s))" % pname, base=base)
1554        for (ident, fields) in result :
1555            self.doDelete(ident)
1556        for parent in self.getParentPrinters(printer) : 
1557            try :
1558                parent.uniqueMember.remove(printer.ident)
1559            except ValueError :   
1560                pass
1561            else :   
1562                fields = {
1563                           "uniqueMember" : parent.uniqueMember,
1564                         } 
1565                self.doModify(parent.ident, fields)         
1566        self.doDelete(printer.ident)   
1567       
1568    def deleteBillingCode(self, code) :
1569        """Deletes a billing code from the Quota Storage (no entries are deleted from the history)"""
1570        self.doDelete(code.ident)
1571       
1572    def extractPrinters(self, extractonly={}) :
1573        """Extracts all printer records."""
1574        pname = extractonly.get("printername")
1575        entries = [p for p in [self.getPrinter(name) for name in self.getAllPrintersNames(pname)] if p.Exists]
1576        if entries :
1577            result = [ ("dn", "printername", "priceperpage", "priceperjob", "description", "maxjobsize", "passthrough") ]
1578            for entry in entries :
1579                if entry.PassThrough in (1, "1", "t", "true", "T", "TRUE", "True") :
1580                    passthrough = "t"
1581                else :   
1582                    passthrough = "f"
1583                result.append((entry.ident, entry.Name, entry.PricePerPage, entry.PricePerJob, entry.Description, entry.MaxJobSize, passthrough))
1584            return result 
1585       
1586    def extractUsers(self, extractonly={}) :
1587        """Extracts all user records."""
1588        uname = extractonly.get("username")
1589        entries = [u for u in [self.getUser(name) for name in self.getAllUsersNames(uname)] if u.Exists]
1590        if entries :
1591            result = [ ("dn", "username", "balance", "lifetimepaid", "limitby", "email", "description") ]
1592            for entry in entries :
1593                result.append((entry.ident, entry.Name, entry.AccountBalance, entry.LifeTimePaid, entry.LimitBy, entry.Email, entry.Description))
1594            return result 
1595       
1596    def extractBillingcodes(self, extractonly={}) :
1597        """Extracts all billing codes records."""
1598        billingcode = extractonly.get("billingcode")
1599        entries = [b for b in [self.getBillingCode(label) for label in self.getAllBillingCodes(billingcode)] if b.Exists]
1600        if entries :
1601            result = [ ("dn", "billingcode", "balance", "pagecounter", "description") ]
1602            for entry in entries :
1603                result.append((entry.ident, entry.BillingCode, entry.Balance, entry.PageCounter, entry.Description))
1604            return result 
1605       
1606    def extractGroups(self, extractonly={}) :
1607        """Extracts all group records."""
1608        gname = extractonly.get("groupname")
1609        entries = [g for g in [self.getGroup(name) for name in self.getAllGroupsNames(gname)] if g.Exists]
1610        if entries :
1611            result = [ ("dn", "groupname", "limitby", "balance", "lifetimepaid", "description") ]
1612            for entry in entries :
1613                result.append((entry.ident, entry.Name, entry.LimitBy, entry.AccountBalance, entry.LifeTimePaid, entry.Description))
1614            return result 
1615       
1616    def extractPayments(self, extractonly={}) :
1617        """Extracts all payment records."""
1618        uname = extractonly.get("username")
1619        entries = [u for u in [self.getUser(name) for name in self.getAllUsersNames(uname)] if u.Exists]
1620        if entries :
1621            result = [ ("username", "amount", "date", "description") ]
1622            for entry in entries :
1623                for (date, amount, description) in entry.Payments :
1624                    result.append((entry.Name, amount, date, description))
1625            return result       
1626       
1627    def extractUpquotas(self, extractonly={}) :
1628        """Extracts all userpquota records."""
1629        pname = extractonly.get("printername")
1630        entries = [p for p in [self.getPrinter(name) for name in self.getAllPrintersNames(pname)] if p.Exists]
1631        if entries :
1632            result = [ ("username", "printername", "dn", "userdn", "printerdn", "lifepagecounter", "pagecounter", "softlimit", "hardlimit", "datelimit") ]
1633            uname = extractonly.get("username")
1634            for entry in entries :
1635                for (user, userpquota) in self.getPrinterUsersAndQuotas(entry, names=[uname or "*"]) :
1636                    result.append((user.Name, entry.Name, userpquota.ident, user.ident, entry.ident, userpquota.LifePageCounter, userpquota.PageCounter, userpquota.SoftLimit, userpquota.HardLimit, userpquota.DateLimit))
1637            return result
1638       
1639    def extractGpquotas(self, extractonly={}) :
1640        """Extracts all grouppquota records."""
1641        pname = extractonly.get("printername")
1642        entries = [p for p in [self.getPrinter(name) for name in self.getAllPrintersNames(pname)] if p.Exists]
1643        if entries :
1644            result = [ ("groupname", "printername", "dn", "groupdn", "printerdn", "lifepagecounter", "pagecounter", "softlimit", "hardlimit", "datelimit") ]
1645            gname = extractonly.get("groupname")
1646            for entry in entries :
1647                for (group, grouppquota) in self.getPrinterGroupsAndQuotas(entry, names=[gname or "*"]) :
1648                    result.append((group.Name, entry.Name, grouppquota.ident, group.ident, entry.ident, grouppquota.LifePageCounter, grouppquota.PageCounter, grouppquota.SoftLimit, grouppquota.HardLimit, grouppquota.DateLimit))
1649            return result
1650       
1651    def extractUmembers(self, extractonly={}) :
1652        """Extracts all user groups members."""
1653        gname = extractonly.get("groupname")
1654        entries = [g for g in [self.getGroup(name) for name in self.getAllGroupsNames(gname)] if g.Exists]
1655        if entries :
1656            result = [ ("groupname", "username", "groupdn", "userdn") ]
1657            uname = extractonly.get("username")
1658            for entry in entries :
1659                for member in entry.Members :
1660                    if (uname is None) or (member.Name == uname) :
1661                        result.append((entry.Name, member.Name, entry.ident, member.ident))
1662            return result       
1663               
1664    def extractPmembers(self, extractonly={}) :
1665        """Extracts all printer groups members."""
1666        pname = extractonly.get("printername")
1667        entries = [p for p in [self.getPrinter(name) for name in self.getAllPrintersNames(pname)] if p.Exists]
1668        if entries :
1669            result = [ ("pgroupname", "printername", "pgroupdn", "printerdn") ]
1670            pgname = extractonly.get("pgroupname")
1671            for entry in entries :
1672                for parent in self.getParentPrinters(entry) :
1673                    if (pgname is None) or (parent.Name == pgname) :
1674                        result.append((parent.Name, entry.Name, parent.ident, entry.ident))
1675            return result       
1676       
1677    def extractHistory(self, extractonly={}) :
1678        """Extracts all jobhistory records."""
1679        uname = extractonly.get("username")
1680        if uname :
1681            user = self.getUser(uname)
1682        else :   
1683            user = None
1684        pname = extractonly.get("printername")
1685        if pname :
1686            printer = self.getPrinter(pname)
1687        else :   
1688            printer = None
1689        startdate = extractonly.get("start")
1690        enddate = extractonly.get("end")
1691        (startdate, enddate) = self.cleanDates(startdate, enddate)
1692        entries = self.retrieveHistory(user, printer, hostname=extractonly.get("hostname"), billingcode=extractonly.get("billingcode"), limit=None, start=startdate, end=enddate)
1693        if entries :
1694            result = [ ("username", "printername", "dn", "jobid", "pagecounter", "jobsize", "action", "jobdate", "filename", "title", "copies", "options", "jobprice", "hostname", "jobsizebytes", "md5sum", "pages", "billingcode", "precomputedjobsize", "precomputedjobprice") ] 
1695            for entry in entries :
1696                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, entry.JobMD5Sum, entry.JobPages, entry.JobBillingCode, entry.PrecomputedJobSize, entry.PrecomputedJobPrice)) 
1697            return result
1698           
1699    def getBillingCodeFromBackend(self, label) :
1700        """Extracts billing code information given its label : returns first matching billing code."""
1701        code = StorageBillingCode(self, label)
1702        ulabel = self.userCharsetToDatabase(label)
1703        result = self.doSearch("(&(objectClass=pykotaBilling)(pykotaBillingCode=%s))" % \
1704                                  ulabel, \
1705                                  ["pykotaBillingCode", "pykotaBalance", "pykotaPageCounter", "description"], \
1706                                  base=self.info["billingcodebase"])
1707        if result :
1708            fields = result[0][1]       # take only first matching code, ignore the rest
1709            code.ident = result[0][0]
1710            code.BillingCode = self.databaseToUserCharset(fields.get("pykotaBillingCode", [ulabel])[0])
1711            code.PageCounter = int(fields.get("pykotaPageCounter", [0])[0])
1712            code.Balance = float(fields.get("pykotaBalance", [0.0])[0])
1713            code.Description = self.databaseToUserCharset(fields.get("description", [""])[0]) 
1714            code.Exists = True
1715        return code   
1716       
1717    def addBillingCode(self, bcode) :
1718        """Adds a billing code to the quota storage, returns it."""
1719        oldentry = self.getBillingCode(bcode.BillingCode)
1720        if oldentry.Exists :
1721            return oldentry # we return the existing entry
1722        uuid = self.genUUID()
1723        dn = "cn=%s,%s" % (uuid, self.info["billingcodebase"])
1724        fields = { "objectClass" : ["pykotaObject", "pykotaBilling"],
1725                   "cn" : uuid,
1726                   "pykotaBillingCode" : self.userCharsetToDatabase(bcode.BillingCode),
1727                   "pykotaPageCounter" : str(bcode.PageCounter or 0),
1728                   "pykotaBalance" : str(bcode.Balance or 0.0),
1729                   "description" : self.userCharsetToDatabase(bcode.Description or ""), 
1730                 } 
1731        self.doAdd(dn, fields)
1732        bcode.isDirty = False
1733        return None # the entry created doesn't need further modification
1734       
1735    def saveBillingCode(self, bcode) :
1736        """Sets the new description for a billing code."""
1737        fields = {
1738                   "description" : self.userCharsetToDatabase(bcode.Description or ""), 
1739                   "pykotaPageCounter" : str(bcode.PageCounter or 0),
1740                   "pykotaBalance" : str(bcode.Balance or 0.0),
1741                 }
1742        self.doModify(bcode.ident, fields)
1743           
1744    def getMatchingBillingCodes(self, billingcodepattern) :
1745        """Returns the list of all billing codes which match a certain pattern."""
1746        codes = []
1747        result = self.doSearch("objectClass=pykotaBilling", \
1748                                ["pykotaBillingCode", "description", "pykotaPageCounter", "pykotaBalance"], \
1749                                base=self.info["billingcodebase"])
1750        if result :
1751            patterns = billingcodepattern.split(",")
1752            try :
1753                patdict = {}.fromkeys(patterns)
1754            except AttributeError :   
1755                # Python v2.2 or earlier
1756                patdict = {}
1757                for p in patterns :
1758                    patdict[p] = None
1759            for (codeid, fields) in result :
1760                codename = self.databaseToUserCharset(fields.get("pykotaBillingCode", [""])[0])
1761                if patdict.has_key(codename) or self.tool.matchString(codename, patterns) :
1762                    code = StorageBillingCode(self, codename)
1763                    code.ident = codeid
1764                    code.PageCounter = int(fields.get("pykotaPageCounter", [0])[0])
1765                    code.Balance = float(fields.get("pykotaBalance", [0.0])[0])
1766                    code.Description = self.databaseToUserCharset(fields.get("description", [""])[0]) 
1767                    code.Exists = True
1768                    codes.append(code)
1769                    self.cacheEntry("BILLINGCODES", code.BillingCode, code)
1770        return codes       
1771       
1772    def consumeBillingCode(self, bcode, pagecounter, balance) :
1773        """Consumes from a billing code."""
1774        fields = {
1775                   "pykotaBalance" : { "operator" : "-", "value" : balance, "convert" : float },
1776                   "pykotaPageCounter" : { "operator" : "+", "value" : pagecounter, "convert" : int },
1777                 }
1778        return self.doModify(bcode.ident, fields)         
1779
1780    def storageUserFromRecord(self, username, record) :
1781        """Returns a StorageUser instance from a database record."""
1782        user = StorageUser(self, username)
1783        user.Exists = True
1784        return user
1785       
1786    def storageGroupFromRecord(self, groupname, record) :
1787        """Returns a StorageGroup instance from a database record."""
1788        group = StorageGroup(self, groupname)
1789        group.Exists = True
1790        return group
1791       
1792    def storagePrinterFromRecord(self, printername, record) :
1793        """Returns a StoragePrinter instance from a database record."""
1794        printer = StoragePrinter(self, printername)
1795        printer.Exists = True
1796        return printer
1797       
1798    def setJobAttributesFromRecord(self, job, record) :   
1799        """Sets the attributes of a job from a database record."""
1800        job.Exists = True
1801       
1802    def storageJobFromRecord(self, record) :
1803        """Returns a StorageJob instance from a database record."""
1804        job = StorageJob(self)
1805        self.setJobAttributesFromRecord(job, record)
1806        return job
1807       
1808    def storageLastJobFromRecord(self, printer, record) :
1809        """Returns a StorageLastJob instance from a database record."""
1810        lastjob = StorageLastJob(self, printer)
1811        self.setJobAttributesFromRecord(lastjob, record)
1812        return lastjob
1813       
1814    def storageUserPQuotaFromRecord(self, user, printer, record) :
1815        """Returns a StorageUserPQuota instance from a database record."""
1816        userpquota = StorageUserPQuota(self, user, printer)
1817        userpquota.Exists = True
1818        return userpquota
1819       
1820    def storageGroupPQuotaFromRecord(self, group, printer, record) :
1821        """Returns a StorageGroupPQuota instance from a database record."""
1822        grouppquota = StorageGroupPQuota(self, group, printer)
1823        grouppquota.Exists = True
1824        return grouppquota
1825       
1826    def storageBillingCodeFromRecord(self, billingcode, record) :
1827        """Returns a StorageBillingCode instance from a database record."""
1828        code = StorageBillingCode(self, billingcode)
1829        code.Exists = True
1830        return code
Note: See TracBrowser for help on using the browser.