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

Revision 1778, 33.7 kB (checked in by jalet, 20 years ago)

UnicodeEncodeError? isn't defined in Python2.1

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