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

Revision 2147, 66.6 kB (checked in by jerome, 19 years ago)

Removed all references to $Log$

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