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

Revision 2266, 27.7 kB (checked in by jerome, 19 years ago)

Now dumpykota and dumpykota.cgi accept start= and end=
to specify the starting and ending dates when dumping the
history.
Syntax allowed is :

start|end=YYYY[MM[DD[hh[mm[ss]]]]]

and this is REALLY powerful !

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