Commit 8024ba17 authored by Arnaud Fontaine's avatar Arnaud Fontaine

2to3: Make Products code compatible with both python2 and python3.

parent d12a23fe
...@@ -101,7 +101,7 @@ class ActiveProcess(Base): ...@@ -101,7 +101,7 @@ class ActiveProcess(Base):
# use a random id in order to store result in a way with # use a random id in order to store result in a way with
# fewer conflict errors # fewer conflict errors
random_id = randrange(0, 10000 * (self.result_len.value + 1)) random_id = randrange(0, 10000 * (self.result_len.value + 1))
while result_list.has_key(random_id): while random_id in result_list:
random_id += 1 random_id += 1
result_list[random_id] = result result_list[random_id] = result
self.result_len.change(1) self.result_len.change(1)
...@@ -132,7 +132,7 @@ class ActiveProcess(Base): ...@@ -132,7 +132,7 @@ class ActiveProcess(Base):
# moment, although this is inefficient and the caller never needs a # moment, although this is inefficient and the caller never needs a
# copy (currently). Same for IOBTree.itervalues(). # copy (currently). Same for IOBTree.itervalues().
if type(result_list) is not ConflictFreeLog: # BBB: result_list is IOBTree if type(result_list) is not ConflictFreeLog: # BBB: result_list is IOBTree
return result_list.values() return list(result_list.values())
return list(result_list) return list(result_list)
security.declareProtected(CMFCorePermissions.ManagePortal, 'getResultDict') security.declareProtected(CMFCorePermissions.ManagePortal, 'getResultDict')
......
...@@ -31,7 +31,6 @@ from hashlib import sha1 ...@@ -31,7 +31,6 @@ from hashlib import sha1
from DateTime import DateTime from DateTime import DateTime
from zLOG import LOG, WARNING, ERROR from zLOG import LOG, WARNING, ERROR
from ZODB.POSException import ConflictError from ZODB.POSException import ConflictError
from cStringIO import StringIO
# Time global parameters # Time global parameters
MAX_PROCESSING_TIME = 900 # in seconds MAX_PROCESSING_TIME = 900 # in seconds
......
...@@ -37,6 +37,7 @@ from .SQLBase import ( ...@@ -37,6 +37,7 @@ from .SQLBase import (
) )
from Products.CMFActivity.ActivityTool import Message from Products.CMFActivity.ActivityTool import Message
from .SQLDict import SQLDict from .SQLDict import SQLDict
from six.moves import xrange
class SQLJoblib(SQLDict): class SQLJoblib(SQLDict):
""" """
...@@ -94,8 +95,8 @@ CREATE TABLE %s ( ...@@ -94,8 +95,8 @@ CREATE TABLE %s (
db.query("SET @uid := %s" % getrandbits(UID_SAFE_BITSIZE)) db.query("SET @uid := %s" % getrandbits(UID_SAFE_BITSIZE))
try: try:
db.query(self._insert_template % (self.sql_table, values)) db.query(self._insert_template % (self.sql_table, values))
except MySQLdb.IntegrityError, (code, _): except MySQLdb.IntegrityError as e:
if code != DUP_ENTRY: if e.args[0] != DUP_ENTRY:
raise raise
reset_uid = True reset_uid = True
else: else:
......
This diff is collapsed.
...@@ -22,6 +22,7 @@ ...@@ -22,6 +22,7 @@
# #
############################################################################## ##############################################################################
from __future__ import print_function
SBALANCE_VERSION = '4.0' SBALANCE_VERSION = '4.0'
import sys import sys
...@@ -90,17 +91,17 @@ class Balancer: ...@@ -90,17 +91,17 @@ class Balancer:
try: try:
# Make a thread for expiration of old sticky entries. # Make a thread for expiration of old sticky entries.
if self.debug: if self.debug:
print "Starting an expiring daemon thread" print("Starting an expiring daemon thread")
t = threading.Thread(target=Balancer.expire, args=(self,)) t = threading.Thread(target=Balancer.expire, args=(self,))
t.setDaemon(1) t.setDaemon(1)
t.start() t.start()
if self.debug: if self.debug:
print "Beginning the main loop to accept clients" print("Beginning the main loop to accept clients")
while 1: while 1:
conn, addr = self.socket.accept() conn, addr = self.socket.accept()
if self.debug: if self.debug:
print "New connection from %s" % str(addr) print("New connection from %s" % str(addr))
t = threading.Thread(target=Balancer.handleClient, args=(self, conn, addr)) t = threading.Thread(target=Balancer.handleClient, args=(self, conn, addr))
t.start() t.start()
finally: finally:
...@@ -119,7 +120,7 @@ class Balancer: ...@@ -119,7 +120,7 @@ class Balancer:
expired_server_list = [] expired_server_list = []
for key,value in self.sticked_server_dict.items(): for key,value in self.sticked_server_dict.items():
if self.debug: if self.debug:
print 'cur_time = %f, value.atime = %f' % (cur_time, value.atime) print('cur_time = %f, value.atime = %f' % (cur_time, value.atime))
if cur_time > value.atime + 60 * 10: if cur_time > value.atime + 60 * 10:
expired_server_list.append(key) expired_server_list.append(key)
else: else:
...@@ -127,14 +128,14 @@ class Balancer: ...@@ -127,14 +128,14 @@ class Balancer:
count_dict[value.addr] += 1 count_dict[value.addr] += 1
for key in expired_server_list: for key in expired_server_list:
if self.debug: if self.debug:
print "Expiring %s" % str(key) print("Expiring %s" % str(key))
del self.sticked_server_dict[key] # Expire this entry. del self.sticked_server_dict[key] # Expire this entry.
# Find the max and the min. # Find the max and the min.
if self.debug: if self.debug:
print 'count_dict = %s, sticked_server_dict = %s, disabled_server_dict = %s' % (str(count_dict), str(self.sticked_server_dict), str(self.disabled_server_dict)) print('count_dict = %s, sticked_server_dict = %s, disabled_server_dict = %s' % (str(count_dict), str(self.sticked_server_dict), str(self.disabled_server_dict)))
max = -1 max = -1
min = len(self.sticked_server_dict) + 1 min = len(self.sticked_server_dict) + 1
for addr,count in count_dict.items(): for addr,count in list(count_dict.items()):
if count > max: if count > max:
max = count max = count
max_addr = addr max_addr = addr
...@@ -144,22 +145,22 @@ class Balancer: ...@@ -144,22 +145,22 @@ class Balancer:
# If the max is significantly greater than the min, move some clients. # If the max is significantly greater than the min, move some clients.
if max > min + 1: if max > min + 1:
num = max - min - 1 num = max - min - 1
for key,value in self.sticked_server_dict.items(): for key,value in list(self.sticked_server_dict.items()):
if value.addr == max_addr: if value.addr == max_addr:
if self.debug: if self.debug:
print "Moving %s from %s to %s" % (str(key), str(max_addr), str(min_addr)) print("Moving %s from %s to %s" % (str(key), str(max_addr), str(min_addr)))
value.addr = min_addr value.addr = min_addr
num -= 1 num -= 1
if num <= 0: if num <= 0:
break break
# Enable old entries in disabled servers. # Enable old entries in disabled servers.
enabled_server_list = [] enabled_server_list = []
for addr,ctime in self.disabled_server_dict.items(): for addr,ctime in list(self.disabled_server_dict.items()):
if cur_time > ctime + 60 * 3: if cur_time > ctime + 60 * 3:
enabled_server_list.append(addr) enabled_server_list.append(addr)
for addr in enabled_server_list: for addr in enabled_server_list:
if self.debug: if self.debug:
print 'Enabling %s again' % addr print('Enabling %s again' % addr)
del self.disabled_server_dict[addr] del self.disabled_server_dict[addr]
finally: finally:
self.lock.release() self.lock.release()
...@@ -241,7 +242,7 @@ class Balancer: ...@@ -241,7 +242,7 @@ class Balancer:
try: try:
self.lock.acquire() self.lock.acquire()
if self.debug: if self.debug:
print 'Disabling %s' % addr print('Disabling %s' % addr)
cur_time = time.time() cur_time = time.time()
self.disabled_server_dict[addr] = cur_time self.disabled_server_dict[addr] = cur_time
finally: finally:
...@@ -260,7 +261,7 @@ class Balancer: ...@@ -260,7 +261,7 @@ class Balancer:
if index == start_index: if index == start_index:
# No way. # No way.
if self.debug: if self.debug:
print 'No available server found.' print('No available server found.')
return return
# Register this client if possible. # Register this client if possible.
...@@ -268,7 +269,7 @@ class Balancer: ...@@ -268,7 +269,7 @@ class Balancer:
try: try:
self.lock.acquire() self.lock.acquire()
if self.debug: if self.debug:
print 'Registering %s with %s' % (signature, addr) print('Registering %s with %s' % (signature, addr))
cur_time = time.time() cur_time = time.time()
if signature in self.sticked_server_dict: if signature in self.sticked_server_dict:
info = self.sticked_server_dict[signature] info = self.sticked_server_dict[signature]
...@@ -306,16 +307,16 @@ def main(): ...@@ -306,16 +307,16 @@ def main():
try: try:
opts, args = getopt.getopt(sys.argv[1:], "hvb:t:T:dfps", opts, args = getopt.getopt(sys.argv[1:], "hvb:t:T:dfps",
["help", "version", "bind=", "connect-timeout=", "select-timeout=", "debug", "foreground", "packet-dump", "sticky"]) ["help", "version", "bind=", "connect-timeout=", "select-timeout=", "debug", "foreground", "packet-dump", "sticky"])
except getopt.GetoptError, msg: except getopt.GetoptError as msg:
print msg print(msg)
print "Try ``sbalance --help'' for more information." print("Try ``sbalance --help'' for more information.")
sys.exit(2) sys.exit(2)
for o, a in opts: for o, a in opts:
if o in ("-v", "--version"): if o in ("-v", "--version"):
print "sbalance version %s" % SBALANCE_VERSION print("sbalance version %s" % SBALANCE_VERSION)
sys.exit() sys.exit()
elif o in ("-h", "--help"): elif o in ("-h", "--help"):
print '''Usage: sbalace [OPTION...] PORT HOST:[PORT]... print('''Usage: sbalace [OPTION...] PORT HOST:[PORT]...
Balance TCP/IP loads with distributed servers. Balance TCP/IP loads with distributed servers.
-h, --help display this message and exit -h, --help display this message and exit
...@@ -331,7 +332,7 @@ Balance TCP/IP loads with distributed servers. ...@@ -331,7 +332,7 @@ Balance TCP/IP loads with distributed servers.
PORT is the port number to listen to. You can specify any number of PORT is the port number to listen to. You can specify any number of
pairs of a host and a port. pairs of a host and a port.
Report bugs to <yo@nexedi.com>.''' Report bugs to <yo@nexedi.com>.''')
sys.exit() sys.exit()
elif o in ("-b", "--bind"): elif o in ("-b", "--bind"):
kwd['bind'] = a kwd['bind'] = a
...@@ -349,8 +350,8 @@ Report bugs to <yo@nexedi.com>.''' ...@@ -349,8 +350,8 @@ Report bugs to <yo@nexedi.com>.'''
pass pass
if len(args) < 2: if len(args) < 2:
print "Too few arguments." print("Too few arguments.")
print "Try ``sbalance --help'' for more information." print("Try ``sbalance --help'' for more information.")
sys.exit(2) sys.exit(2)
port = int(args[0]) port = int(args[0])
...@@ -364,8 +365,8 @@ Report bugs to <yo@nexedi.com>.''' ...@@ -364,8 +365,8 @@ Report bugs to <yo@nexedi.com>.'''
addr = server addr = server
server_list.append(addr) server_list.append(addr)
if len(server_list) < 1: if len(server_list) < 1:
print "No server is specified." print("No server is specified.")
print "Try ``sbalance --help'' for more information." print("Try ``sbalance --help'' for more information.")
sys.exit(2) sys.exit(2)
b = Balancer(port, server_list, **kwd) b = Balancer(port, server_list, **kwd)
......
...@@ -26,6 +26,7 @@ ...@@ -26,6 +26,7 @@
# #
############################################################################## ##############################################################################
from past.builtins import cmp
import string import string
from Products.ERP5Type.Globals import InitializeClass, DTMLFile from Products.ERP5Type.Globals import InitializeClass, DTMLFile
...@@ -349,7 +350,7 @@ class Category(Folder): ...@@ -349,7 +350,7 @@ class Category(Folder):
checkPermission = self.portal_membership.checkPermission checkPermission = self.portal_membership.checkPermission
def permissionFilter(obj): def permissionFilter(obj):
return checkPermission(checked_permission, obj) return checkPermission(checked_permission, obj)
value_list = filter(permissionFilter, value_list) value_list = [v for v in value_list if permissionFilter(v)]
return sortValueList(value_list, sort_on, sort_order, **kw) return sortValueList(value_list, sort_on, sort_order, **kw)
...@@ -606,7 +607,7 @@ class Category(Folder): ...@@ -606,7 +607,7 @@ class Category(Folder):
if current_category_list: if current_category_list:
kw['display_none_category'] = False kw['display_none_category'] = False
current_category_item_list = Renderer(base=base, **kw).render( current_category_item_list = Renderer(base=base, **kw).render(
map(self.portal_categories.resolveCategory, current_category_list)) [self.portal_categories.resolveCategory(c) for c in current_category_list])
item_set = {tuple(x) for x in item_list} item_set = {tuple(x) for x in item_list}
additional_item_list = [] additional_item_list = []
for current_category_item in current_category_item_list: for current_category_item in current_category_item_list:
...@@ -903,7 +904,7 @@ class BaseCategory(Category): ...@@ -903,7 +904,7 @@ class BaseCategory(Category):
checkPermission = self.portal_membership.checkPermission checkPermission = self.portal_membership.checkPermission
def permissionFilter(obj): def permissionFilter(obj):
return checkPermission(checked_permission, obj) return checkPermission(checked_permission, obj)
value_list = filter(permissionFilter, value_list) value_list = [v for v in value_list if permissionFilter(v)]
return sortValueList(value_list, sort_on, sort_order, **kw) return sortValueList(value_list, sort_on, sort_order, **kw)
......
...@@ -30,6 +30,8 @@ ...@@ -30,6 +30,8 @@
"""\ """\
ERP portal_categories tool. ERP portal_categories tool.
""" """
import six
from six import string_types as basestring
from collections import deque from collections import deque
import re import re
from BTrees.OOBTree import OOTreeSet from BTrees.OOBTree import OOTreeSet
...@@ -61,7 +63,7 @@ class RelatedIndex(): # persistent.Persistent can be added ...@@ -61,7 +63,7 @@ class RelatedIndex(): # persistent.Persistent can be added
def __repr__(self): def __repr__(self):
try: try:
contents = ', '.join('%s=%r' % (k, list(v)) contents = ', '.join('%s=%r' % (k, list(v))
for (k, v) in self.__dict__.iteritems()) for (k, v) in six.iteritems(self.__dict__))
except Exception: except Exception:
contents = '...' contents = '...'
return '<%s(%s) at 0x%x>' % (self.__class__.__name__, contents, id(self)) return '<%s(%s) at 0x%x>' % (self.__class__.__name__, contents, id(self))
...@@ -69,6 +71,10 @@ class RelatedIndex(): # persistent.Persistent can be added ...@@ -69,6 +71,10 @@ class RelatedIndex(): # persistent.Persistent can be added
def __nonzero__(self): def __nonzero__(self):
return any(self.__dict__.itervalues()) return any(self.__dict__.itervalues())
def __bool__(self):
return any(six.itervalues(self.__dict__))
__nonzero__ = __bool__ # six.PY2
def add(self, base, relative_url): def add(self, base, relative_url):
try: try:
getattr(self, base).add(relative_url) getattr(self, base).add(relative_url)
...@@ -1404,7 +1410,7 @@ class CategoryTool(BaseTool): ...@@ -1404,7 +1410,7 @@ class CategoryTool(BaseTool):
except AttributeError: except AttributeError:
related = RelatedIndex() related = RelatedIndex()
include_self = False include_self = False
for base_category, category in local_index_dict.iteritems(): for base_category, category in six.iteritems(local_index_dict):
if not category: if not category:
# Categories are member of themselves. # Categories are member of themselves.
include_self = True include_self = True
...@@ -1463,11 +1469,11 @@ class CategoryTool(BaseTool): ...@@ -1463,11 +1469,11 @@ class CategoryTool(BaseTool):
related = aq_base(ob)._related_index related = aq_base(ob)._related_index
except AttributeError: except AttributeError:
continue continue
for base_category, category in local_index_dict.iteritems(): for base_category, category in six.iteritems(local_index_dict):
category += relative_url category += relative_url
check_local() check_local()
# Filter out objects that are not of requested portal type. # Filter out objects that are not of requested portal type.
result = [ob for ob in result_dict.itervalues() if ob is not None and ( result = [ob for ob in six.itervalues(result_dict) if ob is not None and (
not portal_type or ob.getPortalType() in portal_type)] not portal_type or ob.getPortalType() in portal_type)]
# Finish with base categories that are only indexed in catalog, # Finish with base categories that are only indexed in catalog,
# making sure we don't return duplicate values. # making sure we don't return duplicate values.
...@@ -1508,7 +1514,7 @@ class CategoryTool(BaseTool): ...@@ -1508,7 +1514,7 @@ class CategoryTool(BaseTool):
for permission in checked_permission: for permission in checked_permission:
if checkPermission(permission, ob): if checkPermission(permission, ob):
return True return True
return filter(check, result) return [r for r in result if check(r)]
security.declareProtected( Permissions.AccessContentsInformation, security.declareProtected( Permissions.AccessContentsInformation,
'getRelatedPropertyList' ) 'getRelatedPropertyList' )
......
...@@ -100,4 +100,4 @@ class Filter(Implicit): ...@@ -100,4 +100,4 @@ class Filter(Implicit):
def filter(self, value_list): def filter(self, value_list):
#LOG('Filter filter', 0, 'value_list = %s' % repr(value_list)) #LOG('Filter filter', 0, 'value_list = %s' % repr(value_list))
return filter(lambda v: self.test(v), value_list) return [v for v in value_list if self.test(v)]
...@@ -22,11 +22,12 @@ ...@@ -22,11 +22,12 @@
ZServer hook to dump a traceback of the running python threads. ZServer hook to dump a traceback of the running python threads.
""" """
import thread import six
import _thread
from sys import _current_frames from sys import _current_frames
import traceback import traceback
import time import time
from cStringIO import StringIO from io import BytesIO as StringIO
from zLOG import LOG, DEBUG, ERROR from zLOG import LOG, DEBUG, ERROR
from App.config import getConfiguration from App.config import getConfiguration
...@@ -68,7 +69,7 @@ def dump_threads(): ...@@ -68,7 +69,7 @@ def dump_threads():
from Products.ZMySQLDA.db import DB from Products.ZMySQLDA.db import DB
while f is not None: while f is not None:
code = f.f_code code = f.f_code
if code is DB._query.func_code: if code is DB._query.__code__:
mysql_info = "\nMySQL query:\n%s\n" % f.f_locals['query'] mysql_info = "\nMySQL query:\n%s\n" % f.f_locals['query']
break break
f = f.f_back f = f.f_back
...@@ -82,7 +83,7 @@ def dump_threads(): ...@@ -82,7 +83,7 @@ def dump_threads():
res.append("End of dump\n") res.append("End of dump\n")
result = '\n'.join(res) result = '\n'.join(res)
if isinstance(result, unicode): if isinstance(result, six.text_type):
result = result.encode('utf-8') result = result.encode('utf-8')
return result return result
......
...@@ -58,7 +58,7 @@ class AccountingTransactionBalance(Constraint): ...@@ -58,7 +58,7 @@ class AccountingTransactionBalance(Constraint):
destination_sum[section] = destination_sum.get(section, 0) + \ destination_sum[section] = destination_sum.get(section, 0) + \
(line.getDestinationInventoriatedTotalAssetPrice() or 0) (line.getDestinationInventoriatedTotalAssetPrice() or 0)
for section, total in source_sum.items(): for section, total in list(source_sum.items()):
precision = 2 precision = 2
if section is not None and\ if section is not None and\
section.getPortalType() == 'Organisation': section.getPortalType() == 'Organisation':
...@@ -71,7 +71,7 @@ class AccountingTransactionBalance(Constraint): ...@@ -71,7 +71,7 @@ class AccountingTransactionBalance(Constraint):
mapping=dict(section_title=section.getTranslatedTitle()))) mapping=dict(section_title=section.getTranslatedTitle())))
break break
for section, total in destination_sum.items(): for section, total in list(destination_sum.items()):
precision = 2 precision = 2
if section is not None and\ if section is not None and\
section.getPortalType() == 'Organisation': section.getPortalType() == 'Organisation':
......
...@@ -27,7 +27,9 @@ ...@@ -27,7 +27,9 @@
# #
############################################################################## ##############################################################################
from compiler.consts import CO_VARKEYWORDS from past.builtins import cmp
from six import string_types as basestring
from inspect import CO_VARKEYWORDS
from random import getrandbits from random import getrandbits
from Acquisition import aq_base from Acquisition import aq_base
from DateTime import DateTime from DateTime import DateTime
...@@ -162,7 +164,7 @@ class Alarm(XMLObject, PeriodicityMixin): ...@@ -162,7 +164,7 @@ class Alarm(XMLObject, PeriodicityMixin):
activate_kw['tag'] = '%s_%x' % (self.getRelativeUrl(), getrandbits(32)) activate_kw['tag'] = '%s_%x' % (self.getRelativeUrl(), getrandbits(32))
tag = activate_kw['tag'] tag = activate_kw['tag']
method = getattr(self, method_id) method = getattr(self, method_id)
func_code = method.func_code func_code = method.__code__
try: try:
has_kw = func_code.co_flags & CO_VARKEYWORDS has_kw = func_code.co_flags & CO_VARKEYWORDS
except AttributeError: except AttributeError:
......
This diff is collapsed.
...@@ -129,9 +129,9 @@ class Category(CMFCategory, Predicate, MetaNode, MetaResource): ...@@ -129,9 +129,9 @@ class Category(CMFCategory, Predicate, MetaNode, MetaResource):
cache_key = 'web_site_aq_cache' cache_key = 'web_site_aq_cache'
request = self.REQUEST request = self.REQUEST
# Prevent infinite recursion # Prevent infinite recursion
if not request.has_key(cache_key): if cache_key not in request:
request[cache_key] = {} request[cache_key] = {}
elif request[cache_key].has_key(name): elif name in request[cache_key]:
return request[cache_key][name] return request[cache_key][name]
try: try:
result_list = self.portal_catalog(portal_type="Person", id = name) result_list = self.portal_catalog(portal_type="Person", id = name)
...@@ -139,7 +139,7 @@ class Category(CMFCategory, Predicate, MetaNode, MetaResource): ...@@ -139,7 +139,7 @@ class Category(CMFCategory, Predicate, MetaNode, MetaResource):
return result_list[0].getObject() return result_list[0].getObject()
except: except:
# Cleanup non recursion dict in case of exception # Cleanup non recursion dict in case of exception
if request[cache_key].has_key(name): if name in request[cache_key]:
del request[cache_key][name] del request[cache_key][name]
raise raise
return None return None
......
...@@ -806,7 +806,7 @@ class Resource(XMLObject, XMLMatrix, VariatedMixin): ...@@ -806,7 +806,7 @@ class Resource(XMLObject, XMLMatrix, VariatedMixin):
try: try:
result = quantity * self._getConversionRatio(from_unit, variation_list)\ result = quantity * self._getConversionRatio(from_unit, variation_list)\
/ self._getConversionRatio(to_unit, variation_list) / self._getConversionRatio(to_unit, variation_list)
except (ArithmeticError, AttributeError, LookupError, TypeError), error: except (ArithmeticError, AttributeError, LookupError, TypeError) as error:
# For compatibility, we only log the error and return None. # For compatibility, we only log the error and return None.
# No exception for the moment. # No exception for the moment.
LOG('Resource.convertQuantity', WARNING, LOG('Resource.convertQuantity', WARNING,
......
...@@ -26,6 +26,7 @@ ...@@ -26,6 +26,7 @@
# #
############################################################################## ##############################################################################
import six
import zope.interface import zope.interface
from Acquisition import aq_base from Acquisition import aq_base
from AccessControl import ClassSecurityInfo from AccessControl import ClassSecurityInfo
...@@ -96,7 +97,7 @@ class SQLNonContinuousIncreasingIdGenerator(IdGenerator): ...@@ -96,7 +97,7 @@ class SQLNonContinuousIncreasingIdGenerator(IdGenerator):
portal.IdTool_zSetLastId(id_group, None) portal.IdTool_zSetLastId(id_group, None)
# Commit the changement of new_id # Commit the changement of new_id
portal.IdTool_zCommit() portal.IdTool_zCommit()
except ProgrammingError, error: except ProgrammingError as error:
if error[0] != NO_SUCH_TABLE: if error[0] != NO_SUCH_TABLE:
raise raise
...@@ -132,7 +133,7 @@ class SQLNonContinuousIncreasingIdGenerator(IdGenerator): ...@@ -132,7 +133,7 @@ class SQLNonContinuousIncreasingIdGenerator(IdGenerator):
for line in self._getValueListFromTable(): for line in self._getValueListFromTable():
id_group = line['id_group'] id_group = line['id_group']
last_id = line['last_id'] last_id = line['last_id']
if self.last_max_id_dict.has_key(id_group) and \ if id_group in self.last_max_id_dict and \
self.last_max_id_dict[id_group].value > last_id: self.last_max_id_dict[id_group].value > last_id:
set_last_id_method(id_group=id_group, set_last_id_method(id_group=id_group,
last_id=self.last_max_id_dict[id_group].value) last_id=self.last_max_id_dict[id_group].value)
...@@ -159,7 +160,10 @@ class SQLNonContinuousIncreasingIdGenerator(IdGenerator): ...@@ -159,7 +160,10 @@ class SQLNonContinuousIncreasingIdGenerator(IdGenerator):
""" """
new_id = 1 + self._generateNewId(id_group=id_group, id_count=id_count, new_id = 1 + self._generateNewId(id_group=id_group, id_count=id_count,
default=default, poison=poison) default=default, poison=poison)
if six.PY2:
return range(new_id - id_count, new_id) return range(new_id - id_count, new_id)
else:
return list(range(new_id - id_count, new_id))
security.declareProtected(Permissions.ModifyPortalContent, security.declareProtected(Permissions.ModifyPortalContent,
'initializeGenerator') 'initializeGenerator')
...@@ -177,7 +181,7 @@ class SQLNonContinuousIncreasingIdGenerator(IdGenerator): ...@@ -177,7 +181,7 @@ class SQLNonContinuousIncreasingIdGenerator(IdGenerator):
portal = self.getPortalObject() portal = self.getPortalObject()
try: try:
portal.IdTool_zGetValueList() portal.IdTool_zGetValueList()
except ProgrammingError, error: except ProgrammingError as error:
if error[0] != NO_SUCH_TABLE: if error[0] != NO_SUCH_TABLE:
raise raise
portal.IdTool_zDropTable() portal.IdTool_zDropTable()
......
...@@ -26,6 +26,7 @@ ...@@ -26,6 +26,7 @@
# #
############################################################################## ##############################################################################
import six
import zope.interface import zope.interface
from AccessControl import ClassSecurityInfo from AccessControl import ClassSecurityInfo
from Products.ERP5Type import Permissions, interfaces from Products.ERP5Type import Permissions, interfaces
...@@ -85,7 +86,10 @@ class ZODBContinuousIncreasingIdGenerator(IdGenerator): ...@@ -85,7 +86,10 @@ class ZODBContinuousIncreasingIdGenerator(IdGenerator):
""" """
new_id = 1 + self._generateNewId(id_group=id_group, id_count=id_count, new_id = 1 + self._generateNewId(id_group=id_group, id_count=id_count,
default=default, poison=poison) default=default, poison=poison)
if six.PY2:
return range(new_id - id_count, new_id) return range(new_id - id_count, new_id)
else:
return list(range(new_id - id_count, new_id))
security.declareProtected(Permissions.ModifyPortalContent, security.declareProtected(Permissions.ModifyPortalContent,
'initializeGenerator') 'initializeGenerator')
...@@ -106,7 +110,7 @@ class ZODBContinuousIncreasingIdGenerator(IdGenerator): ...@@ -106,7 +110,7 @@ class ZODBContinuousIncreasingIdGenerator(IdGenerator):
for id_group, last_id in portal_ids.dict_ids.items(): for id_group, last_id in portal_ids.dict_ids.items():
if not isinstance(id_group, str): if not isinstance(id_group, str):
id_group = repr(id_group) id_group = repr(id_group)
if self.last_id_dict.has_key(id_group) and \ if id_group in self.last_id_dict and \
self.last_id_dict[id_group] > last_id: self.last_id_dict[id_group] > last_id:
continue continue
self.last_id_dict[id_group] = last_id self.last_id_dict[id_group] = last_id
...@@ -146,7 +150,7 @@ class ZODBContinuousIncreasingIdGenerator(IdGenerator): ...@@ -146,7 +150,7 @@ class ZODBContinuousIncreasingIdGenerator(IdGenerator):
if not isinstance(id_dict, dict): if not isinstance(id_dict, dict):
raise TypeError('the argument given is not a dictionary') raise TypeError('the argument given is not a dictionary')
for value in id_dict.values(): for value in id_dict.values():
if not isinstance(value, (int, long)): if not isinstance(value, six.integer_types):
raise TypeError('the value given in dictionary is not a integer') raise TypeError('the value given in dictionary is not a integer')
self.last_id_dict.update(id_dict) self.last_id_dict.update(id_dict)
......
...@@ -18,8 +18,8 @@ from __future__ import absolute_import ...@@ -18,8 +18,8 @@ from __future__ import absolute_import
from DateTime import DateTime from DateTime import DateTime
from six.moves import map from six.moves import map
import thread, threading
import six import six
import _thread, threading
from weakref import ref as weakref from weakref import ref as weakref
from OFS.Application import Application, AppInitializer from OFS.Application import Application, AppInitializer
from Products.ERP5Type import Globals from Products.ERP5Type import Globals
...@@ -46,7 +46,6 @@ from Products.ERP5Type.dynamic.portal_type_class import synchronizeDynamicModule ...@@ -46,7 +46,6 @@ from Products.ERP5Type.dynamic.portal_type_class import synchronizeDynamicModule
from Products.ERP5Type.mixin.response_header_generator import ResponseHeaderGenerator from Products.ERP5Type.mixin.response_header_generator import ResponseHeaderGenerator
from zLOG import LOG, INFO, WARNING, ERROR from zLOG import LOG, INFO, WARNING, ERROR
from string import join
import os import os
import warnings import warnings
import transaction import transaction
...@@ -371,7 +370,7 @@ class ERP5Site(ResponseHeaderGenerator, FolderMixIn, PortalObjectBase, CacheCook ...@@ -371,7 +370,7 @@ class ERP5Site(ResponseHeaderGenerator, FolderMixIn, PortalObjectBase, CacheCook
def _registerMissingTools(self): def _registerMissingTools(self):
tool_id_list = ("portal_skins", "portal_types", "portal_membership", tool_id_list = ("portal_skins", "portal_types", "portal_membership",
"portal_url", "portal_workflow") "portal_url", "portal_workflow")
if (None in map(self.get, tool_id_list) or not if (None in [self.get(tool_id) for tool_id in tool_id_list] or not
TransactionalResource.registerOnce(__name__, 'site_manager', self.id)): TransactionalResource.registerOnce(__name__, 'site_manager', self.id)):
return return
self._registerTools(tool_id_list + self._registry_tool_id_list) self._registerTools(tool_id_list + self._registry_tool_id_list)
...@@ -467,7 +466,7 @@ class ERP5Site(ResponseHeaderGenerator, FolderMixIn, PortalObjectBase, CacheCook ...@@ -467,7 +466,7 @@ class ERP5Site(ResponseHeaderGenerator, FolderMixIn, PortalObjectBase, CacheCook
security.declareProtected(Permissions.AccessContentsInformation, 'skinSuper') security.declareProtected(Permissions.AccessContentsInformation, 'skinSuper')
def skinSuper(self, skin, id): def skinSuper(self, skin, id):
if id[:1] != '_' and id[:3] != 'aq_': if id[:1] != '_' and id[:3] != 'aq_':
skin_info = SKINDATA.get(thread.get_ident()) skin_info = SKINDATA.get(_thread.get_ident())
if skin_info is not None: if skin_info is not None:
_, skin_selection_name, _, _ = skin_info _, skin_selection_name, _, _ = skin_info
skin_value = skinResolve(self, (skin_selection_name, skin), id) skin_value = skinResolve(self, (skin_selection_name, skin), id)
...@@ -679,7 +678,7 @@ class ERP5Site(ResponseHeaderGenerator, FolderMixIn, PortalObjectBase, CacheCook ...@@ -679,7 +678,7 @@ class ERP5Site(ResponseHeaderGenerator, FolderMixIn, PortalObjectBase, CacheCook
""" """
Returns the absolute path of an object Returns the absolute path of an object
""" """
return join(self.getPhysicalPath(),'/') return '/'.join(self.getPhysicalPath())
security.declareProtected(Permissions.AccessContentsInformation, 'getRelativeUrl') security.declareProtected(Permissions.AccessContentsInformation, 'getRelativeUrl')
def getRelativeUrl(self): def getRelativeUrl(self):
...@@ -704,7 +703,7 @@ class ERP5Site(ResponseHeaderGenerator, FolderMixIn, PortalObjectBase, CacheCook ...@@ -704,7 +703,7 @@ class ERP5Site(ResponseHeaderGenerator, FolderMixIn, PortalObjectBase, CacheCook
Search the content of a folder by calling Search the content of a folder by calling
the portal_catalog. the portal_catalog.
""" """
if not kw.has_key('parent_uid'): if 'parent_uid' not in kw:
kw['parent_uid'] = self.uid kw['parent_uid'] = self.uid
return self.portal_catalog.searchResults(**kw) return self.portal_catalog.searchResults(**kw)
...@@ -714,7 +713,7 @@ class ERP5Site(ResponseHeaderGenerator, FolderMixIn, PortalObjectBase, CacheCook ...@@ -714,7 +713,7 @@ class ERP5Site(ResponseHeaderGenerator, FolderMixIn, PortalObjectBase, CacheCook
Count the content of a folder by calling Count the content of a folder by calling
the portal_catalog. the portal_catalog.
""" """
if not kw.has_key('parent_uid'): if 'parent_uid' not in kw:
kw['parent_uid'] = self.uid kw['parent_uid'] = self.uid
return self.portal_catalog.countResults(**kw) return self.portal_catalog.countResults(**kw)
...@@ -737,7 +736,7 @@ class ERP5Site(ResponseHeaderGenerator, FolderMixIn, PortalObjectBase, CacheCook ...@@ -737,7 +736,7 @@ class ERP5Site(ResponseHeaderGenerator, FolderMixIn, PortalObjectBase, CacheCook
action['disabled'] = 0 action['disabled'] = 0
workflow_title = action.get('workflow_title', None) workflow_title = action.get('workflow_title', None)
if workflow_title is not None: if workflow_title is not None:
if not sorted_workflow_actions.has_key(workflow_title): if workflow_title not in sorted_workflow_actions:
sorted_workflow_actions[workflow_title] = [ sorted_workflow_actions[workflow_title] = [
{'title':workflow_title, {'title':workflow_title,
'disabled':1, 'disabled':1,
...@@ -805,12 +804,12 @@ class ERP5Site(ResponseHeaderGenerator, FolderMixIn, PortalObjectBase, CacheCook ...@@ -805,12 +804,12 @@ class ERP5Site(ResponseHeaderGenerator, FolderMixIn, PortalObjectBase, CacheCook
parameter_dict = config.product_config.get(self.getPath(), {}) parameter_dict = config.product_config.get(self.getPath(), {})
if 'promise_path' in parameter_dict: if 'promise_path' in parameter_dict:
promise_path = parameter_dict['promise_path'] promise_path = parameter_dict['promise_path']
import ConfigParser from six.moves import configparser
configuration = ConfigParser.ConfigParser() configuration = configparser.ConfigParser()
configuration.read(promise_path) configuration.read(promise_path)
try: try:
return configuration.get(section, option) return configuration.get(section, option)
except (ConfigParser.NoOptionError, ConfigParser.NoSectionError): except (configparser.NoOptionError, configparser.NoSectionError):
pass pass
return None return None
......
from __future__ import print_function
def clearData(self,REQUEST=None): def clearData(self,REQUEST=None):
""" """
this allows to erase every data object this allows to erase every data object
...@@ -5,7 +6,7 @@ def clearData(self,REQUEST=None): ...@@ -5,7 +6,7 @@ def clearData(self,REQUEST=None):
import transaction import transaction
context=self context=self
for folder in context.objectValues(("ERP5 Folder",)): for folder in context.objectValues(("ERP5 Folder",)):
print "#### Deleting inside the folder %s ####" % folder.id print("#### Deleting inside the folder %s ####" % folder.id)
# Getting the list of ids # Getting the list of ids
to_delete_list = folder.objectIds() to_delete_list = folder.objectIds()
while len(to_delete_list) > 0: while len(to_delete_list) > 0:
...@@ -14,4 +15,4 @@ def clearData(self,REQUEST=None): ...@@ -14,4 +15,4 @@ def clearData(self,REQUEST=None):
to_delete_list = folder.objectIds() to_delete_list = folder.objectIds()
transaction.commit() transaction.commit()
print "work done" print("work done")
import six
from Products.ERP5Type.Globals import get_request from Products.ERP5Type.Globals import get_request
from Acquisition import aq_base from Acquisition import aq_base
from Products.ERP5Type.Base import Base from Products.ERP5Type.Base import Base
...@@ -31,14 +32,21 @@ def recodeDocumentRecursively(document, dry_run=0): ...@@ -31,14 +32,21 @@ def recodeDocumentRecursively(document, dry_run=0):
if type(value) == type(''): if type(value) == type(''):
if len(value) > 0: if len(value) > 0:
message += 'Recoding %s of %s\n' % (id, document.getRelativeUrl()) message += 'Recoding %s of %s\n' % (id, document.getRelativeUrl())
if not dry_run: setattr(base, id, unicode(value, 'iso-8859-1').encode('utf-8')) if not dry_run:
if six.PY2:
setattr(base, id, unicode(value, 'iso-8859-1').encode('utf-8'))
else:
setattr(base, id, str(value, 'iso-8859-1').encode('utf-8'))
elif type(value) in (type(()), type([])): elif type(value) in (type(()), type([])):
if len(value) > 0: if len(value) > 0:
value_list = list(value) value_list = list(value)
for i in range(len(value_list)): for i in range(len(value_list)):
value = value_list[i] value = value_list[i]
if type(value) == type('') and len(value) > 0: if isinstance(value, six.binary_type) and len(value) > 0:
if six.PY2:
value_list[i] = unicode(value, 'iso-8859-1').encode('utf-8') value_list[i] = unicode(value, 'iso-8859-1').encode('utf-8')
else:
value_list[i] = str(value, 'iso-8859-1').encode('utf-8')
message += 'Recoding %s of %s\n' % (id, document.getRelativeUrl()) message += 'Recoding %s of %s\n' % (id, document.getRelativeUrl())
if not dry_run: setattr(base, id, tuple(value_list)) if not dry_run: setattr(base, id, tuple(value_list))
else: else:
......
...@@ -102,13 +102,13 @@ class InteractionDefinition (SimpleItem): ...@@ -102,13 +102,13 @@ class InteractionDefinition (SimpleItem):
return aq_parent(aq_inner(aq_parent(aq_inner(self)))) return aq_parent(aq_inner(aq_parent(aq_inner(self))))
def getAvailableStateIds(self): def getAvailableStateIds(self):
return self.getWorkflow().states.keys() return list(self.getWorkflow().states.keys())
def getAvailableScriptIds(self): def getAvailableScriptIds(self):
return self.getWorkflow().scripts.keys() return list(self.getWorkflow().scripts.keys())
def getAvailableVarIds(self): def getAvailableVarIds(self):
return self.getWorkflow().variables.keys() return list(self.getWorkflow().variables.keys())
def getTriggerMethodIdList(self): def getTriggerMethodIdList(self):
return self.method_id return self.method_id
...@@ -232,7 +232,7 @@ class InteractionDefinition (SimpleItem): ...@@ -232,7 +232,7 @@ class InteractionDefinition (SimpleItem):
return wf_vars return wf_vars
ret = [] ret = []
for vid in wf_vars: for vid in wf_vars:
if not self.var_exprs.has_key(vid): if vid not in self.var_exprs:
ret.append(vid) ret.append(vid)
return ret return ret
...@@ -256,7 +256,7 @@ class InteractionDefinition (SimpleItem): ...@@ -256,7 +256,7 @@ class InteractionDefinition (SimpleItem):
''' '''
ve = self.var_exprs ve = self.var_exprs
for id in ids: for id in ids:
if ve.has_key(id): if id in ve:
del ve[id] del ve[id]
if REQUEST is not None: if REQUEST is not None:
...@@ -271,7 +271,7 @@ class InteractionDefinition (SimpleItem): ...@@ -271,7 +271,7 @@ class InteractionDefinition (SimpleItem):
ve = self.var_exprs ve = self.var_exprs
if REQUEST is not None: if REQUEST is not None:
for id in ve.keys(): for id in list(ve.keys()):
fname = 'varexpr_%s' % id fname = 'varexpr_%s' % id
val = REQUEST[fname] val = REQUEST[fname]
......
...@@ -40,7 +40,7 @@ from Products.ERP5Type import Permissions ...@@ -40,7 +40,7 @@ from Products.ERP5Type import Permissions
from Products.ERP5 import _dtmldir from Products.ERP5 import _dtmldir
from Products.ERP5.mixin.timer_service import TimerServiceMixin from Products.ERP5.mixin.timer_service import TimerServiceMixin
from DateTime import DateTime from DateTime import DateTime
import urllib from six.moves import urllib
last_tic = time.time() last_tic = time.time()
last_tic_lock = threading.Lock() last_tic_lock = threading.Lock()
...@@ -215,11 +215,11 @@ class AlarmTool(TimerServiceMixin, BaseTool): ...@@ -215,11 +215,11 @@ class AlarmTool(TimerServiceMixin, BaseTool):
REQUEST.RESPONSE.redirect( REQUEST.RESPONSE.redirect(
REQUEST.URL1 + REQUEST.URL1 +
'/manageAlarmNode?manage_tabs_message=' + '/manageAlarmNode?manage_tabs_message=' +
urllib.quote("Distributing Node successfully changed.")) urllib.parse.quote("Distributing Node successfully changed."))
else : else :
if REQUEST is not None: if REQUEST is not None:
REQUEST.RESPONSE.redirect( REQUEST.RESPONSE.redirect(
REQUEST.URL1 + REQUEST.URL1 +
'/manageAlarmNode?manage_tabs_message=' + '/manageAlarmNode?manage_tabs_message=' +
urllib.quote("Malformed Distributing Node.")) urllib.parse.quote("Malformed Distributing Node."))
...@@ -26,6 +26,7 @@ ...@@ -26,6 +26,7 @@
# #
############################################################################## ##############################################################################
import six
import warnings import warnings
import zope.interface import zope.interface
...@@ -62,7 +63,7 @@ class IdTool(BaseTool): ...@@ -62,7 +63,7 @@ class IdTool(BaseTool):
""" """
the newContent is overriden to not use generateNewId the newContent is overriden to not use generateNewId
""" """
if not kw.has_key(id): if id not in kw:
new_id = self._generateNextId() new_id = self._generateNextId()
if new_id is not None: if new_id is not None:
kw['id'] = new_id kw['id'] = new_id
...@@ -228,7 +229,10 @@ class IdTool(BaseTool): ...@@ -228,7 +229,10 @@ class IdTool(BaseTool):
if self.dict_length_ids.get(id_group) is None: if self.dict_length_ids.get(id_group) is None:
self.dict_length_ids[id_group] = Length(new_id) self.dict_length_ids[id_group] = Length(new_id)
self.dict_length_ids[id_group].set(new_id) self.dict_length_ids[id_group].set(new_id)
if six.PY2:
new_id_list = range(new_id - id_count, new_id) new_id_list = range(new_id - id_count, new_id)
else:
new_id_list = list(range(new_id - id_count, new_id))
return new_id_list return new_id_list
security.declareProtected(Permissions.ModifyPortalContent, security.declareProtected(Permissions.ModifyPortalContent,
......
...@@ -28,6 +28,7 @@ ...@@ -28,6 +28,7 @@
############################################################################## ##############################################################################
from webdav.client import Resource from webdav.client import Resource
from past.builtins import cmp
from App.config import getConfiguration from App.config import getConfiguration
import os import os
...@@ -47,14 +48,19 @@ from Products.ERP5.genbt5list import generateInformation ...@@ -47,14 +48,19 @@ from Products.ERP5.genbt5list import generateInformation
from Acquisition import aq_base from Acquisition import aq_base
from tempfile import mkstemp, mkdtemp from tempfile import mkstemp, mkdtemp
from Products.ERP5 import _dtmldir from Products.ERP5 import _dtmldir
from cStringIO import StringIO from six.moves import xrange
from urllib import pathname2url, urlopen, splittype, urlretrieve from six.moves import cStringIO as StringIO
import urllib2 from six.moves.urllib.request import pathname2url, urlopen, urlretrieve
try:
from urllib import splittype
except ImportError: # six.PY3
from urllib.parse import splittype
from six.moves import urllib
import re import re
from xml.dom.minidom import parse from xml.dom.minidom import parse
from xml.parsers.expat import ExpatError from xml.parsers.expat import ExpatError
import struct import struct
import cPickle from six.moves import cPickle as pickle
from base64 import b64encode, b64decode from base64 import b64encode, b64decode
from Products.ERP5Type.Message import translateString from Products.ERP5Type.Message import translateString
from zLOG import LOG, INFO, WARNING from zLOG import LOG, INFO, WARNING
...@@ -513,7 +519,7 @@ class TemplateTool (BaseTool): ...@@ -513,7 +519,7 @@ class TemplateTool (BaseTool):
Migrate business templates to new format where files like .py or .html Migrate business templates to new format where files like .py or .html
are exported seprately than the xml. are exported seprately than the xml.
""" """
repository_list = filter(bool, repository_list) repository_list = [r for r in repository_list if r]
if REQUEST is None: if REQUEST is None:
REQUEST = getattr(self, 'REQUEST', None) REQUEST = getattr(self, 'REQUEST', None)
...@@ -703,7 +709,7 @@ class TemplateTool (BaseTool): ...@@ -703,7 +709,7 @@ class TemplateTool (BaseTool):
Decode the uid of a business template from a repository. Decode the uid of a business template from a repository.
Return a repository and an id. Return a repository and an id.
""" """
return cPickle.loads(b64decode(uid)) return pickle.loads(b64decode(uid))
security.declarePublic( 'encodeRepositoryBusinessTemplateUid' ) security.declarePublic( 'encodeRepositoryBusinessTemplateUid' )
def encodeRepositoryBusinessTemplateUid(self, repository, id): def encodeRepositoryBusinessTemplateUid(self, repository, id):
...@@ -711,7 +717,7 @@ class TemplateTool (BaseTool): ...@@ -711,7 +717,7 @@ class TemplateTool (BaseTool):
encode the repository and the id of a business template. encode the repository and the id of a business template.
Return an uid. Return an uid.
""" """
return b64encode(cPickle.dumps((repository, id))) return b64encode(pickle.dumps((repository, id)))
security.declarePublic('compareVersionStrings') security.declarePublic('compareVersionStrings')
def compareVersionStrings(self, version, comparing_string): def compareVersionStrings(self, version, comparing_string):
...@@ -1380,16 +1386,16 @@ class TemplateTool (BaseTool): ...@@ -1380,16 +1386,16 @@ class TemplateTool (BaseTool):
LOG('ERP5', INFO, "TemplateTool: INSTANCE_HOME_REPOSITORY is %s." \ LOG('ERP5', INFO, "TemplateTool: INSTANCE_HOME_REPOSITORY is %s." \
% url) % url)
try: try:
urllib2.urlopen(url) urllib.request.urlopen(url)
return url return url
except (urllib2.HTTPError, OSError): except (urllib.error.HTTPError, OSError):
# XXX Try again with ".bt5" in case the folder format be used # XXX Try again with ".bt5" in case the folder format be used
# Instead tgz one. # Instead tgz one.
url = "%s.bt5" % url url = "%s.bt5" % url
try: try:
urllib2.urlopen(url) urllib.request.urlopen(url)
return url return url
except (urllib2.HTTPError, OSError): except (urllib.error.HTTPError, OSError):
pass pass
LOG('ERP5', INFO, 'TemplateTool: %s was not found into the url list: ' LOG('ERP5', INFO, 'TemplateTool: %s was not found into the url list: '
'%s.' % (bt5_title, base_url_list)) '%s.' % (bt5_title, base_url_list))
......
...@@ -38,7 +38,7 @@ from zExceptions import BadRequest ...@@ -38,7 +38,7 @@ from zExceptions import BadRequest
from zLOG import LOG, WARNING from zLOG import LOG, WARNING
from DateTime import DateTime from DateTime import DateTime
from Acquisition import aq_base from Acquisition import aq_base
from cStringIO import StringIO from io import BytesIO as StringIO
class TrashTool(BaseTool): class TrashTool(BaseTool):
""" """
......
...@@ -12,7 +12,7 @@ import socket ...@@ -12,7 +12,7 @@ import socket
import sys import sys
from tempfile import TemporaryFile from tempfile import TemporaryFile
import time import time
from urllib import quote, splitport from six.moves.urllib.parse import quote, splitport
from waitress.server import create_server from waitress.server import create_server
import ZConfig import ZConfig
......
...@@ -93,7 +93,7 @@ class Amount(Base, VariatedMixin): ...@@ -93,7 +93,7 @@ class Amount(Base, VariatedMixin):
and not omit_optional_variation): and not omit_optional_variation):
variation_list.append('industrial_phase') variation_list.append('industrial_phase')
if base_category_list: if base_category_list:
variation_list = filter(base_category_list.__contains__, variation_list) variation_list = [v for v in variation_list if v in base_category_list]
return self.getAcquiredCategoryMembershipList(variation_list, base=1) return self.getAcquiredCategoryMembershipList(variation_list, base=1)
security.declareProtected(Permissions.AccessContentsInformation, security.declareProtected(Permissions.AccessContentsInformation,
......
...@@ -28,6 +28,7 @@ ...@@ -28,6 +28,7 @@
# #
############################################################################## ##############################################################################
from six import string_types as basestring
from collections import defaultdict from collections import defaultdict
from AccessControl import ClassSecurityInfo from AccessControl import ClassSecurityInfo
from Products.ERP5Type import Permissions, PropertySheet from Products.ERP5Type import Permissions, PropertySheet
......
...@@ -28,6 +28,7 @@ ...@@ -28,6 +28,7 @@
# #
############################################################################## ##############################################################################
from six import string_types as basestring
import zope.interface import zope.interface
from AccessControl import ClassSecurityInfo from AccessControl import ClassSecurityInfo
......
...@@ -92,7 +92,7 @@ DOCUMENT_CONVERSION_SERVER_RETRY = 0 ...@@ -92,7 +92,7 @@ DOCUMENT_CONVERSION_SERVER_RETRY = 0
global_server_proxy_uri_failure_time = {} global_server_proxy_uri_failure_time = {}
from Products.CMFCore.utils import getToolByName from Products.CMFCore.utils import getToolByName
from functools import partial from functools import partial
from xmlrpclib import Fault, ServerProxy, ProtocolError from six.moves.xmlrpc_client import Fault, ServerProxy, ProtocolError
from socket import error as SocketError from socket import error as SocketError
from DateTime import DateTime from DateTime import DateTime
class DocumentConversionServerProxy(): class DocumentConversionServerProxy():
...@@ -152,18 +152,18 @@ class DocumentConversionServerProxy(): ...@@ -152,18 +152,18 @@ class DocumentConversionServerProxy():
# Cloudooo return result in (200 or 402, dict(), '') format or just based type # Cloudooo return result in (200 or 402, dict(), '') format or just based type
# 402 for error and 200 for ok # 402 for error and 200 for ok
result_set = func(*args, **kw) result_set = func(*args, **kw)
except SocketError, e: except SocketError as e:
message = 'Socket Error: %s' % (repr(e) or 'undefined.') message = 'Socket Error: %s' % (repr(e) or 'undefined.')
socket_error_list.append(message) socket_error_list.append(message)
retry_server_list.append((uri, server_proxy)) retry_server_list.append((uri, server_proxy))
except ProtocolError, e: except ProtocolError as e:
# Network issue # Network issue
message = "%s: %s %s" % (e.url, e.errcode, e.errmsg) message = "%s: %s %s" % (e.url, e.errcode, e.errmsg)
if e.errcode == -1: if e.errcode == -1:
message = "%s: Connection refused" % (e.url) message = "%s: Connection refused" % (e.url)
protocol_error_list.append(message) protocol_error_list.append(message)
retry_server_list.append((uri, server_proxy)) retry_server_list.append((uri, server_proxy))
except Fault, e: except Fault as e:
# Return not supported data types # Return not supported data types
fault_error_list.append(e) fault_error_list.append(e)
else: else:
...@@ -702,7 +702,7 @@ class Document(DocumentExtensibleTraversableMixin, XMLObject, UrlMixin, ...@@ -702,7 +702,7 @@ class Document(DocumentExtensibleTraversableMixin, XMLObject, UrlMixin,
Returns the list of revision numbers of the current document Returns the list of revision numbers of the current document
by by analysing the change log of the current object. by by analysing the change log of the current object.
""" """
return map(str, range(1, 1 + int(self.getRevision()))) return [str(r) for r in range(1, 1 + int(self.getRevision()))]
security.declareProtected(Permissions.ModifyPortalContent, 'mergeRevision') security.declareProtected(Permissions.ModifyPortalContent, 'mergeRevision')
def mergeRevision(self): def mergeRevision(self):
......
...@@ -325,8 +325,8 @@ class ImmobilisableItem(Item, Amount): ...@@ -325,8 +325,8 @@ class ImmobilisableItem(Item, Amount):
'price':{}, 'price':{},
'currency': {}}) 'currency': {}})
kw['immo_cache_dict'] = immo_cache_dict kw['immo_cache_dict'] = immo_cache_dict
if immo_cache_dict['period'].has_key((self.getRelativeUrl(), from_date, to_date) + if (self.getRelativeUrl(), from_date, to_date) +
tuple([(key,kw[key]) for key in kw_key_list])) : tuple([(key,kw[key]) for key in kw_key_list]) in immo_cache_dict['period'] :
return immo_cache_dict['period'][ (self.getRelativeUrl(), from_date, to_date) + return immo_cache_dict['period'][ (self.getRelativeUrl(), from_date, to_date) +
tuple( [(key,kw[key]) for key in kw_key_list]) ] tuple( [(key,kw[key]) for key in kw_key_list]) ]
def setPreviousPeriodParameters(period_list, def setPreviousPeriodParameters(period_list,
...@@ -599,7 +599,7 @@ class ImmobilisableItem(Item, Amount): ...@@ -599,7 +599,7 @@ class ImmobilisableItem(Item, Amount):
# Round dates since immobilisation calculation is made on days # Round dates since immobilisation calculation is made on days
for immo_period in immo_period_list: for immo_period in immo_period_list:
for property_ in ('start_date', 'stop_date', 'initial_date',): for property_ in ('start_date', 'stop_date', 'initial_date',):
if immo_period.has_key(property_): if property_ in immo_period:
immo_period[property_] = roundDate(immo_period[property_]) immo_period[property_] = roundDate(immo_period[property_])
immo_cache_dict['period'][ (self.getRelativeUrl(), from_date, to_date) + immo_cache_dict['period'][ (self.getRelativeUrl(), from_date, to_date) +
tuple([(key,kw[key]) for key in kw_key_list]) ] = immo_period_list tuple([(key,kw[key]) for key in kw_key_list]) ] = immo_period_list
...@@ -644,7 +644,7 @@ class ImmobilisableItem(Item, Amount): ...@@ -644,7 +644,7 @@ class ImmobilisableItem(Item, Amount):
elif len(immo_period_list) > 0 and at_date is None: elif len(immo_period_list) > 0 and at_date is None:
return 1 return 1
immo_period = immo_period_list[-1] immo_period = immo_period_list[-1]
if immo_period.has_key('stop_date'): if 'stop_date' in immo_period:
# It means the latest period is terminated before the current date # It means the latest period is terminated before the current date
return 0 return 0
return 1 return 1
...@@ -667,9 +667,9 @@ class ImmobilisableItem(Item, Amount): ...@@ -667,9 +667,9 @@ class ImmobilisableItem(Item, Amount):
if at_date is None: if at_date is None:
at_date = DateTime() at_date = DateTime()
new_kw = dict(kw) new_kw = dict(kw)
if new_kw.has_key('to_date'): if 'to_date' in new_kw:
del new_kw['to_date'] del new_kw['to_date']
if new_kw.has_key('at_date'): if 'at_date' in new_kw:
del new_kw['at_date'] del new_kw['at_date']
if immo_period_list is None: if immo_period_list is None:
immo_period_list = self.getImmobilisationPeriodList(to_date=at_date, **new_kw) immo_period_list = self.getImmobilisationPeriodList(to_date=at_date, **new_kw)
...@@ -706,9 +706,9 @@ class ImmobilisableItem(Item, Amount): ...@@ -706,9 +706,9 @@ class ImmobilisableItem(Item, Amount):
at_date = DateTime() at_date = DateTime()
new_kw = dict(kw) new_kw = dict(kw)
if new_kw.has_key('to_date'): if 'to_date' in new_kw:
del new_kw['to_date'] del new_kw['to_date']
if new_kw.has_key('at_date'): if 'at_date' in new_kw:
del new_kw['at_date'] del new_kw['at_date']
if immo_period_list is None: if immo_period_list is None:
immo_period_list = self.getImmobilisationPeriodList(to_date=at_date, **new_kw) immo_period_list = self.getImmobilisationPeriodList(to_date=at_date, **new_kw)
...@@ -718,7 +718,7 @@ class ImmobilisableItem(Item, Amount): ...@@ -718,7 +718,7 @@ class ImmobilisableItem(Item, Amount):
immo_period = immo_period_list[-1] immo_period = immo_period_list[-1]
# Second case : the item is not currently immobilised # Second case : the item is not currently immobilised
if immo_period.has_key('stop_date'): if 'stop_date' in immo_period:
return immo_period['stop_durability'] return immo_period['stop_durability']
# Third case : the item is currently immobilised # Third case : the item is currently immobilised
...@@ -778,7 +778,7 @@ class ImmobilisableItem(Item, Amount): ...@@ -778,7 +778,7 @@ class ImmobilisableItem(Item, Amount):
""" """
if at_date is None: if at_date is None:
at_date = DateTime() at_date = DateTime()
kw_key_list = kw.keys() kw_key_list = list(kw.keys())
kw_key_list.sort() kw_key_list.sort()
if kw_key_list.count('immo_cache_dict'): if kw_key_list.count('immo_cache_dict'):
...@@ -790,7 +790,7 @@ class ImmobilisableItem(Item, Amount): ...@@ -790,7 +790,7 @@ class ImmobilisableItem(Item, Amount):
immo_cache_dict_price_key = ((self.getRelativeUrl(), at_date) + immo_cache_dict_price_key = ((self.getRelativeUrl(), at_date) +
tuple([(key,kw[key]) for key in kw_key_list])) tuple([(key,kw[key]) for key in kw_key_list]))
if immo_cache_dict['price'].has_key(immo_cache_dict_price_key) : if immo_cache_dict_price_key in immo_cache_dict['price'] :
returned_price = immo_cache_dict['price'][immo_cache_dict_price_key] returned_price = immo_cache_dict['price'][immo_cache_dict_price_key]
if with_currency: if with_currency:
currency = immo_cache_dict['currency'][immo_cache_dict_price_key] currency = immo_cache_dict['currency'][immo_cache_dict_price_key]
...@@ -827,7 +827,7 @@ class ImmobilisableItem(Item, Amount): ...@@ -827,7 +827,7 @@ class ImmobilisableItem(Item, Amount):
start_durability = self.getRemainingDurability(at_date=start_date, start_durability = self.getRemainingDurability(at_date=start_date,
immo_cache_dict=immo_cache_dict) immo_cache_dict=immo_cache_dict)
# Get the current period stop date, duration and durability # Get the current period stop date, duration and durability
if immo_period.has_key('stop_date'): if 'stop_date' in immo_period:
stop_date = immo_period['stop_date'] stop_date = immo_period['stop_date']
period_stop_date = stop_date period_stop_date = stop_date
else: else:
......
...@@ -26,6 +26,7 @@ ...@@ -26,6 +26,7 @@
# #
############################################################################## ##############################################################################
from six.moves import xrange
from AccessControl import ClassSecurityInfo from AccessControl import ClassSecurityInfo
from Products.ERP5Type import Permissions, PropertySheet from Products.ERP5Type import Permissions, PropertySheet
from Products.ERP5Type.Accessor.Constant import PropertyGetter as ConstantGetter from Products.ERP5Type.Accessor.Constant import PropertyGetter as ConstantGetter
...@@ -175,7 +176,7 @@ class Inventory(Delivery): ...@@ -175,7 +176,7 @@ class Inventory(Delivery):
current_inventory_key[x] = "" current_inventory_key[x] = ""
current_inventory_key = tuple(current_inventory_key) current_inventory_key = tuple(current_inventory_key)
if inventory_calculation_dict.has_key("second_level"): if "second_level" in inventory_calculation_dict:
# two level of variation # two level of variation
try: try:
current_inventory_by_sub_variation = \ current_inventory_by_sub_variation = \
...@@ -219,7 +220,7 @@ class Inventory(Delivery): ...@@ -219,7 +220,7 @@ class Inventory(Delivery):
key_list.append(method()) key_list.append(method())
inventory_value = current_inventory_dict.get(tuple(key_list), 0) inventory_value = current_inventory_dict.get(tuple(key_list), 0)
second_key_list = [] second_key_list = []
if inventory_calculation_dict.has_key('second_level'): if 'second_level' in inventory_calculation_dict:
if inventory_value == 0: if inventory_value == 0:
inventory_value = {} inventory_value = {}
# two level # two level
...@@ -229,7 +230,7 @@ class Inventory(Delivery): ...@@ -229,7 +230,7 @@ class Inventory(Delivery):
if method is not None: if method is not None:
second_key_list.append(method()) second_key_list.append(method())
second_key_list = tuple(second_key_list) second_key_list = tuple(second_key_list)
if inventory_value.has_key(second_key_list): if second_key_list in inventory_value:
total_quantity = inventory_value.pop(second_key_list) total_quantity = inventory_value.pop(second_key_list)
# Put remaining subvariation in a dict to know which one # Put remaining subvariation in a dict to know which one
# to removed at end # to removed at end
...@@ -264,7 +265,7 @@ class Inventory(Delivery): ...@@ -264,7 +265,7 @@ class Inventory(Delivery):
category_list = self.getCategoryList() category_list = self.getCategoryList()
setter_list = [x['setter'] for x in inventory_calculation_dict['first_level']] setter_list = [x['setter'] for x in inventory_calculation_dict['first_level']]
if inventory_calculation_dict.has_key("second_level"): if "second_level" in inventory_calculation_dict:
setter_list.extend([x['setter'] for x in inventory_calculation_dict['second_level']]) setter_list.extend([x['setter'] for x in inventory_calculation_dict['second_level']])
value_list = list(key_list) + list(second_key_list) value_list = list(key_list) + list(second_key_list)
for x in xrange(len(setter_list)): for x in xrange(len(setter_list)):
...@@ -310,7 +311,7 @@ class Inventory(Delivery): ...@@ -310,7 +311,7 @@ class Inventory(Delivery):
category_list = self.getCategoryList() category_list = self.getCategoryList()
setter_list = [x['setter'] for x in inventory_calculation_dict['first_level']] setter_list = [x['setter'] for x in inventory_calculation_dict['first_level']]
if inventory_calculation_dict.has_key("second_level"): if "second_level" in inventory_calculation_dict:
setter_list.extend([x['setter'] for x in inventory_calculation_dict['second_level']]) setter_list.extend([x['setter'] for x in inventory_calculation_dict['second_level']])
value_list = list(first_level_key) + list(second_level_key) value_list = list(first_level_key) + list(second_level_key)
for x in xrange(len(setter_list)): for x in xrange(len(setter_list)):
......
...@@ -35,7 +35,7 @@ from erp5.component.document.Document import Document, ConversionError, _MARKER, ...@@ -35,7 +35,7 @@ from erp5.component.document.Document import Document, ConversionError, _MARKER,
from erp5.component.document.File import File from erp5.component.document.File import File
from erp5.component.module.WebDAVSupport import TextContent from erp5.component.module.WebDAVSupport import TextContent
from erp5.component.document.Document import VALID_IMAGE_FORMAT_LIST, VALID_TEXT_FORMAT_LIST from erp5.component.document.Document import VALID_IMAGE_FORMAT_LIST, VALID_TEXT_FORMAT_LIST
import cStringIO import io
from string import Template from string import Template
# Mixin Import # Mixin Import
...@@ -174,7 +174,7 @@ class TextDocument(CachedConvertableMixin, BaseConvertableFileMixin, TextContent ...@@ -174,7 +174,7 @@ class TextDocument(CachedConvertableMixin, BaseConvertableFileMixin, TextContent
# Include extra parameter for image conversions # Include extra parameter for image conversions
temp_image = self.portal_contributions.newContent( temp_image = self.portal_contributions.newContent(
portal_type='Image', portal_type='Image',
file=cStringIO.StringIO(), file=io.StringIO(),
filename=self.getId(), filename=self.getId(),
temp_object=1) temp_object=1)
temp_image._setData(result) temp_image._setData(result)
......
...@@ -27,6 +27,9 @@ ...@@ -27,6 +27,9 @@
# #
############################################################################## ##############################################################################
import six
from past.builtins import cmp
from hashlib import md5 from hashlib import md5
# Some workflow does not make sense in the context of mass transition and are # Some workflow does not make sense in the context of mass transition and are
...@@ -125,7 +128,7 @@ def getDocumentGroupByWorkflowStateList(self, form_id='', **kw): ...@@ -125,7 +128,7 @@ def getDocumentGroupByWorkflowStateList(self, form_id='', **kw):
for (ptype, workflow_id, _), (doc, document_count) in\ for (ptype, workflow_id, _), (doc, document_count) in\
workflow_state_dict.iteritems(): six.iteritems(workflow_state_dict):
workflow = wf_tool._getOb(workflow_id) workflow = wf_tool._getOb(workflow_id)
state_var = workflow.getStateVariable() state_var = workflow.getStateVariable()
translated_workflow_state_title = doc.getProperty( translated_workflow_state_title = doc.getProperty(
......
from six import string_types as basestring
import json import json
from Products.ERP5Type.Utils import checkPythonSourceCode from Products.ERP5Type.Utils import checkPythonSourceCode
......
...@@ -31,7 +31,7 @@ from AccessControl import ClassSecurityInfo ...@@ -31,7 +31,7 @@ from AccessControl import ClassSecurityInfo
from Products.ERP5Type.Globals import InitializeClass from Products.ERP5Type.Globals import InitializeClass
from Products.ERP5Type import Permissions from Products.ERP5Type import Permissions
from OFS.Image import Pdata from OFS.Image import Pdata
from cStringIO import StringIO from io import StringIO
_MARKER = object() _MARKER = object()
class BaseConvertableFileMixin: class BaseConvertableFileMixin:
......
...@@ -27,6 +27,7 @@ ...@@ -27,6 +27,7 @@
# #
############################################################################## ##############################################################################
import six
from hashlib import md5 from hashlib import md5
from warnings import warn from warnings import warn
import string import string
...@@ -52,7 +53,10 @@ def hashPdataObject(pdata_object): ...@@ -52,7 +53,10 @@ def hashPdataObject(pdata_object):
while pdata_object is not None: while pdata_object is not None:
chunk = pdata_object.aq_base chunk = pdata_object.aq_base
md5_hash.update(chunk.data) md5_hash.update(chunk.data)
if six.PY2:
pdata_object = chunk.next pdata_object = chunk.next
else:
pdata_object = chunk.__next__
chunk._p_deactivate() chunk._p_deactivate()
return md5_hash.hexdigest() return md5_hash.hexdigest()
...@@ -135,7 +139,7 @@ class CachedConvertableMixin: ...@@ -135,7 +139,7 @@ class CachedConvertableMixin:
cached_value = data cached_value = data
conversion_md5 = md5(str(data.data)).hexdigest() conversion_md5 = md5(str(data.data)).hexdigest()
size = len(data.data) size = len(data.data)
elif isinstance(data, (str, unicode,)): elif isinstance(data, six.string_types):
cached_value = data cached_value = data
conversion_md5 = md5(cached_value).hexdigest() conversion_md5 = md5(cached_value).hexdigest()
size = len(cached_value) size = len(cached_value)
......
...@@ -27,11 +27,12 @@ ...@@ -27,11 +27,12 @@
# #
############################################################################## ##############################################################################
import six
from AccessControl import ClassSecurityInfo from AccessControl import ClassSecurityInfo
from Products.ERP5Type.Globals import InitializeClass from Products.ERP5Type.Globals import InitializeClass
from Products.ERP5Type import Permissions from Products.ERP5Type import Permissions
from Products.ERP5Type.Utils import normaliseUrl from Products.ERP5Type.Utils import normaliseUrl
from urlparse import urlsplit, urlunsplit from six.moves.urllib.parse import urlsplit, urlunsplit
from lxml import html as etree_html from lxml import html as etree_html
class CrawlableMixin: class CrawlableMixin:
...@@ -110,7 +111,7 @@ class CrawlableMixin: ...@@ -110,7 +111,7 @@ class CrawlableMixin:
# For now take into acount only a and img tags # For now take into acount only a and img tags
if attribute_name not in ('href',): if attribute_name not in ('href',):
continue continue
if isinstance(link, unicode): if isinstance(link, six.text_type):
link = link.encode('utf-8') link = link.encode('utf-8')
href_list.append(link) href_list.append(link)
return href_list return href_list
...@@ -128,7 +129,7 @@ class CrawlableMixin: ...@@ -128,7 +129,7 @@ class CrawlableMixin:
path_part = '/'.join(path_part.split('/')[:-1]) path_part = '/'.join(path_part.split('/')[:-1])
base_url = urlunsplit((splitted_url[0], splitted_url[1], path_part, None, base_url = urlunsplit((splitted_url[0], splitted_url[1], path_part, None,
None)) None))
if isinstance(base_url, unicode): if isinstance(base_url, six.text_type):
base_url = base_url.encode('utf-8') base_url = base_url.encode('utf-8')
return base_url return base_url
...@@ -144,7 +145,7 @@ class CrawlableMixin: ...@@ -144,7 +145,7 @@ class CrawlableMixin:
# in www.example.com or www.3.example.com # in www.example.com or www.3.example.com
# keep only the example.com part # keep only the example.com part
reference_domain = ''.join(reference_domain.split('.')[-2:]) reference_domain = ''.join(reference_domain.split('.')[-2:])
if isinstance(reference_domain, unicode): if isinstance(reference_domain, six.text_type):
reference_domain = reference_domain.encode('utf-8') reference_domain = reference_domain.encode('utf-8')
url_list = [] url_list = []
base_url = self.getContentBaseURL() base_url = self.getContentBaseURL()
...@@ -158,7 +159,7 @@ class CrawlableMixin: ...@@ -158,7 +159,7 @@ class CrawlableMixin:
if not url: if not url:
continue continue
url_domain = urlsplit(url)[1] url_domain = urlsplit(url)[1]
if isinstance(url_domain, unicode): if isinstance(url_domain, six.text_type):
url_domain = url_domain.encode('utf-8') url_domain = url_domain.encode('utf-8')
if url_domain and ''.join(url_domain.split('.')[-2:]) != reference_domain: if url_domain and ''.join(url_domain.split('.')[-2:]) != reference_domain:
continue continue
......
...@@ -119,7 +119,7 @@ class MailMessageMixin: ...@@ -119,7 +119,7 @@ class MailMessageMixin:
for (name, value) in self._getMessage().items(): for (name, value) in self._getMessage().items():
try: try:
decoded_header = decode_header(value) decoded_header = decode_header(value)
except HeaderParseError, error_message: except HeaderParseError as error_message:
decoded_header = () decoded_header = ()
LOG('MailMessageMixin.getContentInformation', INFO, LOG('MailMessageMixin.getContentInformation', INFO,
'Failed to decode %s header of %s with error: %s' % 'Failed to decode %s header of %s with error: %s' %
......
...@@ -110,7 +110,7 @@ class MovementCollectionUpdaterMixin: ...@@ -110,7 +110,7 @@ class MovementCollectionUpdaterMixin:
# First find out all existing (decision) movements which belong to no group # First find out all existing (decision) movements which belong to no group
no_group_list = [] no_group_list = []
for tester_key in decision_movement_dict.keys(): for tester_key in decision_movement_dict.keys():
if prevision_movement_dict.has_key(tester_key): if tester_key in prevision_movement_dict:
for decision_movement in decision_movement_dict[tester_key]: for decision_movement in decision_movement_dict[tester_key]:
no_match = True no_match = True
for prevision_movement in prevision_movement_dict[tester_key]: for prevision_movement in prevision_movement_dict[tester_key]:
......
...@@ -57,7 +57,7 @@ class UrlMixin: ...@@ -57,7 +57,7 @@ class UrlMixin:
# A quick fix for all objects which did not # A quick fix for all objects which did not
# define protocol such as email addresses # define protocol such as email addresses
ptype = self.getPortalType() ptype = self.getPortalType()
if default_protocol_dict.has_key(ptype): if ptype in default_protocol_dict:
protocol = default_protocol_dict[ptype] protocol = default_protocol_dict[ptype]
else: else:
protocol = 'http' protocol = 'http'
......
...@@ -32,7 +32,6 @@ import warnings ...@@ -32,7 +32,6 @@ import warnings
from AccessControl import ModuleSecurityInfo from AccessControl import ModuleSecurityInfo
from DateTime import DateTime from DateTime import DateTime
from datetime import datetime from datetime import datetime
from string import zfill
security = ModuleSecurityInfo(__name__) security = ModuleSecurityInfo(__name__)
security.declarePublic('addToDate', 'getClosestDate', security.declarePublic('addToDate', 'getClosestDate',
...@@ -446,7 +445,7 @@ def convertDateToHour(date=None): ...@@ -446,7 +445,7 @@ def convertDateToHour(date=None):
# and this provides the use of toordinal method. # and this provides the use of toordinal method.
formatted_creation_date = datetime(creation_date_dict['year'],creation_date_dict['month'],creation_date_dict['day']) formatted_creation_date = datetime(creation_date_dict['year'],creation_date_dict['month'],creation_date_dict['day'])
# reference date which is the first day of creation date year # reference date which is the first day of creation date year
reference_date = datetime(creation_date_dict['year'], 01, 1) reference_date = datetime(creation_date_dict['year'], 0o1, 1)
# calculate the ordinal date of the creation date and the reference date # calculate the ordinal date of the creation date and the reference date
ordinal_date = datetime.toordinal(formatted_creation_date) ordinal_date = datetime.toordinal(formatted_creation_date)
ordinal_reference_date = datetime.toordinal(reference_date) ordinal_reference_date = datetime.toordinal(reference_date)
...@@ -494,7 +493,7 @@ def atTheEndOfPeriod(date, period): ...@@ -494,7 +493,7 @@ def atTheEndOfPeriod(date, period):
if period == 'year': if period == 'year':
end = addToDate(DateTime('%s/01/01 00:00:00 %s' % (date.year(), date.timezone())), **{period:1}) end = addToDate(DateTime('%s/01/01 00:00:00 %s' % (date.year(), date.timezone())), **{period:1})
elif period == 'month': elif period == 'month':
end = addToDate(DateTime('%s/%s/01 00:00:00 %s' % (date.year(), zfill(date.month(), 2), date.timezone())), **{period:1}) end = addToDate(DateTime('%s/%02d/01 00:00:00 %s' % (date.year(), date.month(), date.timezone())), **{period:1})
elif period == 'day': elif period == 'day':
end = addToDate(date.earliestTime(), hour=36).earliestTime() end = addToDate(date.earliestTime(), hour=36).earliestTime()
elif period == 'week': elif period == 'week':
......
...@@ -95,8 +95,9 @@ class DiffFile(object): ...@@ -95,8 +95,9 @@ class DiffFile(object):
tmp.append(line) tmp.append(line)
self.children.append(CodeBlock(os.linesep.join(tmp))) self.children.append(CodeBlock(os.linesep.join(tmp)))
def __nonzero__(self): def __bool__(self):
return self.binary or bool(self.children) return self.binary or bool(self.children)
__nonzero__ = __bool__ # six.PY2
def __len__(self): def __len__(self):
return len(self.children) return len(self.children)
......
...@@ -239,7 +239,7 @@ class ExplanationCache: ...@@ -239,7 +239,7 @@ class ExplanationCache:
# Build a list of path patterns which apply to current business_link # Build a list of path patterns which apply to current business_link
path_list = iter(self.getSimulationPathPatternList()) path_list = iter(self.getSimulationPathPatternList())
path_dict = {x: path_list.next() for x in path_list} path_dict = {x: next(path_list) for x in path_list}
# path_dict is like this; # path_dict is like this;
# {'/erp5/portal_simulation/3/4': r'/erp5/portal\_simulation/3/4/%'} # {'/erp5/portal_simulation/3/4': r'/erp5/portal\_simulation/3/4/%'}
path_list = [] path_list = []
......
...@@ -112,7 +112,7 @@ def _getPropertyList(document, acquire=True): ...@@ -112,7 +112,7 @@ def _getPropertyList(document, acquire=True):
elif (x.get('storage_id') or property_id) not in document_dict: elif (x.get('storage_id') or property_id) not in document_dict:
continue continue
# we don't want acquired properties without acquisition_mask_value # we don't want acquired properties without acquisition_mask_value
elif x.has_key('acquisition_base_category') and not x.get('acquisition_mask_value', 0): elif 'acquisition_base_category' in x and not x.get('acquisition_mask_value', 0):
continue continue
elif x['type'] in list_types and not property_id.endswith('_list'): elif x['type'] in list_types and not property_id.endswith('_list'):
property_dict[property_id] = getPropertyList(property_id) property_dict[property_id] = getPropertyList(property_id)
......
...@@ -26,9 +26,7 @@ ...@@ -26,9 +26,7 @@
# #
############################################################################## ##############################################################################
from xmlrpclib import ProtocolError from six.moves.xmlrpc_client import ProtocolError, Transport, SafeTransport
from xmlrpclib import Transport
from xmlrpclib import SafeTransport
import socket import socket
class TimeoutTransport(SafeTransport): class TimeoutTransport(SafeTransport):
......
...@@ -23,7 +23,7 @@ from Products.ERP5Type.Globals import InitializeClass ...@@ -23,7 +23,7 @@ from Products.ERP5Type.Globals import InitializeClass
from Products.ERP5Type import Permissions from Products.ERP5Type import Permissions
from Products.CMFCore.PortalContent import ResourceLockedError from Products.CMFCore.PortalContent import ResourceLockedError
from zExceptions import Forbidden from zExceptions import Forbidden
from cStringIO import StringIO from io import StringIO
security = ModuleSecurityInfo(__name__) security = ModuleSecurityInfo(__name__)
......
from urllib import unquote from six.moves.urllib.parse import unquote
return unquote(value).decode('base64').split(':', 1)[0] from base64 import standard_b64decode
return standard_b64decode(unquote(value)).split(b':', 1)[0].decode()
...@@ -9,7 +9,7 @@ if username is not None: ...@@ -9,7 +9,7 @@ if username is not None:
) )
) )
REQUEST = portal.REQUEST REQUEST = portal.REQUEST
if REQUEST.has_key('portal_skin'): if 'portal_skin' in REQUEST:
portal.portal_skins.clearSkinCookie() portal.portal_skins.clearSkinCookie()
REQUEST.RESPONSE.expireCookie('__ac', path='/') REQUEST.RESPONSE.expireCookie('__ac', path='/')
......
from urlparse import urlparse from six.moves.urllib.parse import urlparse
portal = context.getPortalObject() portal = context.getPortalObject()
kw = {} kw = {}
......
...@@ -90,7 +90,7 @@ try: ...@@ -90,7 +90,7 @@ try:
request.set('editable_mode', 1) request.set('editable_mode', 1)
form.validate_all_to_request(request) form.validate_all_to_request(request)
request.set('editable_mode', editable_mode) request.set('editable_mode', editable_mode)
except FormValidationError, validation_errors: except FormValidationError as validation_errors:
# Pack errors into the request # Pack errors into the request
field_errors = form.ErrorFields(validation_errors) field_errors = form.ErrorFields(validation_errors)
request.set('field_errors', field_errors) request.set('field_errors', field_errors)
...@@ -159,7 +159,7 @@ listbox_uid = kw.get('listbox_uid', None) ...@@ -159,7 +159,7 @@ listbox_uid = kw.get('listbox_uid', None)
# In some cases, the listbox exists, is editable, but the selection name # In some cases, the listbox exists, is editable, but the selection name
# has no meaning, for example fast input dialogs. # has no meaning, for example fast input dialogs.
# In such cases, we must not try to update a non-existing selection. # In such cases, we must not try to update a non-existing selection.
if listbox_uid is not None and kw.has_key('list_selection_name'): if listbox_uid is not None and 'list_selection_name' in kw:
uids = kw.get('uids') uids = kw.get('uids')
context.portal_selections.updateSelectionCheckedUidList( context.portal_selections.updateSelectionCheckedUidList(
kw['list_selection_name'], kw['list_selection_name'],
......
...@@ -20,7 +20,7 @@ try: ...@@ -20,7 +20,7 @@ try:
sort_on += [(k, v, t)] sort_on += [(k, v, t)]
i += 1 i += 1
context.portal_selections.setSelectionSortOrder(selection_name, sort_on) context.portal_selections.setSelectionSortOrder(selection_name, sort_on)
except FormValidationError, validation_errors: except FormValidationError as validation_errors:
# Pack errors into the request # Pack errors into the request
field_errors = form.ErrorFields(validation_errors) field_errors = form.ErrorFields(validation_errors)
request.set('field_errors', field_errors) request.set('field_errors', field_errors)
......
...@@ -62,7 +62,7 @@ try: ...@@ -62,7 +62,7 @@ try:
if k != 'None': if k != 'None':
columns += [(k , columns_dict[k])] columns += [(k , columns_dict[k])]
context.portal_selections.setSelectionColumns(selection_name, columns, REQUEST=request) context.portal_selections.setSelectionColumns(selection_name, columns, REQUEST=request)
except FormValidationError, validation_errors: except FormValidationError as validation_errors:
# Pack errors into the request # Pack errors into the request
field_errors = form.ErrorFields(validation_errors) field_errors = form.ErrorFields(validation_errors)
request.set('field_errors', field_errors) request.set('field_errors', field_errors)
......
...@@ -13,10 +13,10 @@ kw = { 'selection_index': selection_index, ...@@ -13,10 +13,10 @@ kw = { 'selection_index': selection_index,
# Default behaviour is not as great but returns something # Default behaviour is not as great but returns something
kw.update(request.form) kw.update(request.form)
if kw.has_key('listbox_uid'): del kw['listbox_uid'] if 'listbox_uid' in kw: del kw['listbox_uid']
if kw.has_key('list_start'): del kw['list_start'] if 'list_start' in kw: del kw['list_start']
if request.form.has_key('dialog_id'): if 'dialog_id' in request.form:
form_id = request.form['dialog_id'] form_id = request.form['dialog_id']
else: else:
form_id = request.form['form_id'] form_id = request.form['form_id']
......
...@@ -37,14 +37,14 @@ edit_order = form.edit_order ...@@ -37,14 +37,14 @@ edit_order = form.edit_order
try: try:
# Validate # Validate
form.validate_all_to_request(request, key_prefix=key_prefix) form.validate_all_to_request(request, key_prefix=key_prefix)
except FormValidationError, validation_errors: except FormValidationError as validation_errors:
# Pack errors into the request # Pack errors into the request
field_errors = form.ErrorFields(validation_errors) field_errors = form.ErrorFields(validation_errors)
request.set('field_errors', field_errors) request.set('field_errors', field_errors)
# Make sure editors are pushed back as values into the REQUEST object # Make sure editors are pushed back as values into the REQUEST object
for field in form.get_fields(): for field in form.get_fields():
field_id = field.id field_id = field.id
if request.has_key(field_id): if field_id in request:
value = request.get(field_id) value = request.get(field_id)
if callable(value): if callable(value):
value(request) value(request)
...@@ -163,11 +163,11 @@ def editMatrixBox(matrixbox_field, matrixbox): ...@@ -163,11 +163,11 @@ def editMatrixBox(matrixbox_field, matrixbox):
cell = matrix_context.newCell(*cell_index_tuple, **k_dict) cell = matrix_context.newCell(*cell_index_tuple, **k_dict)
if cell is not None: if cell is not None:
cell.edit(edit_order=edit_order, **global_property_dict) # First update globals which include the def. of property_list cell.edit(edit_order=edit_order, **global_property_dict) # First update globals which include the def. of property_list
if cell_dict.has_key('variated_property'): if 'variated_property' in cell_dict:
# For Variated Properties # For Variated Properties
variated_property = cell_dict['variated_property'] variated_property = cell_dict['variated_property']
del cell_dict['variated_property'] del cell_dict['variated_property']
if global_property_dict.has_key('mapped_value_property_list'): if 'mapped_value_property_list' in global_property_dict:
# Change the property which is defined by the # Change the property which is defined by the
# first element of mapped_value_property_list # first element of mapped_value_property_list
# XXX May require some changes with Sets # XXX May require some changes with Sets
......
...@@ -11,7 +11,7 @@ old_request = dict(saved_form_data) ...@@ -11,7 +11,7 @@ old_request = dict(saved_form_data)
field = getattr(context, form_id).get_field(field_id) field = getattr(context, form_id).get_field(field_id)
field_key = field.generate_field_key() field_key = field.generate_field_key()
if old_request.has_key('sub_index'): if 'sub_index' in old_request:
if len(uids) > 0: if len(uids) > 0:
# XXX Hardcoded # XXX Hardcoded
sub_field_key = field.generate_subfield_key("%s_%s" % (SUB_FIELD_ID, old_request['sub_index']), key=field_key) sub_field_key = field.generate_subfield_key("%s_%s" % (SUB_FIELD_ID, old_request['sub_index']), key=field_key)
......
...@@ -19,14 +19,14 @@ form = getattr(context,form_id) ...@@ -19,14 +19,14 @@ form = getattr(context,form_id)
try: try:
# Validate # Validate
form.validate_all_to_request(request) form.validate_all_to_request(request)
except FormValidationError, validation_errors: except FormValidationError as validation_errors:
# Pack errors into the request # Pack errors into the request
field_errors = form.ErrorFields(validation_errors) field_errors = form.ErrorFields(validation_errors)
request.set('field_errors', field_errors) request.set('field_errors', field_errors)
# Make sure editors are pushed back as values into the REQUEST object # Make sure editors are pushed back as values into the REQUEST object
for f in form.get_fields(): for f in form.get_fields():
field_id = f.id field_id = f.id
if request.has_key(field_id): if field_id in request:
value = request.get(field_id) value = request.get(field_id)
if callable(value): if callable(value):
value(request) value(request)
...@@ -69,7 +69,7 @@ try: ...@@ -69,7 +69,7 @@ try:
for encapsulated_editor in encapsulated_editor_list: for encapsulated_editor in encapsulated_editor_list:
encapsulated_editor.edit(context) encapsulated_editor.edit(context)
except ActivityPendingError,e: except ActivityPendingError as e:
message = Base_translateString("%s" % e) message = Base_translateString("%s" % e)
ignore_layout = int(ignore_layout) ignore_layout = int(ignore_layout)
......
from Products.ERP5Type.Message import translateString from Products.ERP5Type.Message import translateString
from Products.ERP5Type.Document import newTempBase from Products.ERP5Type.Document import newTempBase
from string import zfill
portal = context.getPortalObject() portal = context.getPortalObject()
request = context.REQUEST request = context.REQUEST
domain_list = [] domain_list = []
...@@ -28,7 +27,7 @@ if depth == 0: ...@@ -28,7 +27,7 @@ if depth == 0:
# 0.125 means 3 hours in DateTime float format # 0.125 means 3 hours in DateTime float format
while current_date < bound_stop: while current_date < bound_stop:
# Create one Temp Object # Create one Temp Object
o = newTempBase(portal, id='year', uid='new_%s' % zfill('year',4)) o = newTempBase(portal, id='year', uid='new_year')
# Setting Axis Dates start and stop # Setting Axis Dates start and stop
o.setProperty('start',current_date) o.setProperty('start',current_date)
o.setProperty('stop', current_date + 0.125) o.setProperty('stop', current_date + 0.125)
......
...@@ -4,7 +4,6 @@ ...@@ -4,7 +4,6 @@
from Products.ERP5Type.Message import Message from Products.ERP5Type.Message import Message
from Products.ERP5Type.Document import newTempBase from Products.ERP5Type.Document import newTempBase
from Products.PythonScripts.standard import url_quote from Products.PythonScripts.standard import url_quote
from string import zfill
portal = context.getPortalObject() portal = context.getPortalObject()
request = context.REQUEST request = context.REQUEST
domain_list = [] domain_list = []
...@@ -19,7 +18,7 @@ zoom_begin = DateTime(bound_start.year(), bound_start.month(), bound_start.day() ...@@ -19,7 +18,7 @@ zoom_begin = DateTime(bound_start.year(), bound_start.month(), bound_start.day()
# Normalize Month. # Normalize Month.
month = zoom_begin.month() + zoom_variation month = zoom_begin.month() + zoom_variation
year = zoom_begin.year() + (month - 1) / 12 year = zoom_begin.year() + (month - 1) // 12
month = month % 12 month = month % 12
if month == 0: if month == 0:
month = 12 month = 12
...@@ -47,7 +46,7 @@ if depth == 0: ...@@ -47,7 +46,7 @@ if depth == 0:
while current_date < axis_stop: while current_date < axis_stop:
# Create one Temp Object # Create one Temp Object
o = newTempBase(portal, id=str(current_date.Day()), o = newTempBase(portal, id=str(current_date.Day()),
uid='new_%s' % zfill('year',4)) uid='new_year')
# Setting Axis Dates start and stop # Setting Axis Dates start and stop
o.setProperty('start',current_date) o.setProperty('start',current_date)
......
...@@ -4,7 +4,6 @@ ...@@ -4,7 +4,6 @@
from Products.ERP5Type.Message import translateString from Products.ERP5Type.Message import translateString
from Products.ERP5Type.Document import newTempBase from Products.ERP5Type.Document import newTempBase
from Products.PythonScripts.standard import url_quote from Products.PythonScripts.standard import url_quote
from string import zfill
portal = context.getPortalObject() portal = context.getPortalObject()
request = context.REQUEST request = context.REQUEST
...@@ -39,7 +38,7 @@ if depth == 0: ...@@ -39,7 +38,7 @@ if depth == 0:
# This case show Seven days # This case show Seven days
while current_date < bound_stop: while current_date < bound_stop:
# Create one Temp Object # Create one Temp Object
o = newTempBase(portal, id='week', uid='new_%s' % zfill('week',4)) o = newTempBase(portal, id='week', uid='new_week')
# Setting Axis Dates start and stop # Setting Axis Dates start and stop
o.setProperty('start',current_date) o.setProperty('start',current_date)
o.setProperty('stop', current_date+1) o.setProperty('stop', current_date+1)
......
...@@ -4,7 +4,6 @@ ...@@ -4,7 +4,6 @@
from Products.ERP5Type.Message import translateString from Products.ERP5Type.Message import translateString
from Products.ERP5Type.Document import newTempBase from Products.ERP5Type.Document import newTempBase
from Products.PythonScripts.standard import url_quote from Products.PythonScripts.standard import url_quote
from string import zfill
portal = context.getPortalObject() portal = context.getPortalObject()
request = context.REQUEST request = context.REQUEST
...@@ -27,7 +26,7 @@ if depth == 0: ...@@ -27,7 +26,7 @@ if depth == 0:
count = 0 count = 0
while count < 12: while count < 12:
# Create one Temp Object # Create one Temp Object
o = newTempBase(portal, id='year', uid='new_%s' % zfill('year',4)) o = newTempBase(portal, id='year', uid='new_year')
# Setting delimiter # Setting delimiter
if current_date.month() in [1, 7]: if current_date.month() in [1, 7]:
o.setProperty('delimiter_type', 1) o.setProperty('delimiter_type', 1)
......
...@@ -189,7 +189,7 @@ for table_name in spreadsheet_list.keys(): ...@@ -189,7 +189,7 @@ for table_name in spreadsheet_list.keys():
# we should try to use other line data to get a safe id. # we should try to use other line data to get a safe id.
if cell_id == '' and property_id.startswith('path_'): if cell_id == '' and property_id.startswith('path_'):
for alt_id_source in ['id', 'title']: for alt_id_source in ['id', 'title']:
if line_data.has_key(alt_id_source): if alt_id_source in line_data:
cell_id = getIDFromString(line_data[alt_id_source]) cell_id = getIDFromString(line_data[alt_id_source])
if cell_id not in ('', None): if cell_id not in ('', None):
break break
......
if context.REQUEST.has_key('workflow_action'): # We are on a workflow transition if 'workflow_action' in context.REQUEST: # We are on a workflow transition
help_relative_url = '%s#%s' % (getattr(getattr(context, form_id), 'form_action'),context.REQUEST['workflow_action']) help_relative_url = '%s#%s' % (getattr(getattr(context, form_id), 'form_action'),context.REQUEST['workflow_action'])
elif action is not None: elif action is not None:
help_relative_url = '%s#%s' % (context.getPortalTypeName(), action) help_relative_url = '%s#%s' % (context.getPortalTypeName(), action)
......
...@@ -13,7 +13,7 @@ for item in item_list: ...@@ -13,7 +13,7 @@ for item in item_list:
item_key = '/'.join(item_split[:split_depth]) item_key = '/'.join(item_split[:split_depth])
base_category = item_split[0] base_category = item_split[0]
# Create a new subfield if necessary # Create a new subfield if necessary
if not sub_field_dict.has_key(item_key): if item_key not in sub_field_dict:
# Create property dict (key are field parameters) # Create property dict (key are field parameters)
sub_field_property_dict = default_sub_field_property_dict.copy() sub_field_property_dict = default_sub_field_property_dict.copy()
sub_field_property_dict['key'] = item_key sub_field_property_dict['key'] = item_key
......
...@@ -23,7 +23,7 @@ for item in item_list: ...@@ -23,7 +23,7 @@ for item in item_list:
item_key = '/'.join(item_split[:split_depth]) item_key = '/'.join(item_split[:split_depth])
base_category = item_split[0] base_category = item_split[0]
# Create a new subfield if necessary # Create a new subfield if necessary
if not sub_field_dict.has_key(item_key): if item_key not in sub_field_dict:
# Create property dict (key are field parameters) # Create property dict (key are field parameters)
sub_field_property_dict = default_sub_field_property_dict.copy() sub_field_property_dict = default_sub_field_property_dict.copy()
sub_field_property_dict['key'] = item_key sub_field_property_dict['key'] = item_key
......
...@@ -33,7 +33,7 @@ section_item_list = getPreferredSectionItemList(portal_type, validation_state) ...@@ -33,7 +33,7 @@ section_item_list = getPreferredSectionItemList(portal_type, validation_state)
if base_category: if base_category:
section_item_list = section_item_list[::] # make a copy not to modify the cache value section_item_list = section_item_list[::] # make a copy not to modify the cache value
current_category = context.getProperty(base_category) current_category = context.getProperty(base_category)
if current_category and current_category not in zip(*section_item_list)[1]: if current_category and current_category not in list(zip(*section_item_list))[1]:
section_item_list.append( section_item_list.append(
(context.getProperty('%s_title' % base_category), (context.getProperty('%s_title' % base_category),
context.getProperty(base_category))) context.getProperty(base_category)))
......
...@@ -23,7 +23,7 @@ for history_name in history_name_list: ...@@ -23,7 +23,7 @@ for history_name in history_name_list:
history_element_title_list = [] history_element_title_list = []
for history_element_title in list_history_item[-1].keys(): for history_element_title in list_history_item[-1].keys():
if history_element_title <> history_name: if history_element_title != history_name:
new_title = history_element_title.replace('_', ' ').title() new_title = history_element_title.replace('_', ' ').title()
history_element_title_list.append(new_title) history_element_title_list.append(new_title)
...@@ -31,7 +31,7 @@ for history_name in history_name_list: ...@@ -31,7 +31,7 @@ for history_name in history_name_list:
for history_item in list_history_item: for history_item in list_history_item:
history_item_info = () history_item_info = ()
for history_element_title in list_history_item[-1].keys(): for history_element_title in list_history_item[-1].keys():
if history_element_title <> history_name: if history_element_title != history_name:
history_item_info += (history_item.get(history_element_title),) history_item_info += (history_item.get(history_element_title),)
history_item_list.append(history_item_info) history_item_list.append(history_item_info)
history_item_list.reverse() history_item_list.reverse()
......
...@@ -14,7 +14,7 @@ for workflow_id in workflow_id_list: ...@@ -14,7 +14,7 @@ for workflow_id in workflow_id_list:
for state in workflow.getStateValueList(): for state in workflow.getStateValueList():
state_reference = state.getReference() state_reference = state.getReference()
if state.getTitle() and state_reference != 'deleted': if state.getTitle() and state_reference != 'deleted':
if not state_dict.has_key(state_reference): if state_reference not in state_dict:
# we hide states without titles # we hide states without titles
item_list.append((state.getTitle(), state_reference)) item_list.append((state.getTitle(), state_reference))
state_dict[state_reference] = None state_dict[state_reference] = None
......
import six
from AccessControl import getSecurityManager from AccessControl import getSecurityManager
from zExceptions import Unauthorized from zExceptions import Unauthorized
from Products.ERP5Type.Document import newTempBase from Products.ERP5Type.Document import newTempBase
...@@ -10,9 +11,9 @@ if not getSecurityManager().getUser().has_permission('View History', context): ...@@ -10,9 +11,9 @@ if not getSecurityManager().getUser().has_permission('View History', context):
def beautifyChange(change_dict): def beautifyChange(change_dict):
change_list = [] change_list = []
for property_name, property_value in sorted(change_dict.items()): for property_name, property_value in sorted(change_dict.items()):
if isinstance(property_value, basestring): if isinstance(property_value, six.binary_type):
try: try:
unicode(property_value, 'utf-8') property_value.decode('utf-8')
except UnicodeDecodeError: except UnicodeDecodeError:
property_value = '(binary)' property_value = '(binary)'
change_list.append('%s:%s' % (property_name, property_value)) change_list.append('%s:%s' % (property_name, property_value))
......
...@@ -14,8 +14,8 @@ if from_cat is not None and to_cat is not None: ...@@ -14,8 +14,8 @@ if from_cat is not None and to_cat is not None:
new_category_list += (cat,) new_category_list += (cat,)
if has_changed == 1: if has_changed == 1:
o.setCategoryList(new_category_list) o.setCategoryList(new_category_list)
print "changed category %s with %s on %s" % (str(from_cat),str(to_cat),str(o.getPath())) print("changed category %s with %s on %s" % (str(from_cat),str(to_cat),str(o.getPath())))
print " " print(" ")
return printed return printed
...@@ -43,7 +43,7 @@ erp5_role_dict = { ...@@ -43,7 +43,7 @@ erp5_role_dict = {
erp5_permission_dict = {} erp5_permission_dict = {}
for role,permission_list in erp5_role_dict.items(): for role,permission_list in erp5_role_dict.items():
for permission in permission_list: for permission in permission_list:
if not erp5_permission_dict.has_key(permission): if permission not in erp5_permission_dict:
erp5_permission_dict[permission] = [] erp5_permission_dict[permission] = []
erp5_permission_dict[permission].append(role) erp5_permission_dict[permission].append(role)
......
...@@ -4,6 +4,7 @@ ...@@ -4,6 +4,7 @@
containing searched words as well highlighting the searched containing searched words as well highlighting the searched
words in the text itself. words in the text itself.
""" """
import six
from erp5.component.document.Document import NotConvertedError from erp5.component.document.Document import NotConvertedError
encoding = 'utf-8' encoding = 'utf-8'
...@@ -27,7 +28,7 @@ if document_text is None: ...@@ -27,7 +28,7 @@ if document_text is None:
try: try:
# if SearchableText is joinned as it is, we use it for better performance. # if SearchableText is joinned as it is, we use it for better performance.
document_text = getattr(context, 'SearchableText', None) document_text = getattr(context, 'SearchableText', None)
if not isinstance(document_text, (str, unicode)): if not isinstance(document_text, six.string_types):
document_text = context.getSearchableText() document_text = context.getSearchableText()
except NotConvertedError: except NotConvertedError:
return context.Base_translateString("This document is not converted yet.") return context.Base_translateString("This document is not converted yet.")
......
from past.builtins import cmp
def generic_sort(a,b): def generic_sort(a,b):
result = 0 result = 0
for k,v in sort_order: for k,v in sort_order:
......
from string import zfill
request = context.REQUEST request = context.REQUEST
if kw.get('update', False): if kw.get('update', False):
...@@ -13,10 +12,10 @@ for k in kw.keys(): ...@@ -13,10 +12,10 @@ for k in kw.keys():
if v is not None: if v is not None:
i = 1 i = 1
for line in v: for line in v:
if line.has_key(listbox_key): if listbox_key in line:
key = '%s' % line[listbox_key] key = '%s' % line[listbox_key]
else: else:
key = str(zfill(i,3)) key = '%03d' % i
listbox[key] = line listbox[key] = line
i+=1 i+=1
request.set(k,listbox) request.set(k,listbox)
......
from six import string_types as basestring
portal = context.getPortalObject() portal = context.getPortalObject()
get = portal.REQUEST.get get = portal.REQUEST.get
selection_name = get('list_selection_name') selection_name = get('list_selection_name')
......
return request.has_key('Base_showUpdateDialog') or value return 'Base_showUpdateDialog' in request or value
...@@ -176,7 +176,7 @@ try: ...@@ -176,7 +176,7 @@ try:
request.set('default_module', my_field.get_value('default_module')) request.set('default_module', my_field.get_value('default_module'))
request.set('portal_type', portal_type[0]) request.set('portal_type', portal_type[0])
return o.Base_viewCreateRelationDialog( REQUEST=request ) return o.Base_viewCreateRelationDialog( REQUEST=request )
except FormValidationError, validation_errors: except FormValidationError as validation_errors:
# Pack errors into the request # Pack errors into the request
field_errors = form.ErrorFields(validation_errors) field_errors = form.ErrorFields(validation_errors)
request.set('field_errors', field_errors) request.set('field_errors', field_errors)
......
...@@ -11,7 +11,7 @@ if 1: # keep indentation ...@@ -11,7 +11,7 @@ if 1: # keep indentation
**kw) **kw)
except WorkflowException: except WorkflowException:
pass pass
except ValidationFailed, message: except ValidationFailed as message:
if getattr(message, 'msg', None) and same_type(message.msg, []): if getattr(message, 'msg', None) and same_type(message.msg, []):
message = '. '.join('%s' % x for x in message.msg) message = '. '.join('%s' % x for x in message.msg)
if not batch : if not batch :
......
...@@ -114,7 +114,7 @@ for skin_folder_id in skin_id_list: ...@@ -114,7 +114,7 @@ for skin_folder_id in skin_id_list:
form_id = form.getId() form_id = form.getId()
form_path = '%s/%s' % (skin_folder_id, form_id) form_path = '%s/%s' % (skin_folder_id, form_id)
if modified_object_dict.has_key(form_path): if form_path in modified_object_dict:
# The form is a Field Library # The form is a Field Library
if modified_object_dict[form_path] == '4_delete_form': if modified_object_dict[form_path] == '4_delete_form':
# As the form will be deleted, no need to manage its fields # As the form will be deleted, no need to manage its fields
......
...@@ -45,7 +45,7 @@ for cat_info in cat_info_list: ...@@ -45,7 +45,7 @@ for cat_info in cat_info_list:
for cat in cat_list: for cat in cat_list:
path_cell_list = [''] * (max_cat_depth - 1) path_cell_list = [''] * (max_cat_depth - 1)
path_cell_list[len(cat.getRelativeUrl().split('/')) - 2] = '*' path_cell_list[len(cat.getRelativeUrl().split('/')) - 2] = '*'
category_property_list = map(cat.getProperty, editable_property_id_list) category_property_list = list(map(cat.getProperty, editable_property_id_list))
row_list.append({ row_list.append({
'path_cell_list': path_cell_list, 'path_cell_list': path_cell_list,
'category_property_list': category_property_list, 'category_property_list': category_property_list,
......
...@@ -18,6 +18,7 @@ From document pointed to by 'relative_url': ...@@ -18,6 +18,7 @@ From document pointed to by 'relative_url':
For the portal, 'relative_url' must be false and only module objects are For the portal, 'relative_url' must be false and only module objects are
considered if id_list is None. considered if id_list is None.
""" """
from six.moves import xrange
document = context.getPortalObject() document = context.getPortalObject()
context = document.portal_activities context = document.portal_activities
if relative_url: if relative_url:
......
...@@ -7,6 +7,7 @@ as first element or not (just like category tool API) ...@@ -7,6 +7,7 @@ as first element or not (just like category tool API)
The state titles will be translated unless you pass translate=False The state titles will be translated unless you pass translate=False
''' '''
from six import string_types as basestring
if translate: if translate:
from Products.ERP5Type.Message import translateString from Products.ERP5Type.Message import translateString
else: else:
......
...@@ -18,7 +18,7 @@ inventory_tag = base_tag + 'inventory' ...@@ -18,7 +18,7 @@ inventory_tag = base_tag + 'inventory'
last_inventory_tag = base_tag + 'last_inventory_activity' last_inventory_tag = base_tag + 'last_inventory_activity'
def reindex(document_list, tag, after_tag): def reindex(document_list, tag, after_tag):
for document in document_list: for document in document_list:
print '#### Indexing', document.id, '####' print('#### Indexing', document.id, '####')
document.activate( document.activate(
priority=additional_priority, priority=additional_priority,
tag=tag, tag=tag,
...@@ -37,7 +37,7 @@ def reindex(document_list, tag, after_tag): ...@@ -37,7 +37,7 @@ def reindex(document_list, tag, after_tag):
# security_uid explosion if many users (ex: persons) have local roles on # security_uid explosion if many users (ex: persons) have local roles on
# documents (ex: persons) granting them View permission but the user is not # documents (ex: persons) granting them View permission but the user is not
# indexed before corresponding document is. # indexed before corresponding document is.
print "#### Indexing person_module, stage 1 ####" print("#### Indexing person_module, stage 1 ####")
person_module = getattr(portal, 'person_module', None) person_module = getattr(portal, 'person_module', None)
if person_module is not None: if person_module is not None:
person_module.recurseCallMethod( person_module.recurseCallMethod(
...@@ -51,30 +51,30 @@ if person_module is not None: ...@@ -51,30 +51,30 @@ if person_module is not None:
}, },
max_depth=1, # Do not reindex Person's subobjects max_depth=1, # Do not reindex Person's subobjects
) )
print "#### Indexing translations ####" print("#### Indexing translations ####")
portal.ERP5Site_updateTranslationTable(sql_catalog_id=sql_catalog_id) portal.ERP5Site_updateTranslationTable(sql_catalog_id=sql_catalog_id)
print reindex( print(reindex(
[portal.portal_categories], [portal.portal_categories],
tag=category_tag, tag=category_tag,
after_tag=user_tag, after_tag=user_tag,
), ))
print reindex( print(reindex(
[portal.portal_alarms, portal.portal_activities], [portal.portal_alarms, portal.portal_activities],
tag=document_tag, tag=document_tag,
after_tag=(user_tag, category_tag), after_tag=(user_tag, category_tag),
), ))
print reindex( print(reindex(
[portal.portal_preferences], [portal.portal_preferences],
tag=preference_tag, tag=preference_tag,
after_tag=(user_tag, category_tag), after_tag=(user_tag, category_tag),
), ))
# Simulation is needed to calculate tests (ie. related quantity) # Simulation is needed to calculate tests (ie. related quantity)
print reindex( print(reindex(
[portal.portal_simulation], [portal.portal_simulation],
tag=simulation_tag, tag=simulation_tag,
after_tag=(user_tag, category_tag, document_tag, preference_tag), after_tag=(user_tag, category_tag, document_tag, preference_tag),
), ))
print reindex( print(reindex(
[ [
x for x in portal.objectValues() x for x in portal.objectValues()
if x.getUid != portal.getUid and if x.getUid != portal.getUid and
...@@ -90,7 +90,7 @@ print reindex( ...@@ -90,7 +90,7 @@ print reindex(
], ],
tag=document_tag, tag=document_tag,
after_tag=(user_tag, category_tag, preference_tag), after_tag=(user_tag, category_tag, preference_tag),
), ))
# Then we index ERP5 Python Scripts and ERP5 Form - this is fundamentally broken and will go away, do not depend on it ! # Then we index ERP5 Python Scripts and ERP5 Form - this is fundamentally broken and will go away, do not depend on it !
skin_activate_kw = { skin_activate_kw = {
'tag': document_tag, 'tag': document_tag,
...@@ -100,14 +100,14 @@ skin_activate_kw = { ...@@ -100,14 +100,14 @@ skin_activate_kw = {
for _, obj in portal.portal_skins.ZopeFind(portal.portal_skins, obj_metatypes=('ERP5 Python Script', 'ERP5 Form', 'ERP5 Report'), search_sub=1): for _, obj in portal.portal_skins.ZopeFind(portal.portal_skins, obj_metatypes=('ERP5 Python Script', 'ERP5 Form', 'ERP5 Report'), search_sub=1):
obj.recursiveReindexObject(activate_kw=skin_activate_kw, obj.recursiveReindexObject(activate_kw=skin_activate_kw,
sql_catalog_id=sql_catalog_id) sql_catalog_id=sql_catalog_id)
print reindex( print(reindex(
[ [
x for x in portal.objectValues(("ERP5 Folder", )) x for x in portal.objectValues(("ERP5 Folder", ))
if 'inventory' in x.id if 'inventory' in x.id
], ],
tag=inventory_tag, tag=inventory_tag,
after_tag=(user_tag, category_tag, document_tag, preference_tag), after_tag=(user_tag, category_tag, document_tag, preference_tag),
), ))
portal.portal_activities.activate( portal.portal_activities.activate(
after_tag=(user_tag, category_tag, document_tag, preference_tag, inventory_tag, simulation_tag), after_tag=(user_tag, category_tag, document_tag, preference_tag, inventory_tag, simulation_tag),
......
...@@ -11,7 +11,7 @@ for error in error_list: ...@@ -11,7 +11,7 @@ for error in error_list:
# We count the number of each portal type # We count the number of each portal type
if error[1]=='portal_type': if error[1]=='portal_type':
portal_type = error[3] portal_type = error[3]
if nb_types.has_key(portal_type): if portal_type in nb_types:
nb_types[portal_type] = nb_types[portal_type] + 1 nb_types[portal_type] = nb_types[portal_type] + 1
else: else:
nb_types[portal_type] = 1 nb_types[portal_type] = 1
......
...@@ -24,5 +24,5 @@ for candidate in candidate_list: ...@@ -24,5 +24,5 @@ for candidate in candidate_list:
obj.reindexObject() obj.reindexObject()
reindex_count += 1 reindex_count += 1
print '%s object reindexed, %s object unindexed' % (reindex_count, unindex_count) print('%s object reindexed, %s object unindexed' % (reindex_count, unindex_count))
return printed return printed
from ZTUtils import make_query from ZTUtils import make_query
return make_query((item for item in http_parameter_list.items() if item[1] is not None)) return make_query((item for item in list(http_parameter_list.items()) if item[1] is not None))
...@@ -33,7 +33,7 @@ for portal_type in portal_type_list: ...@@ -33,7 +33,7 @@ for portal_type in portal_type_list:
state_reference = state.getReference() state_reference = state.getReference()
for lang in supported_languages: for lang in supported_languages:
key = (lang, portal_type.getId(), state_var, state_reference) key = (lang, portal_type.getId(), state_var, state_reference)
if not translated_keys.has_key(key): if key not in translated_keys:
translated_message = context.Localizer.erp5_ui.gettext(state_reference, lang=lang).encode('utf-8') translated_message = context.Localizer.erp5_ui.gettext(state_reference, lang=lang).encode('utf-8')
translated_keys[key] = None # mark as translated translated_keys[key] = None # mark as translated
object_list.append(dict(language=lang, message_context=state_var, portal_type=portal_type.getId(), original_message=state_reference, object_list.append(dict(language=lang, message_context=state_var, portal_type=portal_type.getId(), original_message=state_reference,
...@@ -48,7 +48,7 @@ for portal_type in portal_type_list: ...@@ -48,7 +48,7 @@ for portal_type in portal_type_list:
msg_id = state.getTitle() msg_id = state.getTitle()
translated_message = context.Localizer.erp5_ui.gettext(state.getTitle().decode('utf-8'), lang=lang).encode('utf-8') translated_message = context.Localizer.erp5_ui.gettext(state.getTitle().decode('utf-8'), lang=lang).encode('utf-8')
key = (lang, portal_type.getId(), state_var_title, state_reference, msg_id) key = (lang, portal_type.getId(), state_var_title, state_reference, msg_id)
if not translated_keys.has_key(key): if key not in translated_keys:
translated_keys[key] = None # mark as translated translated_keys[key] = None # mark as translated
object_list.append(dict(language=lang, message_context=state_var_title, portal_type=portal_type.getId(), original_message=state_reference, object_list.append(dict(language=lang, message_context=state_var_title, portal_type=portal_type.getId(), original_message=state_reference,
translated_message=translated_message)) translated_message=translated_message))
...@@ -64,12 +64,12 @@ for ptype in context.portal_types.objectValues(): ...@@ -64,12 +64,12 @@ for ptype in context.portal_types.objectValues():
if not portal_type: portal_type = ptype.id if not portal_type: portal_type = ptype.id
for lang in supported_languages: for lang in supported_languages:
key = (lang, 'portal_type', portal_type) key = (lang, 'portal_type', portal_type)
if not translated_keys.has_key(key): if key not in translated_keys:
translated_keys[key] = None # mark as translated translated_keys[key] = None # mark as translated
object_list.append(dict(language=lang, message_context='portal_type', portal_type=portal_type, original_message=portal_type, object_list.append(dict(language=lang, message_context='portal_type', portal_type=portal_type, original_message=portal_type,
translated_message=context.Localizer.erp5_ui.gettext(portal_type, lang=lang).encode('utf-8'))) translated_message=context.Localizer.erp5_ui.gettext(portal_type, lang=lang).encode('utf-8')))
if object_list: if object_list:
catalog_translation_list(object_list) catalog_translation_list(object_list)
print 'Done' print('Done')
return printed return printed
from six.moves import xrange
from Products.Formulator.Errors import FormValidationError from Products.Formulator.Errors import FormValidationError
from Products.ERP5Type.Message import translateString from Products.ERP5Type.Message import translateString
portal = context.getPortalObject() portal = context.getPortalObject()
...@@ -18,7 +19,7 @@ for form in (real_form, target_form): ...@@ -18,7 +19,7 @@ for form in (real_form, target_form):
request.set('editable_mode', 1) request.set('editable_mode', 1)
form.validate_all_to_request(request) form.validate_all_to_request(request)
request.set('editable_mode', editable_mode) request.set('editable_mode', editable_mode)
except FormValidationError, validation_errors: except FormValidationError as validation_errors:
# Pack errors into the request # Pack errors into the request
field_errors = form.ErrorFields(validation_errors) field_errors = form.ErrorFields(validation_errors)
request.set('field_errors', field_errors) request.set('field_errors', field_errors)
......
from Products.ERP5Type.Document import newTempBase from Products.ERP5Type.Document import newTempBase
from string import zfill
if listbox_id is None: if listbox_id is None:
listbox_id = 'listbox' listbox_id = 'listbox'
request = context.REQUEST request = context.REQUEST
# It must be possible to initialise the fast input, and to add empty lines after # It must be possible to initialise the fast input, and to add empty lines after
if request.has_key('my_empty_line_number'): if 'my_empty_line_number' in request:
empty_line_number = request['my_empty_line_number'] empty_line_number = request['my_empty_line_number']
...@@ -28,7 +27,7 @@ if hasattr(request, listbox_id): ...@@ -28,7 +27,7 @@ if hasattr(request, listbox_id):
for i in keys_list: for i in keys_list:
o = newTempBase(portal_object, i) o = newTempBase(portal_object, i)
o.setUid('new_%s' % zfill(i,int_len)) o.setUid('new_%s' % str(i).zfill(int_len))
is_empty = 1 is_empty = 1
...@@ -37,7 +36,7 @@ if hasattr(request, listbox_id): ...@@ -37,7 +36,7 @@ if hasattr(request, listbox_id):
# 0 was added because of checkbox field in some fast input # 0 was added because of checkbox field in some fast input
if (value not in ['',None,0]) and (key != listbox_key): if (value not in ['',None,0]) and (key != listbox_key):
is_empty = 0 is_empty = 0
if (request.has_key('field_errors')): if ('field_errors' in request):
is_empty = 0 is_empty = 0
#o.edit(key=listbox[i][key]) #o.edit(key=listbox[i][key])
o.setProperty(key,listbox[i][key]) o.setProperty(key,listbox[i][key])
...@@ -46,11 +45,11 @@ if hasattr(request, listbox_id): ...@@ -46,11 +45,11 @@ if hasattr(request, listbox_id):
l.append(o) l.append(o)
# add empty lines # add empty lines
if not(request.has_key('field_errors')): if not('field_errors' in request):
for i in range(first_empty_line_id,first_empty_line_id+empty_line_number): for i in range(first_empty_line_id,first_empty_line_id+empty_line_number):
o = newTempBase(portal_object, str(i)) o = newTempBase(portal_object, str(i))
o.setUid('new_%s' % zfill(i,int_len)) o.setUid('new_%s' % str(i).zfill(int_len))
# zfill is used here to garantee sort order - XXX - cleaner approach required # zfill is used here to garantee sort order - XXX - cleaner approach required
l.append(o) l.append(o)
......
...@@ -43,7 +43,7 @@ try: ...@@ -43,7 +43,7 @@ try:
# Update basic attributes # Update basic attributes
context.edit(REQUEST=request, edit_order=edit_order, **kw) context.edit(REQUEST=request, edit_order=edit_order, **kw)
context.reindexObject() context.reindexObject()
except FormValidationError, validation_errors: except FormValidationError as validation_errors:
# Pack errors into the request # Pack errors into the request
field_errors = form.ErrorFields(validation_errors) field_errors = form.ErrorFields(validation_errors)
request.set('field_errors', field_errors) request.set('field_errors', field_errors)
......
...@@ -16,7 +16,7 @@ for item in item_list: ...@@ -16,7 +16,7 @@ for item in item_list:
item_split = string.split(item_value, '/') item_split = string.split(item_value, '/')
item_key = string.join(item_split[:split_depth] , '/' ) item_key = string.join(item_split[:split_depth] , '/' )
if not sub_field_dict.has_key(item_key): if item_key not in sub_field_dict:
# Create property dict # Create property dict
sub_field_property_dict = default_sub_field_property_dict.copy() sub_field_property_dict = default_sub_field_property_dict.copy()
sub_field_property_dict['key'] = item_key sub_field_property_dict['key'] = item_key
......
...@@ -4,6 +4,6 @@ ...@@ -4,6 +4,6 @@
selection_name_dict = context.SkinsTool_getDuplicateSelectionNameDict() selection_name_dict = context.SkinsTool_getDuplicateSelectionNameDict()
for selection_name, field_map in selection_name_dict.items(): for selection_name, field_map in selection_name_dict.items():
print repr(selection_name), '\n\t', '\n\t'.join(["%r: %s" % (field, skin_list) print(repr(selection_name), '\n\t', '\n\t'.join(["%r: %s" % (field, skin_list)
for field, skin_list in field_map.items()]) for field, skin_list in list(field_map.items())]))
return printed return printed
...@@ -31,11 +31,11 @@ for skin_name, skin_path_list in skins_tool.getSkinPaths(): ...@@ -31,11 +31,11 @@ for skin_name, skin_path_list in skins_tool.getSkinPaths():
if external_validator: if external_validator:
method_name = external_validator.getMethodName() method_name = external_validator.getMethodName()
if restrictedTraverse(method_name, None) is None: if restrictedTraverse(method_name, None) is None:
print "{form_path}/{field_id} uses an external validator non existant in {skin_name}: {method_name}".format( print("{form_path}/{field_id} uses an external validator non existant in {skin_name}: {method_name}".format(
form_path=form_path, form_path=form_path,
field_id=field.getId(), field_id=field.getId(),
skin_name=skin_name, skin_name=skin_name,
method_name=method_name, method_name=method_name,
) ))
return printed return printed
...@@ -9,37 +9,37 @@ color_dict = { 'Modified' : '#FDE406', ...@@ -9,37 +9,37 @@ color_dict = { 'Modified' : '#FDE406',
'Removed' : '#FFA4A4' } 'Removed' : '#FFA4A4' }
link = 0 link = 0
request = context.REQUEST request = context.REQUEST
print '<div style="background-color:white;padding:4px">' print('<div style="background-color:white;padding:4px">')
for diff_object in context.BusinessTemplate_getDiffObjectList(): for diff_object in context.BusinessTemplate_getDiffObjectList():
color = color_dict.get(diff_object.object_state, '#FDE406') color = color_dict.get(diff_object.object_state, '#FDE406')
print '<div style="background-color:%s;padding:4px">' % color print('<div style="background-color:%s;padding:4px">' % color)
# XXX This header could be more improved to have icons and more options, like # XXX This header could be more improved to have icons and more options, like
# See XML, full diff, unified diff, link to svn (if available). # See XML, full diff, unified diff, link to svn (if available).
print '&nbsp; [<b>%s</b>] [<b>%s</b>] &nbsp;' % (diff_object.object_state, print('&nbsp; [<b>%s</b>] [<b>%s</b>] &nbsp;' % (diff_object.object_state,
diff_object.object_class) diff_object.object_class))
if diff_object.object_class in ERP5_OBJECT_CLASS_LIST: if diff_object.object_class in ERP5_OBJECT_CLASS_LIST:
print '<a href="%s">' % (diff_object.object_id) print('<a href="%s">' % (diff_object.object_id))
link = 1 link = 1
elif diff_object.object_class in PORTAL_TYPE_OBJECT_LIST: elif diff_object.object_class in PORTAL_TYPE_OBJECT_LIST:
print '<a href="portal_types/%s">' % (diff_object.object_id) print('<a href="portal_types/%s">' % (diff_object.object_id))
link = 1 link = 1
elif diff_object.object_class in ZMI_OBJECT_CLASS_LIST: elif diff_object.object_class in ZMI_OBJECT_CLASS_LIST:
print '<a href="%s/manage_main">' % (diff_object.object_id) print('<a href="%s/manage_main">' % (diff_object.object_id))
link = 1 link = 1
elif diff_object.object_class in WORKFLOW_OBJECT_CLASS_LIST: elif diff_object.object_class in WORKFLOW_OBJECT_CLASS_LIST:
print '<a href="portal_workflow/manage_main">' print('<a href="portal_workflow/manage_main">')
link = 1 link = 1
print '%s' % (diff_object.object_id) print('%s' % (diff_object.object_id))
if link == 1: if link == 1:
print '</a>' print('</a>')
print '</div>' print('</div>')
if diff_object.object_state.startswith('Modified'): if diff_object.object_state.startswith('Modified'):
request.set('bt1', diff_object.bt1) request.set('bt1', diff_object.bt1)
request.set('bt2', diff_object.bt2) request.set('bt2', diff_object.bt2)
request.set('object_id', diff_object.object_id) request.set('object_id', diff_object.object_id)
request.set('object_class', diff_object.object_class) request.set('object_class', diff_object.object_class)
print context.portal_templates.diffObjectAsHTML(request) print(context.portal_templates.diffObjectAsHTML(request))
print '<hr>' print('<hr>')
print '</div>' print('</div>')
return printed return printed
""" """
Changes permissions of all objects related to this workflow Changes permissions of all objects related to this workflow
""" """
from six.moves import xrange
from Products.ERP5Type.Message import translateString from Products.ERP5Type.Message import translateString
portal = context.getPortalObject() portal = context.getPortalObject()
ACTIVITY_GROUPING_COUNT = 100 ACTIVITY_GROUPING_COUNT = 100
......
...@@ -27,10 +27,9 @@ ...@@ -27,10 +27,9 @@
# #
############################################################################## ##############################################################################
import cStringIO import io
import re import re
import urllib2, urllib from six.moves import urllib
import urlparse
from cgi import parse_header from cgi import parse_header
import os import os
...@@ -168,7 +167,7 @@ class ContributionTool(BaseTool): ...@@ -168,7 +167,7 @@ class ContributionTool(BaseTool):
except KeyError: except KeyError:
raise ValueError('data must be provided') raise ValueError('data must be provided')
if data is not None: if data is not None:
file_object = cStringIO.StringIO() file_object = io.StringIO()
file_object.write(data) file_object.write(data)
file_object.seek(0) file_object.seek(0)
kw['file'] = file_object kw['file'] = file_object
...@@ -508,7 +507,7 @@ class ContributionTool(BaseTool): ...@@ -508,7 +507,7 @@ class ContributionTool(BaseTool):
for url in set(content.getContentNormalisedURLList()): for url in set(content.getContentNormalisedURLList()):
# LOG('trying to crawl', 0, url) # LOG('trying to crawl', 0, url)
# Some url protocols should not be crawled # Some url protocols should not be crawled
if urlparse.urlsplit(url)[0] in no_crawl_protocol_list: if urllib.parse.urlsplit(url)[0] in no_crawl_protocol_list:
continue continue
if container is None: if container is None:
#if content.getParentValue() #if content.getParentValue()
...@@ -549,7 +548,7 @@ class ContributionTool(BaseTool): ...@@ -549,7 +548,7 @@ class ContributionTool(BaseTool):
try: try:
url = content.asURL() url = content.asURL()
file_object, filename, content_type = self._openURL(url) file_object, filename, content_type = self._openURL(url)
except urllib2.URLError: except urllib.error.URLError:
if repeat == 0 or not batch_mode: if repeat == 0 or not batch_mode:
# XXX - Call the extendBadURLList method,--NOT Implemented-- # XXX - Call the extendBadURLList method,--NOT Implemented--
raise raise
...@@ -598,7 +597,7 @@ class ContributionTool(BaseTool): ...@@ -598,7 +597,7 @@ class ContributionTool(BaseTool):
elif document.getCrawlingDepth() > 0: elif document.getCrawlingDepth() > 0:
# If this is an index document, stop crawling if crawling_depth is 0 # If this is an index document, stop crawling if crawling_depth is 0
document.activate().crawlContent() document.activate().crawlContent()
except urllib2.HTTPError: except urllib.error.HTTPError:
if repeat == 0 or not batch_mode: if repeat == 0 or not batch_mode:
# here we must call the extendBadURLList method,--NOT Implemented-- # here we must call the extendBadURLList method,--NOT Implemented--
# which had to add this url to bad URL list, so next time we avoid # which had to add this url to bad URL list, so next time we avoid
...@@ -635,10 +634,10 @@ class ContributionTool(BaseTool): ...@@ -635,10 +634,10 @@ class ContributionTool(BaseTool):
# Quote path part of url # Quote path part of url
url = reencodeUrlEscapes(url) url = reencodeUrlEscapes(url)
# build a new file from the url # build a new file from the url
url_file = urllib2.urlopen(urllib2.Request(url, url_file = urllib.request.urlopen(urllib.request.Request(url,
headers={'Accept':'*/*'})) headers={'Accept':'*/*'}))
data = url_file.read() # time out must be set or ... too long XXX data = url_file.read() # time out must be set or ... too long XXX
file_object = cStringIO.StringIO() file_object = io.StringIO()
file_object.write(data) file_object.write(data)
file_object.seek(0) file_object.seek(0)
# if a content-disposition header is present, # if a content-disposition header is present,
...@@ -654,9 +653,9 @@ class ContributionTool(BaseTool): ...@@ -654,9 +653,9 @@ class ContributionTool(BaseTool):
# See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.30 # See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.30
url = url_file.geturl() url = url_file.geturl()
# Create a file name based on the URL and quote it # Create a file name based on the URL and quote it
filename = urlparse.urlsplit(url)[-3] filename = urllib.parse.urlsplit(url)[-3]
filename = os.path.basename(filename) filename = os.path.basename(filename)
filename = urllib.quote(filename, safe='') filename = urllib.parse.quote(filename, safe='')
filename = filename.replace('%', '') filename = filename.replace('%', '')
content_type = header_info.gettype() content_type = header_info.gettype()
return file_object, filename, content_type return file_object, filename, content_type
......
...@@ -285,7 +285,7 @@ class DomainTool(BaseTool): ...@@ -285,7 +285,7 @@ class DomainTool(BaseTool):
# Feel free to improve. # Feel free to improve.
if getMappedValuePropertyList is not None: if getMappedValuePropertyList is not None:
for mapped_value_property in predicate.getMappedValuePropertyList(): for mapped_value_property in predicate.getMappedValuePropertyList():
if not mapped_value_property_dict.has_key(mapped_value_property): if mapped_value_property not in mapped_value_property_dict:
value = predicate.getProperty(mapped_value_property) value = predicate.getProperty(mapped_value_property)
if value is not None: if value is not None:
mapped_value_property_dict[mapped_value_property] = value mapped_value_property_dict[mapped_value_property] = value
......
...@@ -319,8 +319,8 @@ class IntrospectionTool(LogMixin, BaseTool): ...@@ -319,8 +319,8 @@ class IntrospectionTool(LogMixin, BaseTool):
forbidden areas in the system. forbidden areas in the system.
""" """
def cached_loadExternalConfig(): def cached_loadExternalConfig():
import ConfigParser from six.moves import configparser
config = ConfigParser.ConfigParser() config = configparser.ConfigParser()
config.readfp(open('/etc/erp5.cfg')) config.readfp(open('/etc/erp5.cfg'))
return config return config
......
...@@ -26,6 +26,7 @@ ...@@ -26,6 +26,7 @@
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
# #
############################################################################## ##############################################################################
from six import string_types as basestring
from AccessControl import ClassSecurityInfo from AccessControl import ClassSecurityInfo
from Products.ERP5Type.Tool.BaseTool import BaseTool from Products.ERP5Type.Tool.BaseTool import BaseTool
from Products.ERP5Type import Permissions from Products.ERP5Type import Permissions
...@@ -147,7 +148,7 @@ def buildEmailMessage(from_url, to_url, msg=None, ...@@ -147,7 +148,7 @@ def buildEmailMessage(from_url, to_url, msg=None,
attachment_name = attachment.get('name', '') attachment_name = attachment.get('name', '')
# try to guess the mime type # try to guess the mime type
if not attachment.has_key('mime_type'): if 'mime_type' not in attachment:
mime_type, _ = guess_type( attachment_name ) mime_type, _ = guess_type( attachment_name )
if mime_type is not None: if mime_type is not None:
attachment['mime_type'] = mime_type attachment['mime_type'] = mime_type
......
...@@ -38,7 +38,7 @@ from DateTime import DateTime ...@@ -38,7 +38,7 @@ from DateTime import DateTime
from Products.ERP5Type.Message import translateString from Products.ERP5Type.Message import translateString
from Products.ERP5Type.Globals import PersistentMapping from Products.ERP5Type.Globals import PersistentMapping
from BTrees.OOBTree import OOBTree from BTrees.OOBTree import OOBTree
from urllib import urlencode from six.moves.urllib.parse import urlencode
redirect_path = '/login_form' redirect_path = '/login_form'
def redirect(REQUEST, site_url, message): def redirect(REQUEST, site_url, message):
......
...@@ -27,11 +27,13 @@ ...@@ -27,11 +27,13 @@
# #
############################################################################## ##############################################################################
from six import string_types as basestring
from AccessControl import ClassSecurityInfo from AccessControl import ClassSecurityInfo
from Products.ERP5Type.Tool.BaseTool import BaseTool from Products.ERP5Type.Tool.BaseTool import BaseTool
from Products.ERP5Type import Permissions from Products.ERP5Type import Permissions
from Acquisition import aq_base from Acquisition import aq_base
from UserDict import UserDict from collections import UserDict
import collections import collections
# the ERP5 cache factory used as a storage # the ERP5 cache factory used as a storage
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment