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

Revision 2599, 41.1 kB (checked in by jerome, 18 years ago)

Fixed bad import, because some code moved

  • 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., 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 getAllUsersNames(self) :   
138        """Extracts all user names."""
139        usernames = []
140        result = self.doSearch("SELECT username FROM users")
141        if result :
142            usernames = [record["username"] for record in result]
143        return usernames
144       
145    def getAllGroupsNames(self) :   
146        """Extracts all group names."""
147        groupnames = []
148        result = self.doSearch("SELECT groupname FROM groups")
149        if result :
150            groupnames = [record["groupname"] for record in result]
151        return groupnames
152       
153    def getUserNbJobsFromHistory(self, user) :
154        """Returns the number of jobs the user has in history."""
155        result = self.doSearch("SELECT COUNT(*) FROM jobhistory WHERE userid=%s" % self.doQuote(user.ident))
156        if result :
157            return result[0]["count"]
158        return 0
159       
160    def getUserFromBackend(self, username) :   
161        """Extracts user information given its name."""
162        user = StorageUser(self, username)
163        result = self.doSearch("SELECT * FROM users WHERE username=%s LIMIT 1" % self.doQuote(username))
164        if result :
165            fields = result[0]
166            user.ident = fields.get("id")
167            user.Name = fields.get("username", username)
168            user.LimitBy = fields.get("limitby") or "quota"
169            user.AccountBalance = fields.get("balance")
170            user.LifeTimePaid = fields.get("lifetimepaid")
171            user.Email = fields.get("email")
172            user.OverCharge = fields.get("overcharge", 1.0)
173            user.Exists = 1
174        return user
175       
176    def getGroupFromBackend(self, groupname) :   
177        """Extracts group information given its name."""
178        group = StorageGroup(self, groupname)
179        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))
180        if result :
181            fields = result[0]
182            group.ident = fields.get("id")
183            group.Name = fields.get("groupname", groupname)
184            group.LimitBy = fields.get("limitby") or "quota"
185            group.AccountBalance = fields.get("balance")
186            group.LifeTimePaid = fields.get("lifetimepaid")
187            group.Exists = 1
188        return group
189       
190    def getPrinterFromBackend(self, printername) :       
191        """Extracts printer information given its name."""
192        printer = StoragePrinter(self, printername)
193        result = self.doSearch("SELECT * FROM printers WHERE printername=%s LIMIT 1" % self.doQuote(printername))
194        if result :
195            fields = result[0]
196            printer.ident = fields.get("id")
197            printer.Name = fields.get("printername", printername)
198            printer.PricePerJob = fields.get("priceperjob") or 0.0
199            printer.PricePerPage = fields.get("priceperpage") or 0.0
200            printer.MaxJobSize = fields.get("maxjobsize") or 0
201            printer.PassThrough = fields.get("passthrough") or 0
202            if printer.PassThrough in (1, "1", "t", "true", "TRUE", "True") :
203                printer.PassThrough = 1
204            else :
205                printer.PassThrough = 0
206            printer.Description = self.databaseToUserCharset(fields.get("description") or "")
207            printer.Exists = 1
208        return printer   
209       
210    def getBillingCodeFromBackend(self, label) :       
211        """Extracts a billing code information given its name."""
212        code = StorageBillingCode(self, label)
213        result = self.doSearch("SELECT * FROM billingcodes WHERE billingcode=%s LIMIT 1" % self.doQuote(self.userCharsetToDatabase(label)))
214        if result :
215            fields = result[0]
216            code.ident = fields.get("id")
217            code.BillingCode = self.databaseToUserCharset(fields.get("billingcode"))
218            code.Description = self.databaseToUserCharset(fields.get("description") or "")
219            code.Balance = fields.get("balance") or 0.0
220            code.PageCounter = fields.get("pagecounter") or 0
221            code.Exists = 1
222        return code   
223       
224    def getUserPQuotaFromBackend(self, user, printer) :       
225        """Extracts a user print quota."""
226        userpquota = StorageUserPQuota(self, user, printer)
227        if printer.Exists and user.Exists :
228            result = self.doSearch("SELECT * FROM userpquota WHERE userid=%s AND printerid=%s" % (self.doQuote(user.ident), self.doQuote(printer.ident)))
229            if result :
230                fields = result[0]
231                userpquota.ident = fields.get("id")
232                userpquota.PageCounter = fields.get("pagecounter")
233                userpquota.LifePageCounter = fields.get("lifepagecounter")
234                userpquota.SoftLimit = fields.get("softlimit")
235                userpquota.HardLimit = fields.get("hardlimit")
236                userpquota.DateLimit = fields.get("datelimit")
237                userpquota.WarnCount = fields.get("warncount")
238                userpquota.Exists = 1
239        return userpquota
240       
241    def getGroupPQuotaFromBackend(self, group, printer) :       
242        """Extracts a group print quota."""
243        grouppquota = StorageGroupPQuota(self, group, printer)
244        if group.Exists :
245            result = self.doSearch("SELECT * FROM grouppquota WHERE groupid=%s AND printerid=%s" % (self.doQuote(group.ident), self.doQuote(printer.ident)))
246            if result :
247                fields = result[0]
248                grouppquota.ident = fields.get("id")
249                grouppquota.SoftLimit = fields.get("softlimit")
250                grouppquota.HardLimit = fields.get("hardlimit")
251                grouppquota.DateLimit = fields.get("datelimit")
252                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)))
253                if result :
254                    fields = result[0]
255                    grouppquota.PageCounter = fields.get("pagecounter") or 0
256                    grouppquota.LifePageCounter = fields.get("lifepagecounter") or 0
257                grouppquota.Exists = 1
258        return grouppquota
259       
260    def getPrinterLastJobFromBackend(self, printer) :       
261        """Extracts a printer's last job information."""
262        lastjob = StorageLastJob(self, printer)
263        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))
264        if result :
265            fields = result[0]
266            lastjob.ident = fields.get("id")
267            lastjob.JobId = fields.get("jobid")
268            lastjob.UserName = fields.get("username")
269            lastjob.PrinterPageCounter = fields.get("pagecounter")
270            lastjob.JobSize = fields.get("jobsize")
271            lastjob.JobPrice = fields.get("jobprice")
272            lastjob.JobAction = fields.get("action")
273            lastjob.JobFileName = self.databaseToUserCharset(fields.get("filename") or "") 
274            lastjob.JobTitle = self.databaseToUserCharset(fields.get("title") or "") 
275            lastjob.JobCopies = fields.get("copies")
276            lastjob.JobOptions = self.databaseToUserCharset(fields.get("options") or "") 
277            lastjob.JobDate = fields.get("jobdate")
278            lastjob.JobHostName = fields.get("hostname")
279            lastjob.JobSizeBytes = fields.get("jobsizebytes")
280            lastjob.JobMD5Sum = fields.get("md5sum")
281            lastjob.JobPages = fields.get("pages")
282            lastjob.JobBillingCode = self.databaseToUserCharset(fields.get("billingcode"))
283            lastjob.PrecomputedJobSize = fields.get("precomputedjobsize")
284            lastjob.PrecomputedJobPrice = fields.get("precomputedjobprice")
285            if lastjob.JobTitle == lastjob.JobFileName == lastjob.JobOptions == "hidden" :
286                (lastjob.JobTitle, lastjob.JobFileName, lastjob.JobOptions) = (_("Hidden because of privacy concerns"),) * 3
287            lastjob.Exists = 1
288        return lastjob
289           
290    def getGroupMembersFromBackend(self, group) :       
291        """Returns the group's members list."""
292        groupmembers = []
293        result = self.doSearch("SELECT * FROM groupsmembers JOIN users ON groupsmembers.userid=users.id WHERE groupid=%s" % self.doQuote(group.ident))
294        if result :
295            for record in result :
296                user = StorageUser(self, record.get("username"))
297                user.ident = record.get("userid")
298                user.LimitBy = record.get("limitby") or "quota"
299                user.AccountBalance = record.get("balance")
300                user.LifeTimePaid = record.get("lifetimepaid")
301                user.Email = record.get("email")
302                user.OverCharge = record.get("overcharge")
303                user.Exists = 1
304                groupmembers.append(user)
305                self.cacheEntry("USERS", user.Name, user)
306        return groupmembers       
307       
308    def getUserGroupsFromBackend(self, user) :       
309        """Returns the user's groups list."""
310        groups = []
311        result = self.doSearch("SELECT groupname FROM groupsmembers JOIN groups ON groupsmembers.groupid=groups.id WHERE userid=%s" % self.doQuote(user.ident))
312        if result :
313            for record in result :
314                groups.append(self.getGroup(record.get("groupname")))
315        return groups       
316       
317    def getParentPrintersFromBackend(self, printer) :   
318        """Get all the printer groups this printer is a member of."""
319        pgroups = []
320        result = self.doSearch("SELECT groupid,printername FROM printergroupsmembers JOIN printers ON groupid=id WHERE printerid=%s" % self.doQuote(printer.ident))
321        if result :
322            for record in result :
323                if record["groupid"] != printer.ident : # in case of integrity violation
324                    parentprinter = self.getPrinter(record.get("printername"))
325                    if parentprinter.Exists :
326                        pgroups.append(parentprinter)
327        return pgroups
328       
329    def getMatchingPrinters(self, printerpattern) :
330        """Returns the list of all printers for which name matches a certain pattern."""
331        printers = []
332        # We 'could' do a SELECT printername FROM printers WHERE printername LIKE ...
333        # but we don't because other storages semantics may be different, so every
334        # storage should use fnmatch to match patterns and be storage agnostic
335        result = self.doSearch("SELECT * FROM printers")
336        if result :
337            for record in result :
338                if self.tool.matchString(record["printername"], printerpattern.split(",")) :
339                    printer = StoragePrinter(self, record["printername"])
340                    printer.ident = record.get("id")
341                    printer.PricePerJob = record.get("priceperjob") or 0.0
342                    printer.PricePerPage = record.get("priceperpage") or 0.0
343                    printer.Description = self.databaseToUserCharset(record.get("description") or "") 
344                    printer.MaxJobSize = record.get("maxjobsize") or 0
345                    printer.PassThrough = record.get("passthrough") or 0
346                    if printer.PassThrough in (1, "1", "t", "true", "TRUE", "True") :
347                        printer.PassThrough = 1
348                    else :
349                        printer.PassThrough = 0
350                    printer.Exists = 1
351                    printers.append(printer)
352                    self.cacheEntry("PRINTERS", printer.Name, printer)
353        return printers       
354       
355    def getMatchingBillingCodes(self, billingcodepattern) :
356        """Returns the list of all billing codes for which the label matches a certain pattern."""
357        codes = []
358        result = self.doSearch("SELECT * FROM billingcodes")
359        if result :
360            for record in result :
361                bcode = self.databaseToUserCharset(record["billingcode"])
362                if self.tool.matchString(bcode, billingcodepattern.split(",")) :
363                    code = StorageBillingCode(self, bcode)
364                    code.ident = record.get("id")
365                    code.Balance = record.get("balance") or 0.0
366                    code.PageCounter = record.get("pagecounter") or 0
367                    code.Description = self.databaseToUserCharset(record.get("description") or "") 
368                    code.Exists = 1
369                    codes.append(code)
370                    self.cacheEntry("BILLINGCODES", code.BillingCode, code)
371        return codes       
372       
373    def getPrinterUsersAndQuotas(self, printer, names=["*"]) :       
374        """Returns the list of users who uses a given printer, along with their quotas."""
375        usersandquotas = []
376        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))
377        if result :
378            for record in result :
379                if self.tool.matchString(record.get("username"), names) :
380                    user = StorageUser(self, record.get("username"))
381                    user.ident = record.get("uid")
382                    user.LimitBy = record.get("limitby") or "quota"
383                    user.AccountBalance = record.get("balance")
384                    user.LifeTimePaid = record.get("lifetimepaid")
385                    user.Email = record.get("email") 
386                    user.OverCharge = record.get("overcharge")
387                    user.Exists = 1
388                    userpquota = StorageUserPQuota(self, user, printer)
389                    userpquota.ident = record.get("id")
390                    userpquota.PageCounter = record.get("pagecounter")
391                    userpquota.LifePageCounter = record.get("lifepagecounter")
392                    userpquota.SoftLimit = record.get("softlimit")
393                    userpquota.HardLimit = record.get("hardlimit")
394                    userpquota.DateLimit = record.get("datelimit")
395                    userpquota.WarnCount = record.get("warncount")
396                    userpquota.Exists = 1
397                    usersandquotas.append((user, userpquota))
398                    self.cacheEntry("USERS", user.Name, user)
399                    self.cacheEntry("USERPQUOTAS", "%s@%s" % (user.Name, printer.Name), userpquota)
400        return usersandquotas
401               
402    def getPrinterGroupsAndQuotas(self, printer, names=["*"]) :       
403        """Returns the list of groups which uses a given printer, along with their quotas."""
404        groupsandquotas = []
405        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))
406        if result :
407            for record in result :
408                if self.tool.matchString(record.get("groupname"), names) :
409                    group = self.getGroup(record.get("groupname"))
410                    grouppquota = self.getGroupPQuota(group, printer)
411                    groupsandquotas.append((group, grouppquota))
412        return groupsandquotas
413       
414    def addPrinter(self, printername) :       
415        """Adds a printer to the quota storage, returns it."""
416        self.doModify("INSERT INTO printers (printername) VALUES (%s)" % self.doQuote(printername))
417        return self.getPrinter(printername)
418       
419    def addBillingCode(self, label) :       
420        """Adds a billing code to the quota storage, returns it."""
421        self.doModify("INSERT INTO billingcodes (billingcode) VALUES (%s)" % self.doQuote(self.userCharsetToDatabase(label)))
422        return self.getBillingCode(label)
423       
424    def addUser(self, user) :       
425        """Adds a user to the quota storage, returns it."""
426        self.doModify("INSERT INTO users (username, limitby, balance, lifetimepaid, email, overcharge) VALUES (%s, %s, %s, %s, %s, %s)" % (self.doQuote(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)))
427        return self.getUser(user.Name)
428       
429    def addGroup(self, group) :       
430        """Adds a group to the quota storage, returns it."""
431        self.doModify("INSERT INTO groups (groupname, limitby) VALUES (%s, %s)" % (self.doQuote(group.Name), self.doQuote(group.LimitBy or "quota")))
432        return self.getGroup(group.Name)
433
434    def addUserToGroup(self, user, group) :   
435        """Adds an user to a group."""
436        result = self.doSearch("SELECT COUNT(*) AS mexists FROM groupsmembers WHERE groupid=%s AND userid=%s" % (self.doQuote(group.ident), self.doQuote(user.ident)))
437        try :
438            mexists = int(result[0].get("mexists"))
439        except (IndexError, TypeError) :   
440            mexists = 0
441        if not mexists :   
442            self.doModify("INSERT INTO groupsmembers (groupid, userid) VALUES (%s, %s)" % (self.doQuote(group.ident), self.doQuote(user.ident)))
443           
444    def addUserPQuota(self, user, printer) :
445        """Initializes a user print quota on a printer."""
446        self.doModify("INSERT INTO userpquota (userid, printerid) VALUES (%s, %s)" % (self.doQuote(user.ident), self.doQuote(printer.ident)))
447        return self.getUserPQuota(user, printer)
448       
449    def addGroupPQuota(self, group, printer) :
450        """Initializes a group print quota on a printer."""
451        self.doModify("INSERT INTO grouppquota (groupid, printerid) VALUES (%s, %s)" % (self.doQuote(group.ident), self.doQuote(printer.ident)))
452        return self.getGroupPQuota(group, printer)
453       
454    def writePrinterPrices(self, printer) :   
455        """Write the printer's prices back into the storage."""
456        self.doModify("UPDATE printers SET priceperpage=%s, priceperjob=%s WHERE id=%s" % (self.doQuote(printer.PricePerPage), self.doQuote(printer.PricePerJob), self.doQuote(printer.ident)))
457       
458    def writePrinterDescription(self, printer) :   
459        """Write the printer's description back into the storage."""
460        description = self.userCharsetToDatabase(printer.Description)
461        self.doModify("UPDATE printers SET description=%s WHERE id=%s" % (self.doQuote(description), self.doQuote(printer.ident)))
462       
463    def setPrinterMaxJobSize(self, printer, maxjobsize) :     
464        """Write the printer's maxjobsize attribute."""
465        self.doModify("UPDATE printers SET maxjobsize=%s WHERE id=%s" % (self.doQuote(maxjobsize), self.doQuote(printer.ident)))
466       
467    def setPrinterPassThroughMode(self, printer, passthrough) :
468        """Write the printer's passthrough attribute."""
469        self.doModify("UPDATE printers SET passthrough=%s WHERE id=%s" % (self.doQuote((passthrough and "t") or "f"), self.doQuote(printer.ident)))
470       
471    def writeUserOverCharge(self, user, factor) :
472        """Sets the user's overcharging coefficient."""
473        self.doModify("UPDATE users SET overcharge=%s WHERE id=%s" % (self.doQuote(factor), self.doQuote(user.ident)))
474       
475    def writeUserLimitBy(self, user, limitby) :   
476        """Sets the user's limiting factor."""
477        self.doModify("UPDATE users SET limitby=%s WHERE id=%s" % (self.doQuote(limitby), self.doQuote(user.ident)))
478       
479    def writeGroupLimitBy(self, group, limitby) :   
480        """Sets the group's limiting factor."""
481        self.doModify("UPDATE groups SET limitby=%s WHERE id=%s" % (self.doQuote(limitby), self.doQuote(group.ident)))
482       
483    def writeUserPQuotaDateLimit(self, userpquota, datelimit) :   
484        """Sets the date limit permanently for a user print quota."""
485        self.doModify("UPDATE userpquota SET datelimit=%s WHERE id=%s" % (self.doQuote(datelimit), self.doQuote(userpquota.ident)))
486           
487    def writeGroupPQuotaDateLimit(self, grouppquota, datelimit) :   
488        """Sets the date limit permanently for a group print quota."""
489        self.doModify("UPDATE grouppquota SET datelimit=%s WHERE id=%s" % (self.doQuote(datelimit), self.doQuote(grouppquota.ident)))
490       
491    def increaseUserPQuotaPagesCounters(self, userpquota, nbpages) :   
492        """Increase page counters for a user print quota."""
493        self.doModify("UPDATE userpquota SET pagecounter=pagecounter + %s,lifepagecounter=lifepagecounter + %s WHERE id=%s" % (self.doQuote(nbpages), self.doQuote(nbpages), self.doQuote(userpquota.ident)))
494       
495    def writeUserPQuotaPagesCounters(self, userpquota, newpagecounter, newlifepagecounter) :   
496        """Sets the new page counters permanently for a user print quota."""
497        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)))
498       
499    def writeBillingCodeDescription(self, code) :
500        """Sets the new description for a billing code."""
501        self.doModify("UPDATE billingcodes SET description=%s WHERE id=%s" % (self.doQuote(self.userCharsetToDatabase(code.Description or "")), self.doQuote(code.ident)))
502       
503    def setBillingCodeValues(self, code, newpagecounter, newbalance) :   
504        """Sets the new page counter and balance for a billing code."""
505        self.doModify("UPDATE billingcodes SET balance=%s, pagecounter=%s WHERE id=%s" % (self.doQuote(newbalance), self.doQuote(newpagecounter), self.doQuote(code.ident)))
506       
507    def consumeBillingCode(self, code, pagecounter, balance) :
508        """Consumes from a billing code."""
509        self.doModify("UPDATE billingcodes SET balance=balance + %s, pagecounter=pagecounter + %s WHERE id=%s" % (self.doQuote(balance), self.doQuote(pagecounter), self.doQuote(code.ident)))
510       
511    def decreaseUserAccountBalance(self, user, amount) :   
512        """Decreases user's account balance from an amount."""
513        self.doModify("UPDATE users SET balance=balance - %s WHERE id=%s" % (self.doQuote(amount), self.doQuote(user.ident)))
514       
515    def writeUserAccountBalance(self, user, newbalance, newlifetimepaid=None) :   
516        """Sets the new account balance and eventually new lifetime paid."""
517        if newlifetimepaid is not None :
518            self.doModify("UPDATE users SET balance=%s, lifetimepaid=%s WHERE id=%s" % (self.doQuote(newbalance), self.doQuote(newlifetimepaid), self.doQuote(user.ident)))
519        else :   
520            self.doModify("UPDATE users SET balance=%s WHERE id=%s" % (self.doQuote(newbalance), self.doQuote(user.ident)))
521           
522    def writeNewPayment(self, user, amount, comment="") :
523        """Adds a new payment to the payments history."""
524        self.doModify("INSERT INTO payments (userid, amount, description) VALUES (%s, %s, %s)" % (self.doQuote(user.ident), self.doQuote(amount), self.doQuote(comment)))
525       
526    def writeLastJobSize(self, lastjob, jobsize, jobprice) :       
527        """Sets the last job's size permanently."""
528        self.doModify("UPDATE jobhistory SET jobsize=%s, jobprice=%s WHERE id=%s" % (self.doQuote(jobsize), self.doQuote(jobprice), self.doQuote(lastjob.ident)))
529       
530    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) :
531        """Adds a job in a printer's history."""
532        if self.privacy :   
533            # For legal reasons, we want to hide the title, filename and options
534            title = filename = options = "hidden"
535        filename = self.userCharsetToDatabase(filename)
536        title = self.userCharsetToDatabase(title)
537        options = self.userCharsetToDatabase(options)
538        jobbilling = self.userCharsetToDatabase(jobbilling)
539        if (not self.disablehistory) or (not printer.LastJob.Exists) :
540            if jobsize is not None :
541                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)))
542            else :   
543                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)))
544        else :       
545            # here we explicitly want to reset jobsize to NULL if needed
546            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)))
547           
548    def writeUserPQuotaLimits(self, userpquota, softlimit, hardlimit) :
549        """Sets soft and hard limits for a user quota."""
550        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)))
551       
552    def writeUserPQuotaWarnCount(self, userpquota, warncount) :
553        """Sets the warn counter value for a user quota."""
554        self.doModify("UPDATE userpquota SET warncount=%s WHERE id=%s" % (self.doQuote(warncount), self.doQuote(userpquota.ident)))
555       
556    def increaseUserPQuotaWarnCount(self, userpquota) :
557        """Increases the warn counter value for a user quota."""
558        self.doModify("UPDATE userpquota SET warncount=warncount+1 WHERE id=%s" % self.doQuote(userpquota.ident))
559       
560    def writeGroupPQuotaLimits(self, grouppquota, softlimit, hardlimit) :
561        """Sets soft and hard limits for a group quota on a specific printer."""
562        self.doModify("UPDATE grouppquota SET softlimit=%s, hardlimit=%s, datelimit=NULL WHERE id=%s" % (self.doQuote(softlimit), self.doQuote(hardlimit), self.doQuote(grouppquota.ident)))
563
564    def writePrinterToGroup(self, pgroup, printer) :
565        """Puts a printer into a printer group."""
566        children = []
567        result = self.doSearch("SELECT printerid FROM printergroupsmembers WHERE groupid=%s" % self.doQuote(pgroup.ident))
568        if result :
569            for record in result :
570                children.append(record.get("printerid")) # TODO : put this into the database integrity rules
571        if printer.ident not in children :       
572            self.doModify("INSERT INTO printergroupsmembers (groupid, printerid) VALUES (%s, %s)" % (self.doQuote(pgroup.ident), self.doQuote(printer.ident)))
573       
574    def removePrinterFromGroup(self, pgroup, printer) :
575        """Removes a printer from a printer group."""
576        self.doModify("DELETE FROM printergroupsmembers WHERE groupid=%s AND printerid=%s" % (self.doQuote(pgroup.ident), self.doQuote(printer.ident)))
577       
578    def retrieveHistory(self, user=None, printer=None, hostname=None, billingcode=None, limit=100, start=None, end=None) :
579        """Retrieves all print jobs for user on printer (or all) between start and end date, limited to first 100 results."""
580        query = "SELECT jobhistory.*,username,printername FROM jobhistory,users,printers WHERE users.id=userid AND printers.id=printerid"
581        where = []
582        if user is not None : # user.ident is None anyway if user doesn't exist
583            where.append("userid=%s" % self.doQuote(user.ident))
584        if printer is not None : # printer.ident is None anyway if printer doesn't exist
585            where.append("printerid=%s" % self.doQuote(printer.ident))
586        if hostname is not None :   
587            where.append("hostname=%s" % self.doQuote(hostname))
588        if billingcode is not None :   
589            where.append("billingcode=%s" % self.doQuote(self.userCharsetToDatabase(billingcode)))
590        if start is not None :   
591            where.append("jobdate>=%s" % self.doQuote(start))
592        if end is not None :   
593            where.append("jobdate<=%s" % self.doQuote(end))
594        if where :   
595            query += " AND %s" % " AND ".join(where)
596        query += " ORDER BY jobhistory.id DESC"
597        if limit :
598            query += " LIMIT %s" % self.doQuote(int(limit))
599        jobs = []   
600        result = self.doSearch(query)   
601        if result :
602            for fields in result :
603                job = StorageJob(self)
604                job.ident = fields.get("id")
605                job.JobId = fields.get("jobid")
606                job.PrinterPageCounter = fields.get("pagecounter")
607                job.JobSize = fields.get("jobsize")
608                job.JobPrice = fields.get("jobprice")
609                job.JobAction = fields.get("action")
610                job.JobFileName = self.databaseToUserCharset(fields.get("filename") or "") 
611                job.JobTitle = self.databaseToUserCharset(fields.get("title") or "") 
612                job.JobCopies = fields.get("copies")
613                job.JobOptions = self.databaseToUserCharset(fields.get("options") or "") 
614                job.JobDate = fields.get("jobdate")
615                job.JobHostName = fields.get("hostname")
616                job.JobSizeBytes = fields.get("jobsizebytes")
617                job.JobMD5Sum = fields.get("md5sum")
618                job.JobPages = fields.get("pages")
619                job.JobBillingCode = self.databaseToUserCharset(fields.get("billingcode") or "")
620                job.PrecomputedJobSize = fields.get("precomputedjobsize")
621                job.PrecomputedJobPrice = fields.get("precomputedjobprice")
622                job.UserName = fields.get("username")
623                job.PrinterName = fields.get("printername")
624                if job.JobTitle == job.JobFileName == job.JobOptions == "hidden" :
625                    (job.JobTitle, job.JobFileName, job.JobOptions) = (_("Hidden because of privacy concerns"),) * 3
626                job.Exists = 1
627                jobs.append(job)
628        return jobs
629       
630    def deleteUser(self, user) :   
631        """Completely deletes an user from the Quota Storage."""
632        # TODO : What should we do if we delete the last person who used a given printer ?
633        # TODO : we can't reassign the last job to the previous one, because next user would be
634        # TODO : incorrectly charged (overcharged).
635        for q in [ 
636                    "DELETE FROM payments WHERE userid=%s" % self.doQuote(user.ident),
637                    "DELETE FROM groupsmembers WHERE userid=%s" % self.doQuote(user.ident),
638                    "DELETE FROM jobhistory WHERE userid=%s" % self.doQuote(user.ident),
639                    "DELETE FROM userpquota WHERE userid=%s" % self.doQuote(user.ident),
640                    "DELETE FROM users WHERE id=%s" % self.doQuote(user.ident),
641                  ] :
642            self.doModify(q)
643       
644    def deleteGroup(self, group) :   
645        """Completely deletes a group from the Quota Storage."""
646        for q in [
647                   "DELETE FROM groupsmembers WHERE groupid=%s" % self.doQuote(group.ident),
648                   "DELETE FROM grouppquota WHERE groupid=%s" % self.doQuote(group.ident),
649                   "DELETE FROM groups WHERE id=%s" % self.doQuote(group.ident),
650                 ] : 
651            self.doModify(q)
652           
653    def deletePrinter(self, printer) :   
654        """Completely deletes a printer from the Quota Storage."""
655        for q in [ 
656                    "DELETE FROM printergroupsmembers WHERE groupid=%s OR printerid=%s" % (self.doQuote(printer.ident), self.doQuote(printer.ident)),
657                    "DELETE FROM jobhistory WHERE printerid=%s" % self.doQuote(printer.ident),
658                    "DELETE FROM grouppquota WHERE printerid=%s" % self.doQuote(printer.ident),
659                    "DELETE FROM userpquota WHERE printerid=%s" % self.doQuote(printer.ident),
660                    "DELETE FROM printers WHERE id=%s" % self.doQuote(printer.ident),
661                  ] :
662            self.doModify(q)
663           
664    def deleteBillingCode(self, code) :   
665        """Completely deletes a billing code from the Quota Storage."""
666        for q in [
667                   "DELETE FROM billingcodes WHERE id=%s" % self.doQuote(code.ident),
668                 ] : 
669            self.doModify(q)
670       
Note: See TracBrowser for help on using the browser.