root / pykota / trunk / pykota / storage.py @ 2388

Revision 2388, 30.8 kB (checked in by jerome, 19 years ago)

Fixed an LDAP filtering problem when several billing codes were passed on pkbcodes' command line.
The unknown_billingcode directive now works as expected.
The billing code's page counter and balance are updated when printing.
Severity : If you need full management of billing codes, this is for you.

  • 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20#
21# $Id$
22#
23#
24
25from mx import DateTime
26
27class PyKotaStorageError(Exception):
28    """An exception for Quota Storage related stuff."""
29    def __init__(self, message = ""):
30        self.message = message
31        Exception.__init__(self, message)
32    def __repr__(self):
33        return self.message
34    __str__ = __repr__
35       
36class StorageObject :
37    """Object present in the Quota Storage."""
38    def __init__(self, parent) :
39        "Initialize minimal data."""
40        self.parent = parent
41        self.ident = None
42        self.Exists = 0
43       
44class StorageUser(StorageObject) :       
45    """User class."""
46    def __init__(self, parent, name) :
47        StorageObject.__init__(self, parent)
48        self.Name = name
49        self.LimitBy = None
50        self.AccountBalance = None
51        self.LifeTimePaid = None
52        self.Email = None
53        self.OverCharge = 1.0
54        self.Payments = [] # TODO : maybe handle this smartly for SQL, for now just don't retrieve them
55       
56    def consumeAccountBalance(self, amount) :     
57        """Consumes an amount of money from the user's account balance."""
58        self.parent.decreaseUserAccountBalance(self, amount)
59        self.AccountBalance = float(self.AccountBalance or 0.0) - amount
60       
61    def setAccountBalance(self, balance, lifetimepaid) :   
62        """Sets the user's account balance in case he pays more money."""
63        diff = float(lifetimepaid or 0.0) - float(self.LifeTimePaid or 0.0)
64        self.parent.beginTransaction()
65        try :
66            self.parent.writeUserAccountBalance(self, balance, lifetimepaid)
67            self.parent.writeNewPayment(self, diff)
68        except PyKotaStorageError, msg :   
69            self.parent.rollbackTransaction()
70            raise PyKotaStorageError, msg
71        else :   
72            self.parent.commitTransaction()
73            self.AccountBalance = balance
74            self.LifeTimePaid = lifetimepaid
75       
76    def setLimitBy(self, limitby) :   
77        """Sets the user's limiting factor."""
78        try :
79            limitby = limitby.lower()
80        except AttributeError :   
81            limitby = "quota"
82        if limitby in ["quota", "balance", "quota-then-balance", "balance-then-quota"] :
83            self.parent.writeUserLimitBy(self, limitby)
84            self.LimitBy = limitby
85       
86    def setOverChargeFactor(self, factor) :   
87        """Sets the user's overcharging coefficient."""
88        self.parent.writeUserOverCharge(self, factor)
89        self.OverCharge = factor
90       
91    def delete(self) :   
92        """Deletes an user from the Quota Storage."""
93        self.parent.beginTransaction()
94        try :
95            self.parent.deleteUser(self)
96        except PyKotaStorageError, msg :   
97            self.parent.rollbackTransaction()
98            raise PyKotaStorageError, msg
99        else :   
100            self.parent.commitTransaction()
101            self.Exists = 0
102       
103class StorageGroup(StorageObject) :       
104    """User class."""
105    def __init__(self, parent, name) :
106        StorageObject.__init__(self, parent)
107        self.Name = name
108        self.LimitBy = None
109        self.AccountBalance = None
110        self.LifeTimePaid = None
111       
112    def setLimitBy(self, limitby) :   
113        """Sets the user's limiting factor."""
114        try :
115            limitby = limitby.lower()
116        except AttributeError :   
117            limitby = "quota"
118        if limitby in ["quota", "balance"] :
119            self.parent.writeGroupLimitBy(self, limitby)
120            self.LimitBy = limitby
121       
122    def delete(self) :   
123        """Deletes a group from the Quota Storage."""
124        self.parent.beginTransaction()
125        try :
126            self.parent.deleteGroup(self)
127        except PyKotaStorageError, msg :   
128            self.parent.rollbackTransaction()
129            raise PyKotaStorageError, msg
130        else :   
131            self.parent.commitTransaction()
132            self.Exists = 0
133       
134class StoragePrinter(StorageObject) :
135    """Printer class."""
136    def __init__(self, parent, name) :
137        StorageObject.__init__(self, parent)
138        self.Name = name
139        self.PricePerPage = None
140        self.PricePerJob = None
141        self.Description = None
142        self.Coefficients = None
143       
144    def __getattr__(self, name) :   
145        """Delays data retrieval until it's really needed."""
146        if name == "LastJob" : 
147            self.LastJob = self.parent.getPrinterLastJob(self)
148            return self.LastJob
149        else :
150            raise AttributeError, name
151           
152    def addJobToHistory(self, jobid, user, pagecounter, action, jobsize=None, jobprice=None, filename=None, title=None, copies=None, options=None, clienthost=None, jobsizebytes=None, jobmd5sum=None, jobpages=None, jobbilling=None) :
153        """Adds a job to the printer's history."""
154        self.parent.writeJobNew(self, user, jobid, pagecounter, action, jobsize, jobprice, filename, title, copies, options, clienthost, jobsizebytes, jobmd5sum, jobpages, jobbilling)
155        # TODO : update LastJob object ? Probably not needed.
156       
157    def addPrinterToGroup(self, printer) :   
158        """Adds a printer to a printer group."""
159        if (printer not in self.parent.getParentPrinters(self)) and (printer.ident != self.ident) :
160            self.parent.writePrinterToGroup(self, printer)
161            # TODO : reset cached value for printer parents, or add new parent to cached value
162           
163    def delPrinterFromGroup(self, printer) :   
164        """Deletes a printer from a printer group."""
165        self.parent.removePrinterFromGroup(self, printer)
166        # TODO : reset cached value for printer parents, or add new parent to cached value
167       
168    def setPrices(self, priceperpage = None, priceperjob = None) :   
169        """Sets the printer's prices."""
170        if priceperpage is None :
171            priceperpage = self.PricePerPage or 0.0
172        else :   
173            self.PricePerPage = float(priceperpage)
174        if priceperjob is None :   
175            priceperjob = self.PricePerJob or 0.0
176        else :   
177            self.PricePerJob = float(priceperjob)
178        self.parent.writePrinterPrices(self)
179       
180    def setDescription(self, description=None) :
181        """Sets the printer's description."""
182        if description is None :
183            description = self.Description
184        else :   
185            self.Description = str(description)
186        self.parent.writePrinterDescription(self)
187       
188    def delete(self) :   
189        """Deletes a printer from the Quota Storage."""
190        self.parent.beginTransaction()
191        try :
192            self.parent.deletePrinter(self)
193        except PyKotaStorageError, msg :   
194            self.parent.rollbackTransaction()
195            raise PyKotaStorageError, msg
196        else :   
197            self.parent.commitTransaction()
198            self.Exists = 0   
199       
200class StorageUserPQuota(StorageObject) :
201    """User Print Quota class."""
202    def __init__(self, parent, user, printer) :
203        StorageObject.__init__(self, parent)
204        self.User = user
205        self.Printer = printer
206        self.PageCounter = None
207        self.LifePageCounter = None
208        self.SoftLimit = None
209        self.HardLimit = None
210        self.DateLimit = None
211        self.WarnCount = None
212       
213    def __getattr__(self, name) :   
214        """Delays data retrieval until it's really needed."""
215        if name == "ParentPrintersUserPQuota" : 
216            self.ParentPrintersUserPQuota = (self.User.Exists and self.Printer.Exists and self.parent.getParentPrintersUserPQuota(self)) or []
217            return self.ParentPrintersUserPQuota
218        else :
219            raise AttributeError, name
220       
221    def setDateLimit(self, datelimit) :   
222        """Sets the date limit for this quota."""
223        date = "%04i-%02i-%02i %02i:%02i:%02i" % (datelimit.year, datelimit.month, datelimit.day, datelimit.hour, datelimit.minute, datelimit.second)
224        self.parent.writeUserPQuotaDateLimit(self, date)
225        self.DateLimit = date
226       
227    def setLimits(self, softlimit, hardlimit) :   
228        """Sets the soft and hard limit for this quota."""
229        self.parent.writeUserPQuotaLimits(self, softlimit, hardlimit)
230        self.SoftLimit = softlimit
231        self.HardLimit = hardlimit
232        self.DateLimit = None
233        self.WarnCount = 0
234       
235    def setUsage(self, used) :
236        """Sets the PageCounter and LifePageCounter to used, or if used is + or - prefixed, changes the values of {Life,}PageCounter by that amount."""
237        vused = int(used)
238        if used.startswith("+") or used.startswith("-") :
239            self.parent.beginTransaction()
240            try :
241                self.parent.increaseUserPQuotaPagesCounters(self, vused)
242                self.parent.writeUserPQuotaDateLimit(self, None)
243                self.parent.writeUserPQuotaWarnCount(self, 0)
244            except PyKotaStorageError, msg :   
245                self.parent.rollbackTransaction()
246                raise PyKotaStorageError, msg
247            else :
248                self.parent.commitTransaction()
249            self.PageCounter += vused
250            self.LifePageCounter += vused
251        else :
252            self.parent.writeUserPQuotaPagesCounters(self, vused, vused)
253            self.PageCounter = self.LifePageCounter = vused
254        self.DateLimit = None
255        self.WarnCount = 0
256
257    def incDenyBannerCounter(self) :
258        """Increment the deny banner counter for this user quota."""
259        self.parent.increaseUserPQuotaWarnCount(self)
260        self.WarnCount = (self.WarnCount or 0) + 1
261       
262    def resetDenyBannerCounter(self) :
263        """Resets the deny banner counter for this user quota."""
264        self.parent.writeUserPQuotaWarnCount(self, 0)
265        self.WarnCount = 0
266       
267    def reset(self) :   
268        """Resets page counter to 0."""
269        self.parent.writeUserPQuotaPagesCounters(self, 0, int(self.LifePageCounter or 0))
270        self.PageCounter = 0
271        self.DateLimit = None
272       
273    def hardreset(self) :   
274        """Resets actual and life time page counters to 0."""
275        self.parent.writeUserPQuotaPagesCounters(self, 0, 0)
276        self.PageCounter = self.LifePageCounter = 0
277        self.DateLimit = None
278       
279    def computeJobPrice(self, jobsize) :   
280        """Computes the job price as the sum of all parent printers' prices + current printer's ones."""
281        totalprice = 0.0   
282        if jobsize :
283            if self.User.OverCharge != 0.0 :    # optimization, but TODO : beware of rounding errors
284                for upq in [ self ] + self.ParentPrintersUserPQuota :
285                    price = (float(upq.Printer.PricePerPage or 0.0) * jobsize) + float(upq.Printer.PricePerJob or 0.0)
286                    totalprice += price
287        if self.User.OverCharge != 1.0 : # TODO : beware of rounding errors
288            overcharged = totalprice * self.User.OverCharge       
289            self.parent.tool.printInfo("Overcharging %s by a factor of %s ===> User %s will be charged for %s units." % (totalprice, self.User.OverCharge, self.User.Name, overcharged))
290            return overcharged
291        else :   
292            return totalprice
293           
294    def increasePagesUsage(self, jobsize) :
295        """Increase the value of used pages and money."""
296        jobprice = self.computeJobPrice(jobsize)
297        if jobsize :
298            self.parent.beginTransaction()
299            try :
300                if jobprice :
301                    self.User.consumeAccountBalance(jobprice)
302                for upq in [ self ] + self.ParentPrintersUserPQuota :
303                    self.parent.increaseUserPQuotaPagesCounters(upq, jobsize)
304                    upq.PageCounter = int(upq.PageCounter or 0) + jobsize
305                    upq.LifePageCounter = int(upq.LifePageCounter or 0) + jobsize
306            except PyKotaStorageError, msg :   
307                self.parent.rollbackTransaction()
308                raise PyKotaStorageError, msg
309            else :   
310                self.parent.commitTransaction()
311        return jobprice
312       
313class StorageGroupPQuota(StorageObject) :
314    """Group Print Quota class."""
315    def __init__(self, parent, group, printer) :
316        StorageObject.__init__(self, parent)
317        self.Group = group
318        self.Printer = printer
319        self.PageCounter = None
320        self.LifePageCounter = None
321        self.SoftLimit = None
322        self.HardLimit = None
323        self.DateLimit = None
324       
325    def __getattr__(self, name) :   
326        """Delays data retrieval until it's really needed."""
327        if name == "ParentPrintersGroupPQuota" : 
328            self.ParentPrintersGroupPQuota = (self.Group.Exists and self.Printer.Exists and self.parent.getParentPrintersGroupPQuota(self)) or []
329            return self.ParentPrintersGroupPQuota
330        else :
331            raise AttributeError, name
332       
333    def reset(self) :   
334        """Resets page counter to 0."""
335        self.parent.beginTransaction()
336        try :
337            for user in self.parent.getGroupMembers(self.Group) :
338                uq = self.parent.getUserPQuota(user, self.Printer)
339                uq.reset()
340            self.parent.writeGroupPQuotaDateLimit(self, None)
341        except PyKotaStorageError, msg :   
342            self.parent.rollbackTransaction()
343            raise PyKotaStorageError, msg
344        else :   
345            self.parent.commitTransaction()
346        self.PageCounter = 0
347        self.DateLimit = None
348       
349    def hardreset(self) :   
350        """Resets actual and life time page counters to 0."""
351        self.parent.beginTransaction()
352        try :
353            for user in self.parent.getGroupMembers(self.Group) :
354                uq = self.parent.getUserPQuota(user, self.Printer)
355                uq.hardreset()
356            self.parent.writeGroupPQuotaDateLimit(self, None)
357        except PyKotaStorageError, msg :   
358            self.parent.rollbackTransaction()
359            raise PyKotaStorageError, msg
360        else :   
361            self.parent.commitTransaction()
362        self.PageCounter = self.LifePageCounter = 0
363        self.DateLimit = None
364       
365    def setDateLimit(self, datelimit) :   
366        """Sets the date limit for this quota."""
367        date = "%04i-%02i-%02i %02i:%02i:%02i" % (datelimit.year, datelimit.month, datelimit.day, datelimit.hour, datelimit.minute, datelimit.second)
368        self.parent.writeGroupPQuotaDateLimit(self, date)
369        self.DateLimit = date
370       
371    def setLimits(self, softlimit, hardlimit) :   
372        """Sets the soft and hard limit for this quota."""
373        self.parent.writeGroupPQuotaLimits(self, softlimit, hardlimit)
374        self.SoftLimit = softlimit
375        self.HardLimit = hardlimit
376        self.DateLimit = None
377       
378class StorageJob(StorageObject) :
379    """Printer's Job class."""
380    def __init__(self, parent) :
381        StorageObject.__init__(self, parent)
382        self.UserName = None
383        self.PrinterName = None
384        self.JobId = None
385        self.PrinterPageCounter = None
386        self.JobSizeBytes = None
387        self.JobSize = None
388        self.JobAction = None
389        self.JobDate = None
390        self.JobPrice = None
391        self.JobFileName = None
392        self.JobTitle = None
393        self.JobCopies = None
394        self.JobOptions = None
395        self.JobHostName = None
396        self.JobMD5Sum = None
397        self.JobPages = None
398        self.JobBillingCode = None
399       
400    def __getattr__(self, name) :   
401        """Delays data retrieval until it's really needed."""
402        if name == "User" : 
403            self.User = self.parent.getUser(self.UserName)
404            return self.User
405        elif name == "Printer" :   
406            self.Printer = self.parent.getPrinter(self.PrinterName)
407            return self.Printer
408        else :
409            raise AttributeError, name
410       
411class StorageLastJob(StorageJob) :
412    """Printer's Last Job class."""
413    def __init__(self, parent, printer) :
414        StorageJob.__init__(self, parent)
415        self.PrinterName = printer.Name # not needed
416        self.Printer = printer
417       
418class StorageBillingCode(StorageObject) :
419    """Billing code class."""
420    def __init__(self, parent, name) :
421        StorageObject.__init__(self, parent)
422        self.BillingCode = name
423        self.Description = None
424        self.PageCounter = None
425        self.Balance = None
426       
427    def delete(self) :   
428        """Deletes the billing code from the database."""
429        self.parent.deleteBillingCode(self)
430        self.Exists = 0
431       
432    def reset(self, balance=0.0, pagecounter=0) :   
433        """Resets the pagecounter and balance for this billing code."""
434        self.parent.setBillingCodeValues(self, pagecounter, balance)
435        self.Balance = balance
436        self.PageCounter = pagecounter
437       
438    def setDescription(self, description=None) :
439        """Modifies the description for this billing code."""
440        if description is None :
441            description = self.Description
442        else :   
443            self.Description = str(description)
444        self.parent.writeBillingCodeDescription(self)
445       
446    def consume(self, pages, price) :
447        """Consumes some pages and credits for this billing code."""
448        if pages :
449           self.parent.consumeBillingCode(self, pages, price)
450           self.PageCounter += pages
451           self.Balance -= price
452       
453class BaseStorage :
454    def __init__(self, pykotatool) :
455        """Opens the storage connection."""
456        self.closed = 1
457        self.tool = pykotatool
458        self.usecache = pykotatool.config.getCaching()
459        self.disablehistory = pykotatool.config.getDisableHistory()
460        self.privacy = pykotatool.config.getPrivacy()
461        if self.privacy :
462            pykotatool.logdebug("Jobs' title, filename and options will be hidden because of privacy concerns.")
463        if self.usecache :
464            self.tool.logdebug("Caching enabled.")
465            self.caches = { "USERS" : {}, "GROUPS" : {}, "PRINTERS" : {}, "USERPQUOTAS" : {}, "GROUPPQUOTAS" : {}, "JOBS" : {}, "LASTJOBS" : {}, "BILLINGCODES" : {} }
466       
467    def close(self) :   
468        """Must be overriden in children classes."""
469        raise RuntimeError, "BaseStorage.close() must be overriden !"
470       
471    def __del__(self) :       
472        """Ensures that the database connection is closed."""
473        self.close()
474       
475    def getFromCache(self, cachetype, key) :
476        """Tries to extract something from the cache."""
477        if self.usecache :
478            entry = self.caches[cachetype].get(key)
479            if entry is not None :
480                self.tool.logdebug("Cache hit (%s->%s)" % (cachetype, key))
481            else :   
482                self.tool.logdebug("Cache miss (%s->%s)" % (cachetype, key))
483            return entry   
484           
485    def cacheEntry(self, cachetype, key, value) :       
486        """Puts an entry in the cache."""
487        if self.usecache and getattr(value, "Exists", 0) :
488            self.caches[cachetype][key] = value
489            self.tool.logdebug("Cache store (%s->%s)" % (cachetype, key))
490           
491    def getUser(self, username) :       
492        """Returns the user from cache."""
493        user = self.getFromCache("USERS", username)
494        if user is None :
495            user = self.getUserFromBackend(username)
496            self.cacheEntry("USERS", username, user)
497        return user   
498       
499    def getGroup(self, groupname) :       
500        """Returns the group from cache."""
501        group = self.getFromCache("GROUPS", groupname)
502        if group is None :
503            group = self.getGroupFromBackend(groupname)
504            self.cacheEntry("GROUPS", groupname, group)
505        return group   
506       
507    def getPrinter(self, printername) :       
508        """Returns the printer from cache."""
509        printer = self.getFromCache("PRINTERS", printername)
510        if printer is None :
511            printer = self.getPrinterFromBackend(printername)
512            self.cacheEntry("PRINTERS", printername, printer)
513        return printer   
514       
515    def getUserPQuota(self, user, printer) :       
516        """Returns the user quota information from cache."""
517        useratprinter = "%s@%s" % (user.Name, printer.Name)
518        upquota = self.getFromCache("USERPQUOTAS", useratprinter)
519        if upquota is None :
520            upquota = self.getUserPQuotaFromBackend(user, printer)
521            self.cacheEntry("USERPQUOTAS", useratprinter, upquota)
522        return upquota   
523       
524    def getGroupPQuota(self, group, printer) :       
525        """Returns the group quota information from cache."""
526        groupatprinter = "%s@%s" % (group.Name, printer.Name)
527        gpquota = self.getFromCache("GROUPPQUOTAS", groupatprinter)
528        if gpquota is None :
529            gpquota = self.getGroupPQuotaFromBackend(group, printer)
530            self.cacheEntry("GROUPPQUOTAS", groupatprinter, gpquota)
531        return gpquota   
532       
533    def getPrinterLastJob(self, printer) :       
534        """Extracts last job information for a given printer from cache."""
535        lastjob = self.getFromCache("LASTJOBS", printer.Name)
536        if lastjob is None :
537            lastjob = self.getPrinterLastJobFromBackend(printer)
538            self.cacheEntry("LASTJOBS", printer.Name, lastjob)
539        return lastjob   
540       
541    def getBillingCode(self, label) :       
542        """Returns the user from cache."""
543        code = self.getFromCache("BILLINGCODES", label)
544        if code is None :
545            code = self.getBillingCodeFromBackend(label)
546            self.cacheEntry("BILLINGCODES", label, code)
547        return code
548       
549    def getParentPrinters(self, printer) :   
550        """Extracts parent printers information for a given printer from cache."""
551        if self.usecache :
552            if not hasattr(printer, "Parents") :
553                self.tool.logdebug("Cache miss (%s->Parents)" % printer.Name)
554                printer.Parents = self.getParentPrintersFromBackend(printer)
555                self.tool.logdebug("Cache store (%s->Parents)" % printer.Name)
556            else :
557                self.tool.logdebug("Cache hit (%s->Parents)" % printer.Name)
558        else :       
559            printer.Parents = self.getParentPrintersFromBackend(printer)
560        for parent in printer.Parents[:] :   
561            printer.Parents.extend(self.getParentPrinters(parent))
562        uniquedic = {}   
563        for parent in printer.Parents :
564            uniquedic[parent.Name] = parent
565        printer.Parents = uniquedic.values()   
566        return printer.Parents
567       
568    def getGroupMembers(self, group) :       
569        """Returns the group's members list from in-group cache."""
570        if self.usecache :
571            if not hasattr(group, "Members") :
572                self.tool.logdebug("Cache miss (%s->Members)" % group.Name)
573                group.Members = self.getGroupMembersFromBackend(group)
574                self.tool.logdebug("Cache store (%s->Members)" % group.Name)
575            else :
576                self.tool.logdebug("Cache hit (%s->Members)" % group.Name)
577        else :       
578            group.Members = self.getGroupMembersFromBackend(group)
579        return group.Members   
580       
581    def getUserGroups(self, user) :       
582        """Returns the user's groups list from in-user cache."""
583        if self.usecache :
584            if not hasattr(user, "Groups") :
585                self.tool.logdebug("Cache miss (%s->Groups)" % user.Name)
586                user.Groups = self.getUserGroupsFromBackend(user)
587                self.tool.logdebug("Cache store (%s->Groups)" % user.Name)
588            else :
589                self.tool.logdebug("Cache hit (%s->Groups)" % user.Name)
590        else :       
591            user.Groups = self.getUserGroupsFromBackend(user)
592        return user.Groups   
593       
594    def getParentPrintersUserPQuota(self, userpquota) :     
595        """Returns all user print quota on the printer and all its parents recursively."""
596        upquotas = [ ]
597        for printer in self.getParentPrinters(userpquota.Printer) :
598            upq = self.getUserPQuota(userpquota.User, printer)
599            if upq.Exists :
600                upquotas.append(upq)
601        return upquotas       
602       
603    def getParentPrintersGroupPQuota(self, grouppquota) :     
604        """Returns all group print quota on the printer and all its parents recursively."""
605        gpquotas = [ ]
606        for printer in self.getParentPrinters(grouppquota.Printer) :
607            gpq = self.getGroupPQuota(grouppquota.Group, printer)
608            if gpq.Exists :
609                gpquotas.append(gpq)
610        return gpquotas       
611       
612    def databaseToUserCharset(self, text) :
613        """Converts from database format (UTF-8) to user's charset."""
614        if text is not None :
615            try :
616                return unicode(text, "UTF-8").encode(self.tool.getCharset()) 
617            except UnicodeError :   
618                try :
619                    # Incorrect locale settings ?
620                    return unicode(text, "UTF-8").encode("ISO-8859-15") 
621                except UnicodeError :   
622                    pass
623        return text
624       
625    def userCharsetToDatabase(self, text) :
626        """Converts from user's charset to database format (UTF-8)."""
627        if text is not None :
628            try :
629                return unicode(text, self.tool.getCharset()).encode("UTF-8") 
630            except UnicodeError :   
631                try :
632                    # Incorrect locale settings ?
633                    return unicode(text, "ISO-8859-15").encode("UTF-8") 
634                except UnicodeError :   
635                    pass
636        return text
637       
638    def cleanDates(self, startdate, enddate) :   
639        """Clean the dates to create a correct filter."""
640        if startdate is None :
641            startdate = enddate
642        if enddate is None :   
643            enddate = startdate
644        if (startdate is None) and (enddate is None) :   
645            return (None, None)
646           
647        now = DateTime.now()   
648        nameddates = ('yesterday', 'today', 'now', 'tomorrow')
649        datedict = { "start" : startdate.lower(), "end" : enddate.lower() }   
650        for limit in datedict.keys() :
651            dateval = datedict[limit]
652            for name in nameddates :
653                if dateval.startswith(name) :
654                    try :
655                        offset = int(dateval[len(name):])
656                    except :   
657                        offset = 0
658                    dateval = dateval[:len(name)]   
659                    if limit == "start" :
660                        if dateval == "yesterday" :
661                            dateval = (now - 1 + offset).Format("%Y%m%d000000")
662                        elif dateval == "today" :
663                            dateval = (now + offset).Format("%Y%m%d000000")
664                        elif dateval == "now" :
665                            dateval = (now + offset).Format("%Y%m%d%H%M%S")
666                        else : # tomorrow
667                            dateval = (now + 1 + offset).Format("%Y%m%d000000")
668                    else :
669                        if dateval == "yesterday" :
670                            dateval = (now - 1 + offset).Format("%Y%m%d235959")
671                        elif dateval == "today" :
672                            dateval = (now + offset).Format("%Y%m%d235959")
673                        elif dateval == "now" :
674                            dateval = (now + offset).Format("%Y%m%d%H%M%S")
675                        else : # tomorrow
676                            dateval = (now + 1 + offset).Format("%Y%m%d235959")
677                    break
678                   
679            if not dateval.isdigit() :
680                dateval = None
681            else :   
682                lgdateval = len(dateval)
683                if lgdateval == 4 :
684                    if limit == "start" : 
685                        dateval = "%s0101 00:00:00" % dateval
686                    else : 
687                        dateval = "%s1231 23:59:59" % dateval
688                elif lgdateval == 6 :
689                    if limit == "start" : 
690                        dateval = "%s01 00:00:00" % dateval
691                    else : 
692                        mxdate = DateTime.ISO.ParseDateTime("%s01 00:00:00" % dateval)
693                        dateval = "%s%02i 23:59:59" % (dateval, mxdate.days_in_month)
694                elif lgdateval == 8 :
695                    if limit == "start" : 
696                        dateval = "%s 00:00:00" % dateval
697                    else : 
698                        dateval = "%s 23:59:59" % dateval
699                elif lgdateval == 10 :
700                    if limit == "start" : 
701                        dateval = "%s %s:00:00" % (dateval[:8], dateval[8:])
702                    else : 
703                        dateval = "%s %s:59:59" % (dateval[:8], dateval[8:])
704                elif lgdateval == 12 :
705                    if limit == "start" : 
706                        dateval = "%s %s:%s:00" % (dateval[:8], dateval[8:10], dateval[10:])
707                    else : 
708                        dateval = "%s %s:%s:59" % (dateval[:8], dateval[8:10], dateval[10:])
709                elif lgdateval == 14 :       
710                    dateval = "%s %s:%s:%s" % (dateval[:8], dateval[8:10], dateval[10:12], dateval[12:])
711                else :   
712                    dateval = None
713                try :   
714                    DateTime.ISO.ParseDateTime(dateval)
715                except :   
716                    dateval = None
717            datedict[limit] = dateval   
718        (start, end) = (datedict["start"], datedict["end"])
719        if start > end :
720            (start, end) = (end, start)
721        return (start, end)   
722       
723def openConnection(pykotatool) :
724    """Returns a connection handle to the appropriate Quota Storage Database."""
725    backendinfo = pykotatool.config.getStorageBackend()
726    backend = backendinfo["storagebackend"]
727    try :
728        exec "from pykota.storages import %s as storagebackend" % backend.lower()
729    except ImportError :
730        raise PyKotaStorageError, _("Unsupported quota storage backend %s") % backend
731    else :   
732        host = backendinfo["storageserver"]
733        database = backendinfo["storagename"]
734        admin = backendinfo["storageadmin"] or backendinfo["storageuser"]
735        adminpw = backendinfo["storageadminpw"] or backendinfo["storageuserpw"]
736        return storagebackend.Storage(pykotatool, host, database, admin, adminpw)
Note: See TracBrowser for help on using the browser.