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

Revision 1992, 36.8 kB (checked in by jalet, 19 years ago)

Fixed the problem with dumpykota's filtering of printers groups membership

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