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

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

Fixes some case related problems with LDAP

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
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                oc = fields.get("objectClass", fields.get("objectclass", []))
683                oc.extend(["pykotaAccount", "pykotaAccountBalance"])
684                fields.update(newfields)
685                fields.update({ "pykotaBalance" : str(user.AccountBalance or 0.0),
686                                "pykotaLifeTimePaid" : str(user.LifeTimePaid or 0.0), })   
687                self.doModify(dn, fields)
688                mustadd = 0
689            else :
690                message = _("Unable to find an existing objectClass %s entry with %s=%s to attach pykotaAccount objectClass") % (where, self.info["userrdn"], user.Name)
691                if action.lower() == "warn" :   
692                    self.tool.printInfo("%s. A new entry will be created instead." % message, "warn")
693                else : # 'fail' or incorrect setting
694                    raise PyKotaStorageError, "%s. Action aborted. Please check your configuration." % message
695               
696        if mustadd :
697            if self.info["userbase"] == self.info["balancebase"] :           
698                fields = { self.info["userrdn"] : user.Name,
699                           "objectClass" : ["pykotaObject", "pykotaAccount", "pykotaAccountBalance"],
700                           "cn" : user.Name,
701                           "pykotaBalance" : str(user.AccountBalance or 0.0),
702                           "pykotaLifeTimePaid" : str(user.LifeTimePaid or 0.0), 
703                         } 
704            else :             
705                fields = { self.info["userrdn"] : user.Name,
706                           "objectClass" : ["pykotaObject", "pykotaAccount"],
707                           "cn" : user.Name,
708                         } 
709            fields.update(newfields)         
710            dn = "%s=%s,%s" % (self.info["userrdn"], user.Name, self.info["userbase"])
711            self.doAdd(dn, fields)
712            if self.info["userbase"] != self.info["balancebase"] :           
713                fields = { self.info["balancerdn"] : user.Name,
714                           "objectClass" : ["pykotaObject", "pykotaAccountBalance"],
715                           "cn" : user.Name,
716                           "pykotaBalance" : str(user.AccountBalance or 0.0),
717                           "pykotaLifeTimePaid" : str(user.LifeTimePaid or 0.0), 
718                         } 
719                dn = "%s=%s,%s" % (self.info["balancerdn"], user.Name, self.info["balancebase"])
720                self.doAdd(dn, fields)
721           
722        return self.getUser(user.Name)
723       
724    def addGroup(self, group) :       
725        """Adds a group to the quota storage, returns it."""
726        newfields = { 
727                      "pykotaGroupName" : group.Name,
728                      "pykotaLimitBy" : (group.LimitBy or "quota"),
729                    } 
730        mustadd = 1
731        if self.info["newgroup"].lower() != 'below' :
732            try :
733                (where, action) = [s.strip() for s in self.info["newgroup"].split(",")]
734            except ValueError :
735                (where, action) = (self.info["newgroup"].strip(), "fail")
736            result = self.doSearch("(&(objectClass=%s)(%s=%s))" % (where, self.info["grouprdn"], group.Name), None, base=self.info["groupbase"])
737            if result :
738                (dn, fields) = result[0]
739                oc = fields.get("objectClass", fields.get("objectclass", []))
740                oc.extend(["pykotaGroup"])
741                fields.update(newfields)
742                self.doModify(dn, fields)
743                mustadd = 0
744            else :
745                message = _("Unable to find an existing entry to attach pykotaGroup objectclass %s") % group.Name
746                if action.lower() == "warn" :   
747                    self.tool.printInfo("%s. A new entry will be created instead." % message, "warn")
748                else : # 'fail' or incorrect setting
749                    raise PyKotaStorageError, "%s. Action aborted. Please check your configuration." % message
750               
751        if mustadd :
752            fields = { self.info["grouprdn"] : group.Name,
753                       "objectClass" : ["pykotaObject", "pykotaGroup"],
754                       "cn" : group.Name,
755                     } 
756            fields.update(newfields)         
757            dn = "%s=%s,%s" % (self.info["grouprdn"], group.Name, self.info["groupbase"])
758            self.doAdd(dn, fields)
759        return self.getGroup(group.Name)
760       
761    def addUserToGroup(self, user, group) :   
762        """Adds an user to a group."""
763        if user.Name not in [u.Name for u in self.getGroupMembers(group)] :
764            result = self.doSearch("objectClass=pykotaGroup", None, base=group.ident, scope=ldap.SCOPE_BASE)   
765            if result :
766                fields = result[0][1]
767                if not fields.has_key(self.info["groupmembers"]) :
768                    fields[self.info["groupmembers"]] = []
769                fields[self.info["groupmembers"]].append(user.Name)
770                self.doModify(group.ident, fields)
771                group.Members.append(user)
772               
773    def addUserPQuota(self, user, printer) :
774        """Initializes a user print quota on a printer."""
775        uuid = self.genUUID()
776        fields = { "cn" : uuid,
777                   "objectClass" : ["pykotaObject", "pykotaUserPQuota"],
778                   "pykotaUserName" : user.Name,
779                   "pykotaPrinterName" : printer.Name,
780                   "pykotaDateLimit" : "None",
781                   "pykotaPageCounter" : "0",
782                   "pykotaLifePageCounter" : "0",
783                   "pykotaWarnCount" : "0",
784                 } 
785        if self.info["userquotabase"].lower() == "user" :
786            dn = "cn=%s,%s" % (uuid, user.ident)
787        else :   
788            dn = "cn=%s,%s" % (uuid, self.info["userquotabase"])
789        self.doAdd(dn, fields)
790        return self.getUserPQuota(user, printer)
791       
792    def addGroupPQuota(self, group, printer) :
793        """Initializes a group print quota on a printer."""
794        uuid = self.genUUID()
795        fields = { "cn" : uuid,
796                   "objectClass" : ["pykotaObject", "pykotaGroupPQuota"],
797                   "pykotaGroupName" : group.Name,
798                   "pykotaPrinterName" : printer.Name,
799                   "pykotaDateLimit" : "None",
800                 } 
801        if self.info["groupquotabase"].lower() == "group" :
802            dn = "cn=%s,%s" % (uuid, group.ident)
803        else :   
804            dn = "cn=%s,%s" % (uuid, self.info["groupquotabase"])
805        self.doAdd(dn, fields)
806        return self.getGroupPQuota(group, printer)
807       
808    def writePrinterPrices(self, printer) :   
809        """Write the printer's prices back into the storage."""
810        fields = {
811                   "pykotaPricePerPage" : str(printer.PricePerPage),
812                   "pykotaPricePerJob" : str(printer.PricePerJob),
813                 }
814        self.doModify(printer.ident, fields)
815       
816    def writePrinterDescription(self, printer) :   
817        """Write the printer's description back into the storage."""
818        fields = {
819                   "description" : self.userCharsetToDatabase(str(printer.Description)), 
820                 }
821        self.doModify(printer.ident, fields)
822       
823    def writeUserOverCharge(self, user, factor) :
824        """Sets the user's overcharging coefficient."""
825        fields = {
826                   "pykotaOverCharge" : str(factor),
827                 }
828        self.doModify(user.ident, fields)
829       
830    def writeUserLimitBy(self, user, limitby) :   
831        """Sets the user's limiting factor."""
832        fields = {
833                   "pykotaLimitBy" : limitby,
834                 }
835        self.doModify(user.ident, fields)         
836       
837    def writeGroupLimitBy(self, group, limitby) :   
838        """Sets the group's limiting factor."""
839        fields = {
840                   "pykotaLimitBy" : limitby,
841                 }
842        self.doModify(group.ident, fields)         
843       
844    def writeUserPQuotaDateLimit(self, userpquota, datelimit) :   
845        """Sets the date limit permanently for a user print quota."""
846        fields = {
847                   "pykotaDateLimit" : datelimit,
848                 }
849        return self.doModify(userpquota.ident, fields)
850           
851    def writeGroupPQuotaDateLimit(self, grouppquota, datelimit) :   
852        """Sets the date limit permanently for a group print quota."""
853        fields = {
854                   "pykotaDateLimit" : datelimit,
855                 }
856        return self.doModify(grouppquota.ident, fields)
857       
858    def increaseUserPQuotaPagesCounters(self, userpquota, nbpages) :   
859        """Increase page counters for a user print quota."""
860        fields = {
861                   "pykotaPageCounter" : { "operator" : "+", "value" : nbpages, "convert" : int },
862                   "pykotaLifePageCounter" : { "operator" : "+", "value" : nbpages, "convert" : int },
863                 }
864        return self.doModify(userpquota.ident, fields)         
865       
866    def writeUserPQuotaPagesCounters(self, userpquota, newpagecounter, newlifepagecounter) :   
867        """Sets the new page counters permanently for a user print quota."""
868        fields = {
869                   "pykotaPageCounter" : str(newpagecounter),
870                   "pykotaLifePageCounter" : str(newlifepagecounter),
871                   "pykotaDateLimit" : None,
872                   "pykotaWarnCount" : "0",
873                 } 
874        return self.doModify(userpquota.ident, fields)         
875       
876    def decreaseUserAccountBalance(self, user, amount) :   
877        """Decreases user's account balance from an amount."""
878        fields = {
879                   "pykotaBalance" : { "operator" : "-", "value" : amount, "convert" : float },
880                 }
881        return self.doModify(user.idbalance, fields, flushcache=1)         
882       
883    def writeUserAccountBalance(self, user, newbalance, newlifetimepaid=None) :   
884        """Sets the new account balance and eventually new lifetime paid."""
885        fields = {
886                   "pykotaBalance" : str(newbalance),
887                 }
888        if newlifetimepaid is not None :
889            fields.update({ "pykotaLifeTimePaid" : str(newlifetimepaid) })
890        return self.doModify(user.idbalance, fields)         
891           
892    def writeNewPayment(self, user, amount) :       
893        """Adds a new payment to the payments history."""
894        payments = []
895        for payment in user.Payments :
896            payments.append("%s # %s" % (payment[0], str(payment[1])))
897        payments.append("%s # %s" % (str(DateTime.now()), str(amount)))
898        fields = {
899                   "pykotaPayments" : payments,
900                 }
901        return self.doModify(user.idbalance, fields)         
902       
903    def writeLastJobSize(self, lastjob, jobsize, jobprice) :       
904        """Sets the last job's size permanently."""
905        fields = {
906                   "pykotaJobSize" : str(jobsize),
907                   "pykotaJobPrice" : str(jobprice),
908                 }
909        self.doModify(lastjob.ident, fields)         
910       
911    def writeJobNew(self, printer, user, jobid, pagecounter, action, jobsize=None, jobprice=None, filename=None, title=None, copies=None, options=None, clienthost=None, jobsizebytes=None, jobmd5sum=None) :
912        """Adds a job in a printer's history."""
913        if (not self.disablehistory) or (not printer.LastJob.Exists) :
914            uuid = self.genUUID()
915            dn = "cn=%s,%s" % (uuid, self.info["jobbase"])
916        else :   
917            uuid = printer.LastJob.ident[3:].split(",")[0]
918            dn = printer.LastJob.ident
919        if self.privacy :   
920            # For legal reasons, we want to hide the title, filename and options
921            title = filename = options = "Hidden because of privacy concerns"
922        fields = {
923                   "objectClass" : ["pykotaObject", "pykotaJob"],
924                   "cn" : uuid,
925                   "pykotaUserName" : user.Name,
926                   "pykotaPrinterName" : printer.Name,
927                   "pykotaJobId" : jobid,
928                   "pykotaPrinterPageCounter" : str(pagecounter),
929                   "pykotaAction" : action,
930                   "pykotaFileName" : ((filename is None) and "None") or self.userCharsetToDatabase(filename), 
931                   "pykotaTitle" : ((title is None) and "None") or self.userCharsetToDatabase(title), 
932                   "pykotaCopies" : str(copies), 
933                   "pykotaOptions" : ((options is None) and "None") or self.userCharsetToDatabase(options), 
934                   "pykotaHostName" : str(clienthost), 
935                   "pykotaJobSizeBytes" : str(jobsizebytes),
936                   "pykotaMD5Sum" : str(jobmd5sum),
937                 }
938        if (not self.disablehistory) or (not printer.LastJob.Exists) :
939            if jobsize is not None :         
940                fields.update({ "pykotaJobSize" : str(jobsize), "pykotaJobPrice" : str(jobprice) })
941            self.doAdd(dn, fields)
942        else :   
943            # here we explicitly want to reset jobsize to 'None' if needed
944            fields.update({ "pykotaJobSize" : str(jobsize), "pykotaJobPrice" : str(jobprice) })
945            self.doModify(dn, fields)
946           
947        if printer.LastJob.Exists :
948            fields = {
949                       "pykotaLastJobIdent" : uuid,
950                     }
951            self.doModify(printer.LastJob.lastjobident, fields)         
952        else :   
953            lastjuuid = self.genUUID()
954            lastjdn = "cn=%s,%s" % (lastjuuid, self.info["lastjobbase"])
955            fields = {
956                       "objectClass" : ["pykotaObject", "pykotaLastJob"],
957                       "cn" : lastjuuid,
958                       "pykotaPrinterName" : printer.Name,
959                       "pykotaLastJobIdent" : uuid,
960                     } 
961            self.doAdd(lastjdn, fields)         
962           
963    def writeUserPQuotaLimits(self, userpquota, softlimit, hardlimit) :
964        """Sets soft and hard limits for a user quota."""
965        fields = { 
966                   "pykotaSoftLimit" : str(softlimit),
967                   "pykotaHardLimit" : str(hardlimit),
968                   "pykotaDateLimit" : "None",
969                   "pykotaWarnCount" : "0",
970                 }
971        self.doModify(userpquota.ident, fields)
972       
973    def writeUserPQuotaWarnCount(self, userpquota, warncount) :
974        """Sets the warn counter value for a user quota."""
975        fields = { 
976                   "pykotaWarnCount" : str(warncount or 0),
977                 }
978        self.doModify(userpquota.ident, fields)
979       
980    def increaseUserPQuotaWarnCount(self, userpquota) :
981        """Increases the warn counter value for a user quota."""
982        fields = {
983                   "pykotaWarnCount" : { "operator" : "+", "value" : 1, "convert" : int },
984                 }
985        return self.doModify(userpquota.ident, fields)         
986       
987    def writeGroupPQuotaLimits(self, grouppquota, softlimit, hardlimit) :
988        """Sets soft and hard limits for a group quota on a specific printer."""
989        fields = { 
990                   "pykotaSoftLimit" : str(softlimit),
991                   "pykotaHardLimit" : str(hardlimit),
992                   "pykotaDateLimit" : "None",
993                 }
994        self.doModify(grouppquota.ident, fields)
995           
996    def writePrinterToGroup(self, pgroup, printer) :
997        """Puts a printer into a printer group."""
998        if printer.ident not in pgroup.uniqueMember :
999            pgroup.uniqueMember.append(printer.ident)
1000            fields = {
1001                       "uniqueMember" : pgroup.uniqueMember
1002                     } 
1003            self.doModify(pgroup.ident, fields)         
1004           
1005    def removePrinterFromGroup(self, pgroup, printer) :
1006        """Removes a printer from a printer group."""
1007        try :
1008            pgroup.uniqueMember.remove(printer.ident)
1009        except ValueError :   
1010            pass
1011        else :   
1012            fields = {
1013                       "uniqueMember" : pgroup.uniqueMember,
1014                     } 
1015            self.doModify(pgroup.ident, fields)         
1016           
1017    def retrieveHistory(self, user=None, printer=None, datelimit=None, hostname=None, limit=100) :   
1018        """Retrieves all print jobs for user on printer (or all) before date, limited to first 100 results."""
1019        precond = "(objectClass=pykotaJob)"
1020        where = []
1021        if (user is not None) and user.Exists :
1022            where.append("(pykotaUserName=%s)" % user.Name)
1023        if (printer is not None) and printer.Exists :
1024            where.append("(pykotaPrinterName=%s)" % printer.Name)
1025        if hostname is not None :
1026            where.append("(pykotaHostName=%s)" % hostname)
1027        if where :   
1028            where = "(&%s)" % "".join([precond] + where)
1029        else :   
1030            where = precond
1031        jobs = []   
1032        result = self.doSearch(where, fields=["pykotaJobSizeBytes", "pykotaHostName", "pykotaUserName", "pykotaPrinterName", "pykotaJobId", "pykotaPrinterPageCounter", "pykotaAction", "pykotaJobSize", "pykotaJobPrice", "pykotaFileName", "pykotaTitle", "pykotaCopies", "pykotaOptions", "createTimestamp"], base=self.info["jobbase"])
1033        if result :
1034            for (ident, fields) in result :
1035                job = StorageJob(self)
1036                job.ident = ident
1037                job.JobId = fields.get("pykotaJobId")[0]
1038                job.PrinterPageCounter = int(fields.get("pykotaPrinterPageCounter", [0])[0] or 0)
1039                try :
1040                    job.JobSize = int(fields.get("pykotaJobSize", [0])[0])
1041                except ValueError :   
1042                    job.JobSize = None
1043                try :   
1044                    job.JobPrice = float(fields.get("pykotaJobPrice", [0.0])[0])
1045                except ValueError :
1046                    job.JobPrice = None
1047                job.JobAction = fields.get("pykotaAction", [""])[0]
1048                job.JobFileName = self.databaseToUserCharset(fields.get("pykotaFileName", [""])[0]) 
1049                job.JobTitle = self.databaseToUserCharset(fields.get("pykotaTitle", [""])[0]) 
1050                job.JobCopies = int(fields.get("pykotaCopies", [0])[0])
1051                job.JobOptions = self.databaseToUserCharset(fields.get("pykotaOptions", [""])[0]) 
1052                job.JobHostName = fields.get("pykotaHostName", [""])[0]
1053                job.JobSizeBytes = fields.get("pykotaJobSizeBytes", [0L])[0]
1054                date = fields.get("createTimestamp", ["19700101000000"])[0]
1055                year = int(date[:4])
1056                month = int(date[4:6])
1057                day = int(date[6:8])
1058                hour = int(date[8:10])
1059                minute = int(date[10:12])
1060                second = int(date[12:14])
1061                job.JobDate = "%04i-%02i-%02i %02i:%02i:%02i" % (year, month, day, hour, minute, second)
1062                if (datelimit is None) or (job.JobDate <= datelimit) :
1063                    job.UserName = fields.get("pykotaUserName")[0]
1064                    job.PrinterName = fields.get("pykotaPrinterName")[0]
1065                    job.Exists = 1
1066                    jobs.append(job)
1067            jobs.sort(lambda x, y : cmp(y.JobDate, x.JobDate))       
1068            if limit :   
1069                jobs = jobs[:int(limit)]
1070        return jobs
1071       
1072    def deleteUser(self, user) :   
1073        """Completely deletes an user from the Quota Storage."""
1074        todelete = []   
1075        result = self.doSearch("(&(objectClass=pykotaJob)(pykotaUserName=%s))" % user.Name, base=self.info["jobbase"])
1076        for (ident, fields) in result :
1077            todelete.append(ident)
1078        if self.info["userquotabase"].lower() == "user" :
1079            base = self.info["userbase"]
1080        else :
1081            base = self.info["userquotabase"]
1082        result = self.doSearch("(&(objectClass=pykotaUserPQuota)(pykotaUserName=%s))" % user.Name, ["pykotaPrinterName", "pykotaUserName"], base=base)
1083        for (ident, fields) in result :
1084            # ensure the user print quota entry will be deleted
1085            todelete.append(ident)
1086           
1087            # if last job of current printer was printed by the user
1088            # to delete, we also need to delete the printer's last job entry.
1089            printername = fields["pykotaPrinterName"][0]
1090            printer = self.getPrinter(printername)
1091            if printer.LastJob.UserName == user.Name :
1092                todelete.append(printer.LastJob.lastjobident)
1093           
1094        for ident in todelete :   
1095            self.doDelete(ident)
1096           
1097        result = self.doSearch("objectClass=pykotaAccount", None, base=user.ident, scope=ldap.SCOPE_BASE)   
1098        if result :
1099            fields = result[0][1]
1100            for k in fields.keys() :
1101                if k.startswith("pykota") :
1102                    del fields[k]
1103                elif k.lower() == "objectclass" :   
1104                    todelete = []
1105                    for i in range(len(fields[k])) :
1106                        if fields[k][i].startswith("pykota") : 
1107                            todelete.append(i)
1108                    todelete.sort()       
1109                    todelete.reverse()
1110                    for i in todelete :
1111                        del fields[k][i]
1112            if fields.get("objectClass") or fields.get("objectclass") :
1113                self.doModify(user.ident, fields, ignoreold=0)       
1114            else :   
1115                self.doDelete(user.ident)
1116        result = self.doSearch("(&(objectClass=pykotaAccountBalance)(pykotaUserName=%s))" % user.Name, ["pykotaUserName"], base=self.info["balancebase"])
1117        for (ident, fields) in result :
1118            self.doDelete(ident)
1119       
1120    def deleteGroup(self, group) :   
1121        """Completely deletes a group from the Quota Storage."""
1122        if self.info["groupquotabase"].lower() == "group" :
1123            base = self.info["groupbase"]
1124        else :
1125            base = self.info["groupquotabase"]
1126        result = self.doSearch("(&(objectClass=pykotaGroupPQuota)(pykotaGroupName=%s))" % group.Name, ["pykotaGroupName"], base=base)
1127        for (ident, fields) in result :
1128            self.doDelete(ident)
1129        result = self.doSearch("objectClass=pykotaGroup", None, base=group.ident, scope=ldap.SCOPE_BASE)   
1130        if result :
1131            fields = result[0][1]
1132            for k in fields.keys() :
1133                if k.startswith("pykota") :
1134                    del fields[k]
1135                elif k.lower() == "objectclass" :   
1136                    todelete = []
1137                    for i in range(len(fields[k])) :
1138                        if fields[k][i].startswith("pykota") : 
1139                            todelete.append(i)
1140                    todelete.sort()       
1141                    todelete.reverse()
1142                    for i in todelete :
1143                        del fields[k][i]
1144            if fields.get("objectClass") or fields.get("objectclass") :
1145                self.doModify(group.ident, fields, ignoreold=0)       
1146            else :   
1147                self.doDelete(group.ident)
1148               
1149    def deletePrinter(self, printer) :   
1150        """Completely deletes an user from the Quota Storage."""
1151        result = self.doSearch("(&(objectClass=pykotaLastJob)(pykotaPrinterName=%s))" % printer.Name, base=self.info["lastjobbase"])
1152        for (ident, fields) in result :
1153            self.doDelete(ident)
1154        result = self.doSearch("(&(objectClass=pykotaJob)(pykotaPrinterName=%s))" % printer.Name, base=self.info["jobbase"])
1155        for (ident, fields) in result :
1156            self.doDelete(ident)
1157        if self.info["groupquotabase"].lower() == "group" :
1158            base = self.info["groupbase"]
1159        else :
1160            base = self.info["groupquotabase"]
1161        result = self.doSearch("(&(objectClass=pykotaGroupPQuota)(pykotaPrinterName=%s))" % printer.Name, base=base)
1162        for (ident, fields) in result :
1163            self.doDelete(ident)
1164        if self.info["userquotabase"].lower() == "user" :
1165            base = self.info["userbase"]
1166        else :
1167            base = self.info["userquotabase"]
1168        result = self.doSearch("(&(objectClass=pykotaUserPQuota)(pykotaPrinterName=%s))" % printer.Name, base=base)
1169        for (ident, fields) in result :
1170            self.doDelete(ident)
1171        for parent in self.getParentPrinters(printer) : 
1172            try :
1173                parent.uniqueMember.remove(printer.ident)
1174            except ValueError :   
1175                pass
1176            else :   
1177                fields = {
1178                           "uniqueMember" : parent.uniqueMember,
1179                         } 
1180                self.doModify(parent.ident, fields)         
1181        self.doDelete(printer.ident)   
1182       
1183    def extractPrinters(self, extractonly={}) :
1184        """Extracts all printer records."""
1185        pname = extractonly.get("printername")
1186        entries = [p for p in [self.getPrinter(name) for name in self.getAllPrintersNames(pname)] if p.Exists]
1187        if entries :
1188            result = [ ("dn", "printername", "priceperpage", "priceperjob", "description") ]
1189            for entry in entries :
1190                result.append((entry.ident, entry.Name, entry.PricePerPage, entry.PricePerJob, entry.Description))
1191            return result 
1192       
1193    def extractUsers(self, extractonly={}) :
1194        """Extracts all user records."""
1195        uname = extractonly.get("username")
1196        entries = [u for u in [self.getUser(name) for name in self.getAllUsersNames(uname)] if u.Exists]
1197        if entries :
1198            result = [ ("dn", "username", "balance", "lifetimepaid", "limitby", "email") ]
1199            for entry in entries :
1200                result.append((entry.ident, entry.Name, entry.AccountBalance, entry.LifeTimePaid, entry.LimitBy, entry.Email))
1201            return result 
1202       
1203    def extractGroups(self, extractonly={}) :
1204        """Extracts all group records."""
1205        gname = extractonly.get("groupname")
1206        entries = [g for g in [self.getGroup(name) for name in self.getAllGroupsNames(gname)] if g.Exists]
1207        if entries :
1208            result = [ ("dn", "groupname", "limitby", "balance", "lifetimepaid") ]
1209            for entry in entries :
1210                result.append((entry.ident, entry.Name, entry.LimitBy, entry.AccountBalance, entry.LifeTimePaid))
1211            return result 
1212       
1213    def extractPayments(self, extractonly={}) :
1214        """Extracts all payment records."""
1215        uname = extractonly.get("username")
1216        entries = [u for u in [self.getUser(name) for name in self.getAllUsersNames(uname)] if u.Exists]
1217        if entries :
1218            result = [ ("username", "amount", "date") ]
1219            for entry in entries :
1220                for (date, amount) in entry.Payments :
1221                    result.append((entry.Name, amount, date))
1222            return result       
1223       
1224    def extractUpquotas(self, extractonly={}) :
1225        """Extracts all userpquota records."""
1226        pname = extractonly.get("printername")
1227        entries = [p for p in [self.getPrinter(name) for name in self.getAllPrintersNames(pname)] if p.Exists]
1228        if entries :
1229            result = [ ("username", "printername", "dn", "userdn", "printerdn", "lifepagecounter", "pagecounter", "softlimit", "hardlimit", "datelimit") ]
1230            uname = extractonly.get("username")
1231            for entry in entries :
1232                for (user, userpquota) in self.getPrinterUsersAndQuotas(entry, names=[uname or "*"]) :
1233                    result.append((user.Name, entry.Name, userpquota.ident, user.ident, entry.ident, userpquota.LifePageCounter, userpquota.PageCounter, userpquota.SoftLimit, userpquota.HardLimit, userpquota.DateLimit))
1234            return result
1235       
1236    def extractGpquotas(self, extractonly={}) :
1237        """Extracts all grouppquota records."""
1238        pname = extractonly.get("printername")
1239        entries = [p for p in [self.getPrinter(name) for name in self.getAllPrintersNames(pname)] if p.Exists]
1240        if entries :
1241            result = [ ("groupname", "printername", "dn", "groupdn", "printerdn", "lifepagecounter", "pagecounter", "softlimit", "hardlimit", "datelimit") ]
1242            gname = extractonly.get("groupname")
1243            for entry in entries :
1244                for (group, grouppquota) in self.getPrinterGroupsAndQuotas(entry, names=[gname or "*"]) :
1245                    result.append((group.Name, entry.Name, grouppquota.ident, group.ident, entry.ident, grouppquota.LifePageCounter, grouppquota.PageCounter, grouppquota.SoftLimit, grouppquota.HardLimit, grouppquota.DateLimit))
1246            return result
1247       
1248    def extractUmembers(self, extractonly={}) :
1249        """Extracts all user groups members."""
1250        gname = extractonly.get("groupname")
1251        entries = [g for g in [self.getGroup(name) for name in self.getAllGroupsNames(gname)] if g.Exists]
1252        if entries :
1253            result = [ ("groupname", "username", "groupdn", "userdn") ]
1254            uname = extractonly.get("username")
1255            for entry in entries :
1256                for member in entry.Members :
1257                    if (uname is None) or (member.Name == uname) :
1258                        result.append((entry.Name, member.Name, entry.ident, member.ident))
1259            return result       
1260               
1261    def extractPmembers(self, extractonly={}) :
1262        """Extracts all printer groups members."""
1263        pname = extractonly.get("printername")
1264        entries = [p for p in [self.getPrinter(name) for name in self.getAllPrintersNames(pname)] if p.Exists]
1265        if entries :
1266            result = [ ("pgroupname", "printername", "pgroupdn", "printerdn") ]
1267            pgname = extractonly.get("pgroupname")
1268            for entry in entries :
1269                for parent in self.getParentPrinters(entry) :
1270                    if (pgname is None) or (parent.Name == pgname) :
1271                        result.append((parent.Name, entry.Name, parent.ident, entry.ident))
1272            return result       
1273       
1274    def extractHistory(self, extractonly={}) :
1275        """Extracts all jobhistory records."""
1276        uname = extractonly.get("username")
1277        if uname :
1278            user = self.getUser(uname)
1279        else :   
1280            user = None
1281        pname = extractonly.get("printername")
1282        if pname :
1283            printer = self.getPrinter(pname)
1284        else :   
1285            printer = None
1286        entries = self.retrieveHistory(user, printer, limit=None)
1287        if entries :
1288            result = [ ("username", "printername", "dn", "jobid", "pagecounter", "jobsize", "action", "jobdate", "filename", "title", "copies", "options", "jobprice", "hostname", "jobsizebytes") ] 
1289            for entry in entries :
1290                result.append((entry.UserName, entry.PrinterName, entry.ident, entry.JobId, entry.PrinterPageCounter, entry.JobSize, entry.JobAction, entry.JobDate, entry.JobFileName, entry.JobTitle, entry.JobCopies, entry.JobOptions, entry.JobPrice, entry.JobHostName, entry.JobSizeBytes)) 
1291            return result   
Note: See TracBrowser for help on using the browser.