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

Revision 1990, 34.7 kB (checked in by jalet, 19 years ago)

Prepared dumpykota to accept the new --filter command line option. Some
additionnal work needs to be done in the backends though.

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