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

Revision 1875, 34.4 kB (checked in by jalet, 20 years ago)

For URGENT legal reasons (Italy), a new "privacy" directive was added to pykota.conf
to hide print jobs' title, filename, and options.

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