def _getSubsribedUserAndPassword(self): """Retrieve the username and password for the subscription from the system.""" user = CachingMethod(self.getExpressConfigurationPreference, 'WizardTool_preferred_express_user_id', cache_factory='erp5_content_long')( 'preferred_express_user_id', '') pw = CachingMethod(self.getExpressConfigurationPreference, 'WizardTool_preferred_express_password', cache_factory='erp5_content_long')( 'preferred_express_password', '') return (user, pw)
def test_03_cachePersistentObjects(self): # storing persistent objects in cache is not allowed, but this check is # only performed in unit tests. def func(): # return a persistent object return self.portal cached_func = CachingMethod(func, 'cache_persistent_obj') self.assertRaises(TypeError, cached_func) def func(): # return a method bound on a persistent object return self.portal.getTitle cached_func = CachingMethod(func, 'cache_bound_method') self.assertRaises(TypeError, cached_func)
def authenticateCredentials(self, credentials): """Authentificate with credentials""" key = credentials.get('key', None) if key != None: login = self.decrypt(key) # Forbidden the usage of the super user. if login == SUPER_USER: return None #Function to allow cache @UnrestrictedMethod def _authenticateCredentials(login): if not login: return None #Search the user by his login user_list = self.getUserByLogin(login) if len(user_list) != 1: raise _AuthenticationFailure() user = user_list[0] if True: try: # get assignment list assignment_list = [x for x in user.contentValues(portal_type="Assignment") \ if x.getValidationState() == "open"] valid_assignment_list = [] # check dates if exist login_date = DateTime() for assignment in assignment_list: if assignment.getStartDate() is not None and \ assignment.getStartDate() > login_date: continue if assignment.getStopDate() is not None and \ assignment.getStopDate() < login_date: continue valid_assignment_list.append(assignment) # validate if len(valid_assignment_list) > 0: return (login, login) finally: pass raise _AuthenticationFailure() #Cache Method for best performance _authenticateCredentials = CachingMethod( _authenticateCredentials, id='ERP5KeyAuthPlugin_authenticateCredentials', cache_factory='erp5_content_short') try: return _authenticateCredentials(login=login) except _AuthenticationFailure: return None except StandardError, e: #Log standard error LOG('ERP5KeyAuthPlugin.authenticateCredentials', PROBLEM, str(e)) return None
def isAuthenticationPolicyEnabled(self): """ Return True if authentication policy is enabled. This method exists here due to bootstrap issues. It should work even if erp5_authentication_policy bt5 is not installed. """ # XXX: define an interface def _isAuthenticationPolicyEnabled(): portal_preferences = self.getPortalObject().portal_preferences method_id = 'isPreferredAuthenticationPolicyEnabled' method = getattr(self, method_id, None) if method is not None and method(): return True return False tv = getTransactionalVariable() tv_key = 'PreferenceTool._isAuthenticationPolicyEnabled.%s' % getSecurityManager( ).getUser() if tv.get(tv_key, None) is None: _isAuthenticationPolicyEnabled = CachingMethod( _isAuthenticationPolicyEnabled, id='PortalPreferences_isAuthenticationPolicyEnabled', cache_factory='erp5_content_short') tv[tv_key] = _isAuthenticationPolicyEnabled() return tv[tv_key]
def getDocumentTemplateList(self, folder=None): """ returns all document templates that are in acceptable Preferences based on different criteria such as folder, portal_type, etc. """ if folder is None: # as the preference tool is also a Folder, this method is called by # page templates to get the list of document templates for self. folder = self # We must set the user_id as a parameter to make sure each # user can get a different cache def _getDocumentTemplateList(user_id, portal_type=None): acceptable_template_list = [] for pref in self._getSortedPreferenceList(): for doc in pref.contentValues(portal_type=portal_type): acceptable_template_list.append(doc.getRelativeUrl()) return acceptable_template_list _getDocumentTemplateList = CachingMethod( _getDocumentTemplateList, 'portal_preferences.getDocumentTemplateList', cache_factory='erp5_ui_short') allowed_content_types = map(lambda pti: pti.id, folder.allowedContentTypes()) user_id = getToolByName( self, 'portal_membership').getAuthenticatedMember().getId() template_list = [] for portal_type in allowed_content_types: for template_url in _getDocumentTemplateList( user_id, portal_type=portal_type): template = self.restrictedTraverse(template_url, None) if template is not None: template_list.append(template) return template_list
def __call__(self, instance, default=_marker, *args, **kw): def _getPreference(default, *args, **kw): # XXX: sql_catalog_id is passed when calling getPreferredArchive # This is inconsistent with regular accessor API, and indicates that # there is a design problem in current archive API. sql_catalog_id = kw.pop('sql_catalog_id', None) for pref in instance._getSortedPreferenceList( sql_catalog_id=sql_catalog_id): value = getattr(pref, self._preference_getter)(_marker, *args, **kw) # XXX Due to UI limitation, null value is treated as if the property # was not defined. The drawback is that it is not possible for a # user to mask a non-null global value with a null value. if value not in (_marker, None, '', (), []): return value if default is _marker: return self._preference_default return default _getPreference = CachingMethod( _getPreference, id='%s.%s' % (self._preference_cache_id, instance.getPortalObject().portal_preferences._getCacheId()), cache_factory='erp5_ui_long') return _getPreference(default, *args, **kw)
def getVATCategory(self, vat_value): """ This returns the VAT category according to the value set """ def cached_buildVATDict(): vat_dict = {} trade_condition = self.getIntegrationSite().getDefaultSourceTradeValue() while len(trade_condition.contentValues(portal_type="Trade Model Line")) == 0: # Must find a better way to browse specialised objects specialized_trade_condition = trade_condition.getSpecialiseValue() if specialized_trade_condition is None or specialized_trade_condition.getPortalType() == "Business Process": raise ValueError('Impossible to find a trade condition containing VAT lines, last trade condition was %s, parent was %s' %(specialized_trade_condition, trade_condition)) else: trade_condition = specialized_trade_condition for vat_line in trade_condition.contentValues(portal_type="Trade Model Line"): # LOG("browsing line %s" %(vat_line.getPath(), 300, "%s" %(vat_line.getBaseApplicationList(),))) for app in vat_line.getBaseApplicationList(): if "base_amount/trade/base/taxable/vat/" in app: vat_dict["%.2f" %(vat_line.getPrice()*100.)] = app.split('/')[-1] # LOG("vat_dict is %s" %(vat_dict), 300, "") return vat_dict cached_getSynchronizationObjectList = CachingMethod(cached_buildVATDict, id="TioSafeBrain_cached_buildVATDict", cache_factory='erp5_content_long') vat_dict = cached_buildVATDict() return vat_dict["%.2f" %(float(vat_value))]
def test_06_CheckCacheExpiration(self): """Check that expiracy is well handle by Cache Plugins """ print print "="*40 print "TESTING: Cache Expiration Time" portal = self.getPortal() py_script_obj = getattr(portal, self.python_script_id) cache_factory_list = ('ram_cache_factory', 'distributed_ram_cache_factory', 'distributed_persistent_cache_factory') for cache_factory in cache_factory_list: print '\n\t==> %s' % cache_factory my_cache = CachingMethod(py_script_obj, 'py_script_obj', cache_factory=cache_factory) # First call, fill the cache calculation_time = self._callCache(my_cache, real_calculation=True) print "\n\tCalculation time (1st call)", calculation_time ## 2nd call - should be cached now calculation_time = self._callCache(my_cache, real_calculation=False) print "\n\tCalculation time (2nd call)", calculation_time # Wait expiration period then check that value is computed # .1 is an additional epsilon delay to work around time precision issues time_left_to_wait = .1 + self.cache_duration print "\n\tSleep %.2f seconds to wait expiration time" % time_left_to_wait time.sleep(time_left_to_wait) # Call conversion for ram_cache_factory calculation_time = self._callCache(my_cache, real_calculation=True) print "\n\tCalculation time (3rd call)", calculation_time
def _getSystemVersionDict(self): """ Returns a dictionnary with all versions of installed libraries { 'python': '2.4.3' , 'pysvn': '1.2.3' , 'ERP5' : "5.4.3" } NOTE: consider using autoconf / automake tools ? """ def cached_getSystemVersionDict(): import pkg_resources version_dict = {} for dist in pkg_resources.working_set: version_dict[dist.key] = dist.version from Products import ERP5 as erp5_product erp5_product_path = os.path.dirname(erp5_product.__file__) try: with open(os.path.join(erp5_product_path, "VERSION.txt")) as f: erp5_version = f.read().strip().replace("ERP5 ", "") except Exception: erp5_version = None version_dict["ProductS.ERP5"] = erp5_version return version_dict get_system_version_dict = CachingMethod( cached_getSystemVersionDict, id='IntrospectionTool__getSystemVersionDict', cache_factory='erp5_content_long') return get_system_version_dict()
def _checkConsistency(self, fixit=False, filter=None, **kw): template_tool = self.getPortalObject().portal_templates bt5_id = self.getBt5Id().split('.')[0] if bt5_id in template_tool.getInstalledBusinessTemplateTitleList(): LOG( "StandardBT5ConfiguratorItem", INFO, "Business Template already Installed: %s for %s" % (bt5_id, self.getRelativeUrl())) return [] def _getRepositoryBusinessTemplateTitleList(): return [bt.getTitle() for bt in \ template_tool.getRepositoryBusinessTemplateList()] repository_bt_title_list = CachingMethod( _getRepositoryBusinessTemplateTitleList, id='StandardBT5_getRepositoryBusinessTemplateTitleList', cache_factory='erp5_content_long')() if bt5_id in repository_bt_title_list: if fixit: template_tool.installBusinessTemplateListFromRepository( [bt5_id], update_catalog=self.getUpdateCatalog(0), install_dependency=self.getInstallDependency(1), activate=True) return [ self._createConstraintMessage('%s should be installed' % bt5_id), ] raise ValueError("The business template %s was not found on available \ sources." % bt5_id)
def test_02_CacheFactoryMultiPlugins(self): """ Test a cache factory containing multiple cache plugins. """ py_script_obj = getattr(self.portal, self.python_script_id) cf_name = 'erp5_user_factory' my_cache = CachingMethod(py_script_obj, 'py_script_obj', cache_factory=cf_name) self._cacheFactoryInstanceTest(my_cache, cf_name, clear_allowed=False)
def getCategoryChildItemList(self, recursive=1, base=0, cache=DEFAULT_CACHE_FACTORY, current_category_list=None, **kw): """ Returns a list of tuples by parsing recursively all categories in a given list of base categories. Each tuple contains:: (c.relative_url, c.display_id()) base -- if set to 1, relative_url will start with the base category id if set to 0 and if base_category is a single id, relative_url are relative to the base_category (and thus doesn't start with the base category id) if set to string, use string as base display_id -- method called to build the couple recursive -- if set to 0 do not apply recursively current_category_list -- allows to provide list of categories which is not part of the default ItemList. Very useful for displaying values in a popup menu which can no longer be selected. It is required to give url including base category. All parameters supported by getCategoryChildValueList and Render are supported here. """ def _renderCategoryChildItemList(recursive=1, base=0, **kw): value_list = self.getCategoryChildValueList(recursive=recursive, **kw) return Renderer(base=base, **kw).render(value_list) if cache: _renderCategoryChildItemList = CachingMethod( _renderCategoryChildItemList, ( 'Category_getCategoryChildItemList', self.getPortalObject().Localizer.get_selected_language(), self.getPath(), getSecurityManager().getUser().getId() if 'checked_permission' in kw else None, ), cache_factory=cache, ) item_list = _renderCategoryChildItemList(recursive=recursive, base=base, **kw) if current_category_list: kw['display_none_category'] = False current_category_item_list = Renderer(base=base, **kw).render( [self.portal_categories.resolveCategory(c) for c in current_category_list]) item_set = {tuple(x) for x in item_list} additional_item_list = [] for current_category_item in current_category_item_list: if not(tuple(current_category_item) in item_set): additional_item_list.append(current_category_item) if additional_item_list: item_list = item_list + additional_item_list return item_list
def _getSynchronizationObjectList(self, sync_type, object_type_list): """ Render the 'SyncML Publication' or the 'SyncML Subscription' list which correspond to the sync_type and the object_type. """ if not isinstance(object_type_list, list): object_type_list = [object_type_list,] def cached_getSynchronizationObjectList(sync_type, object_type): context = self.context module_list = [] object_module_id = object_type.lower().replace(' ', '_') for module in context.getIntegrationSite().contentValues(portal_type="Integration Module"): if object_module_id in module.getId(): module_list.append(module) if not len(module_list): raise ValueError("Impossible to find a module for %s" % object_type) sync_object_list = [] for module in module_list: # init shortcut of module's data module_source = module.getSourceSectionValue() module_destination = module.getDestinationSectionValue() source_portal_type = module_source.getSourceValue().getPortalType() destination_portal_type = module_destination.getSourceValue().getPortalType() # only work on the ERP5 or TioSafe sync assert sync_type in ("tiosafe", "erp5"), sync_type if (sync_type == "erp5") ^ (source_portal_type == "Integration Module"): # render the source if: # 1. sync_type == erp5 and source_portal_type != Integration Module # 2. sync_type != erp5 and source_portal_type == Integration Module sync_object_list.append(module_source.getPath()) elif (sync_type == "tiosafe") ^ (destination_portal_type != "Integration Module"): # render the destination if: # 1. sync_type == tiosafe and destination_portal_type == Integration Module # 2. sync_type != tiosafe and destination_portal_type != Integration Module sync_object_list.append(module_destination.getPath()) else: raise ValueError("Impossible to find pub/sub related to Integration Module, pub = %s with source = %s, sub = %s with source = %s" %( module.getSourceSection(), module_source.getSource(), module.getDestinationSection(), module_destination.getSource(), )) return sync_object_list # Cache sync object list cached_getSynchronizationObjectList = CachingMethod(cached_getSynchronizationObjectList, id="TioSafeBrain_getSynchronizationObjectList", cache_factory='erp5_content_long') object_list = [] for object_type in object_type_list: object_list.extend(cached_getSynchronizationObjectList(sync_type, object_type)) portal = self.context.getPortalObject() return [portal.restrictedTraverse(x) for x in object_list]
def test_04_CheckConcurrentRamCacheDict(self): """Check that all RamCache doesn't clear the same cache_dict """ print print "=" * 40 print "TESTING: Concurrent RamCache" portal = self.portal result = 'Something short' py_script_obj = getattr(portal, self.python_script_id) ram_cached_method = CachingMethod(py_script_obj, 'py_script_obj', cache_factory='ram_cache_factory') portal.portal_caches.clearCache(cache_factory_list=( 'ram_cache_factory', 'another_ram_cache_factory', )) # First call, fill the cache start = time.time() cached = ram_cached_method(self.nb_iterations, portal_path=('', portal.getId()), result=result) end = time.time() calculation_time = end - start print "\n\tCalculation time (1st call)", calculation_time self.assertEqual(cached, result) self.commit() ## 2nd call - should be cached now start = time.time() cached = ram_cached_method(self.nb_iterations, portal_path=('', portal.getId()), result=result) end = time.time() calculation_time = end - start print "\n\tCalculation time (2nd call)", calculation_time self.assertTrue(1.0 > calculation_time, "1.0 <= %s" % calculation_time) self.assertEqual(cached, result) self.commit() # Clear only another_ram_cache_factory portal.portal_caches.clearCacheFactory('another_ram_cache_factory') # Call conversion for ram_cache_factory start = time.time() cached = ram_cached_method(self.nb_iterations, portal_path=('', portal.getId()), result=result) end = time.time() calculation_time = end - start print "\n\tCalculation time (3rd call)", calculation_time self.assertTrue(1.0 > calculation_time, "1.0 <= %s" % calculation_time) self.assertEqual(cached, result) self.commit()
def getTargetFormatItemList(self): """ Returns a list of acceptable formats for conversion in the form of tuples (for listfield in ERP5Form) NOTE: it is the responsability of the conversion server to provide an extensive list of conversion formats. """ if not self.hasBaseData(): # if we have no date we can not format it return [] def cached_getTargetFormatItemList(content_type): from xmlrpclib import Fault server_proxy = DocumentConversionServerProxy(self) try: allowed_target_item_list = server_proxy.getAllowedTargetItemList( content_type) try: response_code, response_dict, response_message = \ allowed_target_item_list except ValueError: # Compatibility with older oood where getAllowedTargetItemList only # returned response_dict response_code, response_dict, response_message = \ 200, dict(response_data=allowed_target_item_list), '' if response_code == 200: allowed = response_dict['response_data'] else: # This is very temporary code - XXX needs to be changed # so that the system can retry raise ConversionError( "OOoDocument: can not get list of allowed acceptable" " formats for conversion (Code %s: %s)" % (response_code, response_message)) except Fault: allowed = server_proxy.getAllowedTargets(content_type) warn( 'Your oood version is too old, using old method ' 'getAllowedTargets instead of getAllowedTargetList', DeprecationWarning) # tuple order is reversed to be compatible with ERP5 Form return [(y, x) for x, y in allowed] # Cache valid format list cached_getTargetFormatItemList = CachingMethod( cached_getTargetFormatItemList, id="OOoDocument_getTargetFormatItemList", cache_factory='erp5_ui_medium') return cached_getTargetFormatItemList(self.getBaseContentType())
def enumerateUsers(self, id=None, login=None, exact_match=False, sort_by=None, max_results=None, **kw): """ See IUserEnumerationPlugin. """ def _enumerateUsers(id_tuple, exact_match, path): user_info = [] plugin_id = self.getId() id_list = [] for id in id_tuple: if SUPER_USER == id: info = { 'id': SUPER_USER, 'login': SUPER_USER, 'pluginid': plugin_id } user_info.append(info) else: if exact_match: id_list.append(id) else: id_list.append('%%%s%%' % id) if id_list: for user in self.getUserByLogin(tuple(id_list), exact_match=exact_match): info = { 'id': user.getReference(), 'login': user.getReference(), 'pluginid': plugin_id } user_info.append(info) return tuple(user_info) _enumerateUsers = CachingMethod(_enumerateUsers, id='ERP5UserManager_enumerateUsers', cache_factory='erp5_content_short') if id is None: id = login if isinstance(id, list): id = tuple(id) elif not isinstance(id, tuple): id = (id, ) return _enumerateUsers(id_tuple=id, exact_match=exact_match, path=self.getPhysicalPath())
def test_01_CacheFactoryOnePlugin(self): """ Test cache factory containing only one cache plugin. """ portal = self.getPortal() py_script_obj = getattr(portal, self.python_script_id) for cf_name, clear_allowed in (('ram_cache_factory', True), ('distributed_ram_cache_factory', False), ('distributed_persistent_cache_factory', False), ): my_cache = CachingMethod(py_script_obj, 'py_script_obj', cache_factory=cf_name) self._cacheFactoryInstanceTest(my_cache, cf_name, clear_allowed)
def getIDParameterName(self): """ Return the parameter name used for id """ def cached_getIDParameterName(self): if self.getDestinationObjectType(): return "%s_id" %(self.getDestinationObjectType().replace(" ", "_").lower()) else: return "id" cached_getIDParameterName = CachingMethod(cached_getIDParameterName, id="WebServiceRequest_getIDParameterName", cache_factory="erp5_content_long") return cached_getIDParameterName(self)
def getCategoryChildItemList(self, recursive=1, base=0, cache=DEFAULT_CACHE_FACTORY, **kw): """ Returns a list of tuples by parsing recursively all categories in a given list of base categories. Each tuple contains:: (c.relative_url, c.display_id()) base -- if set to 1, relative_url will start with the base category id if set to 0 and if base_category is a single id, relative_url are relative to the base_category (and thus doesn't start with the base category id) if set to string, use string as base display_id -- method called to build the couple recursive -- if set to 0 do not apply recursively All parameters supported by getCategoryChildValueList and Render are supported here. """ def _renderCategoryChildItemList(recursive=1, base=0, **kw): value_list = self.getCategoryChildValueList(recursive=recursive, **kw) return Renderer(base=base, **kw).render(value_list) if not cache: return _renderCategoryChildItemList(recursive=recursive, base=base, **kw) # If checked_permission is specified, we include the username in the # cache key username = None if 'checked_permission' in kw: username = str(getSecurityManager().getUser()) # Some methods are language dependent so we include the language in the # key localizer = getToolByName(self, 'Localizer') language = localizer.get_selected_language() m = CachingMethod(_renderCategoryChildItemList, ('Category_getCategoryChildItemList', language, self.getPath(), username), cache_factory=cache) return m(recursive=recursive, base=base, **kw)
def getWebSectionValueList(self, document): """ Returns a list of sections which a given document is part of. This could be implemented either by testing all sections and building a cache or by using the predicate API to find which sections apply. """ def getWebSectionUidList(section): # Only return visible web section if section.isVisible(): result = [section.getUid()] else: result = [] for o in section.contentValues(portal_type='Web Section'): result.extend(getWebSectionUidList(o)) return result _getWebSectionUidList = CachingMethod( getWebSectionUidList, id='WebSite._getWebSectionUidList', cache_factory='erp5_content_medium') web_section_uid_list = _getWebSectionUidList(self) if web_section_uid_list: section_list = self.portal_domains.searchPredicateList( document, portal_type='Web Section', uid=web_section_uid_list) section_dict = {} for section in section_list: section_dict[section.getPhysicalPath()] = section # Eliminate path for section in section_list: path = section.getPhysicalPath() for i in range(0, len(path)): sub_path = tuple(path[0:i]) if section_dict.has_key(sub_path): del section_dict[sub_path] section_list = section_dict.values() # Sort by Index section_list.sort(key=lambda x: x.getIntIndex()) return section_list else: return []
def getSubFieldDict(): def getSubFieldDictCache(): # Define a dictionary where we store the subfields to display. sub_field_dict = {} # Try to assign each item to a sub field. for item in item_list: # Get value of the item item_value = item[int(not is_right_display)] if item_value is None: continue # Hash key from item_value item_split = item_value.split('/') item_key = '/'.join(item_split[:split_depth]) # Create a new subfield if necessary if not sub_field_dict.has_key(item_key): # Create property dict (key are field parameters) sub_field_property_dict = default_sub_field_property_dict.copy( ) sub_field_property_dict['key'] = item_key sub_field_property_dict['title'] = Base_translateString( "GAP - ${gap_title}", mapping=dict( gap_title=context.portal_categories.resolveCategory( 'gap/%s' % item_key).getTranslatedTitle())) sub_field_property_dict['required'] = 0 sub_field_property_dict['field_type'] = 'ListField' sub_field_property_dict['size'] = 1 sub_field_property_dict['item_list'] = [('', '')] sub_field_property_dict['value'] = None sub_field_dict[item_key] = sub_field_property_dict sub_field_dict[item_key]['item_list'].append(item) sub_field_property_dict['size'] = 1 return sub_field_dict from Products.ERP5Type.Cache import CachingMethod getSubFieldDictCache = CachingMethod( getSubFieldDictCache, id='Account_getSubFieldDict.%s' % portal.Localizer.get_selected_language()) # Those cached dictionnaries are later modified, we just reset the 'value' # key to return clean dictionnaries. sub_field_dict = getSubFieldDictCache() for k in sub_field_dict.keys(): sub_field_dict[k]['value'] = None return sub_field_dict
def _getClassForPortalType(self, obj, type_info): """Computes the class for a portal type. XXX Is there any better way than creating an object ??? """ def _getClassForPortalTypeCache(portal_type_name): folder = obj.getParentValue() new_obj = type_info.constructInstance(folder, None) class_name = str(new_obj.__class__) folder.manage_delObjects([new_obj.getId()]) return class_name _getClassForPortalTypeCache = CachingMethod( _getClassForPortalTypeCache, "PortalTypeClass._getClassForPortalTypeCache", cache_factory='erp5_content_medium') return _getClassForPortalTypeCache(obj.getPortalType())
def _loadExternalConfig(): """ Load configuration from one external file, this configuration should be set for security reasons to prevent people access forbidden areas in the system. """ def cached_loadExternalConfig(): import ConfigParser config = ConfigParser.ConfigParser() config.readfp(open('/etc/erp5.cfg')) return config cached_loadExternalConfig = CachingMethod(cached_loadExternalConfig, id='IntrospectionTool__loadExternalConfig', cache_factory='erp5_content_long') return cached_loadExternalConfig()
def getIntegrationSite(self,): """ return integration site if the wsr """ def cached_getIntegrationSite(self): parent = self.getParentValue() while parent.getPortalType() != "Integration Site": parent = parent.getParentValue() return parent.getPath() cached_getIntegrationSite = CachingMethod(cached_getIntegrationSite, id="WebServiceRequest_getIntegrationSite", cache_factory="erp5_content_long") integration_site = cached_getIntegrationSite(self) return self.getPortalObject().portal_integrations.restrictedTraverse(integration_site)
def _getParsedScribusFile(self): """ Returns a reusable data structure which can be used to generate ERP5 Form, ERP5 Form CSS, PDF Form, etc. """ scribus_form = self.getDefaultScribusFormValue() if scribus_form is None: return def generateParsedScribus(): import_scribus_file = StringIO.StringIO(scribus_form.getData()) scribus_parser = ScribusParser(import_scribus_file) import_scribus_file.close() return scribus_parser.getERP5PropertyDict() generateParsedScribus = CachingMethod( generateParsedScribus, ('PDFTypeInformation_generateParsedScribus', md5(scribus_form.getData()).digest()), cache_factory='dms_cache_factory') return generateParsedScribus()
def getERP5FormCSS(self): """ Returns a CSS file containing all layout instructions """ if self.getDefaultScribusFormValue() is None: return def generateERP5FormCSS(): parsed_scribus = self._getParsedScribusFile() import_pdf_file = StringIO.StringIO( self.getDefaultPdfFormValue().getData()) pdf_parser = PDFParser(import_pdf_file) import_scribus_file = StringIO.StringIO( self.getDefaultScribusFormValue().getData()) scribus_parser = ScribusParser(import_scribus_file) page_gap = scribus_parser.getPageGap() scribus_width = scribus_parser.getPageWidth() scribus_height = scribus_parser.getPageHeight() space_between_pages = 20 # XXX - hardcoded image0 = self.getERP5FormImage(0) properties_css_dict = getPropertiesCSSDict( parsed_scribus, page_gap, image0.getWidth(), image0.getHeight(), scribus_width, scribus_height, space_between_pages, self.getPortalObject().portal_preferences) # declaring object that holds the CSS data css_file_name = "%s_css.css" % self.getId().replace(' ', '') css_file_content = generateCSSOutputContent(properties_css_dict) css_file = DTMLDocument(css_file_content, __name__=css_file_name) import_scribus_file.close() import_pdf_file.close() return css_file generateERP5FormCSS = CachingMethod( generateERP5FormCSS, ('PDFTypeInformation_generateERP5FormCSS', md5(self.getDefaultScribusFormValue().getData()).digest()), cache_factory='dms_cache_factory') self.REQUEST.RESPONSE.setHeader('Content-Type', 'text/css') return generateERP5FormCSS()
def callRemoteProxyMethod(self, distant_method, server_url=None, use_cache=1, ignore_exceptions=1, **kw): """ Call proxy method on server. """ configurator_user_preferred_language = self\ .getConfiguratorUserPreferredLanguage() def wrapper(distant_method, **kw): return self._callRemoteMethod(distant_method, use_proxy=1, ignore_exceptions=ignore_exceptions, **kw)['data'] if use_cache: wrapper = CachingMethod( wrapper, id='callRemoteProxyMethod_%s_%s' % (distant_method, configurator_user_preferred_language), cache_factory='erp5_ui_medium') rc = wrapper(distant_method, **kw) return rc
def getServerRoot(self): return CachingMethod(self.getExpressConfigurationPreference, 'WizardTool_preferred_witch_tool_server_root', cache_factory='erp5_content_long')( 'preferred_witch_tool_server_root', '')
# check if there is a second bt or if we compare to installed one if len(uids) == 2: bt2 = context.portal_catalog.getObject(uids[1]) if bt2.getBuildingState() != 'built': raise TemplateConditionError( 'Business Template must be built to make diff') else: # compare to objects in ZODB bt2 = bt1 def getModifiedObjectList(bt1, bt2): return bt1.preinstall(compare_to=bt2) getModifiedObjectList = CachingMethod(getModifiedObjectList, id='BusinessTemplate_getModifiedObjectList', \ cache_factory='erp5_ui_medium') if p.portal_templates.compareVersions(bt1.getVersion(), bt2.getVersion()) < 0: modified_object_list = getModifiedObjectList(bt2, bt1) else: modified_object_list = getModifiedObjectList(bt1, bt2) keys = modified_object_list.keys() keys.sort() i = 0 object_list = [] for object_id in keys: object_state, object_class = modified_object_list[object_id] line = newTempBase(context, 'tmp_install_%s' % (str(i))) line.edit(object_id=object_id,
def getGroupsForPrincipal(self, principal, request=None): """ See IGroupsPlugin. """ # If this is the super user, skip the check. if principal.getId() == SUPER_USER: return () @UnrestrictedMethod def _getGroupsForPrincipal(user_name, path): security_category_dict = {} # key is the base_category_list, # value is the list of fetched categories security_group_list = [] security_definition_list = () try: # To get the complete list of groups, we try to call the # ERP5Type_getSecurityCategoryMapping which should return a list # of lists of two elements (script, base_category_list) like : # ( # ('script_1', ['base_category_1', 'base_category_2', ...]), # ('script_2', ['base_category_1', 'base_category_3', ...]) # ) # # else, if the script does not exist, falls back to a list containng # only one list : # (('ERP5Type_getSecurityCategoryFromAssignment', # self.getPortalAssignmentBaseCategoryList() ),) mapping_method = getattr( self, 'ERP5Type_getSecurityCategoryMapping', None) if mapping_method is None: security_definition_list = (( 'ERP5Type_getSecurityCategoryFromAssignment', self.getPortalAssignmentBaseCategoryList()), ) else: security_definition_list = mapping_method() # get the person from its reference - no security check needed catalog_result = self.portal_catalog.unrestrictedSearchResults( portal_type="Person", reference=user_name) if len(catalog_result) != 1: # we won't proceed with groups if len(catalog_result) > 1: # configuration is screwed raise ConsistencyError, 'There is more than one Person whose \ login is %s : %s' % ( user_name, repr([r.getObject() for r in catalog_result])) else: # no person is linked to this user login return () person_object = catalog_result[0].getObject() person_id = person_object.getId() # Fetch category values from defined scripts for (method_name, base_category_list) in security_definition_list: base_category_list = tuple(base_category_list) method = getattr(self, method_name) security_category_list = security_category_dict.setdefault( base_category_list, []) try: # The called script may want to distinguish if it is called # from here or from _updateLocalRolesOnSecurityGroups. # Currently, passing portal_type='' (instead of 'Person') # is the only way to make the difference. security_category_list.extend( method(base_category_list, user_name, person_object, '')) except ConflictError: raise except: LOG('ERP5GroupManager', WARNING, 'could not get security categories from %s' % (method_name, ), error=sys.exc_info()) # Get group names from category values # XXX try ERP5Type_asSecurityGroupIdList first for compatibility generator_name = 'ERP5Type_asSecurityGroupIdList' group_id_list_generator = getattr(self, generator_name, None) if group_id_list_generator is None: generator_name = ERP5TYPE_SECURITY_GROUP_ID_GENERATION_SCRIPT group_id_list_generator = getattr(self, generator_name) for base_category_list, category_value_list in \ security_category_dict.iteritems(): for category_dict in category_value_list: try: group_id_list = group_id_list_generator( category_order=base_category_list, **category_dict) if isinstance(group_id_list, str): group_id_list = [group_id_list] security_group_list.extend(group_id_list) except ConflictError: raise except: LOG('ERP5GroupManager', WARNING, 'could not get security groups from %s' % generator_name, error=sys.exc_info()) finally: pass return tuple(security_group_list) if not NO_CACHE_MODE: _getGroupsForPrincipal = CachingMethod( _getGroupsForPrincipal, id='ERP5GroupManager_getGroupsForPrincipal', cache_factory='erp5_content_short') return _getGroupsForPrincipal(user_name=principal.getId(), path=self.getPhysicalPath())