From aaf66a7731451a47c9d4080d17acdc2f5d5d497b Mon Sep 17 00:00:00 2001
From: Julien Muchembled <jm@nexedi.com>
Date: Tue, 8 Jun 2010 13:41:45 +0000
Subject: [PATCH] Make load of local Document modules safer

Modules from local Document folders may override existing module.
If such local module can't be imported, the original module should be restored.
This is useful during upgrades.

git-svn-id: https://svn.erp5.org/repos/public/erp5/trunk@36101 20353a03-c40f-0410-a6d1-a30d3c3de9de
---
 product/ERP5Type/Utils.py | 14 ++++++++++----
 1 file changed, 10 insertions(+), 4 deletions(-)

diff --git a/product/ERP5Type/Utils.py b/product/ERP5Type/Utils.py
index 4c9079417c..9cc4deeef4 100644
--- a/product/ERP5Type/Utils.py
+++ b/product/ERP5Type/Utils.py
@@ -920,15 +920,23 @@ def importLocalDocument(class_id, document_path = None):
     path = document_path
   path = os.path.join(path, "%s.py" % class_id)
 
+  module_path = 'Products.ERP5Type.Document.' + class_id
+  document_module = sys.modules.get(module_path)
   # Import Document Class and Initialize it
   f = open(path)
   try:
-    document_module = imp.load_source(
-          'Products.ERP5Type.Document.%s' % class_id, path, f)
+    document_module = imp.load_source(module_path, path, f)
     document_class = getattr(document_module, class_id)
     document_constructor = DocumentConstructor(document_class)
     document_constructor_name = "add%s" % class_id
     document_constructor.__name__ = document_constructor_name
+  except Exception:
+    f.close()
+    if document_module is not None:
+      sys.modules[module_path] = document_module
+    raise
+  else:
+    f.close()
     setattr(Products.ERP5Type.Document, class_id, document_module)
     setattr(Products.ERP5Type.Document, document_constructor_name,
                                       document_constructor)
@@ -936,8 +944,6 @@ def importLocalDocument(class_id, document_path = None):
     ModuleSecurityInfo('Products.ERP5Type.Document').declareProtected(
         Permissions.AddPortalContent, document_constructor_name,)
     InitializeClass(document_class)
-  finally:
-    f.close()
 
   # Temp documents are created as standard classes with a different constructor
   # which patches some methods are the instance level to prevent reindexing
-- 
2.30.9