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

Revision 2409, 30.5 kB (checked in by jerome, 19 years ago)

The cupspykota backend was rewritten from scratch. MacOSX servers should
work just fine now.
Severity : High. Testers MORE than welcome :-)

  • 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            if jobprice :
299                self.User.consumeAccountBalance(jobprice)
300            for upq in [ self ] + self.ParentPrintersUserPQuota :
301                self.parent.increaseUserPQuotaPagesCounters(upq, jobsize)
302                upq.PageCounter = int(upq.PageCounter or 0) + jobsize
303                upq.LifePageCounter = int(upq.LifePageCounter or 0) + jobsize
304        return jobprice
305       
306class StorageGroupPQuota(StorageObject) :
307    """Group Print Quota class."""
308    def __init__(self, parent, group, printer) :
309        StorageObject.__init__(self, parent)
310        self.Group = group
311        self.Printer = printer
312        self.PageCounter = None
313        self.LifePageCounter = None
314        self.SoftLimit = None
315        self.HardLimit = None
316        self.DateLimit = None
317       
318    def __getattr__(self, name) :   
319        """Delays data retrieval until it's really needed."""
320        if name == "ParentPrintersGroupPQuota" : 
321            self.ParentPrintersGroupPQuota = (self.Group.Exists and self.Printer.Exists and self.parent.getParentPrintersGroupPQuota(self)) or []
322            return self.ParentPrintersGroupPQuota
323        else :
324            raise AttributeError, name
325       
326    def reset(self) :   
327        """Resets page counter to 0."""
328        self.parent.beginTransaction()
329        try :
330            for user in self.parent.getGroupMembers(self.Group) :
331                uq = self.parent.getUserPQuota(user, self.Printer)
332                uq.reset()
333            self.parent.writeGroupPQuotaDateLimit(self, None)
334        except PyKotaStorageError, msg :   
335            self.parent.rollbackTransaction()
336            raise PyKotaStorageError, msg
337        else :   
338            self.parent.commitTransaction()
339        self.PageCounter = 0
340        self.DateLimit = None
341       
342    def hardreset(self) :   
343        """Resets actual and life time page counters to 0."""
344        self.parent.beginTransaction()
345        try :
346            for user in self.parent.getGroupMembers(self.Group) :
347                uq = self.parent.getUserPQuota(user, self.Printer)
348                uq.hardreset()
349            self.parent.writeGroupPQuotaDateLimit(self, None)
350        except PyKotaStorageError, msg :   
351            self.parent.rollbackTransaction()
352            raise PyKotaStorageError, msg
353        else :   
354            self.parent.commitTransaction()
355        self.PageCounter = self.LifePageCounter = 0
356        self.DateLimit = None
357       
358    def setDateLimit(self, datelimit) :   
359        """Sets the date limit for this quota."""
360        date = "%04i-%02i-%02i %02i:%02i:%02i" % (datelimit.year, datelimit.month, datelimit.day, datelimit.hour, datelimit.minute, datelimit.second)
361        self.parent.writeGroupPQuotaDateLimit(self, date)
362        self.DateLimit = date
363       
364    def setLimits(self, softlimit, hardlimit) :   
365        """Sets the soft and hard limit for this quota."""
366        self.parent.writeGroupPQuotaLimits(self, softlimit, hardlimit)
367        self.SoftLimit = softlimit
368        self.HardLimit = hardlimit
369        self.DateLimit = None
370       
371class StorageJob(StorageObject) :
372    """Printer's Job class."""
373    def __init__(self, parent) :
374        StorageObject.__init__(self, parent)
375        self.UserName = None
376        self.PrinterName = None
377        self.JobId = None
378        self.PrinterPageCounter = None
379        self.JobSizeBytes = None
380        self.JobSize = None
381        self.JobAction = None
382        self.JobDate = None
383        self.JobPrice = None
384        self.JobFileName = None
385        self.JobTitle = None
386        self.JobCopies = None
387        self.JobOptions = None
388        self.JobHostName = None
389        self.JobMD5Sum = None
390        self.JobPages = None
391        self.JobBillingCode = None
392       
393    def __getattr__(self, name) :   
394        """Delays data retrieval until it's really needed."""
395        if name == "User" : 
396            self.User = self.parent.getUser(self.UserName)
397            return self.User
398        elif name == "Printer" :   
399            self.Printer = self.parent.getPrinter(self.PrinterName)
400            return self.Printer
401        else :
402            raise AttributeError, name
403       
404class StorageLastJob(StorageJob) :
405    """Printer's Last Job class."""
406    def __init__(self, parent, printer) :
407        StorageJob.__init__(self, parent)
408        self.PrinterName = printer.Name # not needed
409        self.Printer = printer
410       
411class StorageBillingCode(StorageObject) :
412    """Billing code class."""
413    def __init__(self, parent, name) :
414        StorageObject.__init__(self, parent)
415        self.BillingCode = name
416        self.Description = None
417        self.PageCounter = None
418        self.Balance = None
419       
420    def delete(self) :   
421        """Deletes the billing code from the database."""
422        self.parent.deleteBillingCode(self)
423        self.Exists = 0
424       
425    def reset(self, balance=0.0, pagecounter=0) :   
426        """Resets the pagecounter and balance for this billing code."""
427        self.parent.setBillingCodeValues(self, pagecounter, balance)
428        self.Balance = balance
429        self.PageCounter = pagecounter
430       
431    def setDescription(self, description=None) :
432        """Modifies the description for this billing code."""
433        if description is None :
434            description = self.Description
435        else :   
436            self.Description = str(description)
437        self.parent.writeBillingCodeDescription(self)
438       
439    def consume(self, pages, price) :
440        """Consumes some pages and credits for this billing code."""
441        if pages :
442           self.parent.consumeBillingCode(self, pages, price)
443           self.PageCounter += pages
444           self.Balance -= price
445       
446class BaseStorage :
447    def __init__(self, pykotatool) :
448        """Opens the storage connection."""
449        self.closed = 1
450        self.tool = pykotatool
451        self.usecache = pykotatool.config.getCaching()
452        self.disablehistory = pykotatool.config.getDisableHistory()
453        self.privacy = pykotatool.config.getPrivacy()
454        if self.privacy :
455            pykotatool.logdebug("Jobs' title, filename and options will be hidden because of privacy concerns.")
456        if self.usecache :
457            self.tool.logdebug("Caching enabled.")
458            self.caches = { "USERS" : {}, "GROUPS" : {}, "PRINTERS" : {}, "USERPQUOTAS" : {}, "GROUPPQUOTAS" : {}, "JOBS" : {}, "LASTJOBS" : {}, "BILLINGCODES" : {} }
459       
460    def close(self) :   
461        """Must be overriden in children classes."""
462        raise RuntimeError, "BaseStorage.close() must be overriden !"
463       
464    def __del__(self) :       
465        """Ensures that the database connection is closed."""
466        self.close()
467       
468    def getFromCache(self, cachetype, key) :
469        """Tries to extract something from the cache."""
470        if self.usecache :
471            entry = self.caches[cachetype].get(key)
472            if entry is not None :
473                self.tool.logdebug("Cache hit (%s->%s)" % (cachetype, key))
474            else :   
475                self.tool.logdebug("Cache miss (%s->%s)" % (cachetype, key))
476            return entry   
477           
478    def cacheEntry(self, cachetype, key, value) :       
479        """Puts an entry in the cache."""
480        if self.usecache and getattr(value, "Exists", 0) :
481            self.caches[cachetype][key] = value
482            self.tool.logdebug("Cache store (%s->%s)" % (cachetype, key))
483           
484    def getUser(self, username) :       
485        """Returns the user from cache."""
486        user = self.getFromCache("USERS", username)
487        if user is None :
488            user = self.getUserFromBackend(username)
489            self.cacheEntry("USERS", username, user)
490        return user   
491       
492    def getGroup(self, groupname) :       
493        """Returns the group from cache."""
494        group = self.getFromCache("GROUPS", groupname)
495        if group is None :
496            group = self.getGroupFromBackend(groupname)
497            self.cacheEntry("GROUPS", groupname, group)
498        return group   
499       
500    def getPrinter(self, printername) :       
501        """Returns the printer from cache."""
502        printer = self.getFromCache("PRINTERS", printername)
503        if printer is None :
504            printer = self.getPrinterFromBackend(printername)
505            self.cacheEntry("PRINTERS", printername, printer)
506        return printer   
507       
508    def getUserPQuota(self, user, printer) :       
509        """Returns the user quota information from cache."""
510        useratprinter = "%s@%s" % (user.Name, printer.Name)
511        upquota = self.getFromCache("USERPQUOTAS", useratprinter)
512        if upquota is None :
513            upquota = self.getUserPQuotaFromBackend(user, printer)
514            self.cacheEntry("USERPQUOTAS", useratprinter, upquota)
515        return upquota   
516       
517    def getGroupPQuota(self, group, printer) :       
518        """Returns the group quota information from cache."""
519        groupatprinter = "%s@%s" % (group.Name, printer.Name)
520        gpquota = self.getFromCache("GROUPPQUOTAS", groupatprinter)
521        if gpquota is None :
522            gpquota = self.getGroupPQuotaFromBackend(group, printer)
523            self.cacheEntry("GROUPPQUOTAS", groupatprinter, gpquota)
524        return gpquota   
525       
526    def getPrinterLastJob(self, printer) :       
527        """Extracts last job information for a given printer from cache."""
528        lastjob = self.getFromCache("LASTJOBS", printer.Name)
529        if lastjob is None :
530            lastjob = self.getPrinterLastJobFromBackend(printer)
531            self.cacheEntry("LASTJOBS", printer.Name, lastjob)
532        return lastjob   
533       
534    def getBillingCode(self, label) :       
535        """Returns the user from cache."""
536        code = self.getFromCache("BILLINGCODES", label)
537        if code is None :
538            code = self.getBillingCodeFromBackend(label)
539            self.cacheEntry("BILLINGCODES", label, code)
540        return code
541       
542    def getParentPrinters(self, printer) :   
543        """Extracts parent printers information for a given printer from cache."""
544        if self.usecache :
545            if not hasattr(printer, "Parents") :
546                self.tool.logdebug("Cache miss (%s->Parents)" % printer.Name)
547                printer.Parents = self.getParentPrintersFromBackend(printer)
548                self.tool.logdebug("Cache store (%s->Parents)" % printer.Name)
549            else :
550                self.tool.logdebug("Cache hit (%s->Parents)" % printer.Name)
551        else :       
552            printer.Parents = self.getParentPrintersFromBackend(printer)
553        for parent in printer.Parents[:] :   
554            printer.Parents.extend(self.getParentPrinters(parent))
555        uniquedic = {}   
556        for parent in printer.Parents :
557            uniquedic[parent.Name] = parent
558        printer.Parents = uniquedic.values()   
559        return printer.Parents
560       
561    def getGroupMembers(self, group) :       
562        """Returns the group's members list from in-group cache."""
563        if self.usecache :
564            if not hasattr(group, "Members") :
565                self.tool.logdebug("Cache miss (%s->Members)" % group.Name)
566                group.Members = self.getGroupMembersFromBackend(group)
567                self.tool.logdebug("Cache store (%s->Members)" % group.Name)
568            else :
569                self.tool.logdebug("Cache hit (%s->Members)" % group.Name)
570        else :       
571            group.Members = self.getGroupMembersFromBackend(group)
572        return group.Members   
573       
574    def getUserGroups(self, user) :       
575        """Returns the user's groups list from in-user cache."""
576        if self.usecache :
577            if not hasattr(user, "Groups") :
578                self.tool.logdebug("Cache miss (%s->Groups)" % user.Name)
579                user.Groups = self.getUserGroupsFromBackend(user)
580                self.tool.logdebug("Cache store (%s->Groups)" % user.Name)
581            else :
582                self.tool.logdebug("Cache hit (%s->Groups)" % user.Name)
583        else :       
584            user.Groups = self.getUserGroupsFromBackend(user)
585        return user.Groups   
586       
587    def getParentPrintersUserPQuota(self, userpquota) :     
588        """Returns all user print quota on the printer and all its parents recursively."""
589        upquotas = [ ]
590        for printer in self.getParentPrinters(userpquota.Printer) :
591            upq = self.getUserPQuota(userpquota.User, printer)
592            if upq.Exists :
593                upquotas.append(upq)
594        return upquotas       
595       
596    def getParentPrintersGroupPQuota(self, grouppquota) :     
597        """Returns all group print quota on the printer and all its parents recursively."""
598        gpquotas = [ ]
599        for printer in self.getParentPrinters(grouppquota.Printer) :
600            gpq = self.getGroupPQuota(grouppquota.Group, printer)
601            if gpq.Exists :
602                gpquotas.append(gpq)
603        return gpquotas       
604       
605    def databaseToUserCharset(self, text) :
606        """Converts from database format (UTF-8) to user's charset."""
607        if text is not None :
608            try :
609                return unicode(text, "UTF-8").encode(self.tool.getCharset()) 
610            except UnicodeError :   
611                try :
612                    # Incorrect locale settings ?
613                    return unicode(text, "UTF-8").encode("ISO-8859-15") 
614                except UnicodeError :   
615                    pass
616        return text
617       
618    def userCharsetToDatabase(self, text) :
619        """Converts from user's charset to database format (UTF-8)."""
620        if text is not None :
621            try :
622                return unicode(text, self.tool.getCharset()).encode("UTF-8") 
623            except UnicodeError :   
624                try :
625                    # Incorrect locale settings ?
626                    return unicode(text, "ISO-8859-15").encode("UTF-8") 
627                except UnicodeError :   
628                    pass
629        return text
630       
631    def cleanDates(self, startdate, enddate) :   
632        """Clean the dates to create a correct filter."""
633        if startdate is None :
634            startdate = enddate
635        if enddate is None :   
636            enddate = startdate
637        if (startdate is None) and (enddate is None) :   
638            return (None, None)
639           
640        now = DateTime.now()   
641        nameddates = ('yesterday', 'today', 'now', 'tomorrow')
642        datedict = { "start" : startdate.lower(), "end" : enddate.lower() }   
643        for limit in datedict.keys() :
644            dateval = datedict[limit]
645            for name in nameddates :
646                if dateval.startswith(name) :
647                    try :
648                        offset = int(dateval[len(name):])
649                    except :   
650                        offset = 0
651                    dateval = dateval[:len(name)]   
652                    if limit == "start" :
653                        if dateval == "yesterday" :
654                            dateval = (now - 1 + offset).Format("%Y%m%d000000")
655                        elif dateval == "today" :
656                            dateval = (now + offset).Format("%Y%m%d000000")
657                        elif dateval == "now" :
658                            dateval = (now + offset).Format("%Y%m%d%H%M%S")
659                        else : # tomorrow
660                            dateval = (now + 1 + offset).Format("%Y%m%d000000")
661                    else :
662                        if dateval == "yesterday" :
663                            dateval = (now - 1 + offset).Format("%Y%m%d235959")
664                        elif dateval == "today" :
665                            dateval = (now + offset).Format("%Y%m%d235959")
666                        elif dateval == "now" :
667                            dateval = (now + offset).Format("%Y%m%d%H%M%S")
668                        else : # tomorrow
669                            dateval = (now + 1 + offset).Format("%Y%m%d235959")
670                    break
671                   
672            if not dateval.isdigit() :
673                dateval = None
674            else :   
675                lgdateval = len(dateval)
676                if lgdateval == 4 :
677                    if limit == "start" : 
678                        dateval = "%s0101 00:00:00" % dateval
679                    else : 
680                        dateval = "%s1231 23:59:59" % dateval
681                elif lgdateval == 6 :
682                    if limit == "start" : 
683                        dateval = "%s01 00:00:00" % dateval
684                    else : 
685                        mxdate = DateTime.ISO.ParseDateTime("%s01 00:00:00" % dateval)
686                        dateval = "%s%02i 23:59:59" % (dateval, mxdate.days_in_month)
687                elif lgdateval == 8 :
688                    if limit == "start" : 
689                        dateval = "%s 00:00:00" % dateval
690                    else : 
691                        dateval = "%s 23:59:59" % dateval
692                elif lgdateval == 10 :
693                    if limit == "start" : 
694                        dateval = "%s %s:00:00" % (dateval[:8], dateval[8:])
695                    else : 
696                        dateval = "%s %s:59:59" % (dateval[:8], dateval[8:])
697                elif lgdateval == 12 :
698                    if limit == "start" : 
699                        dateval = "%s %s:%s:00" % (dateval[:8], dateval[8:10], dateval[10:])
700                    else : 
701                        dateval = "%s %s:%s:59" % (dateval[:8], dateval[8:10], dateval[10:])
702                elif lgdateval == 14 :       
703                    dateval = "%s %s:%s:%s" % (dateval[:8], dateval[8:10], dateval[10:12], dateval[12:])
704                else :   
705                    dateval = None
706                try :   
707                    DateTime.ISO.ParseDateTime(dateval)
708                except :   
709                    dateval = None
710            datedict[limit] = dateval   
711        (start, end) = (datedict["start"], datedict["end"])
712        if start > end :
713            (start, end) = (end, start)
714        return (start, end)   
715       
716def openConnection(pykotatool) :
717    """Returns a connection handle to the appropriate Quota Storage Database."""
718    backendinfo = pykotatool.config.getStorageBackend()
719    backend = backendinfo["storagebackend"]
720    try :
721        exec "from pykota.storages import %s as storagebackend" % backend.lower()
722    except ImportError :
723        raise PyKotaStorageError, _("Unsupported quota storage backend %s") % backend
724    else :   
725        host = backendinfo["storageserver"]
726        database = backendinfo["storagename"]
727        admin = backendinfo["storageadmin"] or backendinfo["storageuser"]
728        adminpw = backendinfo["storageadminpw"] or backendinfo["storageuserpw"]
729        return storagebackend.Storage(pykotatool, host, database, admin, adminpw)
Note: See TracBrowser for help on using the browser.