Merge remote-tracking branch 'upstream/7.0' into 7.0-travis
[odoo/odoo.git] / openerp / tools / misc.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
6 #    Copyright (C) 2010-2013 OpenERP s.a. (<http://openerp.com>).
7 #
8 #    This program is free software: you can redistribute it and/or modify
9 #    it under the terms of the GNU Affero General Public License as
10 #    published by the Free Software Foundation, either version 3 of the
11 #    License, or (at your option) any later version.
12 #
13 #    This program is distributed in the hope that it will be useful,
14 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
15 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 #    GNU Affero General Public License for more details.
17 #
18 #    You should have received a copy of the GNU Affero General Public License
19 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 #
21 ##############################################################################
22
23 #.apidoc title: Utilities: tools.misc
24
25 """
26 Miscellaneous tools used by OpenERP.
27 """
28
29 from functools import wraps
30 import cProfile
31 import subprocess
32 import logging
33 import os
34 import socket
35 import sys
36 import threading
37 import time
38 import zipfile
39 from collections import defaultdict
40 from datetime import datetime
41 from itertools import islice, izip, groupby
42 from lxml import etree
43 from which import which
44 from threading import local
45
46 try:
47     from html2text import html2text
48 except ImportError:
49     html2text = None
50
51 from config import config
52 from cache import *
53
54 # get_encodings, ustr and exception_to_unicode were originally from tools.misc.
55 # There are moved to loglevels until we refactor tools.
56 from openerp.loglevels import get_encodings, ustr, exception_to_unicode
57
58 _logger = logging.getLogger(__name__)
59
60 # List of etree._Element subclasses that we choose to ignore when parsing XML.
61 # We include the *Base ones just in case, currently they seem to be subclasses of the _* ones.
62 SKIPPED_ELEMENT_TYPES = (etree._Comment, etree._ProcessingInstruction, etree.CommentBase, etree.PIBase)
63
64 def find_in_path(name):
65     try:
66         return which(name)
67     except IOError:
68         return None
69
70 def find_pg_tool(name):
71     path = None
72     if config['pg_path'] and config['pg_path'] != 'None':
73         path = config['pg_path']
74     try:
75         return which(name, path=path)
76     except IOError:
77         return None
78
79 def exec_pg_command(name, *args):
80     prog = find_pg_tool(name)
81     if not prog:
82         raise Exception('Couldn\'t find %s' % name)
83     args2 = (prog,) + args
84
85     return subprocess.call(args2)
86
87 def exec_pg_command_pipe(name, *args):
88     prog = find_pg_tool(name)
89     if not prog:
90         raise Exception('Couldn\'t find %s' % name)
91     # on win32, passing close_fds=True is not compatible
92     # with redirecting std[in/err/out]
93     pop = subprocess.Popen((prog,) + args, bufsize= -1,
94           stdin=subprocess.PIPE, stdout=subprocess.PIPE,
95           close_fds=(os.name=="posix"))
96     return pop.stdin, pop.stdout
97
98 def exec_command_pipe(name, *args):
99     prog = find_in_path(name)
100     if not prog:
101         raise Exception('Couldn\'t find %s' % name)
102     # on win32, passing close_fds=True is not compatible
103     # with redirecting std[in/err/out]
104     pop = subprocess.Popen((prog,) + args, bufsize= -1,
105           stdin=subprocess.PIPE, stdout=subprocess.PIPE,
106           close_fds=(os.name=="posix"))
107     return pop.stdin, pop.stdout
108
109 #----------------------------------------------------------
110 # File paths
111 #----------------------------------------------------------
112 #file_path_root = os.getcwd()
113 #file_path_addons = os.path.join(file_path_root, 'addons')
114
115 def file_open(name, mode="r", subdir='addons', pathinfo=False):
116     """Open a file from the OpenERP root, using a subdir folder.
117
118     Example::
119     
120     >>> file_open('hr/report/timesheer.xsl')
121     >>> file_open('addons/hr/report/timesheet.xsl')
122     >>> file_open('../../base/report/rml_template.xsl', subdir='addons/hr/report', pathinfo=True)
123
124     @param name name of the file
125     @param mode file open mode
126     @param subdir subdirectory
127     @param pathinfo if True returns tuple (fileobject, filepath)
128
129     @return fileobject if pathinfo is False else (fileobject, filepath)
130     """
131     import openerp.modules as addons
132     adps = addons.module.ad_paths
133     rtp = os.path.normcase(os.path.abspath(config['root_path']))
134
135     basename = name
136
137     if os.path.isabs(name):
138         # It is an absolute path
139         # Is it below 'addons_path' or 'root_path'?
140         name = os.path.normcase(os.path.normpath(name))
141         for root in adps + [rtp]:
142             root = os.path.normcase(os.path.normpath(root)) + os.sep
143             if name.startswith(root):
144                 base = root.rstrip(os.sep)
145                 name = name[len(base) + 1:]
146                 break
147         else:
148             # It is outside the OpenERP root: skip zipfile lookup.
149             base, name = os.path.split(name)
150         return _fileopen(name, mode=mode, basedir=base, pathinfo=pathinfo, basename=basename)
151
152     if name.replace(os.sep, '/').startswith('addons/'):
153         subdir = 'addons'
154         name2 = name[7:]
155     elif subdir:
156         name = os.path.join(subdir, name)
157         if name.replace(os.sep, '/').startswith('addons/'):
158             subdir = 'addons'
159             name2 = name[7:]
160         else:
161             name2 = name
162
163     # First, try to locate in addons_path
164     if subdir:
165         for adp in adps:
166             try:
167                 return _fileopen(name2, mode=mode, basedir=adp,
168                                  pathinfo=pathinfo, basename=basename)
169             except IOError:
170                 pass
171
172     # Second, try to locate in root_path
173     return _fileopen(name, mode=mode, basedir=rtp, pathinfo=pathinfo, basename=basename)
174
175
176 def _fileopen(path, mode, basedir, pathinfo, basename=None):
177     name = os.path.normpath(os.path.join(basedir, path))
178
179     if basename is None:
180         basename = name
181     # Give higher priority to module directories, which is
182     # a more common case than zipped modules.
183     if os.path.isfile(name):
184         fo = open(name, mode)
185         if pathinfo:
186             return fo, name
187         return fo
188
189     # Support for loading modules in zipped form.
190     # This will not work for zipped modules that are sitting
191     # outside of known addons paths.
192     head = os.path.normpath(path)
193     zipname = False
194     while os.sep in head:
195         head, tail = os.path.split(head)
196         if not tail:
197             break
198         if zipname:
199             zipname = os.path.join(tail, zipname)
200         else:
201             zipname = tail
202         zpath = os.path.join(basedir, head + '.zip')
203         if zipfile.is_zipfile(zpath):
204             from cStringIO import StringIO
205             zfile = zipfile.ZipFile(zpath)
206             try:
207                 fo = StringIO()
208                 fo.write(zfile.read(os.path.join(
209                     os.path.basename(head), zipname).replace(
210                         os.sep, '/')))
211                 fo.seek(0)
212                 if pathinfo:
213                     return fo, name
214                 return fo
215             except Exception:
216                 pass
217     # Not found
218     if name.endswith('.rml'):
219         raise IOError('Report %r doesn\'t exist or deleted' % basename)
220     raise IOError('File not found: %s' % basename)
221
222
223 #----------------------------------------------------------
224 # iterables
225 #----------------------------------------------------------
226 def flatten(list):
227     """Flatten a list of elements into a uniqu list
228     Author: Christophe Simonis (christophe@tinyerp.com)
229
230     Examples::
231     >>> flatten(['a'])
232     ['a']
233     >>> flatten('b')
234     ['b']
235     >>> flatten( [] )
236     []
237     >>> flatten( [[], [[]]] )
238     []
239     >>> flatten( [[['a','b'], 'c'], 'd', ['e', [], 'f']] )
240     ['a', 'b', 'c', 'd', 'e', 'f']
241     >>> t = (1,2,(3,), [4, 5, [6, [7], (8, 9), ([10, 11, (12, 13)]), [14, [], (15,)], []]])
242     >>> flatten(t)
243     [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
244     """
245
246     def isiterable(x):
247         return hasattr(x, "__iter__")
248
249     r = []
250     for e in list:
251         if isiterable(e):
252             map(r.append, flatten(e))
253         else:
254             r.append(e)
255     return r
256
257 def reverse_enumerate(l):
258     """Like enumerate but in the other sens
259     
260     Usage::
261     >>> a = ['a', 'b', 'c']
262     >>> it = reverse_enumerate(a)
263     >>> it.next()
264     (2, 'c')
265     >>> it.next()
266     (1, 'b')
267     >>> it.next()
268     (0, 'a')
269     >>> it.next()
270     Traceback (most recent call last):
271       File "<stdin>", line 1, in <module>
272     StopIteration
273     """
274     return izip(xrange(len(l)-1, -1, -1), reversed(l))
275
276 #----------------------------------------------------------
277 # SMS
278 #----------------------------------------------------------
279 # text must be latin-1 encoded
280 def sms_send(user, password, api_id, text, to):
281     import urllib
282     url = "http://api.urlsms.com/SendSMS.aspx"
283     #url = "http://196.7.150.220/http/sendmsg"
284     params = urllib.urlencode({'UserID': user, 'Password': password, 'SenderID': api_id, 'MsgText': text, 'RecipientMobileNo':to})
285     urllib.urlopen(url+"?"+params)
286     # FIXME: Use the logger if there is an error
287     return True
288
289 class UpdateableStr(local):
290     """ Class that stores an updateable string (used in wizards)
291     """
292
293     def __init__(self, string=''):
294         self.string = string
295
296     def __str__(self):
297         return str(self.string)
298
299     def __repr__(self):
300         return str(self.string)
301
302     def __nonzero__(self):
303         return bool(self.string)
304
305
306 class UpdateableDict(local):
307     """Stores an updateable dict to use in wizards
308     """
309
310     def __init__(self, dict=None):
311         if dict is None:
312             dict = {}
313         self.dict = dict
314
315     def __str__(self):
316         return str(self.dict)
317
318     def __repr__(self):
319         return str(self.dict)
320
321     def clear(self):
322         return self.dict.clear()
323
324     def keys(self):
325         return self.dict.keys()
326
327     def __setitem__(self, i, y):
328         self.dict.__setitem__(i, y)
329
330     def __getitem__(self, i):
331         return self.dict.__getitem__(i)
332
333     def copy(self):
334         return self.dict.copy()
335
336     def iteritems(self):
337         return self.dict.iteritems()
338
339     def iterkeys(self):
340         return self.dict.iterkeys()
341
342     def itervalues(self):
343         return self.dict.itervalues()
344
345     def pop(self, k, d=None):
346         return self.dict.pop(k, d)
347
348     def popitem(self):
349         return self.dict.popitem()
350
351     def setdefault(self, k, d=None):
352         return self.dict.setdefault(k, d)
353
354     def update(self, E, **F):
355         return self.dict.update(E, F)
356
357     def values(self):
358         return self.dict.values()
359
360     def get(self, k, d=None):
361         return self.dict.get(k, d)
362
363     def has_key(self, k):
364         return self.dict.has_key(k)
365
366     def items(self):
367         return self.dict.items()
368
369     def __cmp__(self, y):
370         return self.dict.__cmp__(y)
371
372     def __contains__(self, k):
373         return self.dict.__contains__(k)
374
375     def __delitem__(self, y):
376         return self.dict.__delitem__(y)
377
378     def __eq__(self, y):
379         return self.dict.__eq__(y)
380
381     def __ge__(self, y):
382         return self.dict.__ge__(y)
383
384     def __gt__(self, y):
385         return self.dict.__gt__(y)
386
387     def __hash__(self):
388         return self.dict.__hash__()
389
390     def __iter__(self):
391         return self.dict.__iter__()
392
393     def __le__(self, y):
394         return self.dict.__le__(y)
395
396     def __len__(self):
397         return self.dict.__len__()
398
399     def __lt__(self, y):
400         return self.dict.__lt__(y)
401
402     def __ne__(self, y):
403         return self.dict.__ne__(y)
404
405 class currency(float):
406     """ Deprecate
407     
408     .. warning::
409     
410     Don't use ! Use res.currency.round()
411     """
412
413     def __init__(self, value, accuracy=2, rounding=None):
414         if rounding is None:
415             rounding=10**-accuracy
416         self.rounding=rounding
417         self.accuracy=accuracy
418
419     def __new__(cls, value, accuracy=2, rounding=None):
420         return float.__new__(cls, round(value, accuracy))
421
422     #def __str__(self):
423     #   display_value = int(self*(10**(-self.accuracy))/self.rounding)*self.rounding/(10**(-self.accuracy))
424     #   return str(display_value)
425
426 def to_xml(s):
427     return s.replace('&','&amp;').replace('<','&lt;').replace('>','&gt;')
428
429 def get_iso_codes(lang):
430     if lang.find('_') != -1:
431         if lang.split('_')[0] == lang.split('_')[1].lower():
432             lang = lang.split('_')[0]
433     return lang
434
435 ALL_LANGUAGES = {
436         'ab_RU': u'Abkhazian / аҧсуа',
437         'am_ET': u'Amharic / አምሃርኛ',
438         'ar_SY': u'Arabic / الْعَرَبيّة',
439         'bg_BG': u'Bulgarian / български език',
440         'bs_BS': u'Bosnian / bosanski jezik',
441         'ca_ES': u'Catalan / Català',
442         'cs_CZ': u'Czech / Čeština',
443         'da_DK': u'Danish / Dansk',
444         'de_DE': u'German / Deutsch',
445         'el_GR': u'Greek / Ελληνικά',
446         'en_CA': u'English (CA)',
447         'en_GB': u'English (UK)',
448         'en_US': u'English (US)',
449         'es_AR': u'Spanish (AR) / Español (AR)',
450         'es_BO': u'Spanish (BO) / Español (BO)',
451         'es_CL': u'Spanish (CL) / Español (CL)',
452         'es_CO': u'Spanish (CO) / Español (CO)',
453         'es_CR': u'Spanish (CR) / Español (CR)',
454         'es_DO': u'Spanish (DO) / Español (DO)',
455         'es_EC': u'Spanish (EC) / Español (EC)',
456         'es_ES': u'Spanish / Español',
457         'es_GT': u'Spanish (GT) / Español (GT)',
458         'es_HN': u'Spanish (HN) / Español (HN)',
459         'es_MX': u'Spanish (MX) / Español (MX)',
460         'es_NI': u'Spanish (NI) / Español (NI)',
461         'es_PA': u'Spanish (PA) / Español (PA)',
462         'es_PE': u'Spanish (PE) / Español (PE)',
463         'es_PR': u'Spanish (PR) / Español (PR)',
464         'es_PY': u'Spanish (PY) / Español (PY)',
465         'es_SV': u'Spanish (SV) / Español (SV)',
466         'es_UY': u'Spanish (UY) / Español (UY)',
467         'es_VE': u'Spanish (VE) / Español (VE)',
468         'et_EE': u'Estonian / Eesti keel',
469         'fa_IR': u'Persian / فارس',
470         'fi_FI': u'Finnish / Suomi',
471         'fr_BE': u'French (BE) / Français (BE)',
472         'fr_CH': u'French (CH) / Français (CH)',
473         'fr_FR': u'French / Français',
474         'gl_ES': u'Galician / Galego',
475         'gu_IN': u'Gujarati / ગુજરાતી',
476         'he_IL': u'Hebrew / עִבְרִי',
477         'hi_IN': u'Hindi / हिंदी',
478         'hr_HR': u'Croatian / hrvatski jezik',
479         'hu_HU': u'Hungarian / Magyar',
480         'id_ID': u'Indonesian / Bahasa Indonesia',
481         'it_IT': u'Italian / Italiano',
482         'iu_CA': u'Inuktitut / ᐃᓄᒃᑎᑐᑦ',
483         'ja_JP': u'Japanese / 日本語',
484         'ko_KP': u'Korean (KP) / 한국어 (KP)',
485         'ko_KR': u'Korean (KR) / 한국어 (KR)',
486         'lo_LA': u'Lao / ພາສາລາວ',
487         'lt_LT': u'Lithuanian / Lietuvių kalba',
488         'lv_LV': u'Latvian / latviešu valoda',
489         'mk_MK': u'Macedonian / македонски јазик',
490         'ml_IN': u'Malayalam / മലയാളം',
491         'mn_MN': u'Mongolian / монгол',
492         'nb_NO': u'Norwegian Bokmål / Norsk bokmål',
493         'nl_NL': u'Dutch / Nederlands',
494         'nl_BE': u'Flemish (BE) / Vlaams (BE)',
495         'oc_FR': u'Occitan (FR, post 1500) / Occitan',
496         'pl_PL': u'Polish / Język polski',
497         'pt_BR': u'Portuguese (BR) / Português (BR)',
498         'pt_PT': u'Portuguese / Português',
499         'ro_RO': u'Romanian / română',
500         'ru_RU': u'Russian / русский язык',
501         'si_LK': u'Sinhalese / සිංහල',
502         'sl_SI': u'Slovenian / slovenščina',
503         'sk_SK': u'Slovak / Slovenský jazyk',
504         'sq_AL': u'Albanian / Shqip',
505         'sr_RS': u'Serbian (Cyrillic) / српски',
506         'sr@latin': u'Serbian (Latin) / srpski',
507         'sv_SE': u'Swedish / svenska',
508         'te_IN': u'Telugu / తెలుగు',
509         'tr_TR': u'Turkish / Türkçe',
510         'vi_VN': u'Vietnamese / Tiếng Việt',
511         'uk_UA': u'Ukrainian / українська',
512         'ur_PK': u'Urdu / اردو',
513         'zh_CN': u'Chinese (CN) / 简体中文',
514         'zh_HK': u'Chinese (HK)',
515         'zh_TW': u'Chinese (TW) / 正體字',
516         'th_TH': u'Thai / ภาษาไทย',
517         'tlh_TLH': u'Klingon',
518     }
519
520 def scan_languages():
521     """ Returns all languages supported by OpenERP for translation
522
523     :returns: a list of (lang_code, lang_name) pairs
524     :rtype: [(str, unicode)]
525     """
526     return sorted(ALL_LANGUAGES.iteritems(), key=lambda k: k[1])
527
528 def get_user_companies(cr, user):
529     def _get_company_children(cr, ids):
530         if not ids:
531             return []
532         cr.execute('SELECT id FROM res_company WHERE parent_id IN %s', (tuple(ids),))
533         res = [x[0] for x in cr.fetchall()]
534         res.extend(_get_company_children(cr, res))
535         return res
536     cr.execute('SELECT company_id FROM res_users WHERE id=%s', (user,))
537     user_comp = cr.fetchone()[0]
538     if not user_comp:
539         return []
540     return [user_comp] + _get_company_children(cr, [user_comp])
541
542 def mod10r(number):
543     """
544     Input number : account or invoice number
545     Output return: the same number completed with the recursive mod10
546     key
547     """
548     codec=[0,9,4,6,8,2,7,1,3,5]
549     report = 0
550     result=""
551     for digit in number:
552         result += digit
553         if digit.isdigit():
554             report = codec[ (int(digit) + report) % 10 ]
555     return result + str((10 - report) % 10)
556
557
558 def human_size(sz):
559     """
560     Return the size in a human readable format
561     """
562     if not sz:
563         return False
564     units = ('bytes', 'Kb', 'Mb', 'Gb')
565     if isinstance(sz,basestring):
566         sz=len(sz)
567     s, i = float(sz), 0
568     while s >= 1024 and i < len(units)-1:
569         s /= 1024
570         i += 1
571     return "%0.2f %s" % (s, units[i])
572
573 def logged(f):
574     @wraps(f)
575     def wrapper(*args, **kwargs):
576         from pprint import pformat
577
578         vector = ['Call -> function: %r' % f]
579         for i, arg in enumerate(args):
580             vector.append('  arg %02d: %s' % (i, pformat(arg)))
581         for key, value in kwargs.items():
582             vector.append('  kwarg %10s: %s' % (key, pformat(value)))
583
584         timeb4 = time.time()
585         res = f(*args, **kwargs)
586
587         vector.append('  result: %s' % pformat(res))
588         vector.append('  time delta: %s' % (time.time() - timeb4))
589         _logger.debug('\n'.join(vector))
590         return res
591
592     return wrapper
593
594 class profile(object):
595     def __init__(self, fname=None):
596         self.fname = fname
597
598     def __call__(self, f):
599         @wraps(f)
600         def wrapper(*args, **kwargs):
601             profile = cProfile.Profile()
602             result = profile.runcall(f, *args, **kwargs)
603             profile.dump_stats(self.fname or ("%s.cprof" % (f.func_name,)))
604             return result
605
606         return wrapper
607
608 __icons_list = ['STOCK_ABOUT', 'STOCK_ADD', 'STOCK_APPLY', 'STOCK_BOLD',
609 'STOCK_CANCEL', 'STOCK_CDROM', 'STOCK_CLEAR', 'STOCK_CLOSE', 'STOCK_COLOR_PICKER',
610 'STOCK_CONNECT', 'STOCK_CONVERT', 'STOCK_COPY', 'STOCK_CUT', 'STOCK_DELETE',
611 'STOCK_DIALOG_AUTHENTICATION', 'STOCK_DIALOG_ERROR', 'STOCK_DIALOG_INFO',
612 'STOCK_DIALOG_QUESTION', 'STOCK_DIALOG_WARNING', 'STOCK_DIRECTORY', 'STOCK_DISCONNECT',
613 'STOCK_DND', 'STOCK_DND_MULTIPLE', 'STOCK_EDIT', 'STOCK_EXECUTE', 'STOCK_FILE',
614 'STOCK_FIND', 'STOCK_FIND_AND_REPLACE', 'STOCK_FLOPPY', 'STOCK_GOTO_BOTTOM',
615 'STOCK_GOTO_FIRST', 'STOCK_GOTO_LAST', 'STOCK_GOTO_TOP', 'STOCK_GO_BACK',
616 'STOCK_GO_DOWN', 'STOCK_GO_FORWARD', 'STOCK_GO_UP', 'STOCK_HARDDISK',
617 'STOCK_HELP', 'STOCK_HOME', 'STOCK_INDENT', 'STOCK_INDEX', 'STOCK_ITALIC',
618 'STOCK_JUMP_TO', 'STOCK_JUSTIFY_CENTER', 'STOCK_JUSTIFY_FILL',
619 'STOCK_JUSTIFY_LEFT', 'STOCK_JUSTIFY_RIGHT', 'STOCK_MEDIA_FORWARD',
620 'STOCK_MEDIA_NEXT', 'STOCK_MEDIA_PAUSE', 'STOCK_MEDIA_PLAY',
621 'STOCK_MEDIA_PREVIOUS', 'STOCK_MEDIA_RECORD', 'STOCK_MEDIA_REWIND',
622 'STOCK_MEDIA_STOP', 'STOCK_MISSING_IMAGE', 'STOCK_NETWORK', 'STOCK_NEW',
623 'STOCK_NO', 'STOCK_OK', 'STOCK_OPEN', 'STOCK_PASTE', 'STOCK_PREFERENCES',
624 'STOCK_PRINT', 'STOCK_PRINT_PREVIEW', 'STOCK_PROPERTIES', 'STOCK_QUIT',
625 'STOCK_REDO', 'STOCK_REFRESH', 'STOCK_REMOVE', 'STOCK_REVERT_TO_SAVED',
626 'STOCK_SAVE', 'STOCK_SAVE_AS', 'STOCK_SELECT_COLOR', 'STOCK_SELECT_FONT',
627 'STOCK_SORT_ASCENDING', 'STOCK_SORT_DESCENDING', 'STOCK_SPELL_CHECK',
628 'STOCK_STOP', 'STOCK_STRIKETHROUGH', 'STOCK_UNDELETE', 'STOCK_UNDERLINE',
629 'STOCK_UNDO', 'STOCK_UNINDENT', 'STOCK_YES', 'STOCK_ZOOM_100',
630 'STOCK_ZOOM_FIT', 'STOCK_ZOOM_IN', 'STOCK_ZOOM_OUT',
631 'terp-account', 'terp-crm', 'terp-mrp', 'terp-product', 'terp-purchase',
632 'terp-sale', 'terp-tools', 'terp-administration', 'terp-hr', 'terp-partner',
633 'terp-project', 'terp-report', 'terp-stock', 'terp-calendar', 'terp-graph',
634 'terp-check','terp-go-month','terp-go-year','terp-go-today','terp-document-new','terp-camera_test',
635 'terp-emblem-important','terp-gtk-media-pause','terp-gtk-stop','terp-gnome-cpu-frequency-applet+',
636 'terp-dialog-close','terp-gtk-jump-to-rtl','terp-gtk-jump-to-ltr','terp-accessories-archiver',
637 'terp-stock_align_left_24','terp-stock_effects-object-colorize','terp-go-home','terp-gtk-go-back-rtl',
638 'terp-gtk-go-back-ltr','terp-personal','terp-personal-','terp-personal+','terp-accessories-archiver-minus',
639 'terp-accessories-archiver+','terp-stock_symbol-selection','terp-call-start','terp-dolar',
640 'terp-face-plain','terp-folder-blue','terp-folder-green','terp-folder-orange','terp-folder-yellow',
641 'terp-gdu-smart-failing','terp-go-week','terp-gtk-select-all','terp-locked','terp-mail-forward',
642 'terp-mail-message-new','terp-mail-replied','terp-rating-rated','terp-stage','terp-stock_format-scientific',
643 'terp-dolar_ok!','terp-idea','terp-stock_format-default','terp-mail-','terp-mail_delete'
644 ]
645
646 def icons(*a, **kw):
647     global __icons_list
648     return [(x, x) for x in __icons_list ]
649
650 def extract_zip_file(zip_file, outdirectory):
651     zf = zipfile.ZipFile(zip_file, 'r')
652     out = outdirectory
653     for path in zf.namelist():
654         tgt = os.path.join(out, path)
655         tgtdir = os.path.dirname(tgt)
656         if not os.path.exists(tgtdir):
657             os.makedirs(tgtdir)
658
659         if not tgt.endswith(os.sep):
660             fp = open(tgt, 'wb')
661             fp.write(zf.read(path))
662             fp.close()
663     zf.close()
664
665 def detect_ip_addr():
666     """Try a very crude method to figure out a valid external
667        IP or hostname for the current machine. Don't rely on this
668        for binding to an interface, but it could be used as basis
669        for constructing a remote URL to the server.
670     """
671     def _detect_ip_addr():
672         from array import array
673         from struct import pack, unpack
674
675         try:
676             import fcntl
677         except ImportError:
678             fcntl = None
679
680         ip_addr = None
681
682         if not fcntl: # not UNIX:
683             host = socket.gethostname()
684             ip_addr = socket.gethostbyname(host)
685         else: # UNIX:
686             # get all interfaces:
687             nbytes = 128 * 32
688             s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
689             names = array('B', '\0' * nbytes)
690             #print 'names: ', names
691             outbytes = unpack('iL', fcntl.ioctl( s.fileno(), 0x8912, pack('iL', nbytes, names.buffer_info()[0])))[0]
692             namestr = names.tostring()
693
694             # try 64 bit kernel:
695             for i in range(0, outbytes, 40):
696                 name = namestr[i:i+16].split('\0', 1)[0]
697                 if name != 'lo':
698                     ip_addr = socket.inet_ntoa(namestr[i+20:i+24])
699                     break
700
701             # try 32 bit kernel:
702             if ip_addr is None:
703                 ifaces = filter(None, [namestr[i:i+32].split('\0', 1)[0] for i in range(0, outbytes, 32)])
704
705                 for ifname in [iface for iface in ifaces if iface != 'lo']:
706                     ip_addr = socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915, pack('256s', ifname[:15]))[20:24])
707                     break
708
709         return ip_addr or 'localhost'
710
711     try:
712         ip_addr = _detect_ip_addr()
713     except Exception:
714         ip_addr = 'localhost'
715     return ip_addr
716
717 # RATIONALE BEHIND TIMESTAMP CALCULATIONS AND TIMEZONE MANAGEMENT:
718 #  The server side never does any timestamp calculation, always
719 #  sends them in a naive (timezone agnostic) format supposed to be
720 #  expressed within the server timezone, and expects the clients to
721 #  provide timestamps in the server timezone as well.
722 #  It stores all timestamps in the database in naive format as well,
723 #  which also expresses the time in the server timezone.
724 #  For this reason the server makes its timezone name available via the
725 #  common/timezone_get() rpc method, which clients need to read
726 #  to know the appropriate time offset to use when reading/writing
727 #  times.
728 def get_win32_timezone():
729     """Attempt to return the "standard name" of the current timezone on a win32 system.
730        @return the standard name of the current win32 timezone, or False if it cannot be found.
731     """
732     res = False
733     if sys.platform == "win32":
734         try:
735             import _winreg
736             hklm = _winreg.ConnectRegistry(None,_winreg.HKEY_LOCAL_MACHINE)
737             current_tz_key = _winreg.OpenKey(hklm, r"SYSTEM\CurrentControlSet\Control\TimeZoneInformation", 0,_winreg.KEY_ALL_ACCESS)
738             res = str(_winreg.QueryValueEx(current_tz_key,"StandardName")[0])  # [0] is value, [1] is type code
739             _winreg.CloseKey(current_tz_key)
740             _winreg.CloseKey(hklm)
741         except Exception:
742             pass
743     return res
744
745 def detect_server_timezone():
746     """Attempt to detect the timezone to use on the server side.
747        Defaults to UTC if no working timezone can be found.
748        @return the timezone identifier as expected by pytz.timezone.
749     """
750     try:
751         import pytz
752     except Exception:
753         _logger.warning("Python pytz module is not available. "
754             "Timezone will be set to UTC by default.")
755         return 'UTC'
756
757     # Option 1: the configuration option (did not exist before, so no backwards compatibility issue)
758     # Option 2: to be backwards compatible with 5.0 or earlier, the value from time.tzname[0], but only if it is known to pytz
759     # Option 3: the environment variable TZ
760     sources = [ (config['timezone'], 'OpenERP configuration'),
761                 (time.tzname[0], 'time.tzname'),
762                 (os.environ.get('TZ',False),'TZ environment variable'), ]
763     # Option 4: OS-specific: /etc/timezone on Unix
764     if os.path.exists("/etc/timezone"):
765         tz_value = False
766         try:
767             f = open("/etc/timezone")
768             tz_value = f.read(128).strip()
769         except Exception:
770             pass
771         finally:
772             f.close()
773         sources.append((tz_value,"/etc/timezone file"))
774     # Option 5: timezone info from registry on Win32
775     if sys.platform == "win32":
776         # Timezone info is stored in windows registry.
777         # However this is not likely to work very well as the standard name
778         # of timezones in windows is rarely something that is known to pytz.
779         # But that's ok, it is always possible to use a config option to set
780         # it explicitly.
781         sources.append((get_win32_timezone(),"Windows Registry"))
782
783     for (value,source) in sources:
784         if value:
785             try:
786                 tz = pytz.timezone(value)
787                 _logger.info("Using timezone %s obtained from %s.", tz.zone, source)
788                 return value
789             except pytz.UnknownTimeZoneError:
790                 _logger.warning("The timezone specified in %s (%s) is invalid, ignoring it.", source, value)
791
792     _logger.warning("No valid timezone could be detected, using default UTC "
793         "timezone. You can specify it explicitly with option 'timezone' in "
794         "the server configuration.")
795     return 'UTC'
796
797 def get_server_timezone():
798     return "UTC"
799
800
801 DEFAULT_SERVER_DATE_FORMAT = "%Y-%m-%d"
802 DEFAULT_SERVER_TIME_FORMAT = "%H:%M:%S"
803 DEFAULT_SERVER_DATETIME_FORMAT = "%s %s" % (
804     DEFAULT_SERVER_DATE_FORMAT,
805     DEFAULT_SERVER_TIME_FORMAT)
806
807 # Python's strftime supports only the format directives
808 # that are available on the platform's libc, so in order to
809 # be cross-platform we map to the directives required by
810 # the C standard (1989 version), always available on platforms
811 # with a C standard implementation.
812 DATETIME_FORMATS_MAP = {
813         '%C': '', # century
814         '%D': '%m/%d/%Y', # modified %y->%Y
815         '%e': '%d',
816         '%E': '', # special modifier
817         '%F': '%Y-%m-%d',
818         '%g': '%Y', # modified %y->%Y
819         '%G': '%Y',
820         '%h': '%b',
821         '%k': '%H',
822         '%l': '%I',
823         '%n': '\n',
824         '%O': '', # special modifier
825         '%P': '%p',
826         '%R': '%H:%M',
827         '%r': '%I:%M:%S %p',
828         '%s': '', #num of seconds since epoch
829         '%T': '%H:%M:%S',
830         '%t': ' ', # tab
831         '%u': ' %w',
832         '%V': '%W',
833         '%y': '%Y', # Even if %y works, it's ambiguous, so we should use %Y
834         '%+': '%Y-%m-%d %H:%M:%S',
835
836         # %Z is a special case that causes 2 problems at least:
837         #  - the timezone names we use (in res_user.context_tz) come
838         #    from pytz, but not all these names are recognized by
839         #    strptime(), so we cannot convert in both directions
840         #    when such a timezone is selected and %Z is in the format
841         #  - %Z is replaced by an empty string in strftime() when
842         #    there is not tzinfo in a datetime value (e.g when the user
843         #    did not pick a context_tz). The resulting string does not
844         #    parse back if the format requires %Z.
845         # As a consequence, we strip it completely from format strings.
846         # The user can always have a look at the context_tz in
847         # preferences to check the timezone.
848         '%z': '',
849         '%Z': '',
850 }
851
852 def server_to_local_timestamp(src_tstamp_str, src_format, dst_format, dst_tz_name,
853         tz_offset=True, ignore_unparsable_time=True):
854     """
855     Convert a source timestamp string into a destination timestamp string, attempting to apply the
856     correct offset if both the server and local timezone are recognized, or no
857     offset at all if they aren't or if tz_offset is false (i.e. assuming they are both in the same TZ).
858
859     WARNING: This method is here to allow formatting dates correctly for inclusion in strings where
860              the client would not be able to format/offset it correctly. DO NOT use it for returning
861              date fields directly, these are supposed to be handled by the client!!
862
863     @param src_tstamp_str: the str value containing the timestamp in the server timezone.
864     @param src_format: the format to use when parsing the server timestamp.
865     @param dst_format: the format to use when formatting the resulting timestamp for the local/client timezone.
866     @param dst_tz_name: name of the destination timezone (such as the 'tz' value of the client context)
867     @param ignore_unparsable_time: if True, return False if src_tstamp_str cannot be parsed
868                                    using src_format or formatted using dst_format.
869
870     @return local/client formatted timestamp, expressed in the local/client timezone if possible
871             and if tz_offset is true, or src_tstamp_str if timezone offset could not be determined.
872     """
873     if not src_tstamp_str:
874         return False
875
876     res = src_tstamp_str
877     if src_format and dst_format:
878         # find out server timezone
879         server_tz = get_server_timezone()
880         try:
881             # dt_value needs to be a datetime.datetime object (so no time.struct_time or mx.DateTime.DateTime here!)
882             dt_value = datetime.strptime(src_tstamp_str, src_format)
883             if tz_offset and dst_tz_name:
884                 try:
885                     import pytz
886                     src_tz = pytz.timezone(server_tz)
887                     dst_tz = pytz.timezone(dst_tz_name)
888                     src_dt = src_tz.localize(dt_value, is_dst=True)
889                     dt_value = src_dt.astimezone(dst_tz)
890                 except Exception:
891                     pass
892             res = dt_value.strftime(dst_format)
893         except Exception:
894             # Normal ways to end up here are if strptime or strftime failed
895             if not ignore_unparsable_time:
896                 return False
897     return res
898
899
900 def split_every(n, iterable, piece_maker=tuple):
901     """Splits an iterable into length-n pieces. The last piece will be shorter
902        if ``n`` does not evenly divide the iterable length.
903        @param ``piece_maker``: function to build the pieces
904        from the slices (tuple,list,...)
905     """
906     iterator = iter(iterable)
907     piece = piece_maker(islice(iterator, n))
908     while piece:
909         yield piece
910         piece = piece_maker(islice(iterator, n))
911
912 if __name__ == '__main__':
913     import doctest
914     doctest.testmod()
915
916 class upload_data_thread(threading.Thread):
917     def __init__(self, email, data, type):
918         self.args = [('email',email),('type',type),('data',data)]
919         super(upload_data_thread,self).__init__()
920     def run(self):
921         try:
922             import urllib
923             args = urllib.urlencode(self.args)
924             fp = urllib.urlopen('http://www.openerp.com/scripts/survey.php', args)
925             fp.read()
926             fp.close()
927         except Exception:
928             pass
929
930 def upload_data(email, data, type='SURVEY'):
931     a = upload_data_thread(email, data, type)
932     a.start()
933     return True
934
935 def get_and_group_by_field(cr, uid, obj, ids, field, context=None):
936     """ Read the values of ``field´´ for the given ``ids´´ and group ids by value.
937
938        :param string field: name of the field we want to read and group by
939        :return: mapping of field values to the list of ids that have it
940        :rtype: dict
941     """
942     res = {}
943     for record in obj.read(cr, uid, ids, [field], context=context):
944         key = record[field]
945         res.setdefault(key[0] if isinstance(key, tuple) else key, []).append(record['id'])
946     return res
947
948 def get_and_group_by_company(cr, uid, obj, ids, context=None):
949     return get_and_group_by_field(cr, uid, obj, ids, field='company_id', context=context)
950
951 # port of python 2.6's attrgetter with support for dotted notation
952 def resolve_attr(obj, attr):
953     for name in attr.split("."):
954         obj = getattr(obj, name)
955     return obj
956
957 def attrgetter(*items):
958     if len(items) == 1:
959         attr = items[0]
960         def g(obj):
961             return resolve_attr(obj, attr)
962     else:
963         def g(obj):
964             return tuple(resolve_attr(obj, attr) for attr in items)
965     return g
966
967 class unquote(str):
968     """A subclass of str that implements repr() without enclosing quotation marks
969        or escaping, keeping the original string untouched. The name come from Lisp's unquote.
970        One of the uses for this is to preserve or insert bare variable names within dicts during eval()
971        of a dict's repr(). Use with care.
972
973        Some examples (notice that there are never quotes surrounding
974        the ``active_id`` name:
975
976        >>> unquote('active_id')
977        active_id
978        >>> d = {'test': unquote('active_id')}
979        >>> d
980        {'test': active_id}
981        >>> print d
982        {'test': active_id}
983     """
984     def __repr__(self):
985         return self
986
987 class UnquoteEvalContext(defaultdict):
988     """Defaultdict-based evaluation context that returns 
989        an ``unquote`` string for any missing name used during
990        the evaluation.
991        Mostly useful for evaluating OpenERP domains/contexts that
992        may refer to names that are unknown at the time of eval,
993        so that when the context/domain is converted back to a string,
994        the original names are preserved.
995
996        **Warning**: using an ``UnquoteEvalContext`` as context for ``eval()`` or
997        ``safe_eval()`` will shadow the builtins, which may cause other
998        failures, depending on what is evaluated.
999
1000        Example (notice that ``section_id`` is preserved in the final
1001        result) :
1002
1003        >>> context_str = "{'default_user_id': uid, 'default_section_id': section_id}"
1004        >>> eval(context_str, UnquoteEvalContext(uid=1))
1005        {'default_user_id': 1, 'default_section_id': section_id}
1006
1007        """
1008     def __init__(self, *args, **kwargs):
1009         super(UnquoteEvalContext, self).__init__(None, *args, **kwargs)
1010
1011     def __missing__(self, key):
1012         return unquote(key)
1013
1014
1015 class mute_logger(object):
1016     """Temporary suppress the logging.
1017     Can be used as context manager or decorator.
1018
1019         @mute_logger('openerp.plic.ploc')
1020         def do_stuff():
1021             blahblah()
1022
1023         with mute_logger('openerp.foo.bar'):
1024             do_suff()
1025
1026     """
1027     def __init__(self, *loggers):
1028         self.loggers = loggers
1029
1030     def filter(self, record):
1031         return 0
1032
1033     def __enter__(self):
1034         for logger in self.loggers:
1035             logging.getLogger(logger).addFilter(self)
1036
1037     def __exit__(self, exc_type=None, exc_val=None, exc_tb=None):
1038         for logger in self.loggers:
1039             logging.getLogger(logger).removeFilter(self)
1040
1041     def __call__(self, func):
1042         @wraps(func)
1043         def deco(*args, **kwargs):
1044             with self:
1045                 return func(*args, **kwargs)
1046         return deco
1047
1048 _ph = object()
1049 class CountingStream(object):
1050     """ Stream wrapper counting the number of element it has yielded. Similar
1051     role to ``enumerate``, but for use when the iteration process of the stream
1052     isn't fully under caller control (the stream can be iterated from multiple
1053     points including within a library)
1054
1055     ``start`` allows overriding the starting index (the index before the first
1056     item is returned).
1057
1058     On each iteration (call to :meth:`~.next`), increases its :attr:`~.index`
1059     by one.
1060
1061     .. attribute:: index
1062
1063         ``int``, index of the last yielded element in the stream. If the stream
1064         has ended, will give an index 1-past the stream
1065     """
1066     def __init__(self, stream, start=-1):
1067         self.stream = iter(stream)
1068         self.index = start
1069         self.stopped = False
1070     def __iter__(self):
1071         return self
1072     def next(self):
1073         if self.stopped: raise StopIteration()
1074         self.index += 1
1075         val = next(self.stream, _ph)
1076         if val is _ph:
1077             self.stopped = True
1078             raise StopIteration()
1079         return val
1080
1081 def stripped_sys_argv(*strip_args):
1082     """Return sys.argv with some arguments stripped, suitable for reexecution or subprocesses"""
1083     strip_args = sorted(set(strip_args) | set(['-s', '--save', '-d', '--database', '-u', '--update', '-i', '--init']))
1084     assert all(config.parser.has_option(s) for s in strip_args)
1085     takes_value = dict((s, config.parser.get_option(s).takes_value()) for s in strip_args)
1086
1087     longs, shorts = list(tuple(y) for _, y in groupby(strip_args, lambda x: x.startswith('--')))
1088     longs_eq = tuple(l + '=' for l in longs if takes_value[l])
1089
1090     args = sys.argv[:]
1091
1092     def strip(args, i):
1093         return args[i].startswith(shorts) \
1094             or args[i].startswith(longs_eq) or (args[i] in longs) \
1095             or (i >= 1 and (args[i - 1] in strip_args) and takes_value[args[i - 1]])
1096
1097     return [x for i, x in enumerate(args) if not strip(args, i)]
1098
1099 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: