[3260] | 1 | # -*- coding: UTF-8 -*- |
---|
[695] | 2 | # |
---|
[3260] | 3 | # PyKota : Print Quotas for CUPS |
---|
| 4 | # |
---|
[3275] | 5 | # (c) 2003, 2004, 2005, 2006, 2007, 2008 Jerome Alet <alet@librelogiciel.com> |
---|
[3260] | 6 | # This program is free software: you can redistribute it and/or modify |
---|
[873] | 7 | # it under the terms of the GNU General Public License as published by |
---|
[3260] | 8 | # the Free Software Foundation, either version 3 of the License, or |
---|
[873] | 9 | # (at your option) any later version. |
---|
[3260] | 10 | # |
---|
[873] | 11 | # This program is distributed in the hope that it will be useful, |
---|
| 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of |
---|
| 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
---|
| 14 | # GNU General Public License for more details. |
---|
| 15 | # |
---|
| 16 | # You should have received a copy of the GNU General Public License |
---|
[3260] | 17 | # along with this program. If not, see <http://www.gnu.org/licenses/>. |
---|
[695] | 18 | # |
---|
| 19 | # $Id$ |
---|
| 20 | # |
---|
[2093] | 21 | # |
---|
[695] | 22 | |
---|
[3184] | 23 | """This module defines the base classes for PyKota command line tools.""" |
---|
| 24 | |
---|
[695] | 25 | import sys |
---|
[1193] | 26 | import os |
---|
[1960] | 27 | import pwd |
---|
[817] | 28 | import fnmatch |
---|
[715] | 29 | import getopt |
---|
[695] | 30 | import smtplib |
---|
[782] | 31 | import locale |
---|
[1469] | 32 | import socket |
---|
[2783] | 33 | import time |
---|
[2643] | 34 | from email.MIMEText import MIMEText |
---|
| 35 | from email.Header import Header |
---|
[3013] | 36 | import email.Utils |
---|
[695] | 37 | |
---|
[708] | 38 | from mx import DateTime |
---|
| 39 | |
---|
[3288] | 40 | from pykota.errors import PyKotaCommandLineError |
---|
[2830] | 41 | from pykota import config, storage, logger |
---|
[2344] | 42 | from pykota.version import __version__, __author__, __years__, __gplblurb__ |
---|
[695] | 43 | |
---|
[1795] | 44 | def N_(message) : |
---|
| 45 | """Fake translation marker for translatable strings extraction.""" |
---|
| 46 | return message |
---|
| 47 | |
---|
[2229] | 48 | def crashed(message="Bug in PyKota") : |
---|
[1546] | 49 | """Minimal crash method.""" |
---|
| 50 | import traceback |
---|
| 51 | lines = [] |
---|
| 52 | for line in traceback.format_exception(*sys.exc_info()) : |
---|
| 53 | lines.extend([l for l in line.split("\n") if l]) |
---|
[2344] | 54 | msg = "ERROR: ".join(["%s\n" % l for l in (["ERROR: PyKota v%s" % __version__, message] + lines)]) |
---|
[1546] | 55 | sys.stderr.write(msg) |
---|
| 56 | sys.stderr.flush() |
---|
| 57 | return msg |
---|
| 58 | |
---|
[2782] | 59 | class Percent : |
---|
| 60 | """A class to display progress.""" |
---|
[2783] | 61 | def __init__(self, app, size=None) : |
---|
[2782] | 62 | """Initializes the engine.""" |
---|
| 63 | self.app = app |
---|
[2783] | 64 | self.size = None |
---|
| 65 | if size : |
---|
| 66 | self.setSize(size) |
---|
| 67 | self.previous = None |
---|
| 68 | self.before = time.time() |
---|
| 69 | |
---|
| 70 | def setSize(self, size) : |
---|
| 71 | """Sets the total size.""" |
---|
| 72 | self.number = 0 |
---|
[2782] | 73 | self.size = size |
---|
[2793] | 74 | if size : |
---|
| 75 | self.factor = 100.0 / float(size) |
---|
[2782] | 76 | |
---|
| 77 | def display(self, msg) : |
---|
| 78 | """Displays the value.""" |
---|
| 79 | self.app.display(msg) |
---|
| 80 | |
---|
| 81 | def oneMore(self) : |
---|
| 82 | """Increments internal counter.""" |
---|
[2783] | 83 | if self.size : |
---|
| 84 | self.number += 1 |
---|
| 85 | percent = "%.02f" % (float(self.number) * self.factor) |
---|
| 86 | if percent != self.previous : # optimize for large number of items |
---|
| 87 | self.display("\r%s%%" % percent) |
---|
| 88 | self.previous = percent |
---|
[2782] | 89 | |
---|
| 90 | def done(self) : |
---|
| 91 | """Displays the 'done' message.""" |
---|
[2783] | 92 | after = time.time() |
---|
| 93 | if self.size : |
---|
[3251] | 94 | try : |
---|
[3286] | 95 | speed = self.size / ((after - self.before) + 0.00000000001) # adds an epsilon to avoid an user's problem I can't reproduce... |
---|
[3251] | 96 | except ZeroDivisionError : |
---|
[3271] | 97 | speed = 1 # Fake value in case of division by zero, shouldn't happen anyway with the epsilon above... |
---|
[2788] | 98 | self.display("\r100.00%%\r \r%s. %s : %.2f %s.\n" \ |
---|
[2783] | 99 | % (_("Done"), _("Average speed"), speed, _("entries per second"))) |
---|
| 100 | else : |
---|
| 101 | self.display("\r100.00%%\r \r%s.\n" % _("Done")) |
---|
[2782] | 102 | |
---|
[1911] | 103 | class Tool : |
---|
| 104 | """Base class for tools with no database access.""" |
---|
[2344] | 105 | def __init__(self, lang="", charset=None, doc="PyKota v%(__version__)s (c) %(__years__)s %(__author__)s") : |
---|
[695] | 106 | """Initializes the command line tool.""" |
---|
[3187] | 107 | self.debug = True # in case of early failure |
---|
[3188] | 108 | self.logger = logger.openLogger("stderr") |
---|
[3187] | 109 | |
---|
[3294] | 110 | # Saves a copy of the locale settings |
---|
[3055] | 111 | (self.language, self.charset) = locale.getlocale() |
---|
| 112 | |
---|
[772] | 113 | # pykota specific stuff |
---|
[715] | 114 | self.documentation = doc |
---|
[1960] | 115 | |
---|
[3276] | 116 | # Extract the effective username |
---|
| 117 | uid = os.geteuid() |
---|
| 118 | try : |
---|
| 119 | self.effectiveUserName = pwd.getpwuid(uid)[0] |
---|
| 120 | except (KeyError, IndexError), msg : |
---|
| 121 | self.printInfo(_("Strange problem with uid(%s) : %s") % (uid, msg), "warn") |
---|
| 122 | self.effectiveUserName = os.getlogin() |
---|
| 123 | |
---|
[2210] | 124 | def deferredInit(self) : |
---|
| 125 | """Deferred initialization.""" |
---|
[3045] | 126 | confdir = os.environ.get("PYKOTA_HOME") |
---|
| 127 | environHome = True |
---|
| 128 | missingUser = False |
---|
| 129 | if confdir is None : |
---|
| 130 | environHome = False |
---|
| 131 | # check for config files in the 'pykota' user's home directory. |
---|
| 132 | try : |
---|
| 133 | self.pykotauser = pwd.getpwnam("pykota") |
---|
| 134 | confdir = self.pykotauser[5] |
---|
| 135 | except KeyError : |
---|
| 136 | self.pykotauser = None |
---|
| 137 | confdir = "/etc/pykota" |
---|
| 138 | missingUser = True |
---|
[1960] | 139 | |
---|
[2210] | 140 | self.config = config.PyKotaConfig(confdir) |
---|
| 141 | self.debug = self.config.getDebug() |
---|
| 142 | self.smtpserver = self.config.getSMTPServer() |
---|
| 143 | self.maildomain = self.config.getMailDomain() |
---|
| 144 | self.logger = logger.openLogger(self.config.getLoggingBackend()) |
---|
[1542] | 145 | |
---|
[1960] | 146 | # We NEED this here, even when not in an accounting filter/backend |
---|
[1497] | 147 | self.softwareJobSize = 0 |
---|
[1495] | 148 | self.softwareJobPrice = 0.0 |
---|
[1960] | 149 | |
---|
[3045] | 150 | if environHome : |
---|
| 151 | self.printInfo("PYKOTA_HOME environment variable is set. Configuration files were searched in %s" % confdir, "info") |
---|
| 152 | else : |
---|
| 153 | if missingUser : |
---|
| 154 | self.printInfo("The 'pykota' system account is missing. Configuration files were searched in %s instead." % confdir, "warn") |
---|
[1960] | 155 | |
---|
[3055] | 156 | self.logdebug("Language in use : %s" % self.language) |
---|
[1761] | 157 | self.logdebug("Charset in use : %s" % self.charset) |
---|
[3055] | 158 | |
---|
[1872] | 159 | arguments = " ".join(['"%s"' % arg for arg in sys.argv]) |
---|
| 160 | self.logdebug("Command line arguments : %s" % arguments) |
---|
[695] | 161 | |
---|
[2804] | 162 | def UTF8ToUserCharset(self, text) : |
---|
| 163 | """Converts from UTF-8 to user's charset.""" |
---|
[3006] | 164 | if text is None : |
---|
| 165 | return None |
---|
[3287] | 166 | else : |
---|
| 167 | return text.decode("UTF-8", "replace").encode(self.charset, "replace") |
---|
[2804] | 168 | |
---|
| 169 | def userCharsetToUTF8(self, text) : |
---|
| 170 | """Converts from user's charset to UTF-8.""" |
---|
[3006] | 171 | if text is None : |
---|
| 172 | return None |
---|
[3287] | 173 | else : |
---|
| 174 | return text.decode(self.charset, "replace").encode("UTF-8", "replace") |
---|
[2804] | 175 | |
---|
[2657] | 176 | def display(self, message) : |
---|
| 177 | """Display a message but only if stdout is a tty.""" |
---|
| 178 | if sys.stdout.isatty() : |
---|
[3287] | 179 | sys.stdout.write(message.encode(sys.stdout.encoding or "UTF-8", \ |
---|
| 180 | "replace")) |
---|
[2657] | 181 | sys.stdout.flush() |
---|
| 182 | |
---|
[1130] | 183 | def logdebug(self, message) : |
---|
| 184 | """Logs something to debug output if debug is enabled.""" |
---|
| 185 | if self.debug : |
---|
[3287] | 186 | self.logger.log_message(message.encode(sys.stdout.encoding \ |
---|
| 187 | or "UTF-8", \ |
---|
| 188 | "replace"), \ |
---|
| 189 | "debug") |
---|
[1582] | 190 | |
---|
[1584] | 191 | def printInfo(self, message, level="info") : |
---|
[1582] | 192 | """Sends a message to standard error.""" |
---|
[3287] | 193 | sys.stderr.write("%s: %s\n" % (level.upper(), \ |
---|
| 194 | message.encode(sys.stdout.encoding \ |
---|
| 195 | or "UTF-8", \ |
---|
| 196 | "replace"))) |
---|
[1582] | 197 | sys.stderr.flush() |
---|
[1130] | 198 | |
---|
[2210] | 199 | def matchString(self, s, patterns) : |
---|
[2650] | 200 | """Returns True if the string s matches one of the patterns, else False.""" |
---|
| 201 | if not patterns : |
---|
| 202 | return True # No pattern, always matches. |
---|
| 203 | else : |
---|
| 204 | for pattern in patterns : |
---|
| 205 | if fnmatch.fnmatchcase(s, pattern) : |
---|
| 206 | return True |
---|
| 207 | return False |
---|
[2210] | 208 | |
---|
[2762] | 209 | def sanitizeNames(self, options, names) : |
---|
| 210 | """Ensures that an user can only see the datas he is allowed to see, by modifying the list of names.""" |
---|
| 211 | if not self.config.isAdmin : |
---|
| 212 | username = pwd.getpwuid(os.geteuid())[0] |
---|
| 213 | if not options["list"] : |
---|
| 214 | raise PyKotaCommandLineError, "%s : %s" % (username, _("You're not allowed to use this command.")) |
---|
| 215 | else : |
---|
| 216 | if options["groups"] : |
---|
| 217 | user = self.storage.getUser(username) |
---|
| 218 | if user.Exists : |
---|
| 219 | return [ g.Name for g in self.storage.getUserGroups(user) ] |
---|
| 220 | return [ username ] |
---|
| 221 | elif not names : |
---|
| 222 | return ["*"] |
---|
| 223 | else : |
---|
| 224 | return names |
---|
| 225 | |
---|
[715] | 226 | def display_version_and_quit(self) : |
---|
| 227 | """Displays version number, then exists successfully.""" |
---|
[1923] | 228 | try : |
---|
| 229 | self.clean() |
---|
| 230 | except AttributeError : |
---|
| 231 | pass |
---|
[2344] | 232 | print __version__ |
---|
[715] | 233 | sys.exit(0) |
---|
| 234 | |
---|
| 235 | def display_usage_and_quit(self) : |
---|
| 236 | """Displays command line usage, then exists successfully.""" |
---|
[1923] | 237 | try : |
---|
| 238 | self.clean() |
---|
| 239 | except AttributeError : |
---|
| 240 | pass |
---|
[2344] | 241 | print _(self.documentation) % globals() |
---|
| 242 | print __gplblurb__ |
---|
| 243 | print |
---|
| 244 | print _("Please report bugs to :"), __author__ |
---|
[715] | 245 | sys.exit(0) |
---|
| 246 | |
---|
[2229] | 247 | def crashed(self, message="Bug in PyKota") : |
---|
[1517] | 248 | """Outputs a crash message, and optionally sends it to software author.""" |
---|
[1546] | 249 | msg = crashed(message) |
---|
[2229] | 250 | fullmessage = "========== Traceback :\n\n%s\n\n========== sys.argv :\n\n%s\n\n========== Environment :\n\n%s\n" % \ |
---|
| 251 | (msg, \ |
---|
| 252 | "\n".join([" %s" % repr(a) for a in sys.argv]), \ |
---|
| 253 | "\n".join([" %s=%s" % (k, v) for (k, v) in os.environ.items()])) |
---|
[1541] | 254 | try : |
---|
| 255 | crashrecipient = self.config.getCrashRecipient() |
---|
| 256 | if crashrecipient : |
---|
[1517] | 257 | admin = self.config.getAdminMail("global") # Nice trick, isn't it ? |
---|
| 258 | server = smtplib.SMTP(self.smtpserver) |
---|
[2795] | 259 | msg = MIMEText(fullmessage, _charset=self.charset) |
---|
[3136] | 260 | msg["Subject"] = Header("PyKota v%s crash traceback !" \ |
---|
| 261 | % __version__, charset=self.charset) |
---|
[2795] | 262 | msg["From"] = admin |
---|
| 263 | msg["To"] = crashrecipient |
---|
| 264 | msg["Cc"] = admin |
---|
[3013] | 265 | msg["Date"] = email.Utils.formatdate(localtime=True) |
---|
[2795] | 266 | server.sendmail(admin, [admin, crashrecipient], msg.as_string()) |
---|
[1517] | 267 | server.quit() |
---|
[1541] | 268 | except : |
---|
| 269 | pass |
---|
[2229] | 270 | return fullmessage |
---|
[1517] | 271 | |
---|
[729] | 272 | def parseCommandline(self, argv, short, long, allownothing=0) : |
---|
[715] | 273 | """Parses the command line, controlling options.""" |
---|
| 274 | # split options in two lists: those which need an argument, those which don't need any |
---|
[2605] | 275 | short = "%sA:" % short |
---|
| 276 | long.append("arguments=") |
---|
[715] | 277 | withoutarg = [] |
---|
| 278 | witharg = [] |
---|
| 279 | lgs = len(short) |
---|
| 280 | i = 0 |
---|
| 281 | while i < lgs : |
---|
| 282 | ii = i + 1 |
---|
| 283 | if (ii < lgs) and (short[ii] == ':') : |
---|
| 284 | # needs an argument |
---|
| 285 | witharg.append(short[i]) |
---|
| 286 | ii = ii + 1 # skip the ':' |
---|
| 287 | else : |
---|
| 288 | # doesn't need an argument |
---|
| 289 | withoutarg.append(short[i]) |
---|
| 290 | i = ii |
---|
| 291 | |
---|
| 292 | for option in long : |
---|
| 293 | if option[-1] == '=' : |
---|
| 294 | # needs an argument |
---|
| 295 | witharg.append(option[:-1]) |
---|
| 296 | else : |
---|
| 297 | # doesn't need an argument |
---|
| 298 | withoutarg.append(option) |
---|
| 299 | |
---|
| 300 | # then we parse the command line |
---|
[2605] | 301 | done = 0 |
---|
| 302 | while not done : |
---|
| 303 | # we begin with all possible options unset |
---|
| 304 | parsed = {} |
---|
| 305 | for option in withoutarg + witharg : |
---|
| 306 | parsed[option] = None |
---|
| 307 | args = [] # to not break if something unexpected happened |
---|
| 308 | try : |
---|
| 309 | options, args = getopt.getopt(argv, short, long) |
---|
| 310 | if options : |
---|
| 311 | for (o, v) in options : |
---|
| 312 | # we skip the '-' chars |
---|
| 313 | lgo = len(o) |
---|
| 314 | i = 0 |
---|
| 315 | while (i < lgo) and (o[i] == '-') : |
---|
| 316 | i = i + 1 |
---|
| 317 | o = o[i:] |
---|
| 318 | if o in witharg : |
---|
| 319 | # needs an argument : set it |
---|
| 320 | parsed[o] = v |
---|
| 321 | elif o in withoutarg : |
---|
| 322 | # doesn't need an argument : boolean |
---|
| 323 | parsed[o] = 1 |
---|
| 324 | else : |
---|
| 325 | # should never occur |
---|
[2610] | 326 | raise PyKotaCommandLineError, "Unexpected problem when parsing command line" |
---|
[2605] | 327 | elif (not args) and (not allownothing) and sys.stdin.isatty() : # no option and no argument, we display help if we are a tty |
---|
| 328 | self.display_usage_and_quit() |
---|
| 329 | except getopt.error, msg : |
---|
[2610] | 330 | raise PyKotaCommandLineError, str(msg) |
---|
[2605] | 331 | else : |
---|
| 332 | if parsed["arguments"] or parsed["A"] : |
---|
| 333 | # arguments are in a file, we ignore all other arguments |
---|
| 334 | # and reset the list of arguments to the lines read from |
---|
| 335 | # the file. |
---|
[3294] | 336 | argsfile = open(parsed["arguments"] or parsed["A"], "r") # TODO : charset decoding |
---|
[2605] | 337 | argv = [ l.strip() for l in argsfile.readlines() ] |
---|
| 338 | argsfile.close() |
---|
| 339 | for i in range(len(argv)) : |
---|
| 340 | argi = argv[i] |
---|
| 341 | if argi.startswith('"') and argi.endswith('"') : |
---|
| 342 | argv[i] = argi[1:-1] |
---|
| 343 | else : |
---|
| 344 | done = 1 |
---|
[715] | 345 | return (parsed, args) |
---|
| 346 | |
---|
[1911] | 347 | class PyKotaTool(Tool) : |
---|
| 348 | """Base class for all PyKota command line tools.""" |
---|
[2344] | 349 | def __init__(self, lang="", charset=None, doc="PyKota v%(__version__)s (c) %(__years__)s %(__author__)s") : |
---|
[1911] | 350 | """Initializes the command line tool and opens the database.""" |
---|
| 351 | Tool.__init__(self, lang, charset, doc) |
---|
[2210] | 352 | |
---|
| 353 | def deferredInit(self) : |
---|
| 354 | """Deferred initialization.""" |
---|
| 355 | Tool.deferredInit(self) |
---|
| 356 | self.storage = storage.openConnection(self) |
---|
| 357 | if self.config.isAdmin : # TODO : We don't know this before, fix this ! |
---|
| 358 | self.logdebug("Beware : running as a PyKota administrator !") |
---|
[2093] | 359 | else : |
---|
[2210] | 360 | self.logdebug("Don't Panic : running as a mere mortal !") |
---|
[1911] | 361 | |
---|
| 362 | def clean(self) : |
---|
| 363 | """Ensures that the database is closed.""" |
---|
| 364 | try : |
---|
| 365 | self.storage.close() |
---|
| 366 | except (TypeError, NameError, AttributeError) : |
---|
| 367 | pass |
---|
| 368 | |
---|
[764] | 369 | def isValidName(self, name) : |
---|
| 370 | """Checks if a user or printer name is valid.""" |
---|
[1725] | 371 | invalidchars = "/@?*,;&|" |
---|
[1637] | 372 | for c in list(invalidchars) : |
---|
[1593] | 373 | if c in name : |
---|
[1394] | 374 | return 0 |
---|
| 375 | return 1 |
---|
[764] | 376 | |
---|
[802] | 377 | def sendMessage(self, adminmail, touser, fullmessage) : |
---|
[695] | 378 | """Sends an email message containing headers to some user.""" |
---|
[1469] | 379 | try : |
---|
| 380 | server = smtplib.SMTP(self.smtpserver) |
---|
| 381 | except socket.error, msg : |
---|
[1584] | 382 | self.printInfo(_("Impossible to connect to SMTP server : %s") % msg, "error") |
---|
[1469] | 383 | else : |
---|
| 384 | try : |
---|
[2795] | 385 | server.sendmail(adminmail, [touser], fullmessage) |
---|
[1469] | 386 | except smtplib.SMTPException, answer : |
---|
| 387 | for (k, v) in answer.recipients.items() : |
---|
[1584] | 388 | self.printInfo(_("Impossible to send mail to %s, error %s : %s") % (k, v[0], v[1]), "error") |
---|
[1469] | 389 | server.quit() |
---|
[695] | 390 | |
---|
[1079] | 391 | def sendMessageToUser(self, admin, adminmail, user, subject, message) : |
---|
[695] | 392 | """Sends an email message to a user.""" |
---|
[802] | 393 | message += _("\n\nPlease contact your system administrator :\n\n\t%s - <%s>\n") % (admin, adminmail) |
---|
[2795] | 394 | usermail = user.Email or user.Name |
---|
| 395 | if "@" not in usermail : |
---|
| 396 | usermail = "%s@%s" % (usermail, self.maildomain or self.smtpserver or "localhost") |
---|
| 397 | msg = MIMEText(message, _charset=self.charset) |
---|
[3136] | 398 | msg["Subject"] = Header(subject, charset=self.charset) |
---|
[2795] | 399 | msg["From"] = adminmail |
---|
| 400 | msg["To"] = usermail |
---|
[3013] | 401 | msg["Date"] = email.Utils.formatdate(localtime=True) |
---|
[2795] | 402 | self.sendMessage(adminmail, usermail, msg.as_string()) |
---|
[695] | 403 | |
---|
[802] | 404 | def sendMessageToAdmin(self, adminmail, subject, message) : |
---|
[695] | 405 | """Sends an email message to the Print Quota administrator.""" |
---|
[2795] | 406 | if "@" not in adminmail : |
---|
| 407 | adminmail = "%s@%s" % (adminmail, self.maildomain or self.smtpserver or "localhost") |
---|
| 408 | msg = MIMEText(message, _charset=self.charset) |
---|
[3136] | 409 | msg["Subject"] = Header(subject, charset=self.charset) |
---|
[2795] | 410 | msg["From"] = adminmail |
---|
| 411 | msg["To"] = adminmail |
---|
| 412 | self.sendMessage(adminmail, adminmail, msg.as_string()) |
---|
[695] | 413 | |
---|
[1365] | 414 | def _checkUserPQuota(self, userpquota) : |
---|
| 415 | """Checks the user quota on a printer and deny or accept the job.""" |
---|
| 416 | # then we check the user's own quota |
---|
| 417 | # if we get there we are sure that policy is not EXTERNAL |
---|
| 418 | user = userpquota.User |
---|
| 419 | printer = userpquota.Printer |
---|
[1495] | 420 | enforcement = self.config.getPrinterEnforcement(printer.Name) |
---|
[1365] | 421 | self.logdebug("Checking user %s's quota on printer %s" % (user.Name, printer.Name)) |
---|
| 422 | (policy, dummy) = self.config.getPrinterPolicy(userpquota.Printer.Name) |
---|
| 423 | if not userpquota.Exists : |
---|
| 424 | # Unknown userquota |
---|
| 425 | if policy == "ALLOW" : |
---|
| 426 | action = "POLICY_ALLOW" |
---|
| 427 | else : |
---|
| 428 | action = "POLICY_DENY" |
---|
[1584] | 429 | self.printInfo(_("Unable to match user %s on printer %s, applying default policy (%s)") % (user.Name, printer.Name, action)) |
---|
[1365] | 430 | else : |
---|
| 431 | pagecounter = int(userpquota.PageCounter or 0) |
---|
[1495] | 432 | if enforcement == "STRICT" : |
---|
| 433 | pagecounter += self.softwareJobSize |
---|
[1365] | 434 | if userpquota.SoftLimit is not None : |
---|
| 435 | softlimit = int(userpquota.SoftLimit) |
---|
| 436 | if pagecounter < softlimit : |
---|
| 437 | action = "ALLOW" |
---|
| 438 | else : |
---|
| 439 | if userpquota.HardLimit is None : |
---|
| 440 | # only a soft limit, this is equivalent to having only a hard limit |
---|
| 441 | action = "DENY" |
---|
| 442 | else : |
---|
| 443 | hardlimit = int(userpquota.HardLimit) |
---|
| 444 | if softlimit <= pagecounter < hardlimit : |
---|
| 445 | now = DateTime.now() |
---|
| 446 | if userpquota.DateLimit is not None : |
---|
[3050] | 447 | datelimit = DateTime.ISO.ParseDateTime(str(userpquota.DateLimit)[:19]) |
---|
[1365] | 448 | else : |
---|
| 449 | datelimit = now + self.config.getGraceDelay(printer.Name) |
---|
| 450 | userpquota.setDateLimit(datelimit) |
---|
| 451 | if now < datelimit : |
---|
| 452 | action = "WARN" |
---|
| 453 | else : |
---|
| 454 | action = "DENY" |
---|
| 455 | else : |
---|
| 456 | action = "DENY" |
---|
| 457 | else : |
---|
| 458 | if userpquota.HardLimit is not None : |
---|
| 459 | # no soft limit, only a hard one. |
---|
| 460 | hardlimit = int(userpquota.HardLimit) |
---|
| 461 | if pagecounter < hardlimit : |
---|
| 462 | action = "ALLOW" |
---|
| 463 | else : |
---|
| 464 | action = "DENY" |
---|
| 465 | else : |
---|
| 466 | # Both are unset, no quota, i.e. accounting only |
---|
| 467 | action = "ALLOW" |
---|
| 468 | return action |
---|
| 469 | |
---|
[1041] | 470 | def checkGroupPQuota(self, grouppquota) : |
---|
[927] | 471 | """Checks the group quota on a printer and deny or accept the job.""" |
---|
[1041] | 472 | group = grouppquota.Group |
---|
| 473 | printer = grouppquota.Printer |
---|
[1495] | 474 | enforcement = self.config.getPrinterEnforcement(printer.Name) |
---|
[1365] | 475 | self.logdebug("Checking group %s's quota on printer %s" % (group.Name, printer.Name)) |
---|
[1061] | 476 | if group.LimitBy and (group.LimitBy.lower() == "balance") : |
---|
[1666] | 477 | val = group.AccountBalance or 0.0 |
---|
[1495] | 478 | if enforcement == "STRICT" : |
---|
| 479 | val -= self.softwareJobPrice # use precomputed size. |
---|
[2692] | 480 | balancezero = self.config.getBalanceZero() |
---|
| 481 | if val <= balancezero : |
---|
[1041] | 482 | action = "DENY" |
---|
[1495] | 483 | elif val <= self.config.getPoorMan() : |
---|
[1077] | 484 | action = "WARN" |
---|
[927] | 485 | else : |
---|
[1041] | 486 | action = "ALLOW" |
---|
[2692] | 487 | if (enforcement == "STRICT") and (val == balancezero) : |
---|
[1529] | 488 | action = "WARN" # we can still print until account is 0 |
---|
[927] | 489 | else : |
---|
[1665] | 490 | val = grouppquota.PageCounter or 0 |
---|
[1495] | 491 | if enforcement == "STRICT" : |
---|
[2992] | 492 | val += int(self.softwareJobSize) # TODO : this is not a fix, problem is elsewhere in grouppquota.PageCounter |
---|
[1041] | 493 | if grouppquota.SoftLimit is not None : |
---|
| 494 | softlimit = int(grouppquota.SoftLimit) |
---|
[1495] | 495 | if val < softlimit : |
---|
[1041] | 496 | action = "ALLOW" |
---|
[927] | 497 | else : |
---|
[1041] | 498 | if grouppquota.HardLimit is None : |
---|
| 499 | # only a soft limit, this is equivalent to having only a hard limit |
---|
| 500 | action = "DENY" |
---|
[927] | 501 | else : |
---|
[1041] | 502 | hardlimit = int(grouppquota.HardLimit) |
---|
[1495] | 503 | if softlimit <= val < hardlimit : |
---|
[1041] | 504 | now = DateTime.now() |
---|
| 505 | if grouppquota.DateLimit is not None : |
---|
[3050] | 506 | datelimit = DateTime.ISO.ParseDateTime(str(grouppquota.DateLimit)[:19]) |
---|
[1041] | 507 | else : |
---|
| 508 | datelimit = now + self.config.getGraceDelay(printer.Name) |
---|
| 509 | grouppquota.setDateLimit(datelimit) |
---|
| 510 | if now < datelimit : |
---|
| 511 | action = "WARN" |
---|
| 512 | else : |
---|
[927] | 513 | action = "DENY" |
---|
[1041] | 514 | else : |
---|
[927] | 515 | action = "DENY" |
---|
[1041] | 516 | else : |
---|
| 517 | if grouppquota.HardLimit is not None : |
---|
| 518 | # no soft limit, only a hard one. |
---|
| 519 | hardlimit = int(grouppquota.HardLimit) |
---|
[1495] | 520 | if val < hardlimit : |
---|
[927] | 521 | action = "ALLOW" |
---|
[1041] | 522 | else : |
---|
| 523 | action = "DENY" |
---|
| 524 | else : |
---|
| 525 | # Both are unset, no quota, i.e. accounting only |
---|
| 526 | action = "ALLOW" |
---|
[927] | 527 | return action |
---|
| 528 | |
---|
[1041] | 529 | def checkUserPQuota(self, userpquota) : |
---|
[1365] | 530 | """Checks the user quota on a printer and all its parents and deny or accept the job.""" |
---|
[1041] | 531 | user = userpquota.User |
---|
| 532 | printer = userpquota.Printer |
---|
| 533 | |
---|
[1365] | 534 | # indicates that a warning needs to be sent |
---|
| 535 | warned = 0 |
---|
| 536 | |
---|
[927] | 537 | # first we check any group the user is a member of |
---|
[1041] | 538 | for group in self.storage.getUserGroups(user) : |
---|
[2452] | 539 | # No need to check anything if the group is in noquota mode |
---|
| 540 | if group.LimitBy != "noquota" : |
---|
| 541 | grouppquota = self.storage.getGroupPQuota(group, printer) |
---|
| 542 | # for the printer and all its parents |
---|
| 543 | for gpquota in [ grouppquota ] + grouppquota.ParentPrintersGroupPQuota : |
---|
| 544 | if gpquota.Exists : |
---|
| 545 | action = self.checkGroupPQuota(gpquota) |
---|
| 546 | if action == "DENY" : |
---|
| 547 | return action |
---|
| 548 | elif action == "WARN" : |
---|
| 549 | warned = 1 |
---|
[1365] | 550 | |
---|
| 551 | # Then we check the user's account balance |
---|
[1152] | 552 | # if we get there we are sure that policy is not EXTERNAL |
---|
| 553 | (policy, dummy) = self.config.getPrinterPolicy(printer.Name) |
---|
[1061] | 554 | if user.LimitBy and (user.LimitBy.lower() == "balance") : |
---|
[1365] | 555 | self.logdebug("Checking account balance for user %s" % user.Name) |
---|
[1041] | 556 | if user.AccountBalance is None : |
---|
[956] | 557 | if policy == "ALLOW" : |
---|
[925] | 558 | action = "POLICY_ALLOW" |
---|
| 559 | else : |
---|
| 560 | action = "POLICY_DENY" |
---|
[1584] | 561 | self.printInfo(_("Unable to find user %s's account balance, applying default policy (%s) for printer %s") % (user.Name, action, printer.Name)) |
---|
[1365] | 562 | return action |
---|
[713] | 563 | else : |
---|
[2054] | 564 | if user.OverCharge == 0.0 : |
---|
| 565 | self.printInfo(_("User %s will not be charged for printing.") % user.Name) |
---|
| 566 | action = "ALLOW" |
---|
[1529] | 567 | else : |
---|
[2054] | 568 | val = float(user.AccountBalance or 0.0) |
---|
| 569 | enforcement = self.config.getPrinterEnforcement(printer.Name) |
---|
| 570 | if enforcement == "STRICT" : |
---|
| 571 | val -= self.softwareJobPrice # use precomputed size. |
---|
[2692] | 572 | balancezero = self.config.getBalanceZero() |
---|
| 573 | if val <= balancezero : |
---|
[2054] | 574 | action = "DENY" |
---|
| 575 | elif val <= self.config.getPoorMan() : |
---|
| 576 | action = "WARN" |
---|
| 577 | else : |
---|
| 578 | action = "ALLOW" |
---|
[2692] | 579 | if (enforcement == "STRICT") and (val == balancezero) : |
---|
[2054] | 580 | action = "WARN" # we can still print until account is 0 |
---|
[1529] | 581 | return action |
---|
[925] | 582 | else : |
---|
[1365] | 583 | # Then check the user quota on current printer and all its parents. |
---|
| 584 | policyallowed = 0 |
---|
| 585 | for upquota in [ userpquota ] + userpquota.ParentPrintersUserPQuota : |
---|
| 586 | action = self._checkUserPQuota(upquota) |
---|
| 587 | if action in ("DENY", "POLICY_DENY") : |
---|
| 588 | return action |
---|
| 589 | elif action == "WARN" : |
---|
| 590 | warned = 1 |
---|
| 591 | elif action == "POLICY_ALLOW" : |
---|
| 592 | policyallowed = 1 |
---|
| 593 | if warned : |
---|
| 594 | return "WARN" |
---|
| 595 | elif policyallowed : |
---|
| 596 | return "POLICY_ALLOW" |
---|
[925] | 597 | else : |
---|
[1365] | 598 | return "ALLOW" |
---|
| 599 | |
---|
[1196] | 600 | def externalMailTo(self, cmd, action, user, printer, message) : |
---|
[1192] | 601 | """Warns the user with an external command.""" |
---|
| 602 | username = user.Name |
---|
[1196] | 603 | printername = printer.Name |
---|
[1192] | 604 | email = user.Email or user.Name |
---|
| 605 | if "@" not in email : |
---|
[1353] | 606 | email = "%s@%s" % (email, self.maildomain or self.smtpserver) |
---|
[1192] | 607 | os.system(cmd % locals()) |
---|
| 608 | |
---|
[1196] | 609 | def formatCommandLine(self, cmd, user, printer) : |
---|
| 610 | """Executes an external command.""" |
---|
| 611 | username = user.Name |
---|
| 612 | printername = printer.Name |
---|
| 613 | return cmd % locals() |
---|
| 614 | |
---|
[1041] | 615 | def warnGroupPQuota(self, grouppquota) : |
---|
[927] | 616 | """Checks a group quota and send messages if quota is exceeded on current printer.""" |
---|
[1041] | 617 | group = grouppquota.Group |
---|
| 618 | printer = grouppquota.Printer |
---|
| 619 | admin = self.config.getAdmin(printer.Name) |
---|
| 620 | adminmail = self.config.getAdminMail(printer.Name) |
---|
[1192] | 621 | (mailto, arguments) = self.config.getMailTo(printer.Name) |
---|
[2547] | 622 | if group.LimitBy in ("noquota", "nochange") : |
---|
| 623 | action = "ALLOW" |
---|
| 624 | else : |
---|
| 625 | action = self.checkGroupPQuota(grouppquota) |
---|
| 626 | if action.startswith("POLICY_") : |
---|
| 627 | action = action[7:] |
---|
| 628 | if action == "DENY" : |
---|
| 629 | adminmessage = _("Print Quota exceeded for group %s on printer %s") % (group.Name, printer.Name) |
---|
| 630 | self.printInfo(adminmessage) |
---|
| 631 | if mailto in [ "BOTH", "ADMIN" ] : |
---|
| 632 | self.sendMessageToAdmin(adminmail, _("Print Quota"), adminmessage) |
---|
| 633 | if mailto in [ "BOTH", "USER", "EXTERNAL" ] : |
---|
| 634 | for user in self.storage.getGroupMembers(group) : |
---|
| 635 | if mailto != "EXTERNAL" : |
---|
| 636 | self.sendMessageToUser(admin, adminmail, user, _("Print Quota Exceeded"), self.config.getHardWarn(printer.Name)) |
---|
| 637 | else : |
---|
| 638 | self.externalMailTo(arguments, action, user, printer, self.config.getHardWarn(printer.Name)) |
---|
| 639 | elif action == "WARN" : |
---|
| 640 | adminmessage = _("Print Quota low for group %s on printer %s") % (group.Name, printer.Name) |
---|
| 641 | self.printInfo(adminmessage) |
---|
| 642 | if mailto in [ "BOTH", "ADMIN" ] : |
---|
| 643 | self.sendMessageToAdmin(adminmail, _("Print Quota"), adminmessage) |
---|
| 644 | if group.LimitBy and (group.LimitBy.lower() == "balance") : |
---|
| 645 | message = self.config.getPoorWarn() |
---|
| 646 | else : |
---|
| 647 | message = self.config.getSoftWarn(printer.Name) |
---|
| 648 | if mailto in [ "BOTH", "USER", "EXTERNAL" ] : |
---|
| 649 | for user in self.storage.getGroupMembers(group) : |
---|
| 650 | if mailto != "EXTERNAL" : |
---|
| 651 | self.sendMessageToUser(admin, adminmail, user, _("Print Quota Exceeded"), message) |
---|
| 652 | else : |
---|
| 653 | self.externalMailTo(arguments, action, user, printer, message) |
---|
[927] | 654 | return action |
---|
[728] | 655 | |
---|
[1041] | 656 | def warnUserPQuota(self, userpquota) : |
---|
[728] | 657 | """Checks a user quota and send him a message if quota is exceeded on current printer.""" |
---|
[1041] | 658 | user = userpquota.User |
---|
[1245] | 659 | printer = userpquota.Printer |
---|
| 660 | admin = self.config.getAdmin(printer.Name) |
---|
| 661 | adminmail = self.config.getAdminMail(printer.Name) |
---|
| 662 | (mailto, arguments) = self.config.getMailTo(printer.Name) |
---|
[2547] | 663 | |
---|
| 664 | if user.LimitBy in ("noquota", "nochange") : |
---|
| 665 | action = "ALLOW" |
---|
| 666 | elif user.LimitBy == "noprint" : |
---|
| 667 | action = "DENY" |
---|
[2558] | 668 | message = _("User %s is not allowed to print at this time.") % user.Name |
---|
| 669 | self.printInfo(message) |
---|
[1245] | 670 | if mailto in [ "BOTH", "USER", "EXTERNAL" ] : |
---|
| 671 | if mailto != "EXTERNAL" : |
---|
[2547] | 672 | self.sendMessageToUser(admin, adminmail, user, _("Printing denied."), message) |
---|
[1245] | 673 | else : |
---|
| 674 | self.externalMailTo(arguments, action, user, printer, message) |
---|
| 675 | if mailto in [ "BOTH", "ADMIN" ] : |
---|
[2547] | 676 | self.sendMessageToAdmin(adminmail, _("Print Quota"), message) |
---|
| 677 | else : |
---|
| 678 | action = self.checkUserPQuota(userpquota) |
---|
| 679 | if action.startswith("POLICY_") : |
---|
| 680 | action = action[7:] |
---|
| 681 | |
---|
| 682 | if action == "DENY" : |
---|
| 683 | adminmessage = _("Print Quota exceeded for user %s on printer %s") % (user.Name, printer.Name) |
---|
| 684 | self.printInfo(adminmessage) |
---|
| 685 | if mailto in [ "BOTH", "USER", "EXTERNAL" ] : |
---|
| 686 | message = self.config.getHardWarn(printer.Name) |
---|
| 687 | if mailto != "EXTERNAL" : |
---|
| 688 | self.sendMessageToUser(admin, adminmail, user, _("Print Quota Exceeded"), message) |
---|
| 689 | else : |
---|
| 690 | self.externalMailTo(arguments, action, user, printer, message) |
---|
| 691 | if mailto in [ "BOTH", "ADMIN" ] : |
---|
| 692 | self.sendMessageToAdmin(adminmail, _("Print Quota"), adminmessage) |
---|
| 693 | elif action == "WARN" : |
---|
| 694 | adminmessage = _("Print Quota low for user %s on printer %s") % (user.Name, printer.Name) |
---|
| 695 | self.printInfo(adminmessage) |
---|
| 696 | if mailto in [ "BOTH", "USER", "EXTERNAL" ] : |
---|
| 697 | if user.LimitBy and (user.LimitBy.lower() == "balance") : |
---|
| 698 | message = self.config.getPoorWarn() |
---|
| 699 | else : |
---|
| 700 | message = self.config.getSoftWarn(printer.Name) |
---|
| 701 | if mailto != "EXTERNAL" : |
---|
| 702 | self.sendMessageToUser(admin, adminmail, user, _("Print Quota Low"), message) |
---|
| 703 | else : |
---|
| 704 | self.externalMailTo(arguments, action, user, printer, message) |
---|
| 705 | if mailto in [ "BOTH", "ADMIN" ] : |
---|
| 706 | self.sendMessageToAdmin(adminmail, _("Print Quota"), adminmessage) |
---|
[1245] | 707 | return action |
---|
[1196] | 708 | |
---|