root / pykota / trunk / pykota / storages / pgstorage.py @ 1274

Revision 1274, 29.8 kB (checked in by jalet, 20 years ago)

Printing history added to CGI script.

  • 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.32  2004/01/12 14:35:02  jalet
25# Printing history added to CGI script.
26#
27# Revision 1.31  2004/01/10 09:44:02  jalet
28# Fixed potential accuracy problem if a user printed on several printers at
29# the very same time.
30#
31# Revision 1.30  2004/01/08 16:33:27  jalet
32# Additionnal check to not create a circular printers group.
33#
34# Revision 1.29  2004/01/08 16:24:49  jalet
35# edpykota now supports adding printers to printer groups.
36#
37# Revision 1.28  2004/01/08 14:10:33  jalet
38# Copyright year changed.
39#
40# Revision 1.27  2004/01/06 14:24:59  jalet
41# Printer groups should be cached now, if caching is enabled.
42#
43# Revision 1.26  2003/12/29 14:12:48  uid67467
44# Tries to workaround possible integrity violations when retrieving printer groups
45#
46# Revision 1.25  2003/12/27 16:49:25  uid67467
47# Should be ok now.
48#
49# Revision 1.24  2003/11/29 22:02:14  jalet
50# Don't try to retrieve the user print quota information if current printer
51# doesn't exist.
52#
53# Revision 1.23  2003/11/23 19:01:37  jalet
54# Job price added to history
55#
56# Revision 1.22  2003/11/21 14:28:46  jalet
57# More complete job history.
58#
59# Revision 1.21  2003/11/12 13:06:38  jalet
60# Bug fix wrt no user/group name command line argument to edpykota
61#
62# Revision 1.20  2003/10/09 21:25:26  jalet
63# Multiple printer names or wildcards can be passed on the command line
64# separated with commas.
65# Beta phase.
66#
67# Revision 1.19  2003/10/08 07:01:20  jalet
68# Job history can be disabled.
69# Some typos in README.
70# More messages in setup script.
71#
72# Revision 1.18  2003/10/07 09:07:30  jalet
73# Character encoding added to please latest version of Python
74#
75# Revision 1.17  2003/10/06 13:12:28  jalet
76# More work on caching
77#
78# Revision 1.16  2003/10/03 18:01:49  jalet
79# Nothing interesting...
80#
81# Revision 1.15  2003/10/03 12:27:03  jalet
82# Several optimizations, especially with LDAP backend
83#
84# Revision 1.14  2003/10/03 08:57:55  jalet
85# Caching mechanism now caches all that's cacheable.
86#
87# Revision 1.13  2003/10/02 20:23:18  jalet
88# Storage caching mechanism added.
89#
90# Revision 1.12  2003/08/17 14:20:25  jalet
91# Bug fix by Oleg Biteryakov
92#
93# Revision 1.11  2003/07/29 20:55:17  jalet
94# 1.14 is out !
95#
96# Revision 1.10  2003/07/16 21:53:08  jalet
97# Really big modifications wrt new configuration file's location and content.
98#
99# Revision 1.9  2003/07/14 17:20:15  jalet
100# Bug in postgresql storage when modifying the prices for a printer
101#
102# Revision 1.8  2003/07/14 14:18:17  jalet
103# Wrong documentation strings
104#
105# Revision 1.7  2003/07/09 20:17:07  jalet
106# Email field added to PostgreSQL schema
107#
108# Revision 1.6  2003/07/07 11:49:24  jalet
109# Lots of small fixes with the help of PyChecker
110#
111# Revision 1.5  2003/07/07 08:33:19  jalet
112# Bug fix due to a typo in LDAP code
113#
114# Revision 1.4  2003/06/30 13:54:21  jalet
115# Sorts by user / group name
116#
117# Revision 1.3  2003/06/25 14:10:01  jalet
118# Hey, it may work (edpykota --reset excepted) !
119#
120# Revision 1.2  2003/06/12 21:09:57  jalet
121# wrongly placed code.
122#
123# Revision 1.1  2003/06/10 16:37:54  jalet
124# Deletion of the second user which is not needed anymore.
125# Added a debug configuration field in /etc/pykota.conf
126# All queries can now be sent to the logger in debug mode, this will
127# greatly help improve performance when time for this will come.
128#
129#
130#
131#
132
133from pykota.storage import PyKotaStorageError,BaseStorage,StorageObject,StorageUser,StorageGroup,StoragePrinter,StorageJob,StorageLastJob,StorageUserPQuota,StorageGroupPQuota
134
135try :
136    import pg
137except ImportError :   
138    import sys
139    # TODO : to translate or not to translate ?
140    raise PyKotaStorageError, "This python version (%s) doesn't seem to have the PygreSQL module installed correctly." % sys.version.split()[0]
141
142class Storage(BaseStorage) :
143    def __init__(self, pykotatool, host, dbname, user, passwd) :
144        """Opens the PostgreSQL database connection."""
145        BaseStorage.__init__(self, pykotatool)
146        try :
147            (host, port) = host.split(":")
148            port = int(port)
149        except ValueError :   
150            port = -1         # Use PostgreSQL's default tcp/ip port (5432).
151       
152        try :
153            self.database = pg.connect(host=host, port=port, dbname=dbname, user=user, passwd=passwd)
154        except pg.error, msg :
155            raise PyKotaStorageError, msg
156        else :   
157            self.closed = 0
158            self.tool.logdebug("Database opened (host=%s, port=%s, dbname=%s, user=%s)" % (host, port, dbname, user))
159           
160    def close(self) :   
161        """Closes the database connection."""
162        if not self.closed :
163            self.database.close()
164            self.closed = 1
165            self.tool.logdebug("Database closed.")
166       
167    def beginTransaction(self) :   
168        """Starts a transaction."""
169        self.database.query("BEGIN;")
170        self.tool.logdebug("Transaction begins...")
171       
172    def commitTransaction(self) :   
173        """Commits a transaction."""
174        self.database.query("COMMIT;")
175        self.tool.logdebug("Transaction committed.")
176       
177    def rollbackTransaction(self) :     
178        """Rollbacks a transaction."""
179        self.database.query("ROLLBACK;")
180        self.tool.logdebug("Transaction aborted.")
181       
182    def doSearch(self, query) :
183        """Does a search query."""
184        query = query.strip()   
185        if not query.endswith(';') :   
186            query += ';'
187        try :
188            self.tool.logdebug("QUERY : %s" % query)
189            result = self.database.query(query)
190        except pg.error, msg :   
191            raise PyKotaStorageError, msg
192        else :   
193            if (result is not None) and (result.ntuples() > 0) : 
194                return result.dictresult()
195           
196    def doModify(self, query) :
197        """Does a (possibly multiple) modify query."""
198        query = query.strip()   
199        if not query.endswith(';') :   
200            query += ';'
201        try :
202            self.tool.logdebug("QUERY : %s" % query)
203            result = self.database.query(query)
204        except pg.error, msg :   
205            raise PyKotaStorageError, msg
206        else :   
207            return result
208           
209    def doQuote(self, field) :
210        """Quotes a field for use as a string in SQL queries."""
211        if type(field) == type(0.0) : 
212            typ = "decimal"
213        elif type(field) == type(0) :   
214            typ = "int"
215        else :   
216            typ = "text"
217        return pg._quote(field, typ)
218       
219    def getAllUsersNames(self) :   
220        """Extracts all user names."""
221        usernames = []
222        result = self.doSearch("SELECT username FROM users")
223        if result :
224            usernames = [record["username"] for record in result]
225        return usernames
226       
227    def getAllGroupsNames(self) :   
228        """Extracts all group names."""
229        groupnames = []
230        result = self.doSearch("SELECT groupname FROM groups")
231        if result :
232            groupnames = [record["groupname"] for record in result]
233        return groupnames
234       
235    def getUserFromBackend(self, username) :   
236        """Extracts user information given its name."""
237        user = StorageUser(self, username)
238        result = self.doSearch("SELECT * FROM users WHERE username=%s LIMIT 1" % self.doQuote(username))
239        if result :
240            fields = result[0]
241            user.ident = fields.get("id")
242            user.LimitBy = fields.get("limitby")
243            user.AccountBalance = fields.get("balance")
244            user.LifeTimePaid = fields.get("lifetimepaid")
245            user.Email = fields.get("email")
246            user.Exists = 1
247        return user
248       
249    def getGroupFromBackend(self, groupname) :   
250        """Extracts group information given its name."""
251        group = StorageGroup(self, groupname)
252        result = self.doSearch("SELECT * FROM groups WHERE groupname=%s LIMIT 1" % self.doQuote(groupname))
253        if result :
254            fields = result[0]
255            group.ident = fields.get("id")
256            group.LimitBy = fields.get("limitby")
257            result = self.doSearch("SELECT SUM(balance) AS balance, SUM(lifetimepaid) AS lifetimepaid FROM users WHERE id IN (SELECT userid FROM groupsmembers WHERE groupid=%s)" % self.doQuote(group.ident))
258            if result :
259                fields = result[0]
260                group.AccountBalance = fields.get("balance")
261                group.LifeTimePaid = fields.get("lifetimepaid")
262            group.Exists = 1
263        return group
264       
265    def getPrinterFromBackend(self, printername) :       
266        """Extracts printer information given its name."""
267        printer = StoragePrinter(self, printername)
268        result = self.doSearch("SELECT * FROM printers WHERE printername=%s LIMIT 1" % self.doQuote(printername))
269        if result :
270            fields = result[0]
271            printer.ident = fields.get("id")
272            printer.PricePerJob = fields.get("priceperjob")
273            printer.PricePerPage = fields.get("priceperpage")
274            printer.LastJob = self.getPrinterLastJob(printer)
275            printer.Exists = 1
276        return printer   
277       
278    def getUserPQuotaFromBackend(self, user, printer) :       
279        """Extracts a user print quota."""
280        userpquota = StorageUserPQuota(self, user, printer)
281        if printer.Exists and user.Exists :
282            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)))
283            if result :
284                fields = result[0]
285                userpquota.ident = fields.get("id")
286                userpquota.PageCounter = fields.get("pagecounter")
287                userpquota.LifePageCounter = fields.get("lifepagecounter")
288                userpquota.SoftLimit = fields.get("softlimit")
289                userpquota.HardLimit = fields.get("hardlimit")
290                userpquota.DateLimit = fields.get("datelimit")
291                userpquota.Exists = 1
292        return userpquota
293       
294    def getGroupPQuotaFromBackend(self, group, printer) :       
295        """Extracts a group print quota."""
296        grouppquota = StorageGroupPQuota(self, group, printer)
297        if group.Exists :
298            result = self.doSearch("SELECT id, softlimit, hardlimit, datelimit FROM grouppquota WHERE groupid=%s AND printerid=%s" % (self.doQuote(group.ident), self.doQuote(printer.ident)))
299            if result :
300                fields = result[0]
301                grouppquota.ident = fields.get("id")
302                grouppquota.SoftLimit = fields.get("softlimit")
303                grouppquota.HardLimit = fields.get("hardlimit")
304                grouppquota.DateLimit = fields.get("datelimit")
305                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)))
306                if result :
307                    fields = result[0]
308                    grouppquota.PageCounter = fields.get("pagecounter")
309                    grouppquota.LifePageCounter = fields.get("lifepagecounter")
310                grouppquota.Exists = 1
311        return grouppquota
312       
313    def getPrinterLastJobFromBackend(self, printer) :       
314        """Extracts a printer's last job information."""
315        lastjob = StorageLastJob(self, printer)
316        result = self.doSearch("SELECT jobhistory.id, jobid, userid, username, pagecounter, jobsize, jobprice, filename, title, copies, options, jobdate FROM jobhistory, users WHERE printerid=%s AND userid=users.id ORDER BY jobdate DESC LIMIT 1" % self.doQuote(printer.ident))
317        if result :
318            fields = result[0]
319            lastjob.ident = fields.get("id")
320            lastjob.JobId = fields.get("jobid")
321            lastjob.User = self.getUser(fields.get("username"))
322            lastjob.PrinterPageCounter = fields.get("pagecounter")
323            lastjob.JobSize = fields.get("jobsize")
324            lastjob.JobPrice = fields.get("jobprice")
325            lastjob.JobAction = fields.get("action")
326            lastjob.JobFileName = fields.get("filename")
327            lastjob.JobTitle = fields.get("title")
328            lastjob.JobCopies = fields.get("copies")
329            lastjob.JobOptions = fields.get("options")
330            lastjob.JobDate = fields.get("jobdate")
331            lastjob.Exists = 1
332        return lastjob
333           
334    def getGroupMembersFromBackend(self, group) :       
335        """Returns the group's members list."""
336        groupmembers = []
337        result = self.doSearch("SELECT * FROM groupsmembers JOIN users ON groupsmembers.userid=users.id WHERE groupid=%s" % self.doQuote(group.ident))
338        if result :
339            for record in result :
340                user = StorageUser(self, record.get("username"))
341                user.ident = record.get("userid")
342                user.LimitBy = record.get("limitby")
343                user.AccountBalance = record.get("balance")
344                user.LifeTimePaid = record.get("lifetimepaid")
345                user.Email = record.get("email")
346                user.Exists = 1
347                groupmembers.append(user)
348                self.cacheEntry("USERS", user.Name, user)
349        return groupmembers       
350       
351    def getUserGroupsFromBackend(self, user) :       
352        """Returns the user's groups list."""
353        groups = []
354        result = self.doSearch("SELECT groupname FROM groupsmembers JOIN groups ON groupsmembers.groupid=groups.id WHERE userid=%s" % self.doQuote(user.ident))
355        if result :
356            for record in result :
357                groups.append(self.getGroup(record.get("groupname")))
358        return groups       
359       
360    def getParentPrintersFromBackend(self, printer) :   
361        """Get all the printer groups this printer is a member of."""
362        pgroups = []
363        result = self.doSearch("SELECT groupid,printername FROM printergroupsmembers JOIN printers ON groupid=id WHERE printerid=%s" % self.doQuote(printer.ident))
364        if result :
365            for record in result :
366                if record["groupid"] != printer.ident : # in case of integrity violation
367                    parentprinter = self.getPrinter(record.get("printername"))
368                    if parentprinter.Exists :
369                        pgroups.append(parentprinter)
370        return pgroups
371       
372    def getMatchingPrinters(self, printerpattern) :
373        """Returns the list of all printers for which name matches a certain pattern."""
374        printers = []
375        # We 'could' do a SELECT printername FROM printers WHERE printername LIKE ...
376        # but we don't because other storages semantics may be different, so every
377        # storage should use fnmatch to match patterns and be storage agnostic
378        result = self.doSearch("SELECT * FROM printers")
379        if result :
380            for record in result :
381                if self.tool.matchString(record["printername"], printerpattern.split(",")) :
382                    printer = StoragePrinter(self, record["printername"])
383                    printer.ident = record.get("id")
384                    printer.PricePerJob = record.get("priceperjob")
385                    printer.PricePerPage = record.get("priceperpage")
386                    printer.LastJob = self.getPrinterLastJob(printer)
387                    printer.Exists = 1
388                    printers.append(printer)
389                    self.cacheEntry("PRINTERS", printer.Name, printer)
390        return printers       
391       
392    def getPrinterUsersAndQuotas(self, printer, names=["*"]) :       
393        """Returns the list of users who uses a given printer, along with their quotas."""
394        usersandquotas = []
395        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))
396        if result :
397            for record in result :
398                if self.tool.matchString(record.get("username"), names) :
399                    user = StorageUser(self, record.get("username"))
400                    user.ident = record.get("uid")
401                    user.LimitBy = record.get("limitby")
402                    user.AccountBalance = record.get("balance")
403                    user.LifeTimePaid = record.get("lifetimepaid")
404                    user.Email = record.get("email") 
405                    user.Exists = 1
406                    userpquota = StorageUserPQuota(self, user, printer)
407                    userpquota.ident = record.get("id")
408                    userpquota.PageCounter = record.get("pagecounter")
409                    userpquota.LifePageCounter = record.get("lifepagecounter")
410                    userpquota.SoftLimit = record.get("softlimit")
411                    userpquota.HardLimit = record.get("hardlimit")
412                    userpquota.DateLimit = record.get("datelimit")
413                    userpquota.Exists = 1
414                    usersandquotas.append((user, userpquota))
415                    self.cacheEntry("USERS", user.Name, user)
416                    self.cacheEntry("USERPQUOTAS", "%s@%s" % (user.Name, printer.Name), userpquota)
417        return usersandquotas
418               
419    def getPrinterGroupsAndQuotas(self, printer, names=["*"]) :       
420        """Returns the list of groups which uses a given printer, along with their quotas."""
421        groupsandquotas = []
422        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))
423        if result :
424            for record in result :
425                if self.tool.matchString(record.get("groupname"), names) :
426                    group = self.getGroup(record.get("groupname"))
427                    grouppquota = self.getGroupPQuota(group, printer)
428                    groupsandquotas.append((group, grouppquota))
429        return groupsandquotas
430       
431    def addPrinter(self, printername) :       
432        """Adds a printer to the quota storage, returns it."""
433        self.doModify("INSERT INTO printers (printername) VALUES (%s)" % self.doQuote(printername))
434        return self.getPrinter(printername)
435       
436    def addUser(self, user) :       
437        """Adds a user to the quota storage, returns its id."""
438        self.doModify("INSERT INTO users (username, limitby, balance, lifetimepaid, email) VALUES (%s, %s, %s, %s, %s)" % (self.doQuote(user.Name), self.doQuote(user.LimitBy), self.doQuote(user.AccountBalance), self.doQuote(user.LifeTimePaid), self.doQuote(user.Email)))
439        return self.getUser(user.Name)
440       
441    def addGroup(self, group) :       
442        """Adds a group to the quota storage, returns its id."""
443        self.doModify("INSERT INTO groups (groupname, limitby) VALUES (%s, %s)" % (self.doQuote(group.Name), self.doQuote(group.LimitBy)))
444        return self.getGroup(group.Name)
445
446    def addUserToGroup(self, user, group) :   
447        """Adds an user to a group."""
448        result = self.doSearch("SELECT COUNT(*) AS mexists FROM groupsmembers WHERE groupid=%s AND userid=%s" % (self.doQuote(group.ident), self.doQuote(user.ident)))
449        try :
450            mexists = int(result[0].get("mexists"))
451        except (IndexError, TypeError) :   
452            mexists = 0
453        if not mexists :   
454            self.doModify("INSERT INTO groupsmembers (groupid, userid) VALUES (%s, %s)" % (self.doQuote(group.ident), self.doQuote(user.ident)))
455           
456    def addUserPQuota(self, user, printer) :
457        """Initializes a user print quota on a printer."""
458        self.doModify("INSERT INTO userpquota (userid, printerid) VALUES (%s, %s)" % (self.doQuote(user.ident), self.doQuote(printer.ident)))
459        return self.getUserPQuota(user, printer)
460       
461    def addGroupPQuota(self, group, printer) :
462        """Initializes a group print quota on a printer."""
463        self.doModify("INSERT INTO grouppquota (groupid, printerid) VALUES (%s, %s)" % (self.doQuote(group.ident), self.doQuote(printer.ident)))
464        return self.getGroupPQuota(group, printer)
465       
466    def writePrinterPrices(self, printer) :   
467        """Write the printer's prices back into the storage."""
468        self.doModify("UPDATE printers SET priceperpage=%s, priceperjob=%s WHERE id=%s" % (self.doQuote(printer.PricePerPage), self.doQuote(printer.PricePerJob), self.doQuote(printer.ident)))
469       
470    def writeUserLimitBy(self, user, limitby) :   
471        """Sets the user's limiting factor."""
472        self.doModify("UPDATE users SET limitby=%s WHERE id=%s" % (self.doQuote(limitby), self.doQuote(user.ident)))
473       
474    def writeGroupLimitBy(self, group, limitby) :   
475        """Sets the group's limiting factor."""
476        self.doModify("UPDATE groups SET limitby=%s WHERE id=%s" % (self.doQuote(limitby), self.doQuote(group.ident)))
477       
478    def writeUserPQuotaDateLimit(self, userpquota, datelimit) :   
479        """Sets the date limit permanently for a user print quota."""
480        self.doModify("UPDATE userpquota SET datelimit=%s WHERE id=%s" % (self.doQuote(datelimit), self.doQuote(userpquota.ident)))
481           
482    def writeGroupPQuotaDateLimit(self, grouppquota, datelimit) :   
483        """Sets the date limit permanently for a group print quota."""
484        self.doModify("UPDATE grouppquota SET datelimit=%s WHERE id=%s" % (self.doQuote(datelimit), self.doQuote(grouppquota.ident)))
485       
486    def increaseUserPQuotaPagesCounters(self, userpquota, nbpages) :   
487        """Increase page counters for a user print quota."""
488        self.doModify("UPDATE userpquota SET pagecounter=pagecounter+%s,lifepagecounter=lifepagecounter+%s WHERE id=%s" % (self.doQuote(nbpages), self.doQuote(nbpages), self.doQuote(userpquota.ident)))
489       
490    def writeUserPQuotaPagesCounters(self, userpquota, newpagecounter, newlifepagecounter) :   
491        """Sets the new page counters permanently for a user print quota."""
492        self.doModify("UPDATE userpquota SET pagecounter=%s,lifepagecounter=%s WHERE id=%s" % (self.doQuote(newpagecounter), self.doQuote(newlifepagecounter), self.doQuote(userpquota.ident)))
493       
494    def decreaseUserAccountBalance(self, user, amount) :   
495        """Decreases user's account balance from an amount."""
496        self.doModify("UPDATE users SET balance=balance-%s WHERE id=%s" % (self.doQuote(amount), self.doQuote(user.ident)))
497       
498    def writeUserAccountBalance(self, user, newbalance, newlifetimepaid=None) :   
499        """Sets the new account balance and eventually new lifetime paid."""
500        if newlifetimepaid is not None :
501            self.doModify("UPDATE users SET balance=%s, lifetimepaid=%s WHERE id=%s" % (self.doQuote(newbalance), self.doQuote(newlifetimepaid), self.doQuote(user.ident)))
502        else :   
503            self.doModify("UPDATE users SET balance=%s WHERE id=%s" % (self.doQuote(newbalance), self.doQuote(user.ident)))
504           
505    def writeLastJobSize(self, lastjob, jobsize, jobprice) :       
506        """Sets the last job's size permanently."""
507        self.doModify("UPDATE jobhistory SET jobsize=%s, jobprice=%s WHERE id=%s" % (self.doQuote(jobsize), self.doQuote(jobprice), self.doQuote(lastjob.ident)))
508       
509    def writeJobNew(self, printer, user, jobid, pagecounter, action, jobsize=None, jobprice=None, filename=None, title=None, copies=None, options=None) :   
510        """Adds a job in a printer's history."""
511        if (not self.disablehistory) or (not printer.LastJob.Exists) :
512            if jobsize is not None :
513                self.doModify("INSERT INTO jobhistory (userid, printerid, jobid, pagecounter, action, jobsize, jobprice, filename, title, copies, options) 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(jobsize), self.doQuote(jobprice), self.doQuote(filename), self.doQuote(title), self.doQuote(copies), self.doQuote(options)))
514            else :   
515                self.doModify("INSERT INTO jobhistory (userid, printerid, jobid, pagecounter, action, filename, title, copies, options) VALUES (%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)))
516        else :       
517            # here we explicitly want to reset jobsize to NULL if needed
518            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, 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(printer.LastJob.ident)))
519           
520    def writeUserPQuotaLimits(self, userpquota, softlimit, hardlimit) :
521        """Sets soft and hard limits for a user quota."""
522        self.doModify("UPDATE userpquota SET softlimit=%s, hardlimit=%s, datelimit=NULL WHERE id=%s" % (self.doQuote(softlimit), self.doQuote(hardlimit), self.doQuote(userpquota.ident)))
523       
524    def writeGroupPQuotaLimits(self, grouppquota, softlimit, hardlimit) :
525        """Sets soft and hard limits for a group quota on a specific printer."""
526        self.doModify("UPDATE grouppquota SET softlimit=%s, hardlimit=%s, datelimit=NULL WHERE id=%s" % (self.doQuote(softlimit), self.doQuote(hardlimit), self.doQuote(grouppquota.ident)))
527
528    def writePrinterToGroup(self, pgroup, printer) :
529        """Puts a printer into a printer group."""
530        children = []
531        result = self.doSearch("SELECT printerid FROM printergroupsmembers WHERE groupid=%s" % self.doQuote(pgroup.ident))
532        if result :
533            for record in result :
534                children.append(record.get("printerid")) # TODO : put this into the database integrity rules
535        if printer.ident not in children :       
536            self.doModify("INSERT INTO printergroupsmembers (groupid, printerid) VALUES (%s, %s)" % (self.doQuote(pgroup.ident), self.doQuote(printer.ident)))
537       
538    def retrieveHistory(self, user=None, printer=None, datelimit=None, limit=100) :   
539        """Retrieves all print jobs for user on printer (or all) before date, limited to first 100 results."""
540        query = "SELECT * FROM jobhistory"
541        where = []
542        if (user is not None) and user.Exists :
543            where.append("userid=%s" % self.doQuote(user.ident))
544        if (printer is not None) and printer.Exists :
545            where.append("printerid=%s" % self.doQuote(printer.ident))
546        if datelimit is not None :   
547            where.append("jobdate<=%s" % self.doQuote(datelimit))
548        if where :   
549            query += "WHERE %s" % " AND ".join(where)
550        query += " ORDER BY id DESC"
551        if limit :
552            query += " LIMIT %s" % self.doQuote(int(limit))
553        jobs = []   
554        result = self.doSearch(query)   
555        if result :
556            for fields in result :
557                job = StorageJob(self)
558                job.ident = fields.get("id")
559                job.JobId = fields.get("jobid")
560                job.PrinterPageCounter = fields.get("pagecounter")
561                job.JobSize = fields.get("jobsize")
562                job.JobPrice = fields.get("jobprice")
563                job.JobAction = fields.get("action")
564                job.JobFileName = fields.get("filename")
565                job.JobTitle = fields.get("title")
566                job.JobCopies = fields.get("copies")
567                job.JobOptions = fields.get("options")
568                job.JobDate = fields.get("jobdate")
569                job.User = self.getUser(fields.get("userid"))
570                job.Printer = self.getPrinter(fields.get("printerid"))
571                job.Exists = 1
572                jobs.append(job)
573        return jobs
574       
575    def deleteUser(self, user) :   
576        """Completely deletes an user from the Quota Storage."""
577        # TODO : What should we do if we delete the last person who used a given printer ?
578        # TODO : we can't reassign the last job to the previous one, because next user would be
579        # TODO : incorrectly charged (overcharged).
580        for q in [ 
581                    "DELETE FROM groupsmembers WHERE userid=%s" % self.doQuote(user.ident),
582                    "DELETE FROM jobhistory WHERE userid=%s" % self.doQuote(user.ident),
583                    "DELETE FROM userpquota WHERE userid=%s" % self.doQuote(user.ident),
584                    "DELETE FROM users WHERE id=%s" % self.doQuote(user.ident),
585                  ] :
586            self.doModify(q)
587       
588    def deleteGroup(self, group) :   
589        """Completely deletes a group from the Quota Storage."""
590        for q in [
591                   "DELETE FROM groupsmembers WHERE groupid=%s" % self.doQuote(group.ident),
592                   "DELETE FROM grouppquota WHERE groupid=%s" % self.doQuote(group.ident),
593                   "DELETE FROM groups WHERE id=%s" % self.doQuote(group.ident),
594                 ] : 
595            self.doModify(q)
596       
Note: See TracBrowser for help on using the browser.