1 | # PyKota |
---|
2 | # -*- coding: ISO-8859-15 -*- |
---|
3 | # |
---|
4 | # PyKota : Print Quotas for CUPS and LPRng |
---|
5 | # |
---|
6 | # (c) 2003-2004 Jerome Alet <alet@librelogiciel.com> |
---|
7 | # This program is free software; you can redistribute it and/or modify |
---|
8 | # it under the terms of the GNU General Public License as published by |
---|
9 | # the Free Software Foundation; either version 2 of the License, or |
---|
10 | # (at your option) any later version. |
---|
11 | # |
---|
12 | # This program is distributed in the hope that it will be useful, |
---|
13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of |
---|
14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
---|
15 | # GNU General Public License for more details. |
---|
16 | # |
---|
17 | # You should have received a copy of the GNU General Public License |
---|
18 | # along with this program; if not, write to the Free Software |
---|
19 | # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. |
---|
20 | # |
---|
21 | # $Id$ |
---|
22 | # |
---|
23 | # $Log$ |
---|
24 | # Revision 1.82 2004/10/05 09:59:20 jalet |
---|
25 | # Restore compatibility with Python 2.1 |
---|
26 | # |
---|
27 | # Revision 1.81 2004/10/04 11:27:57 jalet |
---|
28 | # Finished LDAP support for dumpykota. |
---|
29 | # |
---|
30 | # Revision 1.80 2004/10/03 19:57:57 jalet |
---|
31 | # Dump of payments should work with LDAP backend now. |
---|
32 | # |
---|
33 | # Revision 1.79 2004/10/03 19:52:59 jalet |
---|
34 | # More work done on LDAP and dumpykota |
---|
35 | # |
---|
36 | # Revision 1.78 2004/10/02 05:48:56 jalet |
---|
37 | # Should now correctly deal with charsets both when storing into databases and when |
---|
38 | # retrieving datas. Works with both PostgreSQL and LDAP. |
---|
39 | # |
---|
40 | # Revision 1.77 2004/09/28 14:29:00 jalet |
---|
41 | # dumpykota for LDAP backend is almost there. |
---|
42 | # |
---|
43 | # Revision 1.76 2004/09/28 09:11:56 jalet |
---|
44 | # Fix for accented chars in print job's title, filename, and options |
---|
45 | # |
---|
46 | # Revision 1.75 2004/09/24 20:21:50 jalet |
---|
47 | # Fixed pykotaAccountBalance object location during creation |
---|
48 | # |
---|
49 | # Revision 1.74 2004/09/02 10:09:30 jalet |
---|
50 | # Fixed bug in LDAP user deletion code which didn't correctly delete the user's |
---|
51 | # pykotaLastJob entries. |
---|
52 | # |
---|
53 | # Revision 1.73 2004/07/17 20:37:27 jalet |
---|
54 | # Missing file... Am I really stupid ? |
---|
55 | # |
---|
56 | # Revision 1.72 2004/07/01 19:56:43 jalet |
---|
57 | # Better dispatching of error messages |
---|
58 | # |
---|
59 | # Revision 1.71 2004/07/01 17:45:49 jalet |
---|
60 | # Added code to handle the description field for printers |
---|
61 | # |
---|
62 | # Revision 1.70 2004/06/10 20:50:25 jalet |
---|
63 | # Better log message |
---|
64 | # |
---|
65 | # Revision 1.69 2004/06/05 22:18:04 jalet |
---|
66 | # Now catches some exceptions earlier. |
---|
67 | # storage.py and ldapstorage.py : removed old comments |
---|
68 | # |
---|
69 | # Revision 1.68 2004/06/05 22:03:50 jalet |
---|
70 | # Payments history is now stored in database |
---|
71 | # |
---|
72 | # Revision 1.67 2004/06/03 23:14:10 jalet |
---|
73 | # Now stores the job's size in bytes in the database. |
---|
74 | # Preliminary work on payments storage : database schemas are OK now, |
---|
75 | # but no code to store payments yet. |
---|
76 | # Removed schema picture, not relevant anymore. |
---|
77 | # |
---|
78 | # Revision 1.66 2004/05/28 20:56:45 jalet |
---|
79 | # Extended syntax for LDAP specific newuser and newgroup directives. Untested. |
---|
80 | # |
---|
81 | # Revision 1.65 2004/05/27 12:52:12 jalet |
---|
82 | # More useful error message in case of misconfiguration of an LDAP search base |
---|
83 | # in pykota.conf |
---|
84 | # |
---|
85 | # Revision 1.64 2004/05/26 14:50:01 jalet |
---|
86 | # First try at saving the job-originating-hostname in the database |
---|
87 | # |
---|
88 | # Revision 1.63 2004/05/06 12:37:46 jalet |
---|
89 | # pkpgcounter : comments |
---|
90 | # pkprinters : when --add is used, existing printers are now skipped. |
---|
91 | # |
---|
92 | # Revision 1.62 2004/03/05 14:31:58 jalet |
---|
93 | # Improvement on strange history entries |
---|
94 | # |
---|
95 | # Revision 1.61 2004/03/05 13:19:53 jalet |
---|
96 | # Code safer wrt entries created in other tools |
---|
97 | # |
---|
98 | # Revision 1.60 2004/03/02 14:39:02 jalet |
---|
99 | # Final fix for printers searching |
---|
100 | # |
---|
101 | # Revision 1.59 2004/03/02 14:35:46 jalet |
---|
102 | # Missing test when searching printer objects when these objects were manually |
---|
103 | # created and don't contain the pykotaPrinterName attribute |
---|
104 | # |
---|
105 | # Revision 1.58 2004/02/27 09:30:33 jalet |
---|
106 | # datelimit wasn't reset when modifying soft and hard limits with the LDAP backend |
---|
107 | # |
---|
108 | # Revision 1.57 2004/02/26 14:18:07 jalet |
---|
109 | # Should fix the remaining bugs wrt printers groups and users groups. |
---|
110 | # |
---|
111 | # Revision 1.56 2004/02/25 16:52:39 jalet |
---|
112 | # Small fix wrt empty user groups |
---|
113 | # |
---|
114 | # Revision 1.55 2004/02/23 22:53:21 jalet |
---|
115 | # Don't retrieve data when it's not needed, to avoid database queries |
---|
116 | # |
---|
117 | # Revision 1.54 2004/02/20 16:38:39 jalet |
---|
118 | # ldapcache directive marked as experimental |
---|
119 | # |
---|
120 | # Revision 1.53 2004/02/20 14:42:21 jalet |
---|
121 | # Experimental ldapcache directive added |
---|
122 | # |
---|
123 | # Revision 1.52 2004/02/17 23:41:48 jalet |
---|
124 | # Preliminary work on low-level LDAP specific cache. |
---|
125 | # |
---|
126 | # Revision 1.51 2004/02/04 13:24:41 jalet |
---|
127 | # pkprinters can now remove printers from printers groups. |
---|
128 | # |
---|
129 | # Revision 1.50 2004/02/04 11:17:00 jalet |
---|
130 | # pkprinters command line tool added. |
---|
131 | # |
---|
132 | # Revision 1.49 2004/01/29 22:35:45 jalet |
---|
133 | # Small fix from Matt. |
---|
134 | # |
---|
135 | # Revision 1.48 2004/01/12 14:35:02 jalet |
---|
136 | # Printing history added to CGI script. |
---|
137 | # |
---|
138 | # Revision 1.47 2004/01/10 09:44:02 jalet |
---|
139 | # Fixed potential accuracy problem if a user printed on several printers at |
---|
140 | # the very same time. |
---|
141 | # |
---|
142 | # Revision 1.46 2004/01/08 16:33:27 jalet |
---|
143 | # Additionnal check to not create a circular printers group. |
---|
144 | # |
---|
145 | # Revision 1.45 2004/01/08 16:24:49 jalet |
---|
146 | # edpykota now supports adding printers to printer groups. |
---|
147 | # |
---|
148 | # Revision 1.44 2004/01/08 14:10:33 jalet |
---|
149 | # Copyright year changed. |
---|
150 | # |
---|
151 | # Revision 1.43 2004/01/06 14:24:59 jalet |
---|
152 | # Printer groups should be cached now, if caching is enabled. |
---|
153 | # |
---|
154 | # Revision 1.42 2003/12/29 14:12:48 uid67467 |
---|
155 | # Tries to workaround possible integrity violations when retrieving printer groups |
---|
156 | # |
---|
157 | # Revision 1.41 2003/12/27 16:49:25 uid67467 |
---|
158 | # Should be ok now. |
---|
159 | # |
---|
160 | # Revision 1.40 2003/11/29 22:02:14 jalet |
---|
161 | # Don't try to retrieve the user print quota information if current printer |
---|
162 | # doesn't exist. |
---|
163 | # |
---|
164 | # Revision 1.39 2003/11/26 23:35:32 jalet |
---|
165 | # Added a bit of code to support the setting of the user's email address |
---|
166 | # which was ignored during writes for now. |
---|
167 | # |
---|
168 | # Revision 1.38 2003/11/24 09:54:06 jalet |
---|
169 | # Small fix for LDAP when pykotaOptions attribute wasn't present. |
---|
170 | # |
---|
171 | # Revision 1.37 2003/11/23 19:01:37 jalet |
---|
172 | # Job price added to history |
---|
173 | # |
---|
174 | # Revision 1.36 2003/11/21 14:28:46 jalet |
---|
175 | # More complete job history. |
---|
176 | # |
---|
177 | # Revision 1.35 2003/11/12 13:06:37 jalet |
---|
178 | # Bug fix wrt no user/group name command line argument to edpykota |
---|
179 | # |
---|
180 | # Revision 1.34 2003/10/24 08:37:55 jalet |
---|
181 | # More complete messages in case of LDAP failure. |
---|
182 | # LDAP database connection is now unbound on exit too. |
---|
183 | # |
---|
184 | # Revision 1.33 2003/10/08 07:01:20 jalet |
---|
185 | # Job history can be disabled. |
---|
186 | # Some typos in README. |
---|
187 | # More messages in setup script. |
---|
188 | # |
---|
189 | # Revision 1.32 2003/10/07 14:23:25 jalet |
---|
190 | # More work on cache |
---|
191 | # |
---|
192 | # Revision 1.31 2003/10/07 09:07:30 jalet |
---|
193 | # Character encoding added to please latest version of Python |
---|
194 | # |
---|
195 | # Revision 1.30 2003/10/06 14:42:36 jalet |
---|
196 | # LDAP group access will be slower when cache is disabled, but at least code |
---|
197 | # is consistent with the rest of the caching mechanis, but at least code |
---|
198 | # is consistent with the rest of the caching mechanism |
---|
199 | # |
---|
200 | # Revision 1.29 2003/10/06 13:12:28 jalet |
---|
201 | # More work on caching |
---|
202 | # |
---|
203 | # Revision 1.28 2003/10/03 12:27:02 jalet |
---|
204 | # Several optimizations, especially with LDAP backend |
---|
205 | # |
---|
206 | # Revision 1.27 2003/10/03 08:57:55 jalet |
---|
207 | # Caching mechanism now caches all that's cacheable. |
---|
208 | # |
---|
209 | # Revision 1.26 2003/10/02 20:23:18 jalet |
---|
210 | # Storage caching mechanism added. |
---|
211 | # |
---|
212 | # Revision 1.25 2003/08/20 15:56:24 jalet |
---|
213 | # Better user and group deletion |
---|
214 | # |
---|
215 | # Revision 1.24 2003/07/29 20:55:17 jalet |
---|
216 | # 1.14 is out ! |
---|
217 | # |
---|
218 | # Revision 1.23 2003/07/29 19:52:32 jalet |
---|
219 | # Forgot to read the email field from LDAP |
---|
220 | # |
---|
221 | # Revision 1.22 2003/07/29 09:54:03 jalet |
---|
222 | # Added configurable LDAP mail attribute support |
---|
223 | # |
---|
224 | # Revision 1.21 2003/07/28 09:11:12 jalet |
---|
225 | # PyKota now tries to add its attributes intelligently in existing LDAP |
---|
226 | # directories. |
---|
227 | # |
---|
228 | # Revision 1.20 2003/07/25 10:41:30 jalet |
---|
229 | # Better documentation. |
---|
230 | # pykotme now displays the current user's account balance. |
---|
231 | # Some test changed in ldap module. |
---|
232 | # |
---|
233 | # Revision 1.19 2003/07/14 14:18:16 jalet |
---|
234 | # Wrong documentation strings |
---|
235 | # |
---|
236 | # Revision 1.18 2003/07/11 14:23:13 jalet |
---|
237 | # When adding an user only adds one object containing both the user and |
---|
238 | # its account balance instead of two objects. |
---|
239 | # |
---|
240 | # Revision 1.17 2003/07/07 12:51:07 jalet |
---|
241 | # Small fix |
---|
242 | # |
---|
243 | # Revision 1.16 2003/07/07 12:11:13 jalet |
---|
244 | # Small fix |
---|
245 | # |
---|
246 | # Revision 1.15 2003/07/07 11:49:24 jalet |
---|
247 | # Lots of small fixes with the help of PyChecker |
---|
248 | # |
---|
249 | # Revision 1.14 2003/07/07 08:33:18 jalet |
---|
250 | # Bug fix due to a typo in LDAP code |
---|
251 | # |
---|
252 | # Revision 1.13 2003/07/05 07:46:50 jalet |
---|
253 | # The previous bug fix was incomplete. |
---|
254 | # |
---|
255 | # Revision 1.12 2003/06/30 13:54:21 jalet |
---|
256 | # Sorts by user / group name |
---|
257 | # |
---|
258 | # Revision 1.11 2003/06/25 14:10:01 jalet |
---|
259 | # Hey, it may work (edpykota --reset excepted) ! |
---|
260 | # |
---|
261 | # Revision 1.10 2003/06/16 21:55:15 jalet |
---|
262 | # More work on LDAP, again. Problem detected. |
---|
263 | # |
---|
264 | # Revision 1.9 2003/06/16 11:59:09 jalet |
---|
265 | # More work on LDAP |
---|
266 | # |
---|
267 | # Revision 1.8 2003/06/15 22:26:52 jalet |
---|
268 | # More work on LDAP |
---|
269 | # |
---|
270 | # Revision 1.7 2003/06/14 22:44:21 jalet |
---|
271 | # More work on LDAP storage backend. |
---|
272 | # |
---|
273 | # Revision 1.6 2003/06/13 19:07:57 jalet |
---|
274 | # Two big bugs fixed, time to release something ;-) |
---|
275 | # |
---|
276 | # Revision 1.5 2003/06/10 16:37:54 jalet |
---|
277 | # Deletion of the second user which is not needed anymore. |
---|
278 | # Added a debug configuration field in /etc/pykota.conf |
---|
279 | # All queries can now be sent to the logger in debug mode, this will |
---|
280 | # greatly help improve performance when time for this will come. |
---|
281 | # |
---|
282 | # Revision 1.4 2003/06/10 10:45:32 jalet |
---|
283 | # Not implemented methods now raise an exception when called. |
---|
284 | # |
---|
285 | # Revision 1.3 2003/06/06 20:49:15 jalet |
---|
286 | # Very latest schema. UNTESTED. |
---|
287 | # |
---|
288 | # Revision 1.2 2003/06/06 14:21:08 jalet |
---|
289 | # New LDAP schema. |
---|
290 | # Small bug fixes. |
---|
291 | # |
---|
292 | # Revision 1.1 2003/06/05 11:19:13 jalet |
---|
293 | # More good work on LDAP storage. |
---|
294 | # |
---|
295 | # |
---|
296 | # |
---|
297 | |
---|
298 | # |
---|
299 | # My IANA assigned number, for |
---|
300 | # "Conseil Internet & Logiciels Libres, J�me Alet" |
---|
301 | # is 16868. Use this as a base to create the LDAP schema. |
---|
302 | # |
---|
303 | |
---|
304 | import os |
---|
305 | import types |
---|
306 | import time |
---|
307 | import md5 |
---|
308 | from mx import DateTime |
---|
309 | |
---|
310 | from pykota.storage import PyKotaStorageError,BaseStorage,StorageObject,StorageUser,StorageGroup,StoragePrinter,StorageJob,StorageLastJob,StorageUserPQuota,StorageGroupPQuota |
---|
311 | |
---|
312 | try : |
---|
313 | import ldap |
---|
314 | import ldap.modlist |
---|
315 | except ImportError : |
---|
316 | import sys |
---|
317 | # TODO : to translate or not to translate ? |
---|
318 | raise PyKotaStorageError, "This python version (%s) doesn't seem to have the python-ldap module installed correctly." % sys.version.split()[0] |
---|
319 | |
---|
320 | class Storage(BaseStorage) : |
---|
321 | def __init__(self, pykotatool, host, dbname, user, passwd) : |
---|
322 | """Opens the LDAP connection.""" |
---|
323 | BaseStorage.__init__(self, pykotatool) |
---|
324 | self.info = pykotatool.config.getLDAPInfo() |
---|
325 | try : |
---|
326 | self.database = ldap.initialize(host) |
---|
327 | self.database.simple_bind_s(user, passwd) |
---|
328 | self.basedn = dbname |
---|
329 | except ldap.SERVER_DOWN : |
---|
330 | raise PyKotaStorageError, "LDAP backend for PyKota seems to be down !" # TODO : translate |
---|
331 | except ldap.LDAPError : |
---|
332 | raise PyKotaStorageError, "Unable to connect to LDAP server %s as %s." % (host, user) # TODO : translate |
---|
333 | else : |
---|
334 | self.useldapcache = pykotatool.config.getLDAPCache() |
---|
335 | if self.useldapcache : |
---|
336 | self.tool.logdebug("Low-Level LDAP Caching enabled.") |
---|
337 | self.ldapcache = {} # low-level cache specific to LDAP backend |
---|
338 | self.closed = 0 |
---|
339 | self.tool.logdebug("Database opened (host=%s, dbname=%s, user=%s)" % (host, dbname, user)) |
---|
340 | |
---|
341 | def close(self) : |
---|
342 | """Closes the database connection.""" |
---|
343 | if not self.closed : |
---|
344 | self.database.unbind_s() |
---|
345 | self.closed = 1 |
---|
346 | self.tool.logdebug("Database closed.") |
---|
347 | |
---|
348 | def genUUID(self) : |
---|
349 | """Generates an unique identifier. |
---|
350 | |
---|
351 | TODO : this one is not unique accross several print servers, but should be sufficient for testing. |
---|
352 | """ |
---|
353 | return md5.md5("%s" % time.time()).hexdigest() |
---|
354 | |
---|
355 | def normalizeFields(self, fields) : |
---|
356 | """Ensure all items are lists.""" |
---|
357 | for (k, v) in fields.items() : |
---|
358 | if type(v) not in (types.TupleType, types.ListType) : |
---|
359 | if not v : |
---|
360 | del fields[k] |
---|
361 | else : |
---|
362 | fields[k] = [ v ] |
---|
363 | return fields |
---|
364 | |
---|
365 | def beginTransaction(self) : |
---|
366 | """Starts a transaction.""" |
---|
367 | self.tool.logdebug("Transaction begins... WARNING : No transactions in LDAP !") |
---|
368 | |
---|
369 | def commitTransaction(self) : |
---|
370 | """Commits a transaction.""" |
---|
371 | self.tool.logdebug("Transaction committed. WARNING : No transactions in LDAP !") |
---|
372 | |
---|
373 | def rollbackTransaction(self) : |
---|
374 | """Rollbacks a transaction.""" |
---|
375 | self.tool.logdebug("Transaction aborted. WARNING : No transaction in LDAP !") |
---|
376 | |
---|
377 | def doSearch(self, key, fields=None, base="", scope=ldap.SCOPE_SUBTREE, flushcache=0) : |
---|
378 | """Does an LDAP search query.""" |
---|
379 | try : |
---|
380 | base = base or self.basedn |
---|
381 | if self.useldapcache : |
---|
382 | # Here we overwrite the fields the app want, to try and |
---|
383 | # retrieve ALL user defined attributes ("*") |
---|
384 | # + the createTimestamp attribute, needed by job history |
---|
385 | # |
---|
386 | # This may not work with all LDAP servers |
---|
387 | # but works at least in OpenLDAP (2.1.25) |
---|
388 | # and iPlanet Directory Server (5.1 SP3) |
---|
389 | fields = ["*", "createTimestamp"] |
---|
390 | |
---|
391 | if self.useldapcache and (not flushcache) and (scope == ldap.SCOPE_BASE) and self.ldapcache.has_key(base) : |
---|
392 | entry = self.ldapcache[base] |
---|
393 | self.tool.logdebug("LDAP cache hit %s => %s" % (base, entry)) |
---|
394 | result = [(base, entry)] |
---|
395 | else : |
---|
396 | self.tool.logdebug("QUERY : Filter : %s, BaseDN : %s, Scope : %s, Attributes : %s" % (key, base, scope, fields)) |
---|
397 | result = self.database.search_s(base, scope, key, fields) |
---|
398 | except ldap.NO_SUCH_OBJECT, msg : |
---|
399 | raise PyKotaStorageError, (_("Search base %s doesn't seem to exist. Probable misconfiguration. Please double check /etc/pykota/pykota.conf : %s") % (base, msg)) |
---|
400 | except ldap.LDAPError, msg : |
---|
401 | raise PyKotaStorageError, (_("Search for %s(%s) from %s(scope=%s) returned no answer.") % (key, fields, base, scope)) + " : %s" % str(msg) |
---|
402 | else : |
---|
403 | self.tool.logdebug("QUERY : Result : %s" % result) |
---|
404 | if self.useldapcache : |
---|
405 | for (dn, attributes) in result : |
---|
406 | self.tool.logdebug("LDAP cache store %s => %s" % (dn, attributes)) |
---|
407 | self.ldapcache[dn] = attributes |
---|
408 | return result |
---|
409 | |
---|
410 | def doAdd(self, dn, fields) : |
---|
411 | """Adds an entry in the LDAP directory.""" |
---|
412 | # TODO : store into LDAP specific cache |
---|
413 | fields = self.normalizeFields(fields) |
---|
414 | try : |
---|
415 | self.tool.logdebug("QUERY : ADD(%s, %s)" % (dn, str(fields))) |
---|
416 | entry = ldap.modlist.addModlist(fields) |
---|
417 | self.tool.logdebug("%s" % entry) |
---|
418 | self.database.add_s(dn, entry) |
---|
419 | except ldap.LDAPError, msg : |
---|
420 | raise PyKotaStorageError, (_("Problem adding LDAP entry (%s, %s)") % (dn, str(fields))) + " : %s" % str(msg) |
---|
421 | else : |
---|
422 | if self.useldapcache : |
---|
423 | self.tool.logdebug("LDAP cache add %s => %s" % (dn, fields)) |
---|
424 | self.ldapcache[dn] = fields |
---|
425 | return dn |
---|
426 | |
---|
427 | def doDelete(self, dn) : |
---|
428 | """Deletes an entry from the LDAP directory.""" |
---|
429 | # TODO : delete from LDAP specific cache |
---|
430 | try : |
---|
431 | self.tool.logdebug("QUERY : Delete(%s)" % dn) |
---|
432 | self.database.delete_s(dn) |
---|
433 | except ldap.LDAPError, msg : |
---|
434 | raise PyKotaStorageError, (_("Problem deleting LDAP entry (%s)") % dn) + " : %s" % str(msg) |
---|
435 | else : |
---|
436 | if self.useldapcache : |
---|
437 | try : |
---|
438 | self.tool.logdebug("LDAP cache del %s" % dn) |
---|
439 | del self.ldapcache[dn] |
---|
440 | except KeyError : |
---|
441 | pass |
---|
442 | |
---|
443 | def doModify(self, dn, fields, ignoreold=1, flushcache=0) : |
---|
444 | """Modifies an entry in the LDAP directory.""" |
---|
445 | try : |
---|
446 | # TODO : take care of, and update LDAP specific cache |
---|
447 | if self.useldapcache and not flushcache : |
---|
448 | if self.ldapcache.has_key(dn) : |
---|
449 | old = self.ldapcache[dn] |
---|
450 | self.tool.logdebug("LDAP cache hit %s => %s" % (dn, old)) |
---|
451 | oldentry = {} |
---|
452 | for (k, v) in old.items() : |
---|
453 | if k != "createTimestamp" : |
---|
454 | oldentry[k] = v |
---|
455 | else : |
---|
456 | self.tool.logdebug("LDAP cache miss %s" % dn) |
---|
457 | oldentry = self.doSearch("objectClass=*", base=dn, scope=ldap.SCOPE_BASE)[0][1] |
---|
458 | else : |
---|
459 | oldentry = self.doSearch("objectClass=*", base=dn, scope=ldap.SCOPE_BASE, flushcache=flushcache)[0][1] |
---|
460 | for (k, v) in fields.items() : |
---|
461 | if type(v) == type({}) : |
---|
462 | try : |
---|
463 | oldvalue = v["convert"](oldentry.get(k, [0])[0]) |
---|
464 | except ValueError : |
---|
465 | self.tool.logdebug("Error converting %s with %s(%s)" % (oldentry.get(k), k, v)) |
---|
466 | oldvalue = 0 |
---|
467 | if v["operator"] == '+' : |
---|
468 | newvalue = oldvalue + v["value"] |
---|
469 | else : |
---|
470 | newvalue = oldvalue - v["value"] |
---|
471 | fields[k] = str(newvalue) |
---|
472 | fields = self.normalizeFields(fields) |
---|
473 | self.tool.logdebug("QUERY : Modify(%s, %s ==> %s)" % (dn, oldentry, fields)) |
---|
474 | entry = ldap.modlist.modifyModlist(oldentry, fields, ignore_oldexistent=ignoreold) |
---|
475 | modentry = [] |
---|
476 | for (mop, mtyp, mval) in entry : |
---|
477 | if mtyp != "createTimestamp" : |
---|
478 | modentry.append((mop, mtyp, mval)) |
---|
479 | self.tool.logdebug("MODIFY : %s ==> %s ==> %s" % (fields, entry, modentry)) |
---|
480 | if modentry : |
---|
481 | self.database.modify_s(dn, modentry) |
---|
482 | except ldap.LDAPError, msg : |
---|
483 | raise PyKotaStorageError, (_("Problem modifying LDAP entry (%s, %s)") % (dn, fields)) + " : %s" % str(msg) |
---|
484 | else : |
---|
485 | if self.useldapcache : |
---|
486 | cachedentry = self.ldapcache[dn] |
---|
487 | for (mop, mtyp, mval) in entry : |
---|
488 | if mop in (ldap.MOD_ADD, ldap.MOD_REPLACE) : |
---|
489 | cachedentry[mtyp] = mval |
---|
490 | else : |
---|
491 | try : |
---|
492 | del cachedentry[mtyp] |
---|
493 | except KeyError : |
---|
494 | pass |
---|
495 | self.tool.logdebug("LDAP cache update %s => %s" % (dn, cachedentry)) |
---|
496 | return dn |
---|
497 | |
---|
498 | def getAllPrintersNames(self) : |
---|
499 | """Extracts all printer names.""" |
---|
500 | printernames = [] |
---|
501 | result = self.doSearch("objectClass=pykotaPrinter", ["pykotaPrinterName"], base=self.info["printerbase"]) |
---|
502 | if result : |
---|
503 | printernames = [record[1]["pykotaPrinterName"][0] for record in result] |
---|
504 | return printernames |
---|
505 | |
---|
506 | def getAllUsersNames(self) : |
---|
507 | """Extracts all user names.""" |
---|
508 | usernames = [] |
---|
509 | result = self.doSearch("objectClass=pykotaAccount", ["pykotaUserName"], base=self.info["userbase"]) |
---|
510 | if result : |
---|
511 | usernames = [record[1]["pykotaUserName"][0] for record in result] |
---|
512 | return usernames |
---|
513 | |
---|
514 | def getAllGroupsNames(self) : |
---|
515 | """Extracts all group names.""" |
---|
516 | groupnames = [] |
---|
517 | result = self.doSearch("objectClass=pykotaGroup", ["pykotaGroupName"], base=self.info["groupbase"]) |
---|
518 | if result : |
---|
519 | groupnames = [record[1]["pykotaGroupName"][0] for record in result] |
---|
520 | return groupnames |
---|
521 | |
---|
522 | def getUserFromBackend(self, username) : |
---|
523 | """Extracts user information given its name.""" |
---|
524 | user = StorageUser(self, username) |
---|
525 | result = self.doSearch("(&(objectClass=pykotaAccount)(|(pykotaUserName=%s)(%s=%s)))" % (username, self.info["userrdn"], username), ["pykotaUserName", "pykotaLimitBy", self.info["usermail"]], base=self.info["userbase"]) |
---|
526 | if result : |
---|
527 | fields = result[0][1] |
---|
528 | user.ident = result[0][0] |
---|
529 | user.Name = fields.get("pykotaUserName", [username])[0] |
---|
530 | user.Email = fields.get(self.info["usermail"]) |
---|
531 | if user.Email is not None : |
---|
532 | user.Email = user.Email[0] |
---|
533 | user.LimitBy = fields.get("pykotaLimitBy") |
---|
534 | if user.LimitBy is not None : |
---|
535 | user.LimitBy = user.LimitBy[0] |
---|
536 | result = self.doSearch("(&(objectClass=pykotaAccountBalance)(|(pykotaUserName=%s)(%s=%s)))" % (username, self.info["balancerdn"], username), ["pykotaBalance", "pykotaLifeTimePaid", "pykotaPayments"], base=self.info["balancebase"]) |
---|
537 | if not result : |
---|
538 | raise PyKotaStorageError, _("No pykotaAccountBalance object found for user %s. Did you create LDAP entries manually ?") % username |
---|
539 | else : |
---|
540 | fields = result[0][1] |
---|
541 | user.idbalance = result[0][0] |
---|
542 | user.AccountBalance = fields.get("pykotaBalance") |
---|
543 | if user.AccountBalance is not None : |
---|
544 | if user.AccountBalance[0].upper() == "NONE" : |
---|
545 | user.AccountBalance = None |
---|
546 | else : |
---|
547 | user.AccountBalance = float(user.AccountBalance[0]) |
---|
548 | user.AccountBalance = user.AccountBalance or 0.0 |
---|
549 | user.LifeTimePaid = fields.get("pykotaLifeTimePaid") |
---|
550 | if user.LifeTimePaid is not None : |
---|
551 | if user.LifeTimePaid[0].upper() == "NONE" : |
---|
552 | user.LifeTimePaid = None |
---|
553 | else : |
---|
554 | user.LifeTimePaid = float(user.LifeTimePaid[0]) |
---|
555 | user.LifeTimePaid = user.LifeTimePaid or 0.0 |
---|
556 | user.Payments = [] |
---|
557 | for payment in fields.get("pykotaPayments", []) : |
---|
558 | (date, amount) = payment.split(" # ") |
---|
559 | user.Payments.append((date, amount)) |
---|
560 | user.Exists = 1 |
---|
561 | return user |
---|
562 | |
---|
563 | def getGroupFromBackend(self, groupname) : |
---|
564 | """Extracts group information given its name.""" |
---|
565 | group = StorageGroup(self, groupname) |
---|
566 | result = self.doSearch("(&(objectClass=pykotaGroup)(|(pykotaGroupName=%s)(%s=%s)))" % (groupname, self.info["grouprdn"], groupname), ["pykotaGroupName", "pykotaLimitBy"], base=self.info["groupbase"]) |
---|
567 | if result : |
---|
568 | fields = result[0][1] |
---|
569 | group.ident = result[0][0] |
---|
570 | group.Name = fields.get("pykotaGroupName", [groupname])[0] |
---|
571 | group.LimitBy = fields.get("pykotaLimitBy") |
---|
572 | if group.LimitBy is not None : |
---|
573 | group.LimitBy = group.LimitBy[0] |
---|
574 | group.AccountBalance = 0.0 |
---|
575 | group.LifeTimePaid = 0.0 |
---|
576 | for member in self.getGroupMembers(group) : |
---|
577 | if member.Exists : |
---|
578 | group.AccountBalance += member.AccountBalance |
---|
579 | group.LifeTimePaid += member.LifeTimePaid |
---|
580 | group.Exists = 1 |
---|
581 | return group |
---|
582 | |
---|
583 | def getPrinterFromBackend(self, printername) : |
---|
584 | """Extracts printer information given its name : returns first matching printer.""" |
---|
585 | printer = StoragePrinter(self, printername) |
---|
586 | result = self.doSearch("(&(objectClass=pykotaPrinter)(|(pykotaPrinterName=%s)(%s=%s)))" % (printername, self.info["printerrdn"], printername), ["pykotaPrinterName", "pykotaPricePerPage", "pykotaPricePerJob", "uniqueMember", "description"], base=self.info["printerbase"]) |
---|
587 | if result : |
---|
588 | fields = result[0][1] # take only first matching printer, ignore the rest |
---|
589 | printer.ident = result[0][0] |
---|
590 | printer.Name = fields.get("pykotaPrinterName", [printername])[0] |
---|
591 | printer.PricePerJob = float(fields.get("pykotaPricePerJob", [0.0])[0] or 0.0) |
---|
592 | printer.PricePerPage = float(fields.get("pykotaPricePerPage", [0.0])[0] or 0.0) |
---|
593 | printer.uniqueMember = fields.get("uniqueMember", []) |
---|
594 | printer.Description = unicode(fields.get("description", [""])[0], "UTF-8").encode(self.tool.getCharset()) |
---|
595 | printer.Exists = 1 |
---|
596 | return printer |
---|
597 | |
---|
598 | def getUserPQuotaFromBackend(self, user, printer) : |
---|
599 | """Extracts a user print quota.""" |
---|
600 | userpquota = StorageUserPQuota(self, user, printer) |
---|
601 | if printer.Exists and user.Exists : |
---|
602 | result = self.doSearch("(&(objectClass=pykotaUserPQuota)(pykotaUserName=%s)(pykotaPrinterName=%s))" % (user.Name, printer.Name), ["pykotaPageCounter", "pykotaLifePageCounter", "pykotaSoftLimit", "pykotaHardLimit", "pykotaDateLimit"], base=self.info["userquotabase"]) |
---|
603 | if result : |
---|
604 | fields = result[0][1] |
---|
605 | userpquota.ident = result[0][0] |
---|
606 | userpquota.PageCounter = int(fields.get("pykotaPageCounter", [0])[0] or 0) |
---|
607 | userpquota.LifePageCounter = int(fields.get("pykotaLifePageCounter", [0])[0] or 0) |
---|
608 | userpquota.SoftLimit = fields.get("pykotaSoftLimit") |
---|
609 | if userpquota.SoftLimit is not None : |
---|
610 | if userpquota.SoftLimit[0].upper() == "NONE" : |
---|
611 | userpquota.SoftLimit = None |
---|
612 | else : |
---|
613 | userpquota.SoftLimit = int(userpquota.SoftLimit[0]) |
---|
614 | userpquota.HardLimit = fields.get("pykotaHardLimit") |
---|
615 | if userpquota.HardLimit is not None : |
---|
616 | if userpquota.HardLimit[0].upper() == "NONE" : |
---|
617 | userpquota.HardLimit = None |
---|
618 | elif userpquota.HardLimit is not None : |
---|
619 | userpquota.HardLimit = int(userpquota.HardLimit[0]) |
---|
620 | userpquota.DateLimit = fields.get("pykotaDateLimit") |
---|
621 | if userpquota.DateLimit is not None : |
---|
622 | if userpquota.DateLimit[0].upper() == "NONE" : |
---|
623 | userpquota.DateLimit = None |
---|
624 | else : |
---|
625 | userpquota.DateLimit = userpquota.DateLimit[0] |
---|
626 | userpquota.Exists = 1 |
---|
627 | return userpquota |
---|
628 | |
---|
629 | def getGroupPQuotaFromBackend(self, group, printer) : |
---|
630 | """Extracts a group print quota.""" |
---|
631 | grouppquota = StorageGroupPQuota(self, group, printer) |
---|
632 | if group.Exists : |
---|
633 | result = self.doSearch("(&(objectClass=pykotaGroupPQuota)(pykotaGroupName=%s)(pykotaPrinterName=%s))" % (group.Name, printer.Name), ["pykotaSoftLimit", "pykotaHardLimit", "pykotaDateLimit"], base=self.info["groupquotabase"]) |
---|
634 | if result : |
---|
635 | fields = result[0][1] |
---|
636 | grouppquota.ident = result[0][0] |
---|
637 | grouppquota.SoftLimit = fields.get("pykotaSoftLimit") |
---|
638 | if grouppquota.SoftLimit is not None : |
---|
639 | if grouppquota.SoftLimit[0].upper() == "NONE" : |
---|
640 | grouppquota.SoftLimit = None |
---|
641 | else : |
---|
642 | grouppquota.SoftLimit = int(grouppquota.SoftLimit[0]) |
---|
643 | grouppquota.HardLimit = fields.get("pykotaHardLimit") |
---|
644 | if grouppquota.HardLimit is not None : |
---|
645 | if grouppquota.HardLimit[0].upper() == "NONE" : |
---|
646 | grouppquota.HardLimit = None |
---|
647 | else : |
---|
648 | grouppquota.HardLimit = int(grouppquota.HardLimit[0]) |
---|
649 | grouppquota.DateLimit = fields.get("pykotaDateLimit") |
---|
650 | if grouppquota.DateLimit is not None : |
---|
651 | if grouppquota.DateLimit[0].upper() == "NONE" : |
---|
652 | grouppquota.DateLimit = None |
---|
653 | else : |
---|
654 | grouppquota.DateLimit = grouppquota.DateLimit[0] |
---|
655 | grouppquota.PageCounter = 0 |
---|
656 | grouppquota.LifePageCounter = 0 |
---|
657 | usernamesfilter = "".join(["(pykotaUserName=%s)" % member.Name for member in self.getGroupMembers(group)]) |
---|
658 | if usernamesfilter : |
---|
659 | usernamesfilter = "(|%s)" % usernamesfilter |
---|
660 | result = self.doSearch("(&(objectClass=pykotaUserPQuota)(pykotaPrinterName=%s)%s)" % (printer.Name, usernamesfilter), ["pykotaPageCounter", "pykotaLifePageCounter"], base=self.info["userquotabase"]) |
---|
661 | if result : |
---|
662 | for userpquota in result : |
---|
663 | grouppquota.PageCounter += int(userpquota[1].get("pykotaPageCounter", [0])[0] or 0) |
---|
664 | grouppquota.LifePageCounter += int(userpquota[1].get("pykotaLifePageCounter", [0])[0] or 0) |
---|
665 | grouppquota.Exists = 1 |
---|
666 | return grouppquota |
---|
667 | |
---|
668 | def getPrinterLastJobFromBackend(self, printer) : |
---|
669 | """Extracts a printer's last job information.""" |
---|
670 | lastjob = StorageLastJob(self, printer) |
---|
671 | result = self.doSearch("(&(objectClass=pykotaLastjob)(|(pykotaPrinterName=%s)(%s=%s)))" % (printer.Name, self.info["printerrdn"], printer.Name), ["pykotaLastJobIdent"], base=self.info["lastjobbase"]) |
---|
672 | if result : |
---|
673 | lastjob.lastjobident = result[0][0] |
---|
674 | lastjobident = result[0][1]["pykotaLastJobIdent"][0] |
---|
675 | result = None |
---|
676 | try : |
---|
677 | result = self.doSearch("objectClass=pykotaJob", ["pykotaJobSizeBytes", "pykotaHostName", "pykotaUserName", "pykotaJobId", "pykotaPrinterPageCounter", "pykotaJobSize", "pykotaAction", "pykotaJobPrice", "pykotaFileName", "pykotaTitle", "pykotaCopies", "pykotaOptions", "createTimestamp"], base="cn=%s,%s" % (lastjobident, self.info["jobbase"]), scope=ldap.SCOPE_BASE) |
---|
678 | except PyKotaStorageError : |
---|
679 | pass # Last job entry exists, but job probably doesn't exist anymore. |
---|
680 | if result : |
---|
681 | fields = result[0][1] |
---|
682 | lastjob.ident = result[0][0] |
---|
683 | lastjob.JobId = fields.get("pykotaJobId")[0] |
---|
684 | lastjob.UserName = fields.get("pykotaUserName")[0] |
---|
685 | lastjob.PrinterPageCounter = int(fields.get("pykotaPrinterPageCounter", [0])[0] or 0) |
---|
686 | try : |
---|
687 | lastjob.JobSize = int(fields.get("pykotaJobSize", [0])[0]) |
---|
688 | except ValueError : |
---|
689 | lastjob.JobSize = None |
---|
690 | try : |
---|
691 | lastjob.JobPrice = float(fields.get("pykotaJobPrice", [0.0])[0]) |
---|
692 | except ValueError : |
---|
693 | lastjob.JobPrice = None |
---|
694 | lastjob.JobAction = fields.get("pykotaAction", [""])[0] |
---|
695 | lastjob.JobFileName = unicode(fields.get("pykotaFileName", [""])[0], "UTF-8").encode(self.tool.getCharset()) |
---|
696 | lastjob.JobTitle = unicode(fields.get("pykotaTitle", [""])[0], "UTF-8").encode(self.tool.getCharset()) |
---|
697 | lastjob.JobCopies = int(fields.get("pykotaCopies", [0])[0]) |
---|
698 | lastjob.JobOptions = unicode(fields.get("pykotaOptions", [""])[0], "UTF-8").encode(self.tool.getCharset()) |
---|
699 | lastjob.JobHostName = fields.get("pykotaHostName", [""])[0] |
---|
700 | lastjob.JobSizeBytes = fields.get("pykotaJobSizeBytes", [0L])[0] |
---|
701 | date = fields.get("createTimestamp", ["19700101000000"])[0] |
---|
702 | year = int(date[:4]) |
---|
703 | month = int(date[4:6]) |
---|
704 | day = int(date[6:8]) |
---|
705 | hour = int(date[8:10]) |
---|
706 | minute = int(date[10:12]) |
---|
707 | second = int(date[12:14]) |
---|
708 | lastjob.JobDate = "%04i-%02i-%02i %02i:%02i:%02i" % (year, month, day, hour, minute, second) |
---|
709 | lastjob.Exists = 1 |
---|
710 | return lastjob |
---|
711 | |
---|
712 | def getGroupMembersFromBackend(self, group) : |
---|
713 | """Returns the group's members list.""" |
---|
714 | groupmembers = [] |
---|
715 | result = self.doSearch("(&(objectClass=pykotaGroup)(|(pykotaGroupName=%s)(%s=%s)))" % (group.Name, self.info["grouprdn"], group.Name), [self.info["groupmembers"]], base=self.info["groupbase"]) |
---|
716 | if result : |
---|
717 | for username in result[0][1].get(self.info["groupmembers"], []) : |
---|
718 | groupmembers.append(self.getUser(username)) |
---|
719 | return groupmembers |
---|
720 | |
---|
721 | def getUserGroupsFromBackend(self, user) : |
---|
722 | """Returns the user's groups list.""" |
---|
723 | groups = [] |
---|
724 | result = self.doSearch("(&(objectClass=pykotaGroup)(%s=%s))" % (self.info["groupmembers"], user.Name), [self.info["grouprdn"], "pykotaGroupName", "pykotaLimitBy"], base=self.info["groupbase"]) |
---|
725 | if result : |
---|
726 | for (groupid, fields) in result : |
---|
727 | groupname = (fields.get("pykotaGroupName", [None]) or fields.get(self.info["grouprdn"], [None]))[0] |
---|
728 | group = self.getFromCache("GROUPS", groupname) |
---|
729 | if group is None : |
---|
730 | group = StorageGroup(self, groupname) |
---|
731 | group.ident = groupid |
---|
732 | group.LimitBy = fields.get("pykotaLimitBy") |
---|
733 | if group.LimitBy is not None : |
---|
734 | group.LimitBy = group.LimitBy[0] |
---|
735 | group.AccountBalance = 0.0 |
---|
736 | group.LifeTimePaid = 0.0 |
---|
737 | for member in self.getGroupMembers(group) : |
---|
738 | if member.Exists : |
---|
739 | group.AccountBalance += member.AccountBalance |
---|
740 | group.LifeTimePaid += member.LifeTimePaid |
---|
741 | group.Exists = 1 |
---|
742 | self.cacheEntry("GROUPS", group.Name, group) |
---|
743 | groups.append(group) |
---|
744 | return groups |
---|
745 | |
---|
746 | def getParentPrintersFromBackend(self, printer) : |
---|
747 | """Get all the printer groups this printer is a member of.""" |
---|
748 | pgroups = [] |
---|
749 | result = self.doSearch("(&(objectClass=pykotaPrinter)(uniqueMember=%s))" % printer.ident, ["pykotaPrinterName"], base=self.info["printerbase"]) |
---|
750 | if result : |
---|
751 | for (printerid, fields) in result : |
---|
752 | if printerid != printer.ident : # In case of integrity violation. |
---|
753 | parentprinter = self.getPrinter(fields.get("pykotaPrinterName")[0]) |
---|
754 | if parentprinter.Exists : |
---|
755 | pgroups.append(parentprinter) |
---|
756 | return pgroups |
---|
757 | |
---|
758 | def getMatchingPrinters(self, printerpattern) : |
---|
759 | """Returns the list of all printers for which name matches a certain pattern.""" |
---|
760 | printers = [] |
---|
761 | # see comment at the same place in pgstorage.py |
---|
762 | result = self.doSearch("(&(objectClass=pykotaPrinter)(|%s))" % "".join(["(pykotaPrinterName=%s)(%s=%s)" % (pname, self.info["printerrdn"], pname) for pname in printerpattern.split(",")]), ["pykotaPrinterName", "pykotaPricePerPage", "pykotaPricePerJob", "uniqueMember", "description"], base=self.info["printerbase"]) |
---|
763 | if result : |
---|
764 | for (printerid, fields) in result : |
---|
765 | printername = fields.get("pykotaPrinterName", [""])[0] or fields.get(self.info["printerrdn"], [""])[0] |
---|
766 | printer = StoragePrinter(self, printername) |
---|
767 | printer.ident = printerid |
---|
768 | printer.PricePerJob = float(fields.get("pykotaPricePerJob", [0.0])[0] or 0.0) |
---|
769 | printer.PricePerPage = float(fields.get("pykotaPricePerPage", [0.0])[0] or 0.0) |
---|
770 | printer.uniqueMember = fields.get("uniqueMember", []) |
---|
771 | printer.Description = unicode(fields.get("description", [""])[0], "UTF-8").encode(self.tool.getCharset()) |
---|
772 | printer.Exists = 1 |
---|
773 | printers.append(printer) |
---|
774 | self.cacheEntry("PRINTERS", printer.Name, printer) |
---|
775 | return printers |
---|
776 | |
---|
777 | def getPrinterUsersAndQuotas(self, printer, names=["*"]) : |
---|
778 | """Returns the list of users who uses a given printer, along with their quotas.""" |
---|
779 | usersandquotas = [] |
---|
780 | result = self.doSearch("(&(objectClass=pykotaUserPQuota)(pykotaPrinterName=%s)(|%s))" % (printer.Name, "".join(["(pykotaUserName=%s)" % uname for uname in names])), ["pykotaUserName", "pykotaPageCounter", "pykotaLifePageCounter", "pykotaSoftLimit", "pykotaHardLimit", "pykotaDateLimit"], base=self.info["userquotabase"]) |
---|
781 | if result : |
---|
782 | for (userquotaid, fields) in result : |
---|
783 | user = self.getUser(fields.get("pykotaUserName")[0]) |
---|
784 | userpquota = StorageUserPQuota(self, user, printer) |
---|
785 | userpquota.ident = userquotaid |
---|
786 | userpquota.PageCounter = int(fields.get("pykotaPageCounter", [0])[0] or 0) |
---|
787 | userpquota.LifePageCounter = int(fields.get("pykotaLifePageCounter", [0])[0] or 0) |
---|
788 | userpquota.SoftLimit = fields.get("pykotaSoftLimit") |
---|
789 | if userpquota.SoftLimit is not None : |
---|
790 | if userpquota.SoftLimit[0].upper() == "NONE" : |
---|
791 | userpquota.SoftLimit = None |
---|
792 | else : |
---|
793 | userpquota.SoftLimit = int(userpquota.SoftLimit[0]) |
---|
794 | userpquota.HardLimit = fields.get("pykotaHardLimit") |
---|
795 | if userpquota.HardLimit is not None : |
---|
796 | if userpquota.HardLimit[0].upper() == "NONE" : |
---|
797 | userpquota.HardLimit = None |
---|
798 | elif userpquota.HardLimit is not None : |
---|
799 | userpquota.HardLimit = int(userpquota.HardLimit[0]) |
---|
800 | userpquota.DateLimit = fields.get("pykotaDateLimit") |
---|
801 | if userpquota.DateLimit is not None : |
---|
802 | if userpquota.DateLimit[0].upper() == "NONE" : |
---|
803 | userpquota.DateLimit = None |
---|
804 | else : |
---|
805 | userpquota.DateLimit = userpquota.DateLimit[0] |
---|
806 | userpquota.Exists = 1 |
---|
807 | usersandquotas.append((user, userpquota)) |
---|
808 | self.cacheEntry("USERPQUOTAS", "%s@%s" % (user.Name, printer.Name), userpquota) |
---|
809 | usersandquotas.sort(lambda x, y : cmp(x[0].Name, y[0].Name)) |
---|
810 | return usersandquotas |
---|
811 | |
---|
812 | def getPrinterGroupsAndQuotas(self, printer, names=["*"]) : |
---|
813 | """Returns the list of groups which uses a given printer, along with their quotas.""" |
---|
814 | groupsandquotas = [] |
---|
815 | result = self.doSearch("(&(objectClass=pykotaGroupPQuota)(pykotaPrinterName=%s)(|%s))" % (printer.Name, "".join(["(pykotaGroupName=%s)" % gname for gname in names])), ["pykotaGroupName"], base=self.info["groupquotabase"]) |
---|
816 | if result : |
---|
817 | for (groupquotaid, fields) in result : |
---|
818 | group = self.getGroup(fields.get("pykotaGroupName")[0]) |
---|
819 | grouppquota = self.getGroupPQuota(group, printer) |
---|
820 | groupsandquotas.append((group, grouppquota)) |
---|
821 | groupsandquotas.sort(lambda x, y : cmp(x[0].Name, y[0].Name)) |
---|
822 | return groupsandquotas |
---|
823 | |
---|
824 | def addPrinter(self, printername) : |
---|
825 | """Adds a printer to the quota storage, returns it.""" |
---|
826 | fields = { self.info["printerrdn"] : printername, |
---|
827 | "objectClass" : ["pykotaObject", "pykotaPrinter"], |
---|
828 | "cn" : printername, |
---|
829 | "pykotaPrinterName" : printername, |
---|
830 | "pykotaPricePerPage" : "0.0", |
---|
831 | "pykotaPricePerJob" : "0.0", |
---|
832 | } |
---|
833 | dn = "%s=%s,%s" % (self.info["printerrdn"], printername, self.info["printerbase"]) |
---|
834 | self.doAdd(dn, fields) |
---|
835 | return self.getPrinter(printername) |
---|
836 | |
---|
837 | def addUser(self, user) : |
---|
838 | """Adds a user to the quota storage, returns it.""" |
---|
839 | newfields = { |
---|
840 | "pykotaUserName" : user.Name, |
---|
841 | "pykotaLimitBy" : (user.LimitBy or "quota"), |
---|
842 | } |
---|
843 | |
---|
844 | if user.Email : |
---|
845 | newfields.update({self.info["usermail"]: user.Email}) |
---|
846 | mustadd = 1 |
---|
847 | if self.info["newuser"].lower() != 'below' : |
---|
848 | try : |
---|
849 | (where, action) = [s.strip() for s in self.info["newuser"].split(",")] |
---|
850 | except ValueError : |
---|
851 | (where, action) = (self.info["newuser"].strip(), "fail") |
---|
852 | result = self.doSearch("(&(objectClass=%s)(%s=%s))" % (where, self.info["userrdn"], user.Name), None, base=self.info["userbase"]) |
---|
853 | if result : |
---|
854 | (dn, fields) = result[0] |
---|
855 | fields["objectClass"].extend(["pykotaAccount", "pykotaAccountBalance"]) |
---|
856 | fields.update(newfields) |
---|
857 | fields.update({ "pykotaBalance" : str(user.AccountBalance or 0.0), |
---|
858 | "pykotaLifeTimePaid" : str(user.LifeTimePaid or 0.0), }) |
---|
859 | self.doModify(dn, fields) |
---|
860 | mustadd = 0 |
---|
861 | else : |
---|
862 | message = _("Unable to find an existing objectClass %s entry with %s=%s to attach pykotaAccount objectClass") % (where, self.info["userrdn"], user.Name) |
---|
863 | if action.lower() == "warn" : |
---|
864 | self.tool.printInfo("%s. A new entry will be created instead." % message, "warn") |
---|
865 | else : # 'fail' or incorrect setting |
---|
866 | raise PyKotaStorageError, "%s. Action aborted. Please check your configuration." % message |
---|
867 | |
---|
868 | if mustadd : |
---|
869 | if self.info["userbase"] == self.info["balancebase"] : |
---|
870 | fields = { self.info["userrdn"] : user.Name, |
---|
871 | "objectClass" : ["pykotaObject", "pykotaAccount", "pykotaAccountBalance"], |
---|
872 | "cn" : user.Name, |
---|
873 | "pykotaBalance" : str(user.AccountBalance or 0.0), |
---|
874 | "pykotaLifeTimePaid" : str(user.LifeTimePaid or 0.0), |
---|
875 | } |
---|
876 | else : |
---|
877 | fields = { self.info["userrdn"] : user.Name, |
---|
878 | "objectClass" : ["pykotaObject", "pykotaAccount"], |
---|
879 | "cn" : user.Name, |
---|
880 | } |
---|
881 | fields.update(newfields) |
---|
882 | dn = "%s=%s,%s" % (self.info["userrdn"], user.Name, self.info["userbase"]) |
---|
883 | self.doAdd(dn, fields) |
---|
884 | if self.info["userbase"] != self.info["balancebase"] : |
---|
885 | fields = { self.info["balancerdn"] : user.Name, |
---|
886 | "objectClass" : ["pykotaObject", "pykotaAccountBalance"], |
---|
887 | "cn" : user.Name, |
---|
888 | "pykotaBalance" : str(user.AccountBalance or 0.0), |
---|
889 | "pykotaLifeTimePaid" : str(user.LifeTimePaid or 0.0), |
---|
890 | } |
---|
891 | dn = "%s=%s,%s" % (self.info["balancerdn"], user.Name, self.info["balancebase"]) |
---|
892 | self.doAdd(dn, fields) |
---|
893 | |
---|
894 | return self.getUser(user.Name) |
---|
895 | |
---|
896 | def addGroup(self, group) : |
---|
897 | """Adds a group to the quota storage, returns it.""" |
---|
898 | newfields = { |
---|
899 | "pykotaGroupName" : group.Name, |
---|
900 | "pykotaLimitBY" : (group.LimitBy or "quota"), |
---|
901 | } |
---|
902 | mustadd = 1 |
---|
903 | if self.info["newgroup"].lower() != 'below' : |
---|
904 | try : |
---|
905 | (where, action) = [s.strip() for s in self.info["newgroup"].split(",")] |
---|
906 | except ValueError : |
---|
907 | (where, action) = (self.info["newgroup"].strip(), "fail") |
---|
908 | result = self.doSearch("(&(objectClass=%s)(%s=%s))" % (where, self.info["grouprdn"], group.Name), None, base=self.info["groupbase"]) |
---|
909 | if result : |
---|
910 | (dn, fields) = result[0] |
---|
911 | fields["objectClass"].extend(["pykotaGroup"]) |
---|
912 | fields.update(newfields) |
---|
913 | self.doModify(dn, fields) |
---|
914 | mustadd = 0 |
---|
915 | else : |
---|
916 | message = _("Unable to find an existing entry to attach pykotaGroup objectclass %s") % group.Name |
---|
917 | if action.lower() == "warn" : |
---|
918 | self.tool.printInfo("%s. A new entry will be created instead." % message, "warn") |
---|
919 | else : # 'fail' or incorrect setting |
---|
920 | raise PyKotaStorageError, "%s. Action aborted. Please check your configuration." % message |
---|
921 | |
---|
922 | if mustadd : |
---|
923 | fields = { self.info["grouprdn"] : group.Name, |
---|
924 | "objectClass" : ["pykotaObject", "pykotaGroup"], |
---|
925 | "cn" : group.Name, |
---|
926 | } |
---|
927 | fields.update(newfields) |
---|
928 | dn = "%s=%s,%s" % (self.info["grouprdn"], group.Name, self.info["groupbase"]) |
---|
929 | self.doAdd(dn, fields) |
---|
930 | return self.getGroup(group.Name) |
---|
931 | |
---|
932 | def addUserToGroup(self, user, group) : |
---|
933 | """Adds an user to a group.""" |
---|
934 | if user.Name not in [u.Name for u in self.getGroupMembers(group)] : |
---|
935 | result = self.doSearch("objectClass=pykotaGroup", None, base=group.ident, scope=ldap.SCOPE_BASE) |
---|
936 | if result : |
---|
937 | fields = result[0][1] |
---|
938 | if not fields.has_key(self.info["groupmembers"]) : |
---|
939 | fields[self.info["groupmembers"]] = [] |
---|
940 | fields[self.info["groupmembers"]].append(user.Name) |
---|
941 | self.doModify(group.ident, fields) |
---|
942 | group.Members.append(user) |
---|
943 | |
---|
944 | def addUserPQuota(self, user, printer) : |
---|
945 | """Initializes a user print quota on a printer.""" |
---|
946 | uuid = self.genUUID() |
---|
947 | fields = { "cn" : uuid, |
---|
948 | "objectClass" : ["pykotaObject", "pykotaUserPQuota"], |
---|
949 | "pykotaUserName" : user.Name, |
---|
950 | "pykotaPrinterName" : printer.Name, |
---|
951 | "pykotaDateLimit" : "None", |
---|
952 | "pykotaPageCounter" : "0", |
---|
953 | "pykotaLifePageCounter" : "0", |
---|
954 | } |
---|
955 | dn = "cn=%s,%s" % (uuid, self.info["userquotabase"]) |
---|
956 | self.doAdd(dn, fields) |
---|
957 | return self.getUserPQuota(user, printer) |
---|
958 | |
---|
959 | def addGroupPQuota(self, group, printer) : |
---|
960 | """Initializes a group print quota on a printer.""" |
---|
961 | uuid = self.genUUID() |
---|
962 | fields = { "cn" : uuid, |
---|
963 | "objectClass" : ["pykotaObject", "pykotaGroupPQuota"], |
---|
964 | "pykotaGroupName" : group.Name, |
---|
965 | "pykotaPrinterName" : printer.Name, |
---|
966 | "pykotaDateLimit" : "None", |
---|
967 | } |
---|
968 | dn = "cn=%s,%s" % (uuid, self.info["groupquotabase"]) |
---|
969 | self.doAdd(dn, fields) |
---|
970 | return self.getGroupPQuota(group, printer) |
---|
971 | |
---|
972 | def writePrinterPrices(self, printer) : |
---|
973 | """Write the printer's prices back into the storage.""" |
---|
974 | fields = { |
---|
975 | "pykotaPricePerPage" : str(printer.PricePerPage), |
---|
976 | "pykotaPricePerJob" : str(printer.PricePerJob), |
---|
977 | } |
---|
978 | self.doModify(printer.ident, fields) |
---|
979 | |
---|
980 | def writePrinterDescription(self, printer) : |
---|
981 | """Write the printer's description back into the storage.""" |
---|
982 | fields = { |
---|
983 | "description" : unicode(str(printer.Description), self.tool.getCharset()).encode("UTF-8"), |
---|
984 | } |
---|
985 | self.doModify(printer.ident, fields) |
---|
986 | |
---|
987 | def writeUserLimitBy(self, user, limitby) : |
---|
988 | """Sets the user's limiting factor.""" |
---|
989 | fields = { |
---|
990 | "pykotaLimitBy" : limitby, |
---|
991 | } |
---|
992 | self.doModify(user.ident, fields) |
---|
993 | |
---|
994 | def writeGroupLimitBy(self, group, limitby) : |
---|
995 | """Sets the group's limiting factor.""" |
---|
996 | fields = { |
---|
997 | "pykotaLimitBy" : limitby, |
---|
998 | } |
---|
999 | self.doModify(group.ident, fields) |
---|
1000 | |
---|
1001 | def writeUserPQuotaDateLimit(self, userpquota, datelimit) : |
---|
1002 | """Sets the date limit permanently for a user print quota.""" |
---|
1003 | fields = { |
---|
1004 | "pykotaDateLimit" : datelimit, |
---|
1005 | } |
---|
1006 | return self.doModify(userpquota.ident, fields) |
---|
1007 | |
---|
1008 | def writeGroupPQuotaDateLimit(self, grouppquota, datelimit) : |
---|
1009 | """Sets the date limit permanently for a group print quota.""" |
---|
1010 | fields = { |
---|
1011 | "pykotaDateLimit" : datelimit, |
---|
1012 | } |
---|
1013 | return self.doModify(grouppquota.ident, fields) |
---|
1014 | |
---|
1015 | def increaseUserPQuotaPagesCounters(self, userpquota, nbpages) : |
---|
1016 | """Increase page counters for a user print quota.""" |
---|
1017 | fields = { |
---|
1018 | "pykotaPageCounter" : { "operator" : "+", "value" : nbpages, "convert" : int }, |
---|
1019 | "pykotaLifePageCounter" : { "operator" : "+", "value" : nbpages, "convert" : int }, |
---|
1020 | } |
---|
1021 | return self.doModify(userpquota.ident, fields) |
---|
1022 | |
---|
1023 | def writeUserPQuotaPagesCounters(self, userpquota, newpagecounter, newlifepagecounter) : |
---|
1024 | """Sets the new page counters permanently for a user print quota.""" |
---|
1025 | fields = { |
---|
1026 | "pykotaPageCounter" : str(newpagecounter), |
---|
1027 | "pykotaLifePageCounter" : str(newlifepagecounter), |
---|
1028 | } |
---|
1029 | return self.doModify(userpquota.ident, fields) |
---|
1030 | |
---|
1031 | def decreaseUserAccountBalance(self, user, amount) : |
---|
1032 | """Decreases user's account balance from an amount.""" |
---|
1033 | fields = { |
---|
1034 | "pykotaBalance" : { "operator" : "-", "value" : amount, "convert" : float }, |
---|
1035 | } |
---|
1036 | return self.doModify(user.idbalance, fields, flushcache=1) |
---|
1037 | |
---|
1038 | def writeUserAccountBalance(self, user, newbalance, newlifetimepaid=None) : |
---|
1039 | """Sets the new account balance and eventually new lifetime paid.""" |
---|
1040 | fields = { |
---|
1041 | "pykotaBalance" : str(newbalance), |
---|
1042 | } |
---|
1043 | if newlifetimepaid is not None : |
---|
1044 | fields.update({ "pykotaLifeTimePaid" : str(newlifetimepaid) }) |
---|
1045 | return self.doModify(user.idbalance, fields) |
---|
1046 | |
---|
1047 | def writeNewPayment(self, user, amount) : |
---|
1048 | """Adds a new payment to the payments history.""" |
---|
1049 | payments = [] |
---|
1050 | for payment in user.Payments : |
---|
1051 | payments.append("%s # %s" % (payment[0], str(payment[1]))) |
---|
1052 | payments.append("%s # %s" % (str(DateTime.now()), str(amount))) |
---|
1053 | fields = { |
---|
1054 | "pykotaPayments" : payments, |
---|
1055 | } |
---|
1056 | return self.doModify(user.idbalance, fields) |
---|
1057 | |
---|
1058 | def writeLastJobSize(self, lastjob, jobsize, jobprice) : |
---|
1059 | """Sets the last job's size permanently.""" |
---|
1060 | fields = { |
---|
1061 | "pykotaJobSize" : str(jobsize), |
---|
1062 | "pykotaJobPrice" : str(jobprice), |
---|
1063 | } |
---|
1064 | self.doModify(lastjob.ident, fields) |
---|
1065 | |
---|
1066 | def writeJobNew(self, printer, user, jobid, pagecounter, action, jobsize=None, jobprice=None, filename=None, title=None, copies=None, options=None, clienthost=None, jobsizebytes=None) : |
---|
1067 | """Adds a job in a printer's history.""" |
---|
1068 | if (not self.disablehistory) or (not printer.LastJob.Exists) : |
---|
1069 | uuid = self.genUUID() |
---|
1070 | dn = "cn=%s,%s" % (uuid, self.info["jobbase"]) |
---|
1071 | else : |
---|
1072 | uuid = printer.LastJob.ident[3:].split(",")[0] |
---|
1073 | dn = printer.LastJob.ident |
---|
1074 | fields = { |
---|
1075 | "objectClass" : ["pykotaObject", "pykotaJob"], |
---|
1076 | "cn" : uuid, |
---|
1077 | "pykotaUserName" : user.Name, |
---|
1078 | "pykotaPrinterName" : printer.Name, |
---|
1079 | "pykotaJobId" : jobid, |
---|
1080 | "pykotaPrinterPageCounter" : str(pagecounter), |
---|
1081 | "pykotaAction" : action, |
---|
1082 | "pykotaFileName" : ((filename is None) and "None") or unicode(filename, self.tool.getCharset()).encode("UTF-8"), |
---|
1083 | "pykotaTitle" : ((title is None) and "None") or unicode(title, self.tool.getCharset()).encode("UTF-8"), |
---|
1084 | "pykotaCopies" : str(copies), |
---|
1085 | "pykotaOptions" : ((options is None) and "None") or unicode(options, self.tool.getCharset()).encode("UTF-8"), |
---|
1086 | "pykotaHostName" : str(clienthost), |
---|
1087 | "pykotaJobSizeBytes" : str(jobsizebytes), |
---|
1088 | } |
---|
1089 | if (not self.disablehistory) or (not printer.LastJob.Exists) : |
---|
1090 | if jobsize is not None : |
---|
1091 | fields.update({ "pykotaJobSize" : str(jobsize), "pykotaJobPrice" : str(jobprice) }) |
---|
1092 | self.doAdd(dn, fields) |
---|
1093 | else : |
---|
1094 | # here we explicitly want to reset jobsize to 'None' if needed |
---|
1095 | fields.update({ "pykotaJobSize" : str(jobsize), "pykotaJobPrice" : str(jobprice) }) |
---|
1096 | self.doModify(dn, fields) |
---|
1097 | |
---|
1098 | if printer.LastJob.Exists : |
---|
1099 | fields = { |
---|
1100 | "pykotaLastJobIdent" : uuid, |
---|
1101 | } |
---|
1102 | self.doModify(printer.LastJob.lastjobident, fields) |
---|
1103 | else : |
---|
1104 | lastjuuid = self.genUUID() |
---|
1105 | lastjdn = "cn=%s,%s" % (lastjuuid, self.info["lastjobbase"]) |
---|
1106 | fields = { |
---|
1107 | "objectClass" : ["pykotaObject", "pykotaLastJob"], |
---|
1108 | "cn" : lastjuuid, |
---|
1109 | "pykotaPrinterName" : printer.Name, |
---|
1110 | "pykotaLastJobIdent" : uuid, |
---|
1111 | } |
---|
1112 | self.doAdd(lastjdn, fields) |
---|
1113 | |
---|
1114 | def writeUserPQuotaLimits(self, userpquota, softlimit, hardlimit) : |
---|
1115 | """Sets soft and hard limits for a user quota.""" |
---|
1116 | fields = { |
---|
1117 | "pykotaSoftLimit" : str(softlimit), |
---|
1118 | "pykotaHardLimit" : str(hardlimit), |
---|
1119 | "pykotaDateLimit" : "None", |
---|
1120 | } |
---|
1121 | self.doModify(userpquota.ident, fields) |
---|
1122 | |
---|
1123 | def writeGroupPQuotaLimits(self, grouppquota, softlimit, hardlimit) : |
---|
1124 | """Sets soft and hard limits for a group quota on a specific printer.""" |
---|
1125 | fields = { |
---|
1126 | "pykotaSoftLimit" : str(softlimit), |
---|
1127 | "pykotaHardLimit" : str(hardlimit), |
---|
1128 | "pykotaDateLimit" : "None", |
---|
1129 | } |
---|
1130 | self.doModify(grouppquota.ident, fields) |
---|
1131 | |
---|
1132 | def writePrinterToGroup(self, pgroup, printer) : |
---|
1133 | """Puts a printer into a printer group.""" |
---|
1134 | if printer.ident not in pgroup.uniqueMember : |
---|
1135 | pgroup.uniqueMember.append(printer.ident) |
---|
1136 | fields = { |
---|
1137 | "uniqueMember" : pgroup.uniqueMember |
---|
1138 | } |
---|
1139 | self.doModify(pgroup.ident, fields) |
---|
1140 | |
---|
1141 | def removePrinterFromGroup(self, pgroup, printer) : |
---|
1142 | """Removes a printer from a printer group.""" |
---|
1143 | try : |
---|
1144 | pgroup.uniqueMember.remove(printer.ident) |
---|
1145 | except ValueError : |
---|
1146 | pass |
---|
1147 | else : |
---|
1148 | fields = { |
---|
1149 | "uniqueMember" : pgroup.uniqueMember, |
---|
1150 | } |
---|
1151 | self.doModify(pgroup.ident, fields) |
---|
1152 | |
---|
1153 | def retrieveHistory(self, user=None, printer=None, datelimit=None, hostname=None, limit=100) : |
---|
1154 | """Retrieves all print jobs for user on printer (or all) before date, limited to first 100 results.""" |
---|
1155 | precond = "(objectClass=pykotaJob)" |
---|
1156 | where = [] |
---|
1157 | if (user is not None) and user.Exists : |
---|
1158 | where.append("(pykotaUserName=%s)" % user.Name) |
---|
1159 | if (printer is not None) and printer.Exists : |
---|
1160 | where.append("(pykotaPrinterName=%s)" % printer.Name) |
---|
1161 | if hostname is not None : |
---|
1162 | where.append("(pykotaHostName=%s)" % hostname) |
---|
1163 | if where : |
---|
1164 | where = "(&%s)" % "".join([precond] + where) |
---|
1165 | else : |
---|
1166 | where = precond |
---|
1167 | jobs = [] |
---|
1168 | result = self.doSearch(where, fields=["pykotaJobSizeBytes", "pykotaHostName", "pykotaUserName", "pykotaPrinterName", "pykotaJobId", "pykotaPrinterPageCounter", "pykotaAction", "pykotaJobSize", "pykotaJobPrice", "pykotaFileName", "pykotaTitle", "pykotaCopies", "pykotaOptions", "createTimestamp"], base=self.info["jobbase"]) |
---|
1169 | if result : |
---|
1170 | for (ident, fields) in result : |
---|
1171 | job = StorageJob(self) |
---|
1172 | job.ident = ident |
---|
1173 | job.JobId = fields.get("pykotaJobId")[0] |
---|
1174 | job.PrinterPageCounter = int(fields.get("pykotaPrinterPageCounter", [0])[0] or 0) |
---|
1175 | try : |
---|
1176 | job.JobSize = int(fields.get("pykotaJobSize", [0])[0]) |
---|
1177 | except ValueError : |
---|
1178 | job.JobSize = None |
---|
1179 | try : |
---|
1180 | job.JobPrice = float(fields.get("pykotaJobPrice", [0.0])[0]) |
---|
1181 | except ValueError : |
---|
1182 | job.JobPrice = None |
---|
1183 | job.JobAction = fields.get("pykotaAction", [""])[0] |
---|
1184 | job.JobFileName = unicode(fields.get("pykotaFileName", [""])[0], "UTF-8").encode(self.tool.getCharset()) |
---|
1185 | job.JobTitle = unicode(fields.get("pykotaTitle", [""])[0], "UTF-8").encode(self.tool.getCharset()) |
---|
1186 | job.JobCopies = int(fields.get("pykotaCopies", [0])[0]) |
---|
1187 | job.JobOptions = unicode(fields.get("pykotaOptions", [""])[0], "UTF-8").encode(self.tool.getCharset()) |
---|
1188 | job.JobHostName = fields.get("pykotaHostName", [""])[0] |
---|
1189 | job.JobSizeBytes = fields.get("pykotaJobSizeBytes", [0L])[0] |
---|
1190 | date = fields.get("createTimestamp", ["19700101000000"])[0] |
---|
1191 | year = int(date[:4]) |
---|
1192 | month = int(date[4:6]) |
---|
1193 | day = int(date[6:8]) |
---|
1194 | hour = int(date[8:10]) |
---|
1195 | minute = int(date[10:12]) |
---|
1196 | second = int(date[12:14]) |
---|
1197 | job.JobDate = "%04i-%02i-%02i %02i:%02i:%02i" % (year, month, day, hour, minute, second) |
---|
1198 | if (datelimit is None) or (job.JobDate <= datelimit) : |
---|
1199 | job.UserName = fields.get("pykotaUserName")[0] |
---|
1200 | job.PrinterName = fields.get("pykotaPrinterName")[0] |
---|
1201 | job.Exists = 1 |
---|
1202 | jobs.append(job) |
---|
1203 | jobs.sort(lambda x,y : cmp(y.JobDate, x.JobDate)) |
---|
1204 | if limit : |
---|
1205 | jobs = jobs[:int(limit)] |
---|
1206 | return jobs |
---|
1207 | |
---|
1208 | def deleteUser(self, user) : |
---|
1209 | """Completely deletes an user from the Quota Storage.""" |
---|
1210 | todelete = [] |
---|
1211 | result = self.doSearch("(&(objectClass=pykotaJob)(pykotaUserName=%s))" % user.Name, base=self.info["jobbase"]) |
---|
1212 | for (ident, fields) in result : |
---|
1213 | todelete.append(ident) |
---|
1214 | |
---|
1215 | result = self.doSearch("(&(objectClass=pykotaUserPQuota)(pykotaUserName=%s))" % user.Name, ["pykotaPrinterName", "pykotaUserName"], base=self.info["userquotabase"]) |
---|
1216 | for (ident, fields) in result : |
---|
1217 | # ensure the user print quota entry will be deleted |
---|
1218 | todelete.append(ident) |
---|
1219 | |
---|
1220 | # if last job of current printer was printed by the user |
---|
1221 | # to delete, we also need to delete the printer's last job entry. |
---|
1222 | printername = fields["pykotaPrinterName"][0] |
---|
1223 | printer = self.getPrinter(printername) |
---|
1224 | if printer.LastJob.UserName == user.Name : |
---|
1225 | todelete.append(printer.LastJob.lastjobident) |
---|
1226 | |
---|
1227 | for ident in todelete : |
---|
1228 | self.doDelete(ident) |
---|
1229 | |
---|
1230 | result = self.doSearch("objectClass=pykotaAccount", None, base=user.ident, scope=ldap.SCOPE_BASE) |
---|
1231 | if result : |
---|
1232 | fields = result[0][1] |
---|
1233 | for k in fields.keys() : |
---|
1234 | if k.startswith("pykota") : |
---|
1235 | del fields[k] |
---|
1236 | elif k.lower() == "objectclass" : |
---|
1237 | todelete = [] |
---|
1238 | for i in range(len(fields[k])) : |
---|
1239 | if fields[k][i].startswith("pykota") : |
---|
1240 | todelete.append(i) |
---|
1241 | todelete.sort() |
---|
1242 | todelete.reverse() |
---|
1243 | for i in todelete : |
---|
1244 | del fields[k][i] |
---|
1245 | if fields.get("objectClass") or fields.get("objectclass") : |
---|
1246 | self.doModify(user.ident, fields, ignoreold=0) |
---|
1247 | else : |
---|
1248 | self.doDelete(user.ident) |
---|
1249 | result = self.doSearch("(&(objectClass=pykotaAccountBalance)(pykotaUserName=%s))" % user.Name, ["pykotaUserName"], base=self.info["balancebase"]) |
---|
1250 | for (ident, fields) in result : |
---|
1251 | self.doDelete(ident) |
---|
1252 | |
---|
1253 | def deleteGroup(self, group) : |
---|
1254 | """Completely deletes a group from the Quota Storage.""" |
---|
1255 | result = self.doSearch("(&(objectClass=pykotaGroupPQuota)(pykotaGroupName=%s))" % group.Name, ["pykotaGroupName"], base=self.info["groupquotabase"]) |
---|
1256 | for (ident, fields) in result : |
---|
1257 | self.doDelete(ident) |
---|
1258 | result = self.doSearch("objectClass=pykotaGroup", None, base=group.ident, scope=ldap.SCOPE_BASE) |
---|
1259 | if result : |
---|
1260 | fields = result[0][1] |
---|
1261 | for k in fields.keys() : |
---|
1262 | if k.startswith("pykota") : |
---|
1263 | del fields[k] |
---|
1264 | elif k.lower() == "objectclass" : |
---|
1265 | todelete = [] |
---|
1266 | for i in range(len(fields[k])) : |
---|
1267 | if fields[k][i].startswith("pykota") : |
---|
1268 | todelete.append(i) |
---|
1269 | todelete.sort() |
---|
1270 | todelete.reverse() |
---|
1271 | for i in todelete : |
---|
1272 | del fields[k][i] |
---|
1273 | if fields.get("objectClass") or fields.get("objectclass") : |
---|
1274 | self.doModify(group.ident, fields, ignoreold=0) |
---|
1275 | else : |
---|
1276 | self.doDelete(group.ident) |
---|
1277 | |
---|
1278 | def deletePrinter(self, printer) : |
---|
1279 | """Completely deletes an user from the Quota Storage.""" |
---|
1280 | result = self.doSearch("(&(objectClass=pykotaLastJob)(pykotaPrinterName=%s))" % printer.Name, base=self.info["lastjobbase"]) |
---|
1281 | for (ident, fields) in result : |
---|
1282 | self.doDelete(ident) |
---|
1283 | result = self.doSearch("(&(objectClass=pykotaJob)(pykotaPrinterName=%s))" % printer.Name, base=self.info["jobbase"]) |
---|
1284 | for (ident, fields) in result : |
---|
1285 | self.doDelete(ident) |
---|
1286 | result = self.doSearch("(&(objectClass=pykotaGroupPQuota)(pykotaPrinterName=%s))" % printer.Name, base=self.info["groupquotabase"]) |
---|
1287 | for (ident, fields) in result : |
---|
1288 | self.doDelete(ident) |
---|
1289 | result = self.doSearch("(&(objectClass=pykotaUserPQuota)(pykotaPrinterName=%s))" % printer.Name, base=self.info["userquotabase"]) |
---|
1290 | for (ident, fields) in result : |
---|
1291 | self.doDelete(ident) |
---|
1292 | for parent in self.getParentPrinters(printer) : |
---|
1293 | try : |
---|
1294 | parent.uniqueMember.remove(printer.ident) |
---|
1295 | except ValueError : |
---|
1296 | pass |
---|
1297 | else : |
---|
1298 | fields = { |
---|
1299 | "uniqueMember" : parent.uniqueMember, |
---|
1300 | } |
---|
1301 | self.doModify(parent.ident, fields) |
---|
1302 | self.doDelete(printer.ident) |
---|
1303 | |
---|
1304 | def extractPrinters(self) : |
---|
1305 | """Extracts all printer records.""" |
---|
1306 | entries = [p for p in [self.getPrinter(name) for name in self.getAllPrintersNames()] if p.Exists] |
---|
1307 | if entries : |
---|
1308 | result = [ ("dn", "pykotaPrinterName", "pykotaPricePerPage", "pykotaPricePerPage", "description") ] |
---|
1309 | for entry in entries : |
---|
1310 | result.append((entry.ident, entry.Name, entry.PricePerPage, entry.PricePerJob, entry.Description)) |
---|
1311 | return result |
---|
1312 | |
---|
1313 | def extractUsers(self) : |
---|
1314 | """Extracts all user records.""" |
---|
1315 | entries = [u for u in [self.getUser(name) for name in self.getAllUsersNames()] if u.Exists] |
---|
1316 | if entries : |
---|
1317 | result = [ ("dn", "pykotaUserName", self.info["usermail"], "pykotaBalance", "pykotaLifeTimePaid", "pykotaLimitBy") ] |
---|
1318 | for entry in entries : |
---|
1319 | result.append((entry.ident, entry.Name, entry.Email, entry.AccountBalance, entry.LifeTimePaid, entry.LimitBy)) |
---|
1320 | return result |
---|
1321 | |
---|
1322 | def extractGroups(self) : |
---|
1323 | """Extracts all group records.""" |
---|
1324 | entries = [g for g in [self.getGroup(name) for name in self.getAllGroupsNames()] if g.Exists] |
---|
1325 | if entries : |
---|
1326 | result = [ ("dn", "pykotaGroupName", "pykotaBalance", "pykotaLifeTimePaid", "pykotaLimitBy") ] |
---|
1327 | for entry in entries : |
---|
1328 | result.append((entry.ident, entry.Name, entry.AccountBalance, entry.LifeTimePaid, entry.LimitBy)) |
---|
1329 | return result |
---|
1330 | |
---|
1331 | def extractPayments(self) : |
---|
1332 | """Extracts all payment records.""" |
---|
1333 | entries = [u for u in [self.getUser(name) for name in self.getAllUsersNames()] if u.Exists] |
---|
1334 | if entries : |
---|
1335 | result = [ ("pykotaUserName", "date", "amount") ] |
---|
1336 | for entry in entries : |
---|
1337 | for (date, amount) in entry.Payments : |
---|
1338 | result.append((entry.Name, date, amount)) |
---|
1339 | return result |
---|
1340 | |
---|
1341 | def extractUpquotas(self) : |
---|
1342 | """Extracts all userpquota records.""" |
---|
1343 | entries = [p for p in [self.getPrinter(name) for name in self.getAllPrintersNames()] if p.Exists] |
---|
1344 | if entries : |
---|
1345 | result = [ ("pykotaUserName", "pykotaPrinterName", "dn", "userdn", "printerdn", "pykotaLifePageCounter", "pykotaPageCounter", "pykotaSoftLimit", "pykotaHardLimit", "pykotaDateLimit") ] |
---|
1346 | for entry in entries : |
---|
1347 | for (user, userpquota) in self.getPrinterUsersAndQuotas(entry) : |
---|
1348 | result.append((user.Name, entry.Name, userpquota.ident, user.ident, entry.ident, userpquota.LifePageCounter, userpquota.PageCounter, userpquota.SoftLimit, userpquota.HardLimit, userpquota.DateLimit)) |
---|
1349 | return result |
---|
1350 | |
---|
1351 | def extractGpquotas(self) : |
---|
1352 | """Extracts all grouppquota records.""" |
---|
1353 | entries = [p for p in [self.getPrinter(name) for name in self.getAllPrintersNames()] if p.Exists] |
---|
1354 | if entries : |
---|
1355 | result = [ ("pykotaGroupName", "pykotaPrinterName", "dn", "groupdn", "printerdn", "pykotaLifePageCounter", "pykotaPageCounter", "pykotaSoftLimit", "pykotaHardLimit", "pykotaDateLimit") ] |
---|
1356 | for entry in entries : |
---|
1357 | for (group, grouppquota) in self.getPrinterGroupsAndQuotas(entry) : |
---|
1358 | result.append((group.Name, entry.Name, grouppquota.ident, group.ident, entry.ident, grouppquota.LifePageCounter, grouppquota.PageCounter, grouppquota.SoftLimit, grouppquota.HardLimit, grouppquota.DateLimit)) |
---|
1359 | return result |
---|
1360 | |
---|
1361 | def extractUmembers(self) : |
---|
1362 | """Extracts all user groups members.""" |
---|
1363 | entries = [g for g in [self.getGroup(name) for name in self.getAllGroupsNames()] if g.Exists] |
---|
1364 | if entries : |
---|
1365 | result = [ ("pykotaGroupName", "pykotaUserName", "groupdn", "userdn") ] |
---|
1366 | for entry in entries : |
---|
1367 | for member in entry.Members : |
---|
1368 | result.append((entry.Name, member.Name, entry.ident, member.ident)) |
---|
1369 | return result |
---|
1370 | |
---|
1371 | def extractPmembers(self) : |
---|
1372 | """Extracts all printer groups members.""" |
---|
1373 | entries = [p for p in [self.getPrinter(name) for name in self.getAllPrintersNames()] if p.Exists] |
---|
1374 | if entries : |
---|
1375 | result = [ ("pykotaPGroupName", "pykotaPrinterName", "pgroupdn", "printerdn") ] |
---|
1376 | for entry in entries : |
---|
1377 | for parent in self.getParentPrinters(entry) : |
---|
1378 | result.append((parent.Name, entry.Name, parent.ident, entry.ident)) |
---|
1379 | return result |
---|
1380 | |
---|
1381 | def extractHistory(self) : |
---|
1382 | """Extracts all jobhistory records.""" |
---|
1383 | entries = self.retrieveHistory(limit=None) |
---|
1384 | if entries : |
---|
1385 | result = [ ("pykotaUserName", "pykotaPrinterName", "dn", "pykotaJobId", "pykotaPrinterPageCounter", "pykotaJobSize", "pykotaAction", "createTimeStamp", "pykotaFileName", "pykotaTitle", "pykotaCopies", "pykotaOptions", "pykotaJobPrice", "pykotaHostName", "pykotaJobSizeBytes") ] |
---|
1386 | for entry in entries : |
---|
1387 | result.append((entry.UserName, entry.PrinterName, entry.ident, entry.JobId, entry.PrinterPageCounter, entry.JobSize, entry.JobAction, entry.JobDate, entry.JobFileName, entry.JobTitle, entry.JobCopies, entry.JobOptions, entry.JobPrice, entry.JobHostName, entry.JobSizeBytes)) |
---|
1388 | return result |
---|