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

Revision 1991, 36.4 kB (checked in by jalet, 19 years ago)

The dumpykota command now supports extended filtering capabilities with
the PostgreSQL backend. LDAP doesn't yet support such possibilities.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1# PyKota
2# -*- coding: ISO-8859-15 -*-
3#
4# PyKota : Print Quotas for CUPS and LPRng
5#
6# (c) 2003-2004 Jerome Alet <alet@librelogiciel.com>
7# This program is free software; you can redistribute it and/or modify
8# it under the terms of the GNU General Public License as published by
9# the Free Software Foundation; either version 2 of the License, or
10# (at your option) any later version.
11#
12# This program is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15# GNU General Public License for more details.
16#
17# You should have received a copy of the GNU General Public License
18# along with this program; if not, write to the Free Software
19# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
20#
21# $Id$
22#
23# $Log$
24# Revision 1.61  2004/12/21 15:49:59  jalet
25# The dumpykota command now supports extended filtering capabilities with
26# the PostgreSQL backend. LDAP doesn't yet support such possibilities.
27#
28# Revision 1.60  2004/12/21 14:45:31  jalet
29# Prepared dumpykota to accept the new --filter command line option. Some
30# additionnal work needs to be done in the backends though.
31#
32# Revision 1.59  2004/10/25 14:12:25  jalet
33# For URGENT legal reasons (Italy), a new "privacy" directive was added to pykota.conf
34# to hide print jobs' title, filename, and options.
35#
36# Revision 1.58  2004/10/12 08:58:53  jalet
37# Now warnpykota only warns users who have already printed, to not confuse
38# users who have just opened their account.
39#
40# Revision 1.57  2004/10/10 10:12:21  jalet
41# Improved SQL queries for groups. Same work has to be done for groups print quotas.
42#
43# Revision 1.56  2004/10/07 21:14:28  jalet
44# Hopefully final fix for data encoding to and from the database
45#
46# Revision 1.55  2004/10/07 09:37:53  jalet
47# Fixes recently introduced bug wrt users groups (was it three days ago ?)
48#
49# Revision 1.54  2004/10/05 10:05:04  jalet
50# UnicodeEncodeError isn't defined in Python2.1
51#
52# Revision 1.53  2004/10/05 09:59:20  jalet
53# Restore compatibility with Python 2.1
54#
55# Revision 1.52  2004/10/04 22:23:54  jalet
56# Charset conversions for dumps from the PostgreSQL backend
57#
58# Revision 1.51  2004/10/04 16:11:38  jalet
59# Now outputs page counters when dumping user groups quotas
60#
61# Revision 1.50  2004/10/04 16:01:15  jalet
62# More complete dumps for groups and groups quotas
63#
64# Revision 1.49  2004/10/02 13:33:13  jalet
65# Some work done of user's charset handling in database dumps.
66#
67# Revision 1.48  2004/10/02 05:48:56  jalet
68# Should now correctly deal with charsets both when storing into databases and when
69# retrieving datas. Works with both PostgreSQL and LDAP.
70#
71# Revision 1.47  2004/09/15 07:26:20  jalet
72# Data dumps are now ordered by entry creation date if applicable.
73# Now dumpykota exits with a message when there's a broken pipe like
74# in dumpykota --data history | head -3
75#
76# Revision 1.46  2004/09/15 06:58:25  jalet
77# User groups membership and printer groups membership can now be dumped too
78#
79# Revision 1.45  2004/09/14 22:29:13  jalet
80# First version of dumpykota. Works fine but only with PostgreSQL backend
81# for now.
82#
83# Revision 1.44  2004/09/10 21:32:54  jalet
84# Small fixes for incomplete entry intialization
85#
86# Revision 1.43  2004/07/01 17:45:49  jalet
87# Added code to handle the description field for printers
88#
89# Revision 1.42  2004/06/08 17:44:43  jalet
90# Payment now gets deleted when the user is deleted
91#
92# Revision 1.41  2004/06/05 22:03:50  jalet
93# Payments history is now stored in database
94#
95# Revision 1.40  2004/06/03 23:14:11  jalet
96# Now stores the job's size in bytes in the database.
97# Preliminary work on payments storage : database schemas are OK now,
98# but no code to store payments yet.
99# Removed schema picture, not relevant anymore.
100#
101# Revision 1.39  2004/05/26 14:50:12  jalet
102# First try at saving the job-originating-hostname in the database
103#
104# Revision 1.38  2004/05/06 12:37:47  jalet
105# pkpgcounter : comments
106# pkprinters : when --add is used, existing printers are now skipped.
107#
108# Revision 1.37  2004/02/23 22:53:21  jalet
109# Don't retrieve data when it's not needed, to avoid database queries
110#
111# Revision 1.36  2004/02/04 13:24:41  jalet
112# pkprinters can now remove printers from printers groups.
113#
114# Revision 1.35  2004/02/04 11:17:00  jalet
115# pkprinters command line tool added.
116#
117# Revision 1.34  2004/02/02 22:44:16  jalet
118# Preliminary work on Relationnal Database Independance via DB-API 2.0
119#
120#
121#
122
123from types import StringType
124from pykota.storage import PyKotaStorageError,BaseStorage,StorageObject,StorageUser,StorageGroup,StoragePrinter,StorageJob,StorageLastJob,StorageUserPQuota,StorageGroupPQuota
125
126class SQLStorage :
127    def prepareRawResult(self, result) :
128        """Prepares a raw result by including the headers."""
129        if result.ntuples() > 0 :
130            entries = [result.listfields()]
131            entries.extend(result.getresult())
132            nbfields = len(entries[0])
133            for i in range(1, len(entries)) :
134                fields = list(entries[i])
135                for j in range(nbfields) :
136                    field = fields[j]
137                    if type(field) == StringType :
138                        fields[j] = self.databaseToUserCharset(field) 
139                entries[i] = tuple(fields)   
140            return entries
141       
142    def createFilter(self, only) :   
143        """Returns the appropriate SQL filter."""
144        if only :
145            expressions = []
146            for (k, v) in only.items() :
147                expressions.append("%s=%s" % (k, self.doQuote(v)))
148            return " AND ".join(expressions)     
149        return ""       
150       
151    def extractPrinters(self, extractonly={}) :
152        """Extracts all printer records."""
153        thefilter = self.createFilter(extractonly)
154        if thefilter :
155            thefilter = "WHERE %s" % thefilter
156        result = self.doRawSearch("SELECT * FROM printers %s ORDER BY id ASC" % thefilter)
157        return self.prepareRawResult(result)
158       
159    def extractUsers(self, extractonly={}) :
160        """Extracts all user records."""
161        thefilter = self.createFilter(extractonly)
162        if thefilter :
163            thefilter = "WHERE %s" % thefilter
164        result = self.doRawSearch("SELECT * FROM users %s ORDER BY id ASC" % thefilter)
165        return self.prepareRawResult(result)
166       
167    def extractGroups(self, extractonly={}) :
168        """Extracts all group records."""
169        thefilter = self.createFilter(extractonly)
170        if thefilter :
171            thefilter = "WHERE %s" % thefilter
172        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 ORDER BY groups.id ASC" % thefilter)
173        return self.prepareRawResult(result)
174       
175    def extractPayments(self, extractonly={}) :
176        """Extracts all payment records."""
177        thefilter = self.createFilter(extractonly)
178        if thefilter :
179            thefilter = "AND %s" % thefilter
180        result = self.doRawSearch("SELECT username,payments.* FROM users,payments WHERE users.id=payments.userid %s ORDER BY payments.id ASC" % thefilter)
181        return self.prepareRawResult(result)
182       
183    def extractUpquotas(self, extractonly={}) :
184        """Extracts all userpquota records."""
185        thefilter = self.createFilter(extractonly)
186        if thefilter :
187            thefilter = "AND %s" % thefilter
188        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)
189        return self.prepareRawResult(result)
190       
191    def extractGpquotas(self, extractonly={}) :
192        """Extracts all grouppquota records."""
193        thefilter = self.createFilter(extractonly)
194        if thefilter :
195            thefilter = "AND %s" % thefilter
196        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,groups.groupname,printers.printername ORDER BY grouppquota.id" % thefilter)
197        return self.prepareRawResult(result)
198       
199    def extractUmembers(self, extractonly={}) :
200        """Extracts all user groups members."""
201        thefilter = self.createFilter(extractonly)
202        if thefilter :
203            thefilter = "AND %s" % thefilter
204        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)
205        return self.prepareRawResult(result)
206       
207    def extractPmembers(self, extractonly={}) :
208        """Extracts all printer groups members."""
209        thefilter = self.createFilter(extractonly)
210        if thefilter :
211            thefilter = "AND %s" % thefilter
212        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)
213        return self.prepareRawResult(result)
214       
215    def extractHistory(self, extractonly={}) :
216        """Extracts all jobhistory records."""
217        thefilter = self.createFilter(extractonly)
218        if thefilter :
219            thefilter = "AND %s" % thefilter
220        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)
221        return self.prepareRawResult(result)
222       
223    def getAllUsersNames(self) :   
224        """Extracts all user names."""
225        usernames = []
226        result = self.doSearch("SELECT username FROM users")
227        if result :
228            usernames = [record["username"] for record in result]
229        return usernames
230       
231    def getAllGroupsNames(self) :   
232        """Extracts all group names."""
233        groupnames = []
234        result = self.doSearch("SELECT groupname FROM groups")
235        if result :
236            groupnames = [record["groupname"] for record in result]
237        return groupnames
238       
239    def getUserNbJobsFromHistory(self, user) :
240        """Returns the number of jobs the user has in history."""
241        result = self.doSearch("SELECT COUNT(*) FROM jobhistory WHERE userid=%s" % self.doQuote(user.ident))
242        if result :
243            return result[0]["count"]
244        return 0
245       
246    def getUserFromBackend(self, username) :   
247        """Extracts user information given its name."""
248        user = StorageUser(self, username)
249        result = self.doSearch("SELECT * FROM users WHERE username=%s LIMIT 1" % self.doQuote(username))
250        if result :
251            fields = result[0]
252            user.ident = fields.get("id")
253            user.Name = fields.get("username", username)
254            user.LimitBy = fields.get("limitby")
255            user.AccountBalance = fields.get("balance")
256            user.LifeTimePaid = fields.get("lifetimepaid")
257            user.Email = fields.get("email")
258            user.Exists = 1
259        return user
260       
261    def getGroupFromBackend(self, groupname) :   
262        """Extracts group information given its name."""
263        group = StorageGroup(self, groupname)
264        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 LIMIT 1" % self.doQuote(groupname))
265        if result :
266            fields = result[0]
267            group.ident = fields.get("id")
268            group.Name = fields.get("groupname", groupname)
269            group.LimitBy = fields.get("limitby")
270            group.AccountBalance = fields.get("balance")
271            group.LifeTimePaid = fields.get("lifetimepaid")
272            group.Exists = 1
273        return group
274       
275    def getPrinterFromBackend(self, printername) :       
276        """Extracts printer information given its name."""
277        printer = StoragePrinter(self, printername)
278        result = self.doSearch("SELECT * FROM printers WHERE printername=%s LIMIT 1" % self.doQuote(printername))
279        if result :
280            fields = result[0]
281            printer.ident = fields.get("id")
282            printer.Name = fields.get("printername", printername)
283            printer.PricePerJob = fields.get("priceperjob") or 0.0
284            printer.PricePerPage = fields.get("priceperpage") or 0.0
285            printer.Description = self.databaseToUserCharset(fields.get("description") or "")
286            printer.Exists = 1
287        return printer   
288       
289    def getUserPQuotaFromBackend(self, user, printer) :       
290        """Extracts a user print quota."""
291        userpquota = StorageUserPQuota(self, user, printer)
292        if printer.Exists and user.Exists :
293            result = self.doSearch("SELECT id, lifepagecounter, pagecounter, softlimit, hardlimit, datelimit FROM userpquota WHERE userid=%s AND printerid=%s" % (self.doQuote(user.ident), self.doQuote(printer.ident)))
294            if result :
295                fields = result[0]
296                userpquota.ident = fields.get("id")
297                userpquota.PageCounter = fields.get("pagecounter")
298                userpquota.LifePageCounter = fields.get("lifepagecounter")
299                userpquota.SoftLimit = fields.get("softlimit")
300                userpquota.HardLimit = fields.get("hardlimit")
301                userpquota.DateLimit = fields.get("datelimit")
302                userpquota.Exists = 1
303        return userpquota
304       
305    def getGroupPQuotaFromBackend(self, group, printer) :       
306        """Extracts a group print quota."""
307        grouppquota = StorageGroupPQuota(self, group, printer)
308        if group.Exists :
309            result = self.doSearch("SELECT id, softlimit, hardlimit, datelimit FROM grouppquota WHERE groupid=%s AND printerid=%s" % (self.doQuote(group.ident), self.doQuote(printer.ident)))
310            if result :
311                fields = result[0]
312                grouppquota.ident = fields.get("id")
313                grouppquota.SoftLimit = fields.get("softlimit")
314                grouppquota.HardLimit = fields.get("hardlimit")
315                grouppquota.DateLimit = fields.get("datelimit")
316                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)))
317                if result :
318                    fields = result[0]
319                    grouppquota.PageCounter = fields.get("pagecounter") or 0
320                    grouppquota.LifePageCounter = fields.get("lifepagecounter") or 0
321                grouppquota.Exists = 1
322        return grouppquota
323       
324    def getPrinterLastJobFromBackend(self, printer) :       
325        """Extracts a printer's last job information."""
326        lastjob = StorageLastJob(self, printer)
327        result = self.doSearch("SELECT jobhistory.id, jobid, userid, username, pagecounter, jobsize, jobprice, filename, title, copies, options, hostname, jobdate FROM jobhistory, users WHERE printerid=%s AND userid=users.id ORDER BY jobdate DESC LIMIT 1" % self.doQuote(printer.ident))
328        if result :
329            fields = result[0]
330            lastjob.ident = fields.get("id")
331            lastjob.JobId = fields.get("jobid")
332            lastjob.UserName = fields.get("username")
333            lastjob.PrinterPageCounter = fields.get("pagecounter")
334            lastjob.JobSize = fields.get("jobsize")
335            lastjob.JobPrice = fields.get("jobprice")
336            lastjob.JobAction = fields.get("action")
337            lastjob.JobFileName = self.databaseToUserCharset(fields.get("filename") or "") 
338            lastjob.JobTitle = self.databaseToUserCharset(fields.get("title") or "") 
339            lastjob.JobCopies = fields.get("copies")
340            lastjob.JobOptions = self.databaseToUserCharset(fields.get("options") or "") 
341            lastjob.JobDate = fields.get("jobdate")
342            lastjob.JobHostName = fields.get("hostname")
343            lastjob.JobSizeBytes = fields.get("jobsizebytes")
344            lastjob.Exists = 1
345        return lastjob
346           
347    def getGroupMembersFromBackend(self, group) :       
348        """Returns the group's members list."""
349        groupmembers = []
350        result = self.doSearch("SELECT * FROM groupsmembers JOIN users ON groupsmembers.userid=users.id WHERE groupid=%s" % self.doQuote(group.ident))
351        if result :
352            for record in result :
353                user = StorageUser(self, record.get("username"))
354                user.ident = record.get("userid")
355                user.LimitBy = record.get("limitby")
356                user.AccountBalance = record.get("balance")
357                user.LifeTimePaid = record.get("lifetimepaid")
358                user.Email = record.get("email")
359                user.Exists = 1
360                groupmembers.append(user)
361                self.cacheEntry("USERS", user.Name, user)
362        return groupmembers       
363       
364    def getUserGroupsFromBackend(self, user) :       
365        """Returns the user's groups list."""
366        groups = []
367        result = self.doSearch("SELECT groupname FROM groupsmembers JOIN groups ON groupsmembers.groupid=groups.id WHERE userid=%s" % self.doQuote(user.ident))
368        if result :
369            for record in result :
370                groups.append(self.getGroup(record.get("groupname")))
371        return groups       
372       
373    def getParentPrintersFromBackend(self, printer) :   
374        """Get all the printer groups this printer is a member of."""
375        pgroups = []
376        result = self.doSearch("SELECT groupid,printername FROM printergroupsmembers JOIN printers ON groupid=id WHERE printerid=%s" % self.doQuote(printer.ident))
377        if result :
378            for record in result :
379                if record["groupid"] != printer.ident : # in case of integrity violation
380                    parentprinter = self.getPrinter(record.get("printername"))
381                    if parentprinter.Exists :
382                        pgroups.append(parentprinter)
383        return pgroups
384       
385    def getMatchingPrinters(self, printerpattern) :
386        """Returns the list of all printers for which name matches a certain pattern."""
387        printers = []
388        # We 'could' do a SELECT printername FROM printers WHERE printername LIKE ...
389        # but we don't because other storages semantics may be different, so every
390        # storage should use fnmatch to match patterns and be storage agnostic
391        result = self.doSearch("SELECT * FROM printers")
392        if result :
393            for record in result :
394                if self.tool.matchString(record["printername"], printerpattern.split(",")) :
395                    printer = StoragePrinter(self, record["printername"])
396                    printer.ident = record.get("id")
397                    printer.PricePerJob = record.get("priceperjob") or 0.0
398                    printer.PricePerPage = record.get("priceperpage") or 0.0
399                    printer.Description = self.databaseToUserCharset(record.get("description") or "") 
400                    printer.Exists = 1
401                    printers.append(printer)
402                    self.cacheEntry("PRINTERS", printer.Name, printer)
403        return printers       
404       
405    def getPrinterUsersAndQuotas(self, printer, names=["*"]) :       
406        """Returns the list of users who uses a given printer, along with their quotas."""
407        usersandquotas = []
408        result = self.doSearch("SELECT users.id as uid,username,balance,lifetimepaid,limitby,email,userpquota.id,lifepagecounter,pagecounter,softlimit,hardlimit,datelimit FROM users JOIN userpquota ON users.id=userpquota.userid AND printerid=%s ORDER BY username ASC" % self.doQuote(printer.ident))
409        if result :
410            for record in result :
411                if self.tool.matchString(record.get("username"), names) :
412                    user = StorageUser(self, record.get("username"))
413                    user.ident = record.get("uid")
414                    user.LimitBy = record.get("limitby")
415                    user.AccountBalance = record.get("balance")
416                    user.LifeTimePaid = record.get("lifetimepaid")
417                    user.Email = record.get("email") 
418                    user.Exists = 1
419                    userpquota = StorageUserPQuota(self, user, printer)
420                    userpquota.ident = record.get("id")
421                    userpquota.PageCounter = record.get("pagecounter")
422                    userpquota.LifePageCounter = record.get("lifepagecounter")
423                    userpquota.SoftLimit = record.get("softlimit")
424                    userpquota.HardLimit = record.get("hardlimit")
425                    userpquota.DateLimit = record.get("datelimit")
426                    userpquota.Exists = 1
427                    usersandquotas.append((user, userpquota))
428                    self.cacheEntry("USERS", user.Name, user)
429                    self.cacheEntry("USERPQUOTAS", "%s@%s" % (user.Name, printer.Name), userpquota)
430        return usersandquotas
431               
432    def getPrinterGroupsAndQuotas(self, printer, names=["*"]) :       
433        """Returns the list of groups which uses a given printer, along with their quotas."""
434        groupsandquotas = []
435        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))
436        if result :
437            for record in result :
438                if self.tool.matchString(record.get("groupname"), names) :
439                    group = self.getGroup(record.get("groupname"))
440                    grouppquota = self.getGroupPQuota(group, printer)
441                    groupsandquotas.append((group, grouppquota))
442        return groupsandquotas
443       
444    def addPrinter(self, printername) :       
445        """Adds a printer to the quota storage, returns it."""
446        self.doModify("INSERT INTO printers (printername) VALUES (%s)" % self.doQuote(printername))
447        return self.getPrinter(printername)
448       
449    def addUser(self, user) :       
450        """Adds a user to the quota storage, returns its id."""
451        self.doModify("INSERT INTO users (username, limitby, balance, lifetimepaid, email) VALUES (%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)))
452        return self.getUser(user.Name)
453       
454    def addGroup(self, group) :       
455        """Adds a group to the quota storage, returns its id."""
456        self.doModify("INSERT INTO groups (groupname, limitby) VALUES (%s, %s)" % (self.doQuote(group.Name), self.doQuote(group.LimitBy or "quota")))
457        return self.getGroup(group.Name)
458
459    def addUserToGroup(self, user, group) :   
460        """Adds an user to a group."""
461        result = self.doSearch("SELECT COUNT(*) AS mexists FROM groupsmembers WHERE groupid=%s AND userid=%s" % (self.doQuote(group.ident), self.doQuote(user.ident)))
462        try :
463            mexists = int(result[0].get("mexists"))
464        except (IndexError, TypeError) :   
465            mexists = 0
466        if not mexists :   
467            self.doModify("INSERT INTO groupsmembers (groupid, userid) VALUES (%s, %s)" % (self.doQuote(group.ident), self.doQuote(user.ident)))
468           
469    def addUserPQuota(self, user, printer) :
470        """Initializes a user print quota on a printer."""
471        self.doModify("INSERT INTO userpquota (userid, printerid) VALUES (%s, %s)" % (self.doQuote(user.ident), self.doQuote(printer.ident)))
472        return self.getUserPQuota(user, printer)
473       
474    def addGroupPQuota(self, group, printer) :
475        """Initializes a group print quota on a printer."""
476        self.doModify("INSERT INTO grouppquota (groupid, printerid) VALUES (%s, %s)" % (self.doQuote(group.ident), self.doQuote(printer.ident)))
477        return self.getGroupPQuota(group, printer)
478       
479    def writePrinterPrices(self, printer) :   
480        """Write the printer's prices back into the storage."""
481        self.doModify("UPDATE printers SET priceperpage=%s, priceperjob=%s WHERE id=%s" % (self.doQuote(printer.PricePerPage), self.doQuote(printer.PricePerJob), self.doQuote(printer.ident)))
482       
483    def writePrinterDescription(self, printer) :   
484        """Write the printer's description back into the storage."""
485        description = self.userCharsetToDatabase(printer.Description)
486        self.doModify("UPDATE printers SET description=%s WHERE id=%s" % (self.doQuote(description), self.doQuote(printer.ident)))
487       
488    def writeUserLimitBy(self, user, limitby) :   
489        """Sets the user's limiting factor."""
490        self.doModify("UPDATE users SET limitby=%s WHERE id=%s" % (self.doQuote(limitby), self.doQuote(user.ident)))
491       
492    def writeGroupLimitBy(self, group, limitby) :   
493        """Sets the group's limiting factor."""
494        self.doModify("UPDATE groups SET limitby=%s WHERE id=%s" % (self.doQuote(limitby), self.doQuote(group.ident)))
495       
496    def writeUserPQuotaDateLimit(self, userpquota, datelimit) :   
497        """Sets the date limit permanently for a user print quota."""
498        self.doModify("UPDATE userpquota SET datelimit=%s WHERE id=%s" % (self.doQuote(datelimit), self.doQuote(userpquota.ident)))
499           
500    def writeGroupPQuotaDateLimit(self, grouppquota, datelimit) :   
501        """Sets the date limit permanently for a group print quota."""
502        self.doModify("UPDATE grouppquota SET datelimit=%s WHERE id=%s" % (self.doQuote(datelimit), self.doQuote(grouppquota.ident)))
503       
504    def increaseUserPQuotaPagesCounters(self, userpquota, nbpages) :   
505        """Increase page counters for a user print quota."""
506        self.doModify("UPDATE userpquota SET pagecounter=pagecounter+%s,lifepagecounter=lifepagecounter+%s WHERE id=%s" % (self.doQuote(nbpages), self.doQuote(nbpages), self.doQuote(userpquota.ident)))
507       
508    def writeUserPQuotaPagesCounters(self, userpquota, newpagecounter, newlifepagecounter) :   
509        """Sets the new page counters permanently for a user print quota."""
510        self.doModify("UPDATE userpquota SET pagecounter=%s,lifepagecounter=%s WHERE id=%s" % (self.doQuote(newpagecounter), self.doQuote(newlifepagecounter), self.doQuote(userpquota.ident)))
511       
512    def decreaseUserAccountBalance(self, user, amount) :   
513        """Decreases user's account balance from an amount."""
514        self.doModify("UPDATE users SET balance=balance-%s WHERE id=%s" % (self.doQuote(amount), self.doQuote(user.ident)))
515       
516    def writeUserAccountBalance(self, user, newbalance, newlifetimepaid=None) :   
517        """Sets the new account balance and eventually new lifetime paid."""
518        if newlifetimepaid is not None :
519            self.doModify("UPDATE users SET balance=%s, lifetimepaid=%s WHERE id=%s" % (self.doQuote(newbalance), self.doQuote(newlifetimepaid), self.doQuote(user.ident)))
520        else :   
521            self.doModify("UPDATE users SET balance=%s WHERE id=%s" % (self.doQuote(newbalance), self.doQuote(user.ident)))
522           
523    def writeNewPayment(self, user, amount) :       
524        """Adds a new payment to the payments history."""
525        self.doModify("INSERT INTO payments (userid, amount) VALUES (%s, %s)" % (self.doQuote(user.ident), self.doQuote(amount)))
526       
527    def writeLastJobSize(self, lastjob, jobsize, jobprice) :       
528        """Sets the last job's size permanently."""
529        self.doModify("UPDATE jobhistory SET jobsize=%s, jobprice=%s WHERE id=%s" % (self.doQuote(jobsize), self.doQuote(jobprice), self.doQuote(lastjob.ident)))
530       
531    def writeJobNew(self, printer, user, jobid, pagecounter, action, jobsize=None, jobprice=None, filename=None, title=None, copies=None, options=None, clienthost=None, jobsizebytes=None) :
532        """Adds a job in a printer's history."""
533        if self.privacy :   
534            # For legal reasons, we want to hide the title, filename and options
535            title = filename = options = "Hidden because of privacy concerns"
536        filename = self.userCharsetToDatabase(filename)
537        title = self.userCharsetToDatabase(title)
538        options = self.userCharsetToDatabase(options)
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) VALUES (%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)))
542            else :   
543                self.doModify("INSERT INTO jobhistory (userid, printerid, jobid, pagecounter, action, filename, title, copies, options, hostname, jobsizebytes) VALUES (%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)))
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, 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(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, datelimit=NULL WHERE id=%s" % (self.doQuote(softlimit), self.doQuote(hardlimit), self.doQuote(userpquota.ident)))
551       
552    def writeGroupPQuotaLimits(self, grouppquota, softlimit, hardlimit) :
553        """Sets soft and hard limits for a group quota on a specific printer."""
554        self.doModify("UPDATE grouppquota SET softlimit=%s, hardlimit=%s, datelimit=NULL WHERE id=%s" % (self.doQuote(softlimit), self.doQuote(hardlimit), self.doQuote(grouppquota.ident)))
555
556    def writePrinterToGroup(self, pgroup, printer) :
557        """Puts a printer into a printer group."""
558        children = []
559        result = self.doSearch("SELECT printerid FROM printergroupsmembers WHERE groupid=%s" % self.doQuote(pgroup.ident))
560        if result :
561            for record in result :
562                children.append(record.get("printerid")) # TODO : put this into the database integrity rules
563        if printer.ident not in children :       
564            self.doModify("INSERT INTO printergroupsmembers (groupid, printerid) VALUES (%s, %s)" % (self.doQuote(pgroup.ident), self.doQuote(printer.ident)))
565       
566    def removePrinterFromGroup(self, pgroup, printer) :
567        """Removes a printer from a printer group."""
568        self.doModify("DELETE FROM printergroupsmembers WHERE groupid=%s AND printerid=%s" % (self.doQuote(pgroup.ident), self.doQuote(printer.ident)))
569       
570    def retrieveHistory(self, user=None, printer=None, datelimit=None, hostname=None, limit=100) :   
571        """Retrieves all print jobs for user on printer (or all) before date, limited to first 100 results."""
572        query = "SELECT jobhistory.*,username,printername FROM jobhistory,users,printers WHERE users.id=userid AND printers.id=printerid"
573        where = []
574        if (user is not None) and user.Exists :
575            where.append("userid=%s" % self.doQuote(user.ident))
576        if (printer is not None) and printer.Exists :
577            where.append("printerid=%s" % self.doQuote(printer.ident))
578        if hostname is not None :   
579            where.append("hostname=%s" % self.doQuote(hostname))
580        if datelimit is not None :   
581            where.append("jobdate<=%s" % self.doQuote(datelimit))
582        if where :   
583            query += " AND %s" % " AND ".join(where)
584        query += " ORDER BY id DESC"
585        if limit :
586            query += " LIMIT %s" % self.doQuote(int(limit))
587        jobs = []   
588        result = self.doSearch(query)   
589        if result :
590            for fields in result :
591                job = StorageJob(self)
592                job.ident = fields.get("id")
593                job.JobId = fields.get("jobid")
594                job.PrinterPageCounter = fields.get("pagecounter")
595                job.JobSize = fields.get("jobsize")
596                job.JobPrice = fields.get("jobprice")
597                job.JobAction = fields.get("action")
598                job.JobFileName = self.databaseToUserCharset(fields.get("filename") or "") 
599                job.JobTitle = self.databaseToUserCharset(fields.get("title") or "") 
600                job.JobCopies = fields.get("copies")
601                job.JobOptions = self.databaseToUserCharset(fields.get("options") or "") 
602                job.JobDate = fields.get("jobdate")
603                job.JobHostName = fields.get("hostname")
604                job.JobSizeBytes = fields.get("jobsizebytes")
605                job.UserName = fields.get("username")
606                job.PrinterName = fields.get("printername")
607                job.Exists = 1
608                jobs.append(job)
609        return jobs
610       
611    def deleteUser(self, user) :   
612        """Completely deletes an user from the Quota Storage."""
613        # TODO : What should we do if we delete the last person who used a given printer ?
614        # TODO : we can't reassign the last job to the previous one, because next user would be
615        # TODO : incorrectly charged (overcharged).
616        for q in [ 
617                    "DELETE FROM payments WHERE userid=%s" % self.doQuote(user.ident),
618                    "DELETE FROM groupsmembers WHERE userid=%s" % self.doQuote(user.ident),
619                    "DELETE FROM jobhistory WHERE userid=%s" % self.doQuote(user.ident),
620                    "DELETE FROM userpquota WHERE userid=%s" % self.doQuote(user.ident),
621                    "DELETE FROM users WHERE id=%s" % self.doQuote(user.ident),
622                  ] :
623            self.doModify(q)
624       
625    def deleteGroup(self, group) :   
626        """Completely deletes a group from the Quota Storage."""
627        for q in [
628                   "DELETE FROM groupsmembers WHERE groupid=%s" % self.doQuote(group.ident),
629                   "DELETE FROM grouppquota WHERE groupid=%s" % self.doQuote(group.ident),
630                   "DELETE FROM groups WHERE id=%s" % self.doQuote(group.ident),
631                 ] : 
632            self.doModify(q)
633           
634    def deletePrinter(self, printer) :   
635        """Completely deletes a printer from the Quota Storage."""
636        for q in [ 
637                    "DELETE FROM printergroupsmembers WHERE groupid=%s OR printerid=%s" % (self.doQuote(printer.ident), self.doQuote(printer.ident)),
638                    "DELETE FROM jobhistory WHERE printerid=%s" % self.doQuote(printer.ident),
639                    "DELETE FROM grouppquota WHERE printerid=%s" % self.doQuote(printer.ident),
640                    "DELETE FROM userpquota WHERE printerid=%s" % self.doQuote(printer.ident),
641                    "DELETE FROM printers WHERE id=%s" % self.doQuote(printer.ident),
642                  ] :
643            self.doModify(q)
644       
Note: See TracBrowser for help on using the browser.