def ERP5Site_clearActivities(self): """ This method is used to recreated the activities keeping the previous activities from one activity. The issue related to recreate the Activity tables from one activity is that the activity (this method) is also recreated, so it is kept for ever. This method use a flag to define if the portal already recreated the activities table. If yes, the flag is removed and the recreation will be ignored. This method should be run into a single activity to prevent some action be excetured many times other parts. """ instance_home = getConfiguration().instancehome flag_fs_path = instance_home + "/ACTIVITY_RECREATE_FLAG" log("Start to Clear activities.") if not os.path.exists(flag_fs_path): try: flag = open(flag_fs_path, 'w+') log("Clear Activities") self.getPortalObject().portal_activities.manageClearActivities( keep=1) active_result = ActiveResult() active_result.edit( summary="Activities Recreated", severity=0, detail="Activities Tables was recreated Sucessfully.") return active_result except: os.remove(flag_fs_path) raise os.remove(flag_fs_path) return
def ERP5Site_clearActivities(self): """ This method is used to recreated the activities keeping the previous activities from one activity. The issue related to recreate the Activity tables from one activity is that the activity (this method) is also recreated, so it is kept for ever. This method use a flag to define if the portal already recreated the activities table. If yes, the flag is removed and the recreation will be ignored. This method should be run into a single activity to prevent some action be excetured many times other parts. """ instance_home = getConfiguration().instancehome flag_fs_path = instance_home + "/ACTIVITY_RECREATE_FLAG" log("Start to Clear activities.") if not os.path.exists(flag_fs_path): try: flag = open(flag_fs_path, 'w+') log("Clear Activities") self.getPortalObject().portal_activities.manageClearActivities(keep=1) active_result = ActiveResult() active_result.edit(summary="Activities Recreated", severity=0, detail="Activities Tables was recreated Sucessfully.") return active_result except: os.remove(flag_fs_path) raise os.remove(flag_fs_path) return
def example_random_forest_function(self, active_process_path): digits = load_digits() X_train, X_test, y_train, y_test = train_test_split(digits.data, digits.target, random_state=0) # Create an active process active_process = self.portal_activities.unrestrictedTraverse( active_process_path) # Use CMFActivity as a backend for joblib with parallel_backend('CMFActivity', n_jobs=2, active_process=active_process): final_model = grow_ensemble(RandomForestClassifier(), X_train, y_train, n_estimators=10, n_jobs=2, random_state=42) score = final_model.score(X_test, y_test) # Set result value and an id to the active result and post it result = ActiveResult(result=score, signature=123) active_process.postResult(result) log('ok', len(final_model.estimators_)) return 'ok', len(final_model.estimators_), score
def getMovementTitle(movement): title = movement.getTitle() parent_value = movement.getParentValue() while parent_value.getPortalType() not in order_type_list: title = parent_value.getTitle() + ' / ' + title log('parent_value', parent_value) parent_value = parent_value.getParentValue() return title
def getBucketItemSequence(self, start_key=None, count=None, exclude_start_key=False): log('DeprecationWarning: Please use getBucketKeyItemSequenceByKey') return self.getBucketKeyItemSequenceByKey( start_key=start_key, count=count, exclude_start_key=exclude_start_key)
def getFieldRawProperties(field, meta_type=None, key=None, key_prefix=None): """ Return the raw properties of the field """ if meta_type is None: meta_type = field.meta_type if key is None: key = field.generate_field_key(key_prefix=key_prefix) if meta_type == "ProxyField": meta_type = field.getRecursiveTemplateField().meta_type result = { "type": meta_type, "key": key, "values": {}, "overrides": field.overrides, "message_values": field.message_values } # these patchs change the field property names as are required by js rendering form_list_patch = False gadget_field_patch = False for key in field.values.keys(): # sometimes, field.values returns a key as string and also as a tuple if type(key) is str: result["values"][key] = field.values[key] if key == "columns": form_list_patch = True if key == "gadget_url": gadget_field_patch = True if form_list_patch: try: result["values"]["column_list"] = result["values"]["columns"] result["values"]["sort_column_list"] = result["values"][ "sort_columns"] result["values"]["search_column_list"] = result["values"][ "search_columns"] portal_type = result["values"]["portal_types"][0][ 0] if "portal_types" in result["values"] else False if not portal_type: portal_type = result["values"]["portal_type"][0][ 0] if "portal_type" in result["values"] else False query = "portal_type%3A%22" + portal_type + "%22" if portal_type else "" full_query = "urn:jio:allDocs?query=" + query result["values"]["query"] = full_query except KeyError: log("error while patching form list definition") if gadget_field_patch: try: result["values"]["url"] = result["values"]["gadget_url"] result["values"]["renderjs_extra"] = result["values"][ "renderjs_extra"][0][0] except (ValueError, KeyError, IndexError): log("error while patching form gadget list definition") return result
def example_simple_function(self, active_process_path): """ simple function to calculate sqrt """ active_process = self.portal_activities.unrestrictedTraverse(active_process_path) # Use CMFActivity as a backend for joblob with parallel_backend('CMFActivity', active_process=active_process): result = Parallel(n_jobs=2, pre_dispatch='all', timeout=30, verbose=30)(delayed(sqrt)(i**2) for i in range(5)) # Set result value and an id to the active result and post it result = ActiveResult(result=result) active_process.postResult(result) log("joblib activity result", result) return result
def example_simple_function(self, active_process_path): """ simple function to calculate sqrt """ active_process = self.portal_activities.unrestrictedTraverse( active_process_path) # Use CMFActivity as a backend for joblob with parallel_backend('CMFActivity', active_process=active_process): result = Parallel(n_jobs=2, pre_dispatch='all', timeout=30, verbose=30)(delayed(sqrt)(i**2) for i in range(5)) # Set result value and an id to the active result and post it result = ActiveResult(result=result) active_process.postResult(result) log("joblib activity result", result) return result
def example_random_forest_function(self, active_process_path): digits = load_digits() X_train, X_test, y_train, y_test = train_test_split( digits.data, digits.target, random_state=0) # Create an active process active_process = self.portal_activities.unrestrictedTraverse(active_process_path) # Use CMFActivity as a backend for joblib with parallel_backend('CMFActivity', n_jobs=2, active_process=active_process): final_model = grow_ensemble(RandomForestClassifier(), X_train, y_train, n_estimators=10, n_jobs=2, random_state=42) score = final_model.score(X_test, y_test) # Set result value and an id to the active result and post it result = ActiveResult(result=score, signature=123) active_process.postResult(result) log('ok', len(final_model.estimators_)) return 'ok', len(final_model.estimators_), score
def ERP5Site_restartZopeInstance(self): """ Zope must be restart after update the Products or Software But the restart into one activity, will make the activity always fail and with the server will be restart many times. This method use a flag to define if the server was already restarted. If yes, the flag is removed and the restart will be ignored. This method should be run into a single activity to prevent rollback other parts. """ import Lifetime Lifetime.shutdown(1,fast=1) log("Zope Restart was launched.") active_result = ActiveResult() active_result.edit(summary="Zope Restart", severity=0, detail="Zope was restart Sucessfully.") return active_result
def ERP5Site_restartZopeInstance(self): """ Zope must be restart after update the Products or Software But the restart into one activity, will make the activity always fail and with the server will be restart many times. This method use a flag to define if the server was already restarted. If yes, the flag is removed and the restart will be ignored. This method should be run into a single activity to prevent rollback other parts. """ import Lifetime Lifetime.shutdown(1, fast=1) log("Zope Restart was launched.") active_result = ActiveResult() active_result.edit(summary="Zope Restart", severity=0, detail="Zope was restart Sucessfully.") return active_result
object = sci['object'] portal = object.getPortalObject() translateString = portal.Base_translateString # Get the owner owner = object.getViewPermissionOwner() owner_value = portal.Base_getUserValueByUserId(owner) # Get the authenticated user user_value = portal.portal_membership.getAuthenticatedMember().getUserValue() # If users are not defined, we need to log and return if not owner or owner_value is None: # We keep a trace because this is the best we # can do (preventing answers is even worse) log("ERP5 Query Workflow", "No owner defined") return if user_value is None: # We keep a trace because this is the best we # can do (preventing answers is even worse) log("ERP5 Query Workflow", "Current user is not defined") return # Build the message and translate it subject = translateString("Query was answered.") msg = """The Query ID ${id} which you posted has been answered by ${user} Question: ${question}
'inventory_module', 'purchase_order_module', 'purchase_packing_list_module', 'purchase_trade_condition_module', 'returned_sale_packing_list_module', 'sale_order_module', 'sale_packing_list_module', 'sale_trade_condition_module'), 'pdm': ('component_module', 'product_module', 'purchase_supply_module', 'sale_supply_module', 'service_module', 'transformation_module',), } for business_application_category_id, module_ids in module_business_application_map.items(): for module_id in module_ids: module = getattr(portal, module_id, None) if module is not None: module.edit(business_application = business_application_category_id) print "Indexing translations" portal.ERP5Site_updateTranslationTable() # clear cache so user security is recalculated portal.portal_caches.clearAllCache() print "Clear cache." log("%s" % printed)
""" This script will setup the default ERP5's configuration as saved in erp5_scalability_test business template. As this modifies your site care must be taken! """ from Products.ERP5Type.Log import log portal = context.getPortalObject() configurator = getattr(portal.business_configuration_module, "default_standard_configuration", None) if configurator is None: log("Could not find the scalability business configuration object. Be sure to have erp5_scalability_test business template installed.") return if not portal.ERP5Site_isReady(): # nothing installed, thus do it log("START auto-configuration for ERP5's default configuration.") context.ERP5Site_bootstrapScalabilityTest(user_quantity=0, setup_activity_tool=False, create_test_data=False, set_id_generator=False) else: log("All configured. Nothing to do.")
from Products.PythonScripts.standard import html_quote result = '' error_message = None try: result = context.asStrippedHTML() if result: return result if not context.hasBaseData(): error_message = context.Base_translateString( "This document is not converted yet.") except Exception, e: from Products.ERP5Type.Log import log log("asStrippedHTML", str(e)) error_message = "%s %s" % (context.Base_translateString("Preview Error:"), str(e)) if error_message is not None: return '<div class="error">%s</div>' % html_quote(error_message) return result
try: for base_category in base_category_list: if base_category == 'follow_up': category_value = assignment.getDestinationProject() else: category_value = assignment.getProperty(base_category) #XXX the role is not aquire in the assignment get if from the user_object if base_category == 'role' and category_value in (None, ''): category_value = person_object.getRole() if category_value not in (None, ''): if root: category_value = category_value.split('/')[0] category_dict[base_category] = category_value else: raise RuntimeError, "Error: '%s' property is required in order to update person security group" % ( base_category) category_list.append(category_dict) # if not strict, we go up the hierarchy (because if you work in group/a/b/c, chances are you # are working in group/a/b, too :) if not strict: grouplist = category_value.split('/') for i in range(1, len(grouplist)): cdict = category_dict.copy() cdict[base_category] = '/'.join(grouplist[:-i]) category_list.append(cdict) except RuntimeError, e: log(str(e)) return category_list
from Products.ERP5Type.Log import log, WARNING from Products.ERP5Type.Message import translateString translate = context.Base_translateString current_type = context.getPortalType() file_name = file.filename # we check for appropriate file type (by extension) # ContributionTool_getCandidateTypeListByExtension script returns a tuple of # one or more possible portal types for given extension # we accept or suggest appropriate portal type ext = file_name[file_name.rfind('.')+1:] candidate_type_list = context.ContributionTool_getCandidateTypeListByExtension(ext) if not candidate_type_list and current_type != 'File': log("Document {!s} does not support extension {!s}. Use generic 'File' document.".format(current_type, ext), level=WARNING) return context.Base_redirect(dialog_id, keep_items={ 'portal_status_message': translate("Current document does not support ${ext} file extension.", mapping={'ext': ext}), 'cancel_url': cancel_url}) if candidate_type_list and current_type not in candidate_type_list: log("File extension {!s} is supported only by {!s}, not by current document {!s}.".format(ext, candidate_type_list, current_type), level=WARNING) return context.Base_redirect(dialog_id, keep_items={ 'portal_status_message': translate("Current document does not support ${ext} file extension.", mapping={'ext': ext}), 'cancel_url': cancel_url}) context.edit(file=file) context.activate().Document_convertToBaseFormatAndDiscoverMetadata(file_name=file_name) # Return to view mode return context.Base_redirect(form_id, keep_items={'portal_status_message': translateString('File uploaded.')})
from Products.ERP5Type.Log import log after_script_id = context.getResourceValue().getConfigurationAfterScriptId() after_script = getattr(context, after_script_id, None) if after_script is not None: return after_script() log("After script not found for %s." % context.getRelativeUrl())
if field.meta_type == "ListBox": return True elif field.meta_type == "ProxyField": template_field = field.getRecursiveTemplateField() if template_field.meta_type == "ListBox": return True return False if form_or_id is None: form = context elif isinstance(form_or_id, str): try: form = getattr(context, form_or_id) except AttributeError: log("Form '{}' does not exist!", level=ERROR) return None else: form = form_or_id if form.meta_type not in ('ERP5 Form', 'Folder', 'ERP5 Folder'): raise RuntimeError( "Cannot get Listbox field from \"{!s}\"! Supported is only ERP5 Form and (ERP5) Folder" .format(form.meta_type)) listbox = None if "Form" in form.meta_type and form.has_field("listbox"): listbox = form.get_field("listbox") elif "Folder" in form.meta_type: listbox = getattr(form, "listbox", None)
"""Check the object have an unique reference in it's parent folder """ from Products.ERP5Type.Log import log if editor is None : return 1 reference = editor document = context.restrictedTraverse(request.object_path, None) if document is None : log('Base_uniqueReferenceInFolderValidator', 'document is None') return 0 parent_folder = document.getParentValue() for same_reference in parent_folder.searchFolder(reference = reference): if same_reference.uid != document.getUid() : log('Base_uniqueReferenceInFolderValidator', 'another document with reference %s exists at %s' % (reference, same_reference.getPath())) return 0 return 1
def getBucketValueSequence(self, start_key=None, count=None): log('DeprecationWarning: Please use getBucketValueSequenceByKey') return self.getBucketValueSequenceByKey(start_key=start_key, count=count)
def getBucket(self, key): log('DeprecationWarning: Please use getBucketByKey') return self.getBucketByKey(key)
from Products.PythonScripts.standard import newline_to_br from Products.ERP5Type.Log import log log("Event_getTextContentCorrespondToFormat is deprecated, use Event_getEditorFieldTextContent instead", level=100) # WARNING content_type = context.getContentType() if content_type == 'text/html' and context.hasFile(): return context.asStrippedHTML() else: value = context.getTextContent() if editable: return value else: return newline_to_br(value or "")
from Products.ERP5Type.Log import log log('Depracated usage of Item_getQuantityUnit, please use Item_getQuantityUnitItemList instead') return context.Item_getQuantityUnitItemList()
from Products.ERP5Type.Log import log, WARNING translate = context.Base_translateString request = context.REQUEST current_type = context.getPortalType() file_name = file.filename # we check for appropriate file type (by extension) # ContributionTool_getCandidateTypeListByExtension script returns a tuple of # one or more possible portal types for given extension # we accept or suggest appropriate portal type ext = file_name[file_name.rfind('.')+1:] candidate_type_list = context.ContributionTool_getCandidateTypeListByExtension(ext) if not candidate_type_list and current_type != 'File': log("Document {!s} does not support extension {!s}. Use generic 'File' document.".format(current_type, ext), level=WARNING) return context.Base_redirect(dialog_id, keep_items={ 'portal_status_message': translate("Current document does not support ${ext} file extension.", mapping={'ext': ext}), 'cancel_url': cancel_url}) if candidate_type_list and current_type not in candidate_type_list: log("File extension {!s} is supported only by {!s}, not by current document {!s}.".format(ext, candidate_type_list, current_type), level=WARNING) return context.Base_redirect(dialog_id, keep_items={ 'portal_status_message': translate("Current document does not support ${ext} file extension.", mapping={'ext': ext}), 'cancel_url': cancel_url}) context.edit(file=file) context.activate().Document_convertToBaseFormatAndDiscoverMetadata(file_name=file_name) # Return to view mode return context.Base_redirect(form_id, keep_items={'portal_status_message': translateString('File uploaded.')})
portal.portal_workflow.doActionFor(context, doaction_param_list['workflow_action'], **doaction_param_list) except ValidationFailed, error_message: if getattr(error_message, 'msg', None): # use of Message class to store message+mapping+domain message = error_message.msg if same_type(message, []): message = '. '.join('%s' % x for x in message) else: message = str(message) else: message = str(error_message) if len(message) > 2000: # too long message will generate a too long URI # that would become an error. log("Status message has been truncated") message = "%s ..." % message[:(2000 - 4)] except WorkflowException, error_message: if str(error_message) == "No workflow provides the '${action_id}' action.": message = translateString( "Workflow state may have been updated by other user. Please try again." ) return context.Base_redirect( form_id, keep_items={'portal_status_message': message}, **kw) else: raise else: message = request.get('portal_status_message') if message is None: message = translateString('Status changed.') kw.clear() # useful ?
get_inventory_kw.pop('at_date', None) if period_start_date: if is_pl_account: # if we have on an expense / income account, only take into account # movements from the current period. if initial_balance_from_date: initial_balance_from_date = max(period_start_date, initial_balance_from_date) else: initial_balance_from_date = period_start_date else: # for all other accounts, we calculate initial balance if not initial_balance_from_date: # I don't think this should happen log('from_date not passed, defaulting to period_start_date') initial_balance_from_date = period_start_date # Get previous debit and credit if not (initial_balance_from_date == period_start_date and is_pl_account): getInventoryAssetPrice = portal.portal_simulation.getInventoryAssetPrice section_uid_list = params.get('section_uid', []) if not same_type(section_uid_list, []): section_uid_list = [section_uid_list] for section_uid in section_uid_list: # We add one initial balance line per section. The main reason is to be able # to know the section_title for the GL export. # XXX we may also want detail by resource or analytic columns sometimes. get_inventory_kw['section_uid'] = section_uid # Initial balance calculation uses the same logic as Trial Balance. # first to the balance at the period start date
""" Security categories assigned from the Person who is set as the destination of the document (e.g. in Memo type). """ from Products.ERP5Type.Log import log category_list = [] for ob in object.getDestinationValueList(): category_dict = {} for base_category in base_category_list: if base_category == "group": category_value = ob.Person_getPrincipalGroup() else: category_value = ob.getProperty(base_category) if category_value not in (None, ""): category_dict[base_category] = category_value else: raise RuntimeError, "Error: '%s' property is required in order to update person security group" % ( base_category ) category_list.append(category_dict) log(category_list) return category_list
""" Sets the causality relation on a delivery from the order it comes from. This script should be called in the after generation script of the DeliveryBuilder. IMPORTANT WARNING: this script will not work if your simulation movements are not reindexed yet () It will also not work if strict security is set on simulation. It's recommended to use (Delivery) Causality Movement Group as delivery level movement group in the corresponding delivery builder. """ from Products.ERP5Type.Log import log LOG = lambda msg:log( "Delivery_setCausalityFromSimulation on %s" % context.getPath(), msg) LOG = lambda msg:'DISABLED' delivery = context # get the list of simulation movement which have built this delivery simulation_movement_list = [] for movement in delivery.getMovementList() : LOG("movement %s " % movement.getPath()) simulation_movement_list.extend( movement.getDeliveryRelatedValueList( portal_type = 'Simulation Movement')) LOG("simulation_movement_list %s " % simulation_movement_list) causality_value_set = {} for simulation_movement in simulation_movement_list : LOG("simulation_movement %s " % simulation_movement.getPath()) if simulation_movement.getParentValue() != simulation_movement.getRootAppliedRule():
context, doaction_param_list['workflow_action'], **doaction_param_list) except ValidationFailed, error_message: if getattr(error_message, 'msg', None): # use of Message class to store message+mapping+domain message = error_message.msg if same_type(message, []): message = '. '.join('%s' % x for x in message) else: message = str(message) else: message = str(error_message) if len(message) > 2000: # too long message will generate a too long URI # that would become an error. log("Status message has been truncated") message = "%s ..." % message[:(2000 - 4)] except WorkflowException, error_message: if str(error_message) == "No workflow provides the '${action_id}' action.": message = translateString("Workflow state may have been updated by other user. Please try again.") return context.Base_redirect(form_id, keep_items={'portal_status_message': message}, **kw) else: raise else: message = request.get('portal_status_message') if message is None: message = translateString('Status changed.') kw.clear() # useful ? # Allow to redirect to another document redirect_document_path = request.get('redirect_document_path', None)
if hasattr(v, 'as_dict'): # This is an encapsulated editor # convert it kw.update(v.as_dict()) else: kw[splitted[1]] = request_form[splitted[1]] = v else: kw[k] = request_form[k] = v if len(listbox_id_list): can_redirect = 0 # Warn if there are more than one listbox in form ... if len(listbox_id_list) > 1: log('Base_callDialogMethod', 'There are %s listboxes in form %s.' % (len(listbox_id_list), form.id)) # ... but handle them anyway. for listbox_id in listbox_id_list: listbox_line_list = [] listbox = kw[listbox_id] listbox_keys = listbox.keys() listbox_keys.sort() for key in listbox_keys: listbox_line = listbox[key] listbox_line['listbox_key'] = key listbox_line_list.append(listbox_line) listbox_line_list = tuple(listbox_line_list) kw[listbox_id] = request_form[listbox_id] = listbox_line_list # Check if the selection changed
""" Must call all the script in appropriated order to setup UNG. """ from Products.ERP5Type.Log import log log('Launching activities to setup the demo UNG configuration!') kw = {} installed_business_template_list = context.portal_templates.getInstalledBusinessTemplateTitleList( ) if 'erp5_web_ung_theme' not in installed_business_template_list: kw = context.Alarm_installUngBusinessTemplateList() context.activate(**kw).Alarm_configureUng() log('Finished to launch the activities to setup the demo UNG configuration!') context.setEnabled(False)
from Products.ERP5Type.Log import log # this script is no longer needed. log('Category_getSortedCategoryChildValueList', 'use getCategoryChildValueList method') value_list = [ o for o in context.getCategoryChildValueList() if o.getRelativeUrl() != context.getRelativeUrl() ] sort_id = 'int_index' value_list.sort(key=lambda x: x.getProperty(sort_id)) return value_list
from Products.ERP5Type.Log import log log('Deprecated: use Base_getPreferredSectionItemList instead.') section_cat = context.portal_preferences.getPreferredSectionCategory() if section_cat in (None, '') : section_cat = context.getPortalDefaultSectionCategory() section_cat_obj = None result = [] if section_cat is not None: # get the organisations belonging to this group section_cat_obj = context.portal_categories.resolveCategory(section_cat) if section_cat_obj is not None: result = section_cat_obj.getGroupRelatedValueList(portal_type='Organisation', checked_permission='View') result = [r for r in result if r.getProperty('validation_state') not in ('invalidated', 'deleted')] current_source_section = context.getSourceSectionValue() if current_source_section is not None and current_source_section not in result: result.append(current_source_section) # convert to ListField format return [('', '')] + [(i.getTitle(), i.getRelativeUrl()) for i in result]
""" Call the scripts to decouple the TioLive Instance. """ from Products.ERP5Type.Log import log log("Starting to decouple the TioLive Instance!") # Update person module. result = context.Alarm_updatePersonModulePasswordInformation() if not result: log("TioLive Instance hasn't been decoupled with success! It could not update the objects from Person Module.") return False # Disable the remove user creation. if not context.Alarm_moveObsoleteSkinObjectList(): log("TioLive Instance hasn't been decoupled with success! It could not move the obsolete objects.") return False # Remove Authentication Plugin context.Alarm_removeAuthenticationPlugin() context.setEnabled(False) # Hide change password action context.Alarm_hideChangePasswordAction() # Notify customer context.Alarm_notifyDecoupleInstance(person_list=result) log("Finished to decouple the TioLive Instance!") return True
""" Call the scripts to decouple the TioLive Instance. """ from Products.ERP5Type.Log import log log("Starting to decouple the TioLive Instance!") # Update person module. result = context.Alarm_updatePersonModulePasswordInformation() if not result: log("TioLive Instance hasn't been decoupled with success! It could not update the objects from Person Module." ) return False # Disable the remove user creation. if not context.Alarm_moveObsoleteSkinObjectList(): log("TioLive Instance hasn't been decoupled with success! It could not move the obsolete objects." ) return False # Remove Authentication Plugin context.Alarm_removeAuthenticationPlugin() context.setEnabled(False) # Hide change password action context.Alarm_hideChangePasswordAction() # Notify customer context.Alarm_notifyDecoupleInstance(person_list=result) log("Finished to decouple the TioLive Instance!")
block_end = input_object.getObject().getProperty(stop_property_id, None) block_size = input_object.getObject().getProperty(size_property_id, None) if block_begin != None and block_end != None: # do not create stat on non completed objects. # prevent bug while size property is not defined on the object if block_size == None: block_size = block_end - block_begin #updating block_size value block_size = float(block_size) / (block_end - block_begin) # creating new object temp_object = newTempBase(context.getPortalObject(), id=str(temp_object_id), uid='new_%s' % zfill(temp_object_id, 4)) # editing object with new values log("%s" % (",".join([ start_property_id, str(block_begin), stop_property_id, str(block_end), size_property_id, str(block_size) ]))) temp_object.setProperty(start_property_id, block_begin) temp_object.setProperty(stop_property_id, block_end) temp_object.setProperty(size_property_id, block_size) # adding new object to list temp_object_list.append(temp_object) temp_object_id += 1 ########################################################### ################ BUILDING STATS ACTIVITES ################# ########################################################### # building a special list structure. prop_list = []
from Products.ERP5Type.Log import log log("ERP5Type_getSecurityCategoryFromArrow is deprecated, " "use ERP5Type_getSecurityCategoryFromContent instead") return context.ERP5Type_getSecurityCategoryFromContent(base_category_list, user_name, object, portal_type)
from ZODB.POSException import ConflictError from Products.ERP5.Document.Document import ConversionError from Products.ERP5Type.Log import log message = None try: return context.updateBaseMetadata(**kw) except ConflictError: raise except ConversionError, e: message = 'Conversion Error: %s' % (str(e) or 'undefined.') except Exception, e: message = 'Problem: %s' % (repr(e) or 'undefined.') except: message = 'Problem: unknown' # reach here, then exception was raised, message must be logged in workflow # do not simply raise but rather change external processing state # so user will see something is wrong. As usually updateBaseMetadata is called # after convertToBaseFormat it's possible that object is in conversion failed state isTransitionPossible = context.getPortalObject().portal_workflow.isTransitionPossible if isTransitionPossible(context, 'conversion_failed'): # mark document as conversion failed if not already done by convertToBaseFormat context.conversionFailed(comment=message) else: # just save problem message in workflow history context.processConversionFailed(comment=message) log('%s %s' %(context.getRelativeUrl(), message)) return message
""" Invalidate global user account. Only invalidate if the local user has no Valid Assigments and reference. """ if person is None: person = context reference = person.getReference() assignment_len = len(person.Person_getAvailableAssignmentValueList()) if reference is not None and assignment_len == 0: # invalidate user in Authentification Server only if # its a loggable user in current instance kw = context.Person_getDataDict(person=person) context.portal_wizard.callRemoteProxyMethod( 'WitchTool_invalidateGlobalUserAccountFromExpressInstance', \ use_cache = 0, \ ignore_exceptions = 0, \ **kw) else: from Products.ERP5Type.Log import log log("Unable to invalidate remote global account for "\ "%s (reference=%s , len(assignment_list)=%s)" % (person.getRelativeUrl(), reference, assignment_len))
if field_id.startswith("my_") or field_id.startswith("your_"): _, field_name = field_id.split('_', 1) if hasattr(field_value, 'as_dict'): # This is an encapsulated editor - convert it kw.update(field_value.as_dict()) else: kw[field_name] = request_form[field_name] = field_value else: kw[field_id] = request_form[field_id] = field_value if len(listbox_id_list): # Warn if there are more than one listbox in form ... if len(listbox_id_list) > 1: log( 'Base_callDialogMethod', 'There are %s listboxes in form %s.' % (len(listbox_id_list), form.id)) # ... but handle them anyway. for listbox_id in listbox_id_list: listbox_line_list = [] listbox = kw[listbox_id] listbox_keys = listbox.keys() listbox_keys.sort() for key in listbox_keys: listbox_line = listbox[key] listbox_line['listbox_key'] = key listbox_line_list.append(listbox_line) listbox_line_list = tuple(listbox_line_list) kw[listbox_id] = request_form[listbox_id] = listbox_line_list # Handle selection the new way
from Products.ERP5Type.Log import log log("Folder method received dialog_id, form_id, uids and {!s}".format( kwargs.keys())) message = "First submission." if kwargs.get("update_method", ""): return context.Base_renderForm(dialog_id, message="Updated. " + message) if donothing_confirmation == 0: # Here is an example of an adversary Script which hijacks `keep_items` # It should take keep_items from parameters, update it and pass it # through. But no programmer will ever comply therefor we are ready! return context.Base_renderForm(dialog_id, message="Submit again to confirm. " + message, level='warning', keep_items={'donothing_confirmation': 1}) return context.Base_redirect(form_id, keep_items={"portal_status_message": message})
""" from Products.ERP5Type.Log import log req = context.REQUEST # check if everything was filled fields = ('email', 'email_repeated', 'group', 'function', 'site', 'first_name', 'last_name') missing_string = '' kwargs = {} for f in fields: value = req.get('your_' + f) if not value: missing_string += '&missing:list=' + f else: kwargs[f] = value returned_params = '&'.join([f+'='+kwargs[f] for f in kwargs]) log(returned_params) if missing_string: params = returned_params + '&' + missing_string + '&portal_status_message=You did not fill all the required fields. See below to find out which fields still have to be filled.' log(params) return req.RESPONSE.redirect(context.absolute_url()+'?'+params) if req.get('your_email') != req.get('your_email_repeated'): missing_string += '&missing:list=email&missing:list=email_repeated' params = returned_params + '&' + missing_string + '&portal_status_message=You entered two different email addresses. Please make sure to enter the same email address in the fields Email Address and Repeat Email Address.' return req.RESPONSE.redirect(context.absolute_url()+'?'+params) # create a user log(kwargs) try: user = context.WebSite_createUser(**kwargs) log(user) msg = 'Thank you for registering. Your password will be sent to the email address that you provided once your account has been validated by the appropriate department.'
"""Find and returns Person object for current logged in user. Returns None if no corresponding person, for example when not using ERP5Security.ERP5UserManager. """ from Products.ERP5Type.Log import log if user_name is None: log('DEPRECATED: call context.getPortalObject().portal_membership.getAuthenticatedMember().getUserValue()') return context.getPortalObject().portal_membership.getAuthenticatedMember().getUserValue() log('DEPRECATED: call context.Base_getUserValueByUserId(user_name)') return context.Base_getUserValueByUserId(user_name)
""" Get the reference list of all validated business configuration related to the logged user. """ from Products.ERP5Type.Log import log portal = context.getPortalObject() reference = portal.portal_membership.getAuthenticatedMember().getId() kw = {'reference': reference} # XXX: This try except is used in case of connection refused # and to make sure that the user interface will never be broken. try: return context.portal_wizard.callRemoteProxyMethod( 'WitchTool_getBusinessConfigurationReferenceList', use_cache=1, ignore_exceptions=0, **kw) except: log('Base_getUserRemoteBusinessConfigurationReferenceList: ' 'Could not retrieve the Business Configuration reference list.', level=100) return []
category_dict = {} if assignment.getValidationState() == 'open': try: for base_category in base_category_list: if base_category == 'follow_up': category_value = assignment.getDestinationProject() else: category_value = assignment.getProperty(base_category) #XXX the role is not aquire in the assignment get if from the user_object if base_category=='role' and category_value in (None, ''): category_value = person_object.getRole() if category_value not in (None, ''): if root: category_value=category_value.split('/')[0] category_dict[base_category] = category_value else: raise RuntimeError, "Error: '%s' property is required in order to update person security group" % (base_category) category_list.append(category_dict) # if not strict, we go up the hierarchy (because if you work in group/a/b/c, chances are you # are working in group/a/b, too :) if not strict: grouplist = category_value.split('/') for i in range(1,len(grouplist)): cdict = category_dict.copy() cdict[base_category] = '/'.join(grouplist[:-i]) category_list.append(cdict) except RuntimeError,e: log(str(e)) return category_list
from Products.ERP5Type.Log import log from Products.ZSQLCatalog.SQLCatalog import Query # warn by logging (not possible use python's warn module in restricted environment) log("'quick_search_text' and 'advanced_search_text' scriptable keys are deprecated. Use 'search_text' instead.") return Query(search_text=value)
RESPONSE = request.RESPONSE stat_line = request.get('stat_line', None) return stat_line # XXX example of another way to get the stat line but this is slower from Products.ERP5Type.Log import log from Products.PythonScripts.standard import Object from Products.ZSQLCatalog.SQLCatalog import Query request = container.REQUEST from_date = request.get('from_date', None) to_date = request.get('at_date', None) aggregation_level = request.get('aggregation_level', None) log("in stat method", "") # build document portal type list portal_type_list = [] extend = portal_type_list.extend for title, path in context.ERP5Site_getModuleItemList(): document_type_list = context.restrictedTraverse(path).allowedContentTypes() extend([x.id for x in document_type_list]) # compute sql params, we group and order by date and portal type if aggregation_level == "year": sql_format = "%Y" elif aggregation_level == "month": sql_format = "%Y-%m" elif aggregation_level == "week": sql_format = "%Y-%u" elif aggregation_level == "day":
and must be moved to tiolive_decouple_obsolete. The folder tiolive_decouple_obsolete is created only when it is required and it is not present into portal skins selection. """ from Products.ERP5Type.Log import log portal = context.getPortalObject() obsolete_object_list = ['Person_createUser', 'Person_viewCreateUserActionDialog'] express_customisation_folder = getattr(portal.portal_skins, "express_customisation", None) if express_customisation_folder is None: express_customisation_folder = getattr(portal.portal_skins, "express_customisation_user_synchronization", None) if express_customisation_folder is None: return True obsolete_skin_folder_id = "tiolive_decouple_obsolete" obsolete_skin_folder = getattr(portal.portal_skins, obsolete_skin_folder_id, None) if obsolete_skin_folder is None: portal.portal_skins.manage_addFolder(id=obsolete_skin_folder_id) try: object_list = express_customisation_folder.manage_cutObjects(obsolete_object_list) portal.portal_skins[obsolete_skin_folder_id].manage_pasteObjects(object_list) except AttributeError: log('FAILED to move %s to %s skin folder. Please check is the objects are already into %s.' % \ (obsolete_object_list, obsolete_skin_folder_id, obsolete_skin_folder_id)) return False return True
from Products.ERP5Type.Log import log log('Obsoleted, please use Base_addEvent (with Base_viewAddEventDialog) instead') return context.Base_addEvent(title, direction, portal_type, resource, **kw)
# Script to call in action scripts before executig the actual action. from Products.ERP5Type.Log import log log("ERP5Site_prepare is deprecated, " "use Base_updateListboxSelection instead") # Update checked uids if None not in (selection_name, uids, listbox_uid): context.getPortalObject().portal_selections.updateSelectionCheckedUidList( selection_name, uids=uids, listbox_uid=listbox_uid, REQUEST=context.REQUEST)
"""Compatibility script for old portal type Base_printPdf actions. """ from Products.ERP5Type.Log import log portal = context.getPortalObject() log('Deprecated Base_printPdf action called on a %s. ' 'Remove this action to use global print action.' % context.getPortalType()) portal.changeSkin('Print') return getattr(context, form_id)()