root / pykota / trunk / pykota / storages / sql.py @ 2657

Revision 2657, 46.2 kB (checked in by jerome, 18 years ago)

Huge speed improvements when using the --delete command line option for pkprinters, pkbcodes and edpykota.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1# PyKota
2# -*- coding: ISO-8859-15 -*-
3#
4# PyKota : Print Quotas for CUPS and LPRng
5#
6# (c) 2003, 2004, 2005, 2006 Jerome Alet <alet@librelogiciel.com>
7# This program is free software; you can redistribute it and/or modify
8# it under the terms of the GNU General Public License as published by
9# the Free Software Foundation; either version 2 of the License, or
10# (at your option) any later version.
11#
12# This program is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15# GNU General Public License for more details.
16#
17# You should have received a copy of the GNU General Public License
18# along with this program; if not, write to the Free Software
19# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20#
21# $Id$
22#
23#
24
25from pykota.storage import PyKotaStorageError, BaseStorage, StorageObject, \
26                           StorageUser, StorageGroup, StoragePrinter, \
27                           StorageJob, StorageLastJob, StorageUserPQuota, \
28                           StorageGroupPQuota, StorageBillingCode
29
30class SQLStorage :
31    def createFilter(self, only) :   
32        """Returns the appropriate SQL filter."""
33        if only :
34            expressions = []
35            for (k, v) in only.items() :
36                expressions.append("%s=%s" % (k, self.doQuote(self.userCharsetToDatabase(v))))
37            return " AND ".join(expressions)     
38        return ""       
39       
40    def extractPrinters(self, extractonly={}) :
41        """Extracts all printer records."""
42        thefilter = self.createFilter(extractonly)
43        if thefilter :
44            thefilter = "WHERE %s" % thefilter
45        result = self.doRawSearch("SELECT * FROM printers %s ORDER BY id ASC" % thefilter)
46        return self.prepareRawResult(result)
47       
48    def extractUsers(self, extractonly={}) :
49        """Extracts all user records."""
50        thefilter = self.createFilter(extractonly)
51        if thefilter :
52            thefilter = "WHERE %s" % thefilter
53        result = self.doRawSearch("SELECT * FROM users %s ORDER BY id ASC" % thefilter)
54        return self.prepareRawResult(result)
55       
56    def extractBillingcodes(self, extractonly={}) :
57        """Extracts all billing codes records."""
58        thefilter = self.createFilter(extractonly)
59        if thefilter :
60            thefilter = "WHERE %s" % thefilter
61        result = self.doRawSearch("SELECT * FROM billingcodes %s ORDER BY id ASC" % thefilter)
62        return self.prepareRawResult(result)
63       
64    def extractGroups(self, extractonly={}) :
65        """Extracts all group records."""
66        thefilter = self.createFilter(extractonly)
67        if thefilter :
68            thefilter = "WHERE %s" % thefilter
69        result = self.doRawSearch("SELECT groups.*,COALESCE(SUM(balance), 0) AS balance, COALESCE(SUM(lifetimepaid), 0) as lifetimepaid FROM groups LEFT OUTER JOIN users ON users.id IN (SELECT userid FROM groupsmembers WHERE groupid=groups.id) %s GROUP BY groups.id,groups.groupname,groups.limitby,groups.description ORDER BY groups.id ASC" % thefilter)
70        return self.prepareRawResult(result)
71       
72    def extractPayments(self, extractonly={}) :
73        """Extracts all payment records."""
74        thefilter = self.createFilter(extractonly)
75        if thefilter :
76            thefilter = "AND %s" % thefilter
77        result = self.doRawSearch("SELECT username,payments.* FROM users,payments WHERE users.id=payments.userid %s ORDER BY payments.id ASC" % thefilter)
78        return self.prepareRawResult(result)
79       
80    def extractUpquotas(self, extractonly={}) :
81        """Extracts all userpquota records."""
82        thefilter = self.createFilter(extractonly)
83        if thefilter :
84            thefilter = "AND %s" % thefilter
85        result = self.doRawSearch("SELECT users.username,printers.printername,userpquota.* FROM users,printers,userpquota WHERE users.id=userpquota.userid AND printers.id=userpquota.printerid %s ORDER BY userpquota.id ASC" % thefilter)
86        return self.prepareRawResult(result)
87       
88    def extractGpquotas(self, extractonly={}) :
89        """Extracts all grouppquota records."""
90        thefilter = self.createFilter(extractonly)
91        if thefilter :
92            thefilter = "AND %s" % thefilter
93        result = self.doRawSearch("SELECT groups.groupname,printers.printername,grouppquota.*,coalesce(sum(pagecounter), 0) AS pagecounter,coalesce(sum(lifepagecounter), 0) AS lifepagecounter FROM groups,printers,grouppquota,userpquota WHERE groups.id=grouppquota.groupid AND printers.id=grouppquota.printerid AND userpquota.printerid=grouppquota.printerid AND userpquota.userid IN (SELECT userid FROM groupsmembers WHERE groupsmembers.groupid=grouppquota.groupid) %s GROUP BY grouppquota.id,grouppquota.groupid,grouppquota.printerid,grouppquota.softlimit,grouppquota.hardlimit,grouppquota.datelimit,grouppquota.maxjobsize,groups.groupname,printers.printername ORDER BY grouppquota.id" % thefilter)
94        return self.prepareRawResult(result)
95       
96    def extractUmembers(self, extractonly={}) :
97        """Extracts all user groups members."""
98        thefilter = self.createFilter(extractonly)
99        if thefilter :
100            thefilter = "AND %s" % thefilter
101        result = self.doRawSearch("SELECT groups.groupname, users.username, groupsmembers.* FROM groups,users,groupsmembers WHERE users.id=groupsmembers.userid AND groups.id=groupsmembers.groupid %s ORDER BY groupsmembers.groupid, groupsmembers.userid ASC" % thefilter)
102        return self.prepareRawResult(result)
103       
104    def extractPmembers(self, extractonly={}) :
105        """Extracts all printer groups members."""
106        for (k, v) in extractonly.items() :
107            if k == "pgroupname" :
108                del extractonly[k]
109                extractonly["p1.printername"] = v
110            elif k == "printername" :
111                del extractonly[k]
112                extractonly["p2.printername"] = v
113        thefilter = self.createFilter(extractonly)
114        if thefilter :
115            thefilter = "AND %s" % thefilter
116        result = self.doRawSearch("SELECT p1.printername as pgroupname, p2.printername as printername, printergroupsmembers.* FROM printers p1, printers p2, printergroupsmembers WHERE p1.id=printergroupsmembers.groupid AND p2.id=printergroupsmembers.printerid %s ORDER BY printergroupsmembers.groupid, printergroupsmembers.printerid ASC" % thefilter)
117        return self.prepareRawResult(result)
118       
119    def extractHistory(self, extractonly={}) :
120        """Extracts all jobhistory records."""
121        startdate = extractonly.get("start")
122        enddate = extractonly.get("end")
123        for limit in ("start", "end") :
124            try :
125                del extractonly[limit]
126            except KeyError :   
127                pass
128        thefilter = self.createFilter(extractonly)
129        if thefilter :
130            thefilter = "AND %s" % thefilter
131        (startdate, enddate) = self.cleanDates(startdate, enddate)
132        if startdate and enddate : 
133            thefilter = "%s AND jobdate>=%s AND jobdate<=%s" % (thefilter, self.doQuote(startdate), self.doQuote(enddate))
134        result = self.doRawSearch("SELECT users.username,printers.printername,jobhistory.* FROM users,printers,jobhistory WHERE users.id=jobhistory.userid AND printers.id=jobhistory.printerid %s ORDER BY jobhistory.id ASC" % thefilter)
135        return self.prepareRawResult(result)
136           
137    def filterNames(self, records, attribute, patterns=None) :
138        """Returns a list of 'attribute' from a list of records.
139       
140           Logs any missing attribute.
141        """   
142        result = []
143        for record in records :
144            attrval = record.get(attribute, [None])
145            if attrval is None :
146                self.tool.printInfo("Object %s has no %s attribute !" % (repr(record), attribute), "error")
147            else :
148                attrval = self.databaseToUserCharset(attrval)
149                if patterns :
150                    if (not isinstance(patterns, type([]))) and (not isinstance(patterns, type(()))) :
151                        patterns = [ patterns ]
152                    if self.tool.matchString(attrval, patterns) :
153                        result.append(attrval)
154                else :   
155                    result.append(attrval)
156        return result   
157               
158    def getAllBillingCodes(self, billingcode=None) :   
159        """Extracts all billing codes or only the billing codes matching the optional parameter."""
160        result = self.doSearch("SELECT billingcode FROM billingcodes")
161        if result :
162            return self.filterNames(result, "billingcode", billingcode)
163        else :   
164            return []
165       
166    def getAllPrintersNames(self, printername=None) :   
167        """Extracts all printer names or only the printers' names matching the optional parameter."""
168        result = self.doSearch("SELECT printername FROM printers")
169        if result :
170            return self.filterNames(result, "printername", printername)
171        else :   
172            return []
173   
174    def getAllUsersNames(self, username=None) :   
175        """Extracts all user names."""
176        result = self.doSearch("SELECT username FROM users")
177        if result :
178            return self.filterNames(result, "username", username)
179        else :   
180            return []
181       
182    def getAllGroupsNames(self, groupname=None) :   
183        """Extracts all group names."""
184        result = self.doSearch("SELECT groupname FROM groups")
185        if result :
186            return self.filterNames(result, "groupname", groupname)
187        else :
188            return []
189       
190    def getUserNbJobsFromHistory(self, user) :
191        """Returns the number of jobs the user has in history."""
192        result = self.doSearch("SELECT COUNT(*) FROM jobhistory WHERE userid=%s" % self.doQuote(user.ident))
193        if result :
194            return result[0]["count"]
195        return 0
196       
197    def getUserFromBackend(self, username) :   
198        """Extracts user information given its name."""
199        user = StorageUser(self, username)
200        username = self.userCharsetToDatabase(username)
201        result = self.doSearch("SELECT * FROM users WHERE username=%s LIMIT 1" % self.doQuote(username))
202        if result :
203            fields = result[0]
204            user.ident = fields.get("id")
205            user.LimitBy = fields.get("limitby") or "quota"
206            user.AccountBalance = fields.get("balance")
207            user.LifeTimePaid = fields.get("lifetimepaid")
208            user.Email = fields.get("email")
209            user.Description = self.databaseToUserCharset(fields.get("description"))
210            user.OverCharge = fields.get("overcharge", 1.0)
211            user.Exists = 1
212        return user
213       
214    def getGroupFromBackend(self, groupname) :   
215        """Extracts group information given its name."""
216        group = StorageGroup(self, groupname)
217        groupname = self.userCharsetToDatabase(groupname)
218        result = self.doSearch("SELECT groups.*,COALESCE(SUM(balance), 0.0) AS balance, COALESCE(SUM(lifetimepaid), 0.0) AS lifetimepaid FROM groups LEFT OUTER JOIN users ON users.id IN (SELECT userid FROM groupsmembers WHERE groupid=groups.id) WHERE groupname=%s GROUP BY groups.id,groups.groupname,groups.limitby,groups.description LIMIT 1" % self.doQuote(groupname))
219        if result :
220            fields = result[0]
221            group.ident = fields.get("id")
222            group.LimitBy = fields.get("limitby") or "quota"
223            group.AccountBalance = fields.get("balance")
224            group.LifeTimePaid = fields.get("lifetimepaid")
225            group.Description = self.databaseToUserCharset(fields.get("description"))
226            group.Exists = 1
227        return group
228       
229    def getPrinterFromBackend(self, printername) :       
230        """Extracts printer information given its name."""
231        printer = StoragePrinter(self, printername)
232        printername = self.userCharsetToDatabase(printername)
233        result = self.doSearch("SELECT * FROM printers WHERE printername=%s LIMIT 1" % self.doQuote(printername))
234        if result :
235            fields = result[0]
236            printer.ident = fields.get("id")
237            printer.PricePerJob = fields.get("priceperjob") or 0.0
238            printer.PricePerPage = fields.get("priceperpage") or 0.0
239            printer.MaxJobSize = fields.get("maxjobsize") or 0
240            printer.PassThrough = fields.get("passthrough") or 0
241            if printer.PassThrough in (1, "1", "t", "true", "TRUE", "True") :
242                printer.PassThrough = 1
243            else :
244                printer.PassThrough = 0
245            printer.Description = self.databaseToUserCharset(fields.get("description") or "")
246            printer.Exists = 1
247        return printer   
248       
249    def getBillingCodeFromBackend(self, label) :       
250        """Extracts a billing code information given its name."""
251        code = StorageBillingCode(self, label)
252        result = self.doSearch("SELECT * FROM billingcodes WHERE billingcode=%s LIMIT 1" % self.doQuote(self.userCharsetToDatabase(label)))
253        if result :
254            fields = result[0]
255            code.ident = fields.get("id")
256            code.Description = self.databaseToUserCharset(fields.get("description") or "")
257            code.Balance = fields.get("balance") or 0.0
258            code.PageCounter = fields.get("pagecounter") or 0
259            code.Exists = 1
260        return code   
261       
262    def getUserPQuotaFromBackend(self, user, printer) :       
263        """Extracts a user print quota."""
264        userpquota = StorageUserPQuota(self, user, printer)
265        if printer.Exists and user.Exists :
266            result = self.doSearch("SELECT * FROM userpquota WHERE userid=%s AND printerid=%s;" % (self.doQuote(user.ident), self.doQuote(printer.ident)))
267            if result :
268                fields = result[0]
269                userpquota.ident = fields.get("id")
270                userpquota.PageCounter = fields.get("pagecounter")
271                userpquota.LifePageCounter = fields.get("lifepagecounter")
272                userpquota.SoftLimit = fields.get("softlimit")
273                userpquota.HardLimit = fields.get("hardlimit")
274                userpquota.DateLimit = fields.get("datelimit")
275                userpquota.WarnCount = fields.get("warncount")
276                userpquota.Exists = 1
277        return userpquota
278       
279    def getGroupPQuotaFromBackend(self, group, printer) :       
280        """Extracts a group print quota."""
281        grouppquota = StorageGroupPQuota(self, group, printer)
282        if group.Exists :
283            result = self.doSearch("SELECT * FROM grouppquota WHERE groupid=%s AND printerid=%s" % (self.doQuote(group.ident), self.doQuote(printer.ident)))
284            if result :
285                fields = result[0]
286                grouppquota.ident = fields.get("id")
287                grouppquota.SoftLimit = fields.get("softlimit")
288                grouppquota.HardLimit = fields.get("hardlimit")
289                grouppquota.DateLimit = fields.get("datelimit")
290                result = self.doSearch("SELECT SUM(lifepagecounter) AS lifepagecounter, SUM(pagecounter) AS pagecounter FROM userpquota WHERE printerid=%s AND userid IN (SELECT userid FROM groupsmembers WHERE groupid=%s)" % (self.doQuote(printer.ident), self.doQuote(group.ident)))
291                if result :
292                    fields = result[0]
293                    grouppquota.PageCounter = fields.get("pagecounter") or 0
294                    grouppquota.LifePageCounter = fields.get("lifepagecounter") or 0
295                grouppquota.Exists = 1
296        return grouppquota
297       
298    def getPrinterLastJobFromBackend(self, printer) :       
299        """Extracts a printer's last job information."""
300        lastjob = StorageLastJob(self, printer)
301        result = self.doSearch("SELECT jobhistory.id, jobid, userid, username, pagecounter, jobsize, jobprice, filename, title, copies, options, hostname, jobdate, md5sum, pages, billingcode, precomputedjobsize, precomputedjobprice FROM jobhistory, users WHERE printerid=%s AND userid=users.id ORDER BY jobdate DESC LIMIT 1" % self.doQuote(printer.ident))
302        if result :
303            fields = result[0]
304            lastjob.ident = fields.get("id")
305            lastjob.JobId = fields.get("jobid")
306            lastjob.UserName = self.databaseToUserCharset(fields.get("username"))
307            lastjob.PrinterPageCounter = fields.get("pagecounter")
308            lastjob.JobSize = fields.get("jobsize")
309            lastjob.JobPrice = fields.get("jobprice")
310            lastjob.JobAction = fields.get("action")
311            lastjob.JobFileName = self.databaseToUserCharset(fields.get("filename") or "") 
312            lastjob.JobTitle = self.databaseToUserCharset(fields.get("title") or "") 
313            lastjob.JobCopies = fields.get("copies")
314            lastjob.JobOptions = self.databaseToUserCharset(fields.get("options") or "") 
315            lastjob.JobDate = fields.get("jobdate")
316            lastjob.JobHostName = fields.get("hostname")
317            lastjob.JobSizeBytes = fields.get("jobsizebytes")
318            lastjob.JobMD5Sum = fields.get("md5sum")
319            lastjob.JobPages = fields.get("pages")
320            lastjob.JobBillingCode = self.databaseToUserCharset(fields.get("billingcode"))
321            lastjob.PrecomputedJobSize = fields.get("precomputedjobsize")
322            lastjob.PrecomputedJobPrice = fields.get("precomputedjobprice")
323            if lastjob.JobTitle == lastjob.JobFileName == lastjob.JobOptions == "hidden" :
324                (lastjob.JobTitle, lastjob.JobFileName, lastjob.JobOptions) = (_("Hidden because of privacy concerns"),) * 3
325            lastjob.Exists = 1
326        return lastjob
327           
328    def getGroupMembersFromBackend(self, group) :       
329        """Returns the group's members list."""
330        groupmembers = []
331        result = self.doSearch("SELECT * FROM groupsmembers JOIN users ON groupsmembers.userid=users.id WHERE groupid=%s" % self.doQuote(group.ident))
332        if result :
333            for record in result :
334                user = StorageUser(self, self.databaseToUserCharset(record.get("username")))
335                user.ident = record.get("userid")
336                user.LimitBy = record.get("limitby") or "quota"
337                user.AccountBalance = record.get("balance")
338                user.LifeTimePaid = record.get("lifetimepaid")
339                user.Email = record.get("email")
340                user.OverCharge = record.get("overcharge")
341                user.Exists = 1
342                groupmembers.append(user)
343                self.cacheEntry("USERS", user.Name, user)
344        return groupmembers       
345       
346    def getUserGroupsFromBackend(self, user) :       
347        """Returns the user's groups list."""
348        groups = []
349        result = self.doSearch("SELECT groupname FROM groupsmembers JOIN groups ON groupsmembers.groupid=groups.id WHERE userid=%s" % self.doQuote(user.ident))
350        if result :
351            for record in result :
352                groups.append(self.getGroup(self.databaseToUserCharset(record.get("groupname"))))
353        return groups       
354       
355    def getParentPrintersFromBackend(self, printer) :   
356        """Get all the printer groups this printer is a member of."""
357        pgroups = []
358        result = self.doSearch("SELECT groupid,printername FROM printergroupsmembers JOIN printers ON groupid=id WHERE printerid=%s" % self.doQuote(printer.ident))
359        if result :
360            for record in result :
361                if record["groupid"] != printer.ident : # in case of integrity violation
362                    parentprinter = self.getPrinter(self.databaseToUserCharset(record.get("printername")))
363                    if parentprinter.Exists :
364                        pgroups.append(parentprinter)
365        return pgroups
366       
367    def getMatchingPrinters(self, printerpattern) :
368        """Returns the list of all printers for which name matches a certain pattern."""
369        printers = []
370        # We 'could' do a SELECT printername FROM printers WHERE printername LIKE ...
371        # but we don't because other storages semantics may be different, so every
372        # storage should use fnmatch to match patterns and be storage agnostic
373        result = self.doSearch("SELECT * FROM printers")
374        if result :
375            patterns = printerpattern.split(",")
376            for record in result :
377                pname = self.databaseToUserCharset(record["printername"])
378                if self.tool.matchString(pname, patterns) :
379                    printer = StoragePrinter(self, pname)
380                    printer.ident = record.get("id")
381                    printer.PricePerJob = record.get("priceperjob") or 0.0
382                    printer.PricePerPage = record.get("priceperpage") or 0.0
383                    printer.Description = self.databaseToUserCharset(record.get("description") or "") 
384                    printer.MaxJobSize = record.get("maxjobsize") or 0
385                    printer.PassThrough = record.get("passthrough") or 0
386                    if printer.PassThrough in (1, "1", "t", "true", "TRUE", "True") :
387                        printer.PassThrough = 1
388                    else :
389                        printer.PassThrough = 0
390                    printer.Exists = 1
391                    printers.append(printer)
392                    self.cacheEntry("PRINTERS", printer.Name, printer)
393        return printers       
394       
395    def getMatchingUsers(self, userpattern) :
396        """Returns the list of all users for which name matches a certain pattern."""
397        users = []
398        # We 'could' do a SELECT username FROM users WHERE username LIKE ...
399        # but we don't because other storages semantics may be different, so every
400        # storage should use fnmatch to match patterns and be storage agnostic
401        result = self.doSearch("SELECT * FROM users")
402        if result :
403            patterns = userpattern.split(",")
404            for record in result :
405                uname = self.databaseToUserCharset(record["username"])
406                if self.tool.matchString(uname, patterns) :
407                    user = StorageUser(self, uname)
408                    user.ident = record.get("id")
409                    user.LimitBy = record.get("limitby") or "quota"
410                    user.AccountBalance = record.get("balance")
411                    user.LifeTimePaid = record.get("lifetimepaid")
412                    user.Email = record.get("email")
413                    user.Description = self.databaseToUserCharset(record.get("description"))
414                    user.OverCharge = record.get("overcharge", 1.0)
415                    user.Exists = 1
416                    users.append(user)
417                    self.cacheEntry("USERS", user.Name, user)
418        return users       
419       
420    def getMatchingGroups(self, grouppattern) :
421        """Returns the list of all groups for which name matches a certain pattern."""
422        groups = []
423        # We 'could' do a SELECT groupname FROM groups WHERE groupname LIKE ...
424        # but we don't because other storages semantics may be different, so every
425        # storage should use fnmatch to match patterns and be storage agnostic
426        result = self.doSearch("SELECT groups.*,COALESCE(SUM(balance), 0.0) AS balance, COALESCE(SUM(lifetimepaid), 0.0) AS lifetimepaid FROM groups LEFT OUTER JOIN users ON users.id IN (SELECT userid FROM groupsmembers WHERE groupid=groups.id) GROUP BY groups.id,groups.groupname,groups.limitby,groups.description")
427        if result :
428            patterns = grouppattern.split(",")
429            for record in result :
430                gname = self.databaseToUserCharset(record["groupname"])
431                if self.tool.matchString(gname, patterns) :
432                    group = StorageGroup(self, gname)
433                    group.ident = record.get("id")
434                    group.LimitBy = record.get("limitby") or "quota"
435                    group.AccountBalance = record.get("balance")
436                    group.LifeTimePaid = record.get("lifetimepaid")
437                    group.Description = self.databaseToUserCharset(record.get("description"))
438                    group.Exists = 1
439                    groups.append(group)
440                    self.cacheEntry("GROUPS", group.Name, group)
441        return groups       
442       
443    def getMatchingBillingCodes(self, billingcodepattern) :
444        """Returns the list of all billing codes for which the label matches a certain pattern."""
445        codes = []
446        result = self.doSearch("SELECT * FROM billingcodes")
447        if result :
448            patterns = billingcodepattern.split(",")
449            for record in result :
450                bcode = self.databaseToUserCharset(record["billingcode"])
451                if self.tool.matchString(bcode, patterns) :
452                    code = StorageBillingCode(self, bcode)
453                    code.ident = record.get("id")
454                    code.Balance = record.get("balance") or 0.0
455                    code.PageCounter = record.get("pagecounter") or 0
456                    code.Description = self.databaseToUserCharset(record.get("description") or "") 
457                    code.Exists = 1
458                    codes.append(code)
459                    self.cacheEntry("BILLINGCODES", code.BillingCode, code)
460        return codes       
461       
462    def getPrinterUsersAndQuotas(self, printer, names=["*"]) :       
463        """Returns the list of users who uses a given printer, along with their quotas."""
464        usersandquotas = []
465        result = self.doSearch("SELECT users.id as uid,username,balance,lifetimepaid,limitby,email,overcharge,userpquota.id,lifepagecounter,pagecounter,softlimit,hardlimit,datelimit,warncount FROM users JOIN userpquota ON users.id=userpquota.userid AND printerid=%s ORDER BY username ASC" % self.doQuote(printer.ident))
466        if result :
467            for record in result :
468                uname = self.databaseToUserCharset(record.get("username"))
469                if self.tool.matchString(uname, names) :
470                    user = StorageUser(self, uname)
471                    user.ident = record.get("uid")
472                    user.LimitBy = record.get("limitby") or "quota"
473                    user.AccountBalance = record.get("balance")
474                    user.LifeTimePaid = record.get("lifetimepaid")
475                    user.Email = record.get("email") 
476                    user.OverCharge = record.get("overcharge")
477                    user.Exists = 1
478                    userpquota = StorageUserPQuota(self, user, printer)
479                    userpquota.ident = record.get("id")
480                    userpquota.PageCounter = record.get("pagecounter")
481                    userpquota.LifePageCounter = record.get("lifepagecounter")
482                    userpquota.SoftLimit = record.get("softlimit")
483                    userpquota.HardLimit = record.get("hardlimit")
484                    userpquota.DateLimit = record.get("datelimit")
485                    userpquota.WarnCount = record.get("warncount")
486                    userpquota.Exists = 1
487                    usersandquotas.append((user, userpquota))
488                    self.cacheEntry("USERS", user.Name, user)
489                    self.cacheEntry("USERPQUOTAS", "%s@%s" % (user.Name, printer.Name), userpquota)
490        return usersandquotas
491               
492    def getPrinterGroupsAndQuotas(self, printer, names=["*"]) :       
493        """Returns the list of groups which uses a given printer, along with their quotas."""
494        groupsandquotas = []
495        result = self.doSearch("SELECT groupname FROM groups JOIN grouppquota ON groups.id=grouppquota.groupid AND printerid=%s ORDER BY groupname ASC" % self.doQuote(printer.ident))
496        if result :
497            for record in result :
498                gname = self.databaseToUserCharset(record.get("groupname"))
499                if self.tool.matchString(gname, names) :
500                    group = self.getGroup(gname)
501                    grouppquota = self.getGroupPQuota(group, printer)
502                    groupsandquotas.append((group, grouppquota))
503        return groupsandquotas
504       
505    def addPrinter(self, printername) :       
506        """Adds a printer to the quota storage, returns it."""
507        self.doModify("INSERT INTO printers (printername) VALUES (%s)" % self.doQuote(self.userCharsetToDatabase(printername)))
508        return self.getPrinter(printername)
509       
510    def addBillingCode(self, label) :       
511        """Adds a billing code to the quota storage, returns it."""
512        self.doModify("INSERT INTO billingcodes (billingcode) VALUES (%s)" % self.doQuote(self.userCharsetToDatabase(label)))
513        return self.getBillingCode(label)
514       
515    def addUser(self, user) :       
516        """Adds a user to the quota storage, returns it."""
517        self.doModify("INSERT INTO users (username, limitby, balance, lifetimepaid, email, overcharge) VALUES (%s, %s, %s, %s, %s, %s)" % \
518                                         (self.doQuote(self.userCharsetToDatabase(user.Name)), self.doQuote(user.LimitBy or 'quota'), self.doQuote(user.AccountBalance or 0.0), self.doQuote(user.LifeTimePaid or 0.0), self.doQuote(user.Email), self.doQuote(user.OverCharge)))
519        return self.getUser(user.Name)
520       
521    def addGroup(self, group) :       
522        """Adds a group to the quota storage, returns it."""
523        self.doModify("INSERT INTO groups (groupname, limitby) VALUES (%s, %s)" % \
524                                          (self.doQuote(self.userCharsetToDatabase(group.Name)), self.doQuote(group.LimitBy or "quota")))
525        return self.getGroup(group.Name)
526
527    def addUserToGroup(self, user, group) :   
528        """Adds an user to a group."""
529        result = self.doSearch("SELECT COUNT(*) AS mexists FROM groupsmembers WHERE groupid=%s AND userid=%s" % (self.doQuote(group.ident), self.doQuote(user.ident)))
530        try :
531            mexists = int(result[0].get("mexists"))
532        except (IndexError, TypeError) :   
533            mexists = 0
534        if not mexists :   
535            self.doModify("INSERT INTO groupsmembers (groupid, userid) VALUES (%s, %s)" % (self.doQuote(group.ident), self.doQuote(user.ident)))
536           
537    def addUserPQuota(self, user, printer) :
538        """Initializes a user print quota on a printer."""
539        self.doModify("INSERT INTO userpquota (userid, printerid) VALUES (%s, %s)" % (self.doQuote(user.ident), self.doQuote(printer.ident)))
540        return self.getUserPQuota(user, printer)
541       
542    def addGroupPQuota(self, group, printer) :
543        """Initializes a group print quota on a printer."""
544        self.doModify("INSERT INTO grouppquota (groupid, printerid) VALUES (%s, %s)" % (self.doQuote(group.ident), self.doQuote(printer.ident)))
545        return self.getGroupPQuota(group, printer)
546       
547    def writePrinterPrices(self, printer) :   
548        """Write the printer's prices back into the storage."""
549        self.doModify("UPDATE printers SET priceperpage=%s, priceperjob=%s WHERE id=%s" % (self.doQuote(printer.PricePerPage), self.doQuote(printer.PricePerJob), self.doQuote(printer.ident)))
550       
551    def writePrinterDescription(self, printer) :   
552        """Write the printer's description back into the storage."""
553        description = self.userCharsetToDatabase(printer.Description)
554        self.doModify("UPDATE printers SET description=%s WHERE id=%s" % (self.doQuote(description), self.doQuote(printer.ident)))
555       
556    def setPrinterMaxJobSize(self, printer, maxjobsize) :     
557        """Write the printer's maxjobsize attribute."""
558        self.doModify("UPDATE printers SET maxjobsize=%s WHERE id=%s" % (self.doQuote(maxjobsize), self.doQuote(printer.ident)))
559       
560    def setPrinterPassThroughMode(self, printer, passthrough) :
561        """Write the printer's passthrough attribute."""
562        self.doModify("UPDATE printers SET passthrough=%s WHERE id=%s" % (self.doQuote((passthrough and "t") or "f"), self.doQuote(printer.ident)))
563       
564    def writeUserOverCharge(self, user, factor) :
565        """Sets the user's overcharging coefficient."""
566        self.doModify("UPDATE users SET overcharge=%s WHERE id=%s" % (self.doQuote(factor), self.doQuote(user.ident)))
567       
568    def writeUserLimitBy(self, user, limitby) :   
569        """Sets the user's limiting factor."""
570        self.doModify("UPDATE users SET limitby=%s WHERE id=%s" % (self.doQuote(limitby), self.doQuote(user.ident)))
571       
572    def writeGroupLimitBy(self, group, limitby) :   
573        """Sets the group's limiting factor."""
574        self.doModify("UPDATE groups SET limitby=%s WHERE id=%s" % (self.doQuote(limitby), self.doQuote(group.ident)))
575       
576    def writeUserPQuotaDateLimit(self, userpquota, datelimit) :   
577        """Sets the date limit permanently for a user print quota."""
578        self.doModify("UPDATE userpquota SET datelimit=%s WHERE id=%s" % (self.doQuote(datelimit), self.doQuote(userpquota.ident)))
579           
580    def writeGroupPQuotaDateLimit(self, grouppquota, datelimit) :   
581        """Sets the date limit permanently for a group print quota."""
582        self.doModify("UPDATE grouppquota SET datelimit=%s WHERE id=%s" % (self.doQuote(datelimit), self.doQuote(grouppquota.ident)))
583       
584    def increaseUserPQuotaPagesCounters(self, userpquota, nbpages) :   
585        """Increase page counters for a user print quota."""
586        self.doModify("UPDATE userpquota SET pagecounter=pagecounter + %s,lifepagecounter=lifepagecounter + %s WHERE id=%s" % (self.doQuote(nbpages), self.doQuote(nbpages), self.doQuote(userpquota.ident)))
587       
588    def writeUserPQuotaPagesCounters(self, userpquota, newpagecounter, newlifepagecounter) :   
589        """Sets the new page counters permanently for a user print quota."""
590        self.doModify("UPDATE userpquota SET pagecounter=%s, lifepagecounter=%s, warncount=0, datelimit=NULL WHERE id=%s" % (self.doQuote(newpagecounter), self.doQuote(newlifepagecounter), self.doQuote(userpquota.ident)))
591       
592    def writeBillingCodeDescription(self, code) :
593        """Sets the new description for a billing code."""
594        self.doModify("UPDATE billingcodes SET description=%s WHERE id=%s" % (self.doQuote(self.userCharsetToDatabase(code.Description or "")), self.doQuote(code.ident)))
595       
596    def setBillingCodeValues(self, code, newpagecounter, newbalance) :   
597        """Sets the new page counter and balance for a billing code."""
598        self.doModify("UPDATE billingcodes SET balance=%s, pagecounter=%s WHERE id=%s" % (self.doQuote(newbalance), self.doQuote(newpagecounter), self.doQuote(code.ident)))
599       
600    def consumeBillingCode(self, code, pagecounter, balance) :
601        """Consumes from a billing code."""
602        self.doModify("UPDATE billingcodes SET balance=balance + %s, pagecounter=pagecounter + %s WHERE id=%s" % (self.doQuote(balance), self.doQuote(pagecounter), self.doQuote(code.ident)))
603       
604    def decreaseUserAccountBalance(self, user, amount) :   
605        """Decreases user's account balance from an amount."""
606        self.doModify("UPDATE users SET balance=balance - %s WHERE id=%s" % (self.doQuote(amount), self.doQuote(user.ident)))
607       
608    def writeUserAccountBalance(self, user, newbalance, newlifetimepaid=None) :   
609        """Sets the new account balance and eventually new lifetime paid."""
610        if newlifetimepaid is not None :
611            self.doModify("UPDATE users SET balance=%s, lifetimepaid=%s WHERE id=%s" % (self.doQuote(newbalance), self.doQuote(newlifetimepaid), self.doQuote(user.ident)))
612        else :   
613            self.doModify("UPDATE users SET balance=%s WHERE id=%s" % (self.doQuote(newbalance), self.doQuote(user.ident)))
614           
615    def writeNewPayment(self, user, amount, comment="") :
616        """Adds a new payment to the payments history."""
617        self.doModify("INSERT INTO payments (userid, amount, description) VALUES (%s, %s, %s)" % (self.doQuote(user.ident), self.doQuote(amount), self.doQuote(self.userCharsetToDatabase(comment))))
618       
619    def writeLastJobSize(self, lastjob, jobsize, jobprice) :       
620        """Sets the last job's size permanently."""
621        self.doModify("UPDATE jobhistory SET jobsize=%s, jobprice=%s WHERE id=%s" % (self.doQuote(jobsize), self.doQuote(jobprice), self.doQuote(lastjob.ident)))
622       
623    def writeJobNew(self, printer, user, jobid, pagecounter, action, jobsize=None, jobprice=None, filename=None, title=None, copies=None, options=None, clienthost=None, jobsizebytes=None, jobmd5sum=None, jobpages=None, jobbilling=None, precomputedsize=None, precomputedprice=None) :
624        """Adds a job in a printer's history."""
625        if self.privacy :   
626            # For legal reasons, we want to hide the title, filename and options
627            title = filename = options = "hidden"
628        filename = self.userCharsetToDatabase(filename)
629        title = self.userCharsetToDatabase(title)
630        options = self.userCharsetToDatabase(options)
631        jobbilling = self.userCharsetToDatabase(jobbilling)
632        if (not self.disablehistory) or (not printer.LastJob.Exists) :
633            if jobsize is not None :
634                self.doModify("INSERT INTO jobhistory (userid, printerid, jobid, pagecounter, action, jobsize, jobprice, filename, title, copies, options, hostname, jobsizebytes, md5sum, pages, billingcode, precomputedjobsize, precomputedjobprice) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)" % (self.doQuote(user.ident), self.doQuote(printer.ident), self.doQuote(jobid), self.doQuote(pagecounter), self.doQuote(action), self.doQuote(jobsize), self.doQuote(jobprice), self.doQuote(filename), self.doQuote(title), self.doQuote(copies), self.doQuote(options), self.doQuote(clienthost), self.doQuote(jobsizebytes), self.doQuote(jobmd5sum), self.doQuote(jobpages), self.doQuote(jobbilling), self.doQuote(precomputedsize), self.doQuote(precomputedprice)))
635            else :   
636                self.doModify("INSERT INTO jobhistory (userid, printerid, jobid, pagecounter, action, filename, title, copies, options, hostname, jobsizebytes, md5sum, pages, billingcode, precomputedjobsize, precomputedjobprice) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)" % (self.doQuote(user.ident), self.doQuote(printer.ident), self.doQuote(jobid), self.doQuote(pagecounter), self.doQuote(action), self.doQuote(filename), self.doQuote(title), self.doQuote(copies), self.doQuote(options), self.doQuote(clienthost), self.doQuote(jobsizebytes), self.doQuote(jobmd5sum), self.doQuote(jobpages), self.doQuote(jobbilling), self.doQuote(precomputedsize), self.doQuote(precomputedprice)))
637        else :       
638            # here we explicitly want to reset jobsize to NULL if needed
639            self.doModify("UPDATE jobhistory SET userid=%s, jobid=%s, pagecounter=%s, action=%s, jobsize=%s, jobprice=%s, filename=%s, title=%s, copies=%s, options=%s, hostname=%s, jobsizebytes=%s, md5sum=%s, pages=%s, billingcode=%s, precomputedjobsize=%s, precomputedjobprice=%s, jobdate=now() WHERE id=%s" % (self.doQuote(user.ident), self.doQuote(jobid), self.doQuote(pagecounter), self.doQuote(action), self.doQuote(jobsize), self.doQuote(jobprice), self.doQuote(filename), self.doQuote(title), self.doQuote(copies), self.doQuote(options), self.doQuote(clienthost), self.doQuote(jobsizebytes), self.doQuote(jobmd5sum), self.doQuote(jobpages), self.doQuote(jobbilling), self.doQuote(precomputedsize), self.doQuote(precomputedprice), self.doQuote(printer.LastJob.ident)))
640           
641    def writeUserPQuotaLimits(self, userpquota, softlimit, hardlimit) :
642        """Sets soft and hard limits for a user quota."""
643        self.doModify("UPDATE userpquota SET softlimit=%s, hardlimit=%s, warncount=0, datelimit=NULL WHERE id=%s" % (self.doQuote(softlimit), self.doQuote(hardlimit), self.doQuote(userpquota.ident)))
644       
645    def writeUserPQuotaWarnCount(self, userpquota, warncount) :
646        """Sets the warn counter value for a user quota."""
647        self.doModify("UPDATE userpquota SET warncount=%s WHERE id=%s" % (self.doQuote(warncount), self.doQuote(userpquota.ident)))
648       
649    def increaseUserPQuotaWarnCount(self, userpquota) :
650        """Increases the warn counter value for a user quota."""
651        self.doModify("UPDATE userpquota SET warncount=warncount+1 WHERE id=%s" % self.doQuote(userpquota.ident))
652       
653    def writeGroupPQuotaLimits(self, grouppquota, softlimit, hardlimit) :
654        """Sets soft and hard limits for a group quota on a specific printer."""
655        self.doModify("UPDATE grouppquota SET softlimit=%s, hardlimit=%s, datelimit=NULL WHERE id=%s" % (self.doQuote(softlimit), self.doQuote(hardlimit), self.doQuote(grouppquota.ident)))
656
657    def writePrinterToGroup(self, pgroup, printer) :
658        """Puts a printer into a printer group."""
659        children = []
660        result = self.doSearch("SELECT printerid FROM printergroupsmembers WHERE groupid=%s" % self.doQuote(pgroup.ident))
661        if result :
662            for record in result :
663                children.append(record.get("printerid")) # TODO : put this into the database integrity rules
664        if printer.ident not in children :       
665            self.doModify("INSERT INTO printergroupsmembers (groupid, printerid) VALUES (%s, %s)" % (self.doQuote(pgroup.ident), self.doQuote(printer.ident)))
666       
667    def removePrinterFromGroup(self, pgroup, printer) :
668        """Removes a printer from a printer group."""
669        self.doModify("DELETE FROM printergroupsmembers WHERE groupid=%s AND printerid=%s" % (self.doQuote(pgroup.ident), self.doQuote(printer.ident)))
670       
671    def retrieveHistory(self, user=None, printer=None, hostname=None, billingcode=None, limit=100, start=None, end=None) :
672        """Retrieves all print jobs for user on printer (or all) between start and end date, limited to first 100 results."""
673        query = "SELECT jobhistory.*,username,printername FROM jobhistory,users,printers WHERE users.id=userid AND printers.id=printerid"
674        where = []
675        if user is not None : # user.ident is None anyway if user doesn't exist
676            where.append("userid=%s" % self.doQuote(user.ident))
677        if printer is not None : # printer.ident is None anyway if printer doesn't exist
678            where.append("printerid=%s" % self.doQuote(printer.ident))
679        if hostname is not None :   
680            where.append("hostname=%s" % self.doQuote(hostname))
681        if billingcode is not None :   
682            where.append("billingcode=%s" % self.doQuote(self.userCharsetToDatabase(billingcode)))
683        if start is not None :   
684            where.append("jobdate>=%s" % self.doQuote(start))
685        if end is not None :   
686            where.append("jobdate<=%s" % self.doQuote(end))
687        if where :   
688            query += " AND %s" % " AND ".join(where)
689        query += " ORDER BY jobhistory.id DESC"
690        if limit :
691            query += " LIMIT %s" % self.doQuote(int(limit))
692        jobs = []   
693        result = self.doSearch(query)   
694        if result :
695            for fields in result :
696                job = StorageJob(self)
697                job.ident = fields.get("id")
698                job.JobId = fields.get("jobid")
699                job.PrinterPageCounter = fields.get("pagecounter")
700                job.JobSize = fields.get("jobsize")
701                job.JobPrice = fields.get("jobprice")
702                job.JobAction = fields.get("action")
703                job.JobFileName = self.databaseToUserCharset(fields.get("filename") or "") 
704                job.JobTitle = self.databaseToUserCharset(fields.get("title") or "") 
705                job.JobCopies = fields.get("copies")
706                job.JobOptions = self.databaseToUserCharset(fields.get("options") or "") 
707                job.JobDate = fields.get("jobdate")
708                job.JobHostName = fields.get("hostname")
709                job.JobSizeBytes = fields.get("jobsizebytes")
710                job.JobMD5Sum = fields.get("md5sum")
711                job.JobPages = fields.get("pages")
712                job.JobBillingCode = self.databaseToUserCharset(fields.get("billingcode") or "")
713                job.PrecomputedJobSize = fields.get("precomputedjobsize")
714                job.PrecomputedJobPrice = fields.get("precomputedjobprice")
715                job.UserName = self.databaseToUserCharset(fields.get("username"))
716                job.PrinterName = self.databaseToUserCharset(fields.get("printername"))
717                if job.JobTitle == job.JobFileName == job.JobOptions == "hidden" :
718                    (job.JobTitle, job.JobFileName, job.JobOptions) = (_("Hidden because of privacy concerns"),) * 3
719                job.Exists = 1
720                jobs.append(job)
721        return jobs
722       
723    def deleteUser(self, user) :   
724        """Completely deletes an user from the Quota Storage."""
725        # TODO : What should we do if we delete the last person who used a given printer ?
726        # TODO : we can't reassign the last job to the previous one, because next user would be
727        # TODO : incorrectly charged (overcharged).
728        for q in [ 
729                    "DELETE FROM payments WHERE userid=%s" % self.doQuote(user.ident),
730                    "DELETE FROM groupsmembers WHERE userid=%s" % self.doQuote(user.ident),
731                    "DELETE FROM jobhistory WHERE userid=%s" % self.doQuote(user.ident),
732                    "DELETE FROM userpquota WHERE userid=%s" % self.doQuote(user.ident),
733                    "DELETE FROM users WHERE id=%s" % self.doQuote(user.ident),
734                  ] :
735            self.doModify(q)
736       
737    def deleteGroup(self, group) :   
738        """Completely deletes a group from the Quota Storage."""
739        for q in [
740                   "DELETE FROM groupsmembers WHERE groupid=%s" % self.doQuote(group.ident),
741                   "DELETE FROM grouppquota WHERE groupid=%s" % self.doQuote(group.ident),
742                   "DELETE FROM groups WHERE id=%s" % self.doQuote(group.ident),
743                 ] : 
744            self.doModify(q)
745           
746    def deletePrinter(self, printer) :   
747        """Completely deletes a printer from the Quota Storage."""
748        for q in [ 
749                    "DELETE FROM printergroupsmembers WHERE groupid=%s OR printerid=%s" % (self.doQuote(printer.ident), self.doQuote(printer.ident)),
750                    "DELETE FROM jobhistory WHERE printerid=%s" % self.doQuote(printer.ident),
751                    "DELETE FROM grouppquota WHERE printerid=%s" % self.doQuote(printer.ident),
752                    "DELETE FROM userpquota WHERE printerid=%s" % self.doQuote(printer.ident),
753                    "DELETE FROM printers WHERE id=%s" % self.doQuote(printer.ident),
754                  ] :
755            self.doModify(q)
756           
757    def deleteBillingCode(self, code) :   
758        """Completely deletes a billing code from the Quota Storage."""
759        for q in [
760                   "DELETE FROM billingcodes WHERE id=%s" % self.doQuote(code.ident),
761                 ] : 
762            self.doModify(q)
763       
Note: See TracBrowser for help on using the browser.