def __repr__(self): repr_str = '<%s object at 0x%x\n' % (self.__class__.__name__, id(self)) repr_str += ' _movement_group = %r,\n' % self._movement_group if getattr(self, '_property_dict', None) is not None: repr_str += ' _property_dict = %r,\n' % self._property_dict if self._movement_list: repr_str += ' _movement_list = %r,\n' % self._movement_list if self._group_list: repr_str += ' _group_list = [\n%s]>' % ( '\n'.join([' %s' % x for x in (',\n'.join([repr(i) for i in self._group_list])).split('\n')])) else: repr_str += ' _last_line_movement_group = %r,\n' % self._last_line_movement_group repr_str += ' _separate_method_name_list = %r>' % self._separate_method_name_list return repr_str allow_class(MovementGroupNode) class FakeMovement: """ A fake movement which simulates some methods on a movement needed by DeliveryBuilder. It contains a list of real ERP5 Movements and can modify them. """ def __init__(self, movement_list): """ Create a fake movement and store the list of real movements """ self.__price_method = None self.__quantity_method = None self.__movement_list = []
else: obj = self.getObject() if obj is not None: return getattr(obj, name) else: raise AttributeError(name) def getObject(self): """ Get the Object. """ from Products.ERP5Type.Globals import get_request request = get_request()['PARENTS'] if request is not None: for item in request: if item.meta_type == 'ERP5 Site': return item.unrestrictedTraverse(self.object_relative_url) return None def __repr__(self): repr_str = '<%s object at 0x%x\n ' % (self.__class__.__name__, id(self)) repr_str += '\n '.join([' %r: %r' % (k, v) \ for k, v in self.__dict__.items()]) repr_str += '>' return repr_str allow_class(ObjectMessage)
# modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # ############################################################################## from Products.DCWorkflow.Expression import StateChangeInfo from Products.PythonScripts.Utility import allow_class allow_class(StateChangeInfo) def setWorkflowVariable(self, **kw): """ Allows to go through security checking and let a script allows to modify a workflow variable """ history = self.object.workflow_history[self.workflow.id] history[-1].update(kw) history._p_changed = 1 StateChangeInfo.setWorkflowVariable = setWorkflowVariable
A simple getter """ return getattr(self,value,d) def getResult(self): """ Returns the result """ return self.result def isResult(self): """ Tells if the result is a result or an error """ return self.severity <= INFO def isError(self): """ Tells if the result is a result or an error """ return self.severity > INFO def __str__(self): """ String representation of this active result """ return "<%s at %s\n%s - %s\n%s>" % ( self.__class__, id(self), self.severity, self.summary, self.detail) allow_class(ActiveResult)
constraint_relative_url = constraint.getRelativeUrl() except AttributeError: constraint_relative_url = constraint.id self.constraint_relative_url = constraint_relative_url self.__dict__.update(kw) def __getitem__(self, key): """ Backward compatibilty with previous tuple message returned by Constraint """ if key == 0: return self.object_relative_url elif key == 1: return '%s inconsistency' % self.class_name elif key == 2: return 104 elif key in (4, -1): return self.description else: return self.getTranslatedMessage() def __repr__(self): return "<ERP5Type.ConsistencyMessage for %s %s on %s (message: %s)>" % ( self.class_name, self.constraint_relative_url, self.object_relative_url, self.getTranslatedMessage()) allow_class(ConsistencyMessage)
return self.invert_mode security.declarePublic('getInvertModeUidList') def getInvertModeUidList(self): return self.uids security.declarePublic('getDomainTreeMode') def getDomainTreeMode(self): return getattr(self, 'domain_tree_mode', 0) security.declarePublic('getReportTreeMode') def getReportTreeMode(self): return getattr(self, 'report_tree_mode', 0) InitializeClass(Selection) allow_class(Selection) class DomainSelection(Acquisition.Implicit, Traversable, Persistent): """ A class to store a selection of domains which defines a report section. There are different ways to use DomainSelection in SQL methods. As a general principle, SQL methods are passed DomainSelection instances as a parameter. Example 1: (hand coded) The domain is accessed directly from the selection and a list of uids is gathered from the ZODB to feed the SQL request. This approach is only suitable for categories and relations. It is not suitable for predicates. Do not use it unless there is no other way.
repr_str += ' _property_dict = %r,\n' % self._property_dict if self._movement_list: repr_str += ' _movement_list = %r,\n' % self._movement_list if self._group_list: repr_str += ' _group_list = [\n%s]>' % ('\n'.join([ ' %s' % x for x in (',\n'.join([repr(i) for i in self._group_list])).split('\n') ])) else: repr_str += ' _last_line_movement_group = %r,\n' % self._last_line_movement_group repr_str += ' _separate_method_name_list = %r>' % self._separate_method_name_list return repr_str allow_class(MovementGroupNode) class FakeMovement: """ A fake movement which simulates some methods on a movement needed by DeliveryBuilder. It contains a list of real ERP5 Movements and can modify them. """ def __init__(self, movement_list): """ Create a fake movement and store the list of real movements """ self.__price_method = None self.__quantity_method = None self.__movement_list = []
"""Exception Classes for ERP5""" # These classes are placed here so that they can be imported into TTW Python # scripts. To do so, add the following line to your Py script: # from Products.CMFActivity.Errors import DeferredCatalogError from Products.PythonScripts.Utility import allow_class class ActivityPendingError(Exception): """Pending activities""" class ActivityFlushError(Exception): """Error during active message flush""" allow_class(ActivityPendingError) allow_class(ActivityFlushError)
VALID_TRANSPARENT_IMAGE_FORMAT_LIST = ('png', 'gif', 'tiff', 'svg') DEFAULT_DISPLAY_ID_LIST = ('nano', 'micro', 'thumbnail', 'xsmall', 'small', 'medium', 'large', 'xlarge',) # default image qualitay (obsoleted use getPreferredImageQuality on a portal_preferences tool) DEFAULT_IMAGE_QUALITY = 75.0 DEFAULT_CONTENT_TYPE = 'text/html' class ConversionError(Exception):pass class DocumentProxyError(Exception):pass class NotConvertedError(Exception):pass allow_class(NotConvertedError) from Products.ERP5.mixin.extensible_traversable import DocumentExtensibleTraversableMixin class Document(DocumentExtensibleTraversableMixin, XMLObject, UrlMixin, CachedConvertableMixin, CrawlableMixin, TextConvertableMixin, DownloadableMixin, DocumentMixin, DiscoverableMixin): """Document is an abstract class with all methods related to document management in ERP5. This includes searchable text, explicit relations, implicit relations, metadata, versions, languages, etc. Documents may either store their content directly or cache content which is retrieved from a specified URL. The second case if often referred as "External Document". Standalone "External Documents" may be created by specifying a URL to the contribution tool which is in charge of initiating the download process and selecting the appropriate
""" init specific variable to constraint """ ObjectMessage.__init__(self, object_relative_url, message, mapping) self.description = constraint.description self.class_name = constraint.__class__.__name__ self.__dict__.update(kw) def __getitem__(self, key): """ Backward compatibilty with previous tuple message returned by Constraint """ if key == 0: return self.object_relative_url elif key == 1: return '%s inconsistency' % self.class_name elif key == 2: return 104 elif key in (4, -1): return self.description else: return self.getTranslatedMessage() def __repr__(self): return "<ERP5Type.ConsistencyMessage for %s on %s (message: %s)>" % ( self.class_name, self.object_relative_url, self.getTranslatedMessage()) allow_class(ConsistencyMessage)
allow_module("perfact.winvnc") allow_module("perfact.xls") allow_module("perfact.zopeinterface") allow_module("perfact.zodbsync") # This is on by default in Zope2, but not in Zope4 allow_module("Products.PythonScripts.standard") # Needed for sql_quote() allow_module("DocumentTemplate.DT_Var") # In order to use the central connector, we need to allow access to # the class. try: from perfact.dbconn import DBConn allow_class(DBConn) except ImportError: pass try: from perfact.latex import HTML2Tex allow_class(HTML2Tex) except ImportError: pass try: from perfact.network import InterfacesParser allow_class(InterfacesParser) except ImportError: pass
from Products.ERP5Type import Permissions from Products.PythonScripts.Utility import allow_class class DocumentationSection(Implicit): # security = ClassSecurityInfo() # security.declareObjectProtected(Permissions.AccessContentsInformation) def __init__(self, id, title, class_name, uri_list): self.id = id self.title = title self.class_name = class_name self.uri_list = uri_list # security.declareProtected(Permissions.AccessContentsInformation, 'getClassName') def getClassName(self): return self.class_name # security.declareProtected(Permissions.AccessContentsInformation, 'getURIList') def getURIList(self): return self.uri_list # more API needed XXX #InitializeClass(DocumentationSection) allow_class(DocumentationSection)
result = sum(filter(lambda y: y is not None, map(lambda x: x.getTotalPrice(), self))) return result security.declarePublic('getTotalDuration') def getTotalDuration(self): """ Return total duration """ result = sum(filter(lambda y: y is not None, map(lambda x: x.getDuration(), self))) return result def multiplyQuantity(self,context=None): """ Take into account the quantity of the context. Change the quantity of each element. """ quantity = None if context is not None: if context.getQuantity() is not None: quantity = context.getQuantity() if quantity is not None: for x in self: previous_quantity = x.getQuantity() if previous_quantity is not None: x.edit(quantity=context.getQuantity()*previous_quantity) InitializeClass(AggregatedAmountList) allow_class(AggregatedAmountList)
relation_item_key = field.generate_subfield_key(ITEM_ID, key=key) relation_item_list = REQUEST.get(relation_item_key, []) return [(Widget.TextWidgetInstance, relation_field_id, relation_item_list, value, None)] class RelationEditor(MultiRelationField.MultiRelationEditor): """ A class holding all values required to update a relation """ def __call__(self, REQUEST): MultiRelationField.MultiRelationEditor.__call__(self, REQUEST) value = REQUEST.get(self.field_id) if value is not None: REQUEST.set(self.field_id, value[0]) allow_class(RelationEditor) class RelationStringFieldValidator( MultiRelationField.MultiRelationStringFieldValidator, Validator.StringValidator): """ Validation includes lookup of relared instances """ message_names = Validator.StringValidator.message_names + \ MultiRelationField.MultiRelationStringFieldValidator.message_names property_names = Validator.StringValidator.property_names + \ MultiRelationField.MultiRelationStringFieldValidator.property_names # Delete double in order to keep a usable ZMI... # Need to keep order !
%(class_name)s objects can be synchronized accross multiple sites \"\"\" meta_type = 'ERP5 %(portal_type_name)s' portal_type = '%(portal_type_name)s' add_permission = Permissions.AddPortalContent # Declarative Security security = ClassSecurityInfo() security.declareObjectProtected(Permissions.AccessContentsInformation) # Declarative Properties property_sheets = ( PropertySheet.Base , PropertySheet.XMLObject , PropertySheet.CategoryCore , PropertySheet.DublinCore , PropertySheet.Arrow , PropertySheet.Task , PropertySheet.%(class_name)s ) """ % formating_dict writeLocalDocument(class_name, string) InitializeClass(LocalGenerator) allow_class(LocalGenerator)
def render(self, name='', extension='sxw', source=False): """ returns the OOo document """ if name and not (source): request = get_request() request.response.setHeader( 'Content-Disposition', 'attachment; filename=%s.%s' % (name, extension)) self._document.seek(0) return self._document.read() allow_class(OOoBuilder) class OOoParser(Implicit): """ General purpose tools to parse and handle OpenOffice v1.x documents. """ __allow_access_to_unprotected_subobjects__ = 1 def __init__(self): self.oo_content_dom = None self.oo_styles_dom = None self.oo_files = {} self.pictures = {} self.filename = None
# These classes are placed here so that they can be imported into TTW Python # scripts. To do so, add the following line to your Py script: # from Products.Formulator.Errors import ValidationError, FormValidationError from Products.PythonScripts.Utility import allow_class class FormValidationError(Exception): def __init__(self, errors, result): Exception.__init__(self, "Form Validation Error") self.errors = errors self.result = result allow_class(FormValidationError) class ValidationError(Exception): def __init__(self, error_key, field, error_text=None): Exception.__init__(self, error_key) self.error_key = error_key self.field_id = field.id self.field = field if error_text is not None: self.error_text = error_text else: self.error_text = field.get_error_message(error_key) allow_class(ValidationError)
""" message = self.translate() if isinstance(message, unicode): message = message.encode('utf-8') return message def __unicode__(self): """ Return the translated message as a unicode object. """ message = self.translate() if isinstance(message, str): message = message.decode('utf-8') return message def __len__(self): return len(str(self)) def __getitem__(self, index): return str(self)[index] def __getslice__(self, i, j): return str(self)[i:j] InitializeClass(Message) allow_class(Message) def translateString(message, **kw): return Message(domain='erp5_ui', message=message, **kw)
pass class ConfigurationError(MetadataError): pass class NotFound(MetadataError, AttributeError): pass class ImportError(MetadataError): pass class ValidationError(MetadataError): pass class BindingError(MetadataError): pass class XMLMarshallError(MetadataError): pass # For use in python scripts from Products.PythonScripts.Utility import allow_class allow_class(BindingError)
encapsulated_editor.edit(context) def as_dict(self): """ This method is used to return parameter dict. XXX This API is probably not stable and may change, as some editors are used to edit multiple objects. """ result_dict = self.result[0] for encapsulated_editor in self.result[1]: if hasattr(encapsulated_editor, 'as_dict'): result_dict.update( encapsulated_editor.as_dict()) return result_dict allow_class(FormBoxEditor) class FormBoxValidator(Validator.Validator): """ Validate all fields of the form and return the result as a single variable. """ property_names = Validator.Validator.property_names message_names = Validator.Validator.message_names + \ ['form_invalidated', 'required_not_found'] form_invalidated = "Form invalidated." required_not_found = 'Input is required but no input given.' def validate(self, field, key, REQUEST): # XXX hardcoded acquisition
'www/StringField.gif') # register help for the product context.registerHelp() # register field help for all fields FieldRegistry.registerFieldHelp(context) # make Dummy Fields into real fields FieldRegistry.initializeFields() # do initialization of Form class to make fields addable Form.initializeForm(FieldRegistry) Form.initializeForm(FieldRegistry, form_class=Report.ERP5Report) # Register FSPDFTemplate icon registerIcon(PDFTemplate.FSPDFTemplate, 'www/PDF.png', globals()) # Register ProxyField icon registerIcon(ProxyField.ProxyField, 'www/ProxyField.png', globals()) ## Initialize security ## ModuleSecurityInfo('Products.ERP5Form.Report').declarePublic('ReportSection',) ModuleSecurityInfo('Products.ERP5Form.MultiRelationField').declarePublic('SUB_FIELD_ID',) import Selection allow_class(Selection) __module_aliases__ = ('Products.ERP5Form.SelectionTool', SelectionTool),
"""Exception Classes for ERP5""" # These classes are placed here so that they can be imported into TTW Python # scripts. To do so, add the following line to your Py script: # from Products.ERP5.Errors import DeferredCatalogError from Products.PythonScripts.Utility import allow_class from Products.CMFCore.WorkflowCore import WorkflowException from MySQLdb import ProgrammingError allow_class(ProgrammingError) class DeferredCatalogError(Exception): def __init__(self, error_key, context): Exception.__init__(self, error_key) self.error_key = error_key self.field_id = context.getRelativeUrl() class SSHConnectionError(Exception): def __init__(self, message): Exception.__init__(self, message) self.message = message def __str__(self): return self.message class UnsupportedWorkflowMethod(WorkflowException):
""" message = self.translate() if isinstance(message, six.text_type): message = message.encode('utf-8') return message def __unicode__(self): """ Return the translated message as a unicode object. """ message = self.translate() if isinstance(message, str): message = message.decode('utf-8') return message def __len__(self): return len(str(self)) def __getitem__(self, index): return str(self)[index] def __getslice__(self, i, j): return str(self)[i:j] InitializeClass(Message) allow_class(Message) def translateString(message, **kw): return Message(domain='erp5_ui', message=message, **kw)
# This program is Free Software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # ############################################################################## """Exception Classes for ERP5Configurator""" # These classes are placed here so that they can be imported into TTW Python # scripts. To do so, add the following line to your Py script: # from Products.ERP5.Errors import DeferredCatalogError from Products.PythonScripts.Utility import allow_class from Products.CMFCore.WorkflowCore import WorkflowException class SMSGatewayError(Exception): pass allow_class(SMSGatewayError)
elif uid is not None: append(getObject(uid)) set_method_name = self.relation_setter_id set_method_kw = {} if not set_method_name: # XXX: we could call a generic method which create the setter method name set_method_name = 'set%sValueList' % \ convertToUpperCase(self.base_category) set_method_kw['checked_permission'] = 'View' getattr(o, set_method_name)(relation_object_list, portal_type=self.portal_type_list, **set_method_kw) allow_class(MultiRelationEditor) class MultiRelationStringFieldValidator(Validator.LinesValidator): """ Validation includes lookup of relared instances """ message_names = Validator.LinesValidator.message_names +\ ['relation_result_too_long', 'relation_result_ambiguous', 'relation_result_empty',] relation_result_too_long = "Too many documents were found." relation_result_ambiguous = "Select appropriate document in the list." relation_result_empty = "No such document was found." # Relation field variable
is_legacy = ('oasis.opendocument' not in self.getMimeType()) return "%s%s" % (is_legacy and '#' or '', name,) def render(self, name='', extension='sxw', source=False): """ returns the OOo document """ if name and not(source): request = get_request() request.response.setHeader('Content-Disposition', 'attachment; filename=%s.%s' % (name, extension)) self._document.seek(0) return self._document.read() allow_class(OOoBuilder) class OOoParser(Implicit): """ General purpose tools to parse and handle OpenOffice v1.x documents. """ __allow_access_to_unprotected_subobjects__ = 1 def __init__(self): self.oo_content_dom = None self.oo_styles_dom = None self.oo_files = {} self.pictures = {} self.filename = None def openFromString(self, text_content): return self.openFile(StringIO(text_content))
class ReadOnlyError(MetadataError): pass class NoContext(MetadataError): pass class NamespaceConflict(MetadataError): pass class ConfigurationError(MetadataError): pass class NotFound(MetadataError, AttributeError): pass class ImportError(MetadataError): pass class ValidationError(MetadataError): pass class BindingError(MetadataError): pass class XMLMarshallError(MetadataError): pass # For use in python scripts from Products.PythonScripts.Utility import allow_class allow_class(BindingError)
# from request.form and edits selection with those parameters, so if you # happen to pass explicitly selection params that have the same name as # some request parameters (some dialog fields) but different values, # listbox would not use your explicit parameters, but the ones from # REQUEST.form, so we remove eventual request parameters that have the same # name of selections parameters passed explicitly. for selection_parameter in (self.selection_params or ()): REQUEST.form.pop(selection_parameter, None) security.declarePublic('popReport') def popReport(self, context, render_prefix=None): self.popRequest() portal_selections = context.portal_selections selection_list = [] form_id = self.getFormId() if form_id: listbox = getattr(getattr(context, form_id), 'listbox', None) if listbox is not None: selection_list.append(listbox.get_value('selection_name')) selection_list.append(self.selection_name) if self.temporary_selection: for selection_name in selection_list: if selection_name is not None: portal_selections.popSelection(selection_name) InitializeClass(ReportSection) allow_class(ReportSection)
if movement_group.getDivergenceScope() == divergence_scope: if tested_property is None or \ tested_property in movement_group.getTestedPropertyList(): return movement_group def getCollectOrderGroup(self): """Wraps and canonises result of Movement Groups' getCollectOrderGroup getter""" movement_group = self.getMovementGroup() if movement_group is not None: return movement_group.getCollectOrderGroup() elif getattr(self, 'divergence_scope', None) == 'quantity': # We have no MovementGroup for quantity, so try to guess from the # portal_type. portal_type = self.getObject().getPortalType() if 'Line' in portal_type: return 'line' elif 'Cell' in portal_type: return 'cell' return None def __eq__(self, other): try: return self.__dict__ == other.__dict__ except AttributeError: return False def __ne__(self, other): return not self.__eq__(other) allow_class(DivergenceMessage)
if name.startswith('__') : raise AttributeError, name else: obj = self.getObject() if obj is not None: return getattr(obj, name) else: raise AttributeError, name def getObject(self): """ Get the Object. """ from Products.ERP5Type.Globals import get_request request = get_request()['PARENTS'] if request is not None: for item in request: if item.meta_type == 'ERP5 Site': return item.unrestrictedTraverse(self.object_relative_url) return None def __repr__(self): repr_str = '<%s object at 0x%x\n ' % (self.__class__.__name__, id(self)) repr_str += '\n '.join([' %r: %r' % (k, v) \ for k, v in self.__dict__.items()]) repr_str += '>' return repr_str allow_class(ObjectMessage)
VALID_IMAGE_FORMAT_LIST = ('jpg', 'jpeg', 'png', 'gif', 'pnm', 'ppm', 'tiff') DEFAULT_DISPLAY_ID_LIST = ('nano', 'micro', 'thumbnail', 'xsmall', 'small', 'medium', 'large', 'xlarge',) # default image quality DEFAULT_IMAGE_QUALITY = 75 DEFAULT_CONTENT_TYPE = 'text/html' class ConversionError(Exception):pass class DocumentProxyError(Exception):pass class NotConvertedError(Exception):pass allow_class(NotConvertedError) class Document(DocumentExtensibleTraversableMixin, XMLObject, UrlMixin, CachedConvertableMixin, CrawlableMixin, TextConvertableMixin, DownloadableMixin, DocumentMixin, DiscoverableMixin): """Document is an abstract class with all methods related to document management in ERP5. This includes searchable text, explicit relations, implicit relations, metadata, versions, languages, etc. Documents may either store their content directly or cache content which is retrieved from a specified URL. The second case if often referred as "External Document". Standalone "External Documents" may be created by specifying a URL to the contribution tool which is in charge of initiating the download process and selecting the appropriate document type. Groups of "External Documents" may also be generated from so-called "External Source" (refer to ExternalSource class for more
## Hide internal implementation #from Products.ERP5Type.Globals import InitializeClass #import Products.ERP5Type.Core.Folder as ERP5Folder ## Default constructor for Folder ## Can be overriden by adding a method addFolder in class Folder #def addFolder(folder, id, REQUEST=None, **kw): #o = ERP5Folder.Folder(id) #folder._setObject(id, o) #if kw is not None: o.__of__(folder)._edit(force_update=1, **kw) ## contentCreate already calls reindex 3 times ... ## o.reindexObject() #if REQUEST is not None: #REQUEST['RESPONSE'].redirect( 'manage_main' ) #InitializeClass(ERP5Folder.Folder) from Products.ERP5Type.Base import TempBase from Products.PythonScripts.Utility import allow_class allow_class(TempBase) def newTempBase(folder, id, REQUEST=None, **kw): o = TempBase(id) o = o.__of__(folder) if kw is not None: o._edit(force_update=1, **kw) return o from AccessControl import ModuleSecurityInfo ModuleSecurityInfo('Products.ERP5Type.Document').declarePublic('newTempBase', )
# of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # ############################################################################## from Products.DCWorkflow.Expression import StateChangeInfo from Products.PythonScripts.Utility import allow_class allow_class(StateChangeInfo) def setWorkflowVariable(self, **kw): """ Allows to go through security checking and let a script allows to modify a workflow variable """ history = self.object.workflow_history[self.workflow.getReference()] history[-1].update(kw) history._p_changed = 1 StateChangeInfo.setWorkflowVariable = setWorkflowVariable
def __init__(self, summary='', severity=INFO, detail='', **kw): """ set all parameters """ if 'object_path' in kw: self.object_path = getPath(kw['object_path'], tuple=1) del kw['object_path'] self.summary = summary self.severity = severity self.detail = detail self.__dict__.update(kw) def edit(self, **kw): """ set all parameters """ if 'object_path' in kw: self.object_path = getPath(kw['object_path'], tuple=1) del kw['object_path'] self.__dict__.update(kw) def getProperty(self, key, d=_MARKER, **kw): """ A simple getter """ return getattr(self, key, d) allow_class(Error)
_MARKER = None def __init__(self,summary='',severity=INFO,detail='',**kw): """ set all parameters """ if kw.has_key('object_path'): self.object_path = getPath(kw['object_path'],tuple=1) del kw['object_path'] self.summary = summary self.severity = severity self.detail = detail self.__dict__.update(kw) def edit(self,**kw): """ set all parameters """ if kw.has_key('object_path'): self.object_path = getPath(kw['object_path'],tuple=1) del kw['object_path'] self.__dict__.update(kw) def getProperty(self, key, d=_MARKER, **kw): """ A simple getter """ return getattr(self, key, d) allow_class(Error)
else: # we could call a generic method which create the setter method name if len(relation_object_list) == 1: set_method_name = '_set%sValue' % \ convertToUpperCase(self.base_category) getattr(o, set_method_name)(relation_object_list[0], portal_type=self.portal_type_list, checked_permission='View') else: set_method_name = '_set%sValueList' % \ convertToUpperCase(self.base_category) getattr(o, set_method_name)(relation_object_list, portal_type=self.portal_type_list, checked_permission='View') allow_class(MultiRelationEditor) class MultiRelationStringFieldValidator(Validator.LinesValidator): """ Validation includes lookup of relared instances """ message_names = Validator.LinesValidator.message_names +\ ['relation_result_too_long', 'relation_result_ambiguous', 'relation_result_empty',] relation_result_too_long = "Too many documents were found." relation_result_ambiguous = "Select appropriate document in the list." relation_result_empty = "No such document was found." # Relation field variable editor = MultiRelationEditor
self.color = Config.color_error self.msg = "%s: %s" % (Config.error_messages.get(str(status), "Unknown error!"), msg) def __eq__(self, other): # Useful for testing. return other.msg == self.msg and other.status == self.status def __repr__(self): # Useful for testing. return '%s("%s", %s)' % (self.__class__.__name__, self.msg, self.status) # This is necessary in order to use the Msg classes in untrusted code. from Products.PythonScripts.Utility import allow_class allow_class(StatusMsg) allow_class(TextMsg) ############################################################################ # Utility classes & functions ############################################################################ def normalizeRelativeURL(url): """ utility function - does basically what os.path.normpath() does for filesystem paths, but for URLs instead. Does not verify whether anything exists at the path. """ if not isinstance(url, types.StringType):
import GadgetField FieldRegistry.registerField(GadgetField.GadgetField, 'www/StringField.gif') # register help for the product context.registerHelp() # register field help for all fields FieldRegistry.registerFieldHelp(context) # make Dummy Fields into real fields FieldRegistry.initializeFields() # do initialization of Form class to make fields addable Form.initializeForm(FieldRegistry) Form.initializeForm(FieldRegistry, form_class=Report.ERP5Report) # Register FSPDFTemplate icon registerIcon(PDFTemplate.FSPDFTemplate, 'www/PDF.png', globals()) # Register ProxyField icon registerIcon(ProxyField.ProxyField, 'www/ProxyField.png', globals()) ## Initialize security ## ModuleSecurityInfo('Products.ERP5Form.Report').declarePublic('ReportSection', ) ModuleSecurityInfo('Products.ERP5Form.MultiRelationField').declarePublic( 'SUB_FIELD_ID', ) allow_module('Products.ERP5Form.Selection') import Selection allow_class(Selection) __module_aliases__ = ('Products.ERP5Form.SelectionTool', SelectionTool),
# When rendering a report section with a listbox, listbox gets parameters # from request.form and edits selection with those parameters, so if you # happen to pass explicitly selection params that have the same name as # some request parameters (some dialog fields) but different values, # listbox would not use your explicit parameters, but the ones from # REQUEST.form, so we remove eventual request parameters that have the same # name of selections parameters passed explicitly. for selection_parameter in (self.selection_params or ()): REQUEST.form.pop(selection_parameter, None) security.declarePublic('popReport') def popReport(self, context, render_prefix=None): self.popRequest() portal_selections = context.portal_selections selection_list = [] form_id = self.getFormId() if form_id: listbox = getattr(getattr(context, form_id), 'listbox', None) if listbox is not None: selection_list.append(listbox.get_value('selection_name')) selection_list.append(self.selection_name) if self.temporary_selection: for selection_name in selection_list: if selection_name is not None: portal_selections.popSelection(selection_name) InitializeClass(ReportSection) allow_class(ReportSection)
if tested_property is None or \ tested_property in movement_group.getTestedPropertyList(): return movement_group def getCollectOrderGroup(self): """Wraps and canonises result of Movement Groups' getCollectOrderGroup getter""" movement_group = self.getMovementGroup() if movement_group is not None: return movement_group.getCollectOrderGroup() elif getattr(self, 'divergence_scope', None) == 'quantity': # We have no MovementGroup for quantity, so try to guess from the # portal_type. portal_type = self.getObject().getPortalType() if 'Line' in portal_type: return 'line' elif 'Cell' in portal_type: return 'cell' return None def __eq__(self, other): try: return self.__dict__ == other.__dict__ except AttributeError: return False def __ne__(self, other): return not self.__eq__(other) allow_class(DivergenceMessage)
# ERP5Type has a specific __init__ file to circumvent circular references ## Hide internal implementation #from Products.ERP5Type.Globals import InitializeClass #import Products.ERP5Type.Core.Folder as ERP5Folder ## Default constructor for Folder ## Can be overriden by adding a method addFolder in class Folder #def addFolder(folder, id, REQUEST=None, **kw): #o = ERP5Folder.Folder(id) #folder._setObject(id, o) #if kw is not None: o.__of__(folder)._edit(force_update=1, **kw) ## contentCreate already calls reindex 3 times ... ## o.reindexObject() #if REQUEST is not None: #REQUEST['RESPONSE'].redirect( 'manage_main' ) #InitializeClass(ERP5Folder.Folder) from Products.ERP5Type.Base import TempBase from Products.PythonScripts.Utility import allow_class allow_class(TempBase) def newTempBase(folder, id, REQUEST=None, **kw): o = TempBase(id) o = o.__of__(folder) if kw is not None: o._edit(force_update=1, **kw) return o from AccessControl import ModuleSecurityInfo ModuleSecurityInfo('Products.ERP5Type.Document').declarePublic('newTempBase',)
This test is experimental for new simulation implementation. """ from Products.ERP5Type.tests.SecurityTestCase import SecurityTestCase from Products.ERP5Type.tests.Sequence import SequenceList from testPackingList import TestPackingListMixin from Products.PythonScripts.Utility import allow_class class DummySolverConfiguration(object): def as_dict(self): return {'tested_property_list': ['quantity']} allow_class(DummySolverConfiguration) class TestERP5Simulation(TestPackingListMixin, SecurityTestCase): run_all_test = 1 quiet = 0 def afterSetUp(self): super(TestERP5Simulation, self).afterSetUp() self.loginByUserName('manager') self.portal.portal_rules.new_delivery_simulation_rule.quantity_tester.edit( quantity_range_max=2, quantity_range_min=-1) def beforeTearDown(self): super(TestERP5Simulation, self).beforeTearDown() self.portal.portal_rules.new_delivery_simulation_rule.quantity_tester.edit(
""" return getattr(self, value, d) def getResult(self): """ Returns the result """ return self.result def isResult(self): """ Tells if the result is a result or an error """ return self.severity <= INFO def isError(self): """ Tells if the result is a result or an error """ return self.severity > INFO def __str__(self): """ String representation of this active result """ return "<%s at %s\n%s - %s\n%s>" % ( self.__class__, id(self), self.severity, self.summary, self.detail) allow_class(ActiveResult)
def __delitem__(self, key): self._dictionary.__delitem__(self._prefixKey(key)) # These are the method names called by zope __guarded_setitem__ = __setitem__ __guarded_getitem__ = __getitem__ __guarded_delitem__ = __delitem__ def get(self, key, default=None): return self._dictionary.get(self._prefixKey(key), default) def set(self, key, value): self._dictionary.set(self._prefixKey(key), value) allow_class(SharedDict) class MemcachedTool(_MemcacheTool): """ Memcached interface available as a tool. """ security = ClassSecurityInfo() memcached_tool_configure = DTMLFile('memcached_tool_configure', _dtmldir) erp5_site_global_id = '' security.declareProtected(Permissions.AccessContentsInformation, 'getMemcachedDict') def getMemcachedDict(self, key_prefix, plugin_path): """ Returns an object which can be used as a dict and which gets from/stores to memcached server.
from Acquisition import Implicit from AccessControl import ClassSecurityInfo from Products.ERP5Type.Globals import InitializeClass from Products.ERP5Type import Permissions from Products.PythonScripts.Utility import allow_class class DocumentationSection(Implicit): # security = ClassSecurityInfo() # security.declareObjectProtected(Permissions.AccessContentsInformation) def __init__(self, id, title, class_name, uri_list): self.id = id self.title = title self.class_name = class_name self.uri_list = uri_list # security.declareProtected(Permissions.AccessContentsInformation, 'getClassName') def getClassName(self): return self.class_name # security.declareProtected(Permissions.AccessContentsInformation, 'getURIList') def getURIList(self): return self.uri_list # more API needed XXX #InitializeClass(DocumentationSection) allow_class(DocumentationSection)
# ############################################################################## """ ERP5 Free Software ERP """ # Update ERP5 Globals from Products.ERP5Type.Utils import initializeProduct, updateGlobals import sys, Permissions this_module = sys.modules[ __name__ ] document_classes = updateGlobals( this_module, globals(), permissions_module = Permissions) from Products.PythonScripts.Utility import allow_class from AccessControl import ModuleSecurityInfo import MovementGroup allow_class(MovementGroup) from Products.ERP5Type.Globals import package_home product_path = package_home( globals() ) # Define object classes and tools from Tool import CategoryTool, SimulationTool, RuleTool, IdTool, TemplateTool,\ TestTool, DomainTool, AlarmTool, OrderTool, DeliveryTool,\ TrashTool, ContributionTool, NotificationTool, PasswordTool,\ GadgetTool, ContributionRegistryTool, IntrospectionTool,\ AcknowledgementTool, SolverTool, SolverProcessTool,\ ConversionTool, RoundingTool, UrlRegistryTool, InterfaceTool,\ CertificateAuthorityTool, InotifyTool, TaskDistributionTool import ERP5Site from Document import PythonScript object_classes = ( ERP5Site.ERP5Site,
encapsulated_editor.edit(context) def as_dict(self): """ This method is used to return parameter dict. XXX This API is probably not stable and may change, as some editors are used to edit multiple objects. """ result_dict = self.result[0] for encapsulated_editor in self.result[1]: if hasattr(encapsulated_editor, 'as_dict'): result_dict.update(encapsulated_editor.as_dict()) return result_dict allow_class(FormBoxEditor) class FormBoxValidator(Validator.Validator): """ Validate all fields of the form and return the result as a single variable. """ property_names = Validator.Validator.property_names message_names = Validator.Validator.message_names + \ ['form_invalidated', 'required_not_found'] form_invalidated = "Form invalidated." required_not_found = 'Input is required but no input given.' def validate(self, field, key, REQUEST):
"""Exception Classes for ERP5""" # These classes are placed here so that they can be imported into TTW Python # scripts. To do so, add the following line to your Py script: # from Products.ERP5.Errors import DeferredCatalogError from Products.PythonScripts.Utility import allow_class from Products.CMFCore.WorkflowCore import WorkflowException from MySQLdb import ProgrammingError allow_class(ProgrammingError) class DeferredCatalogError(Exception): def __init__(self, error_key, context): Exception.__init__(self, error_key) self.error_key = error_key self.field_id = context.getRelativeUrl() class UnsupportedWorkflowMethod(WorkflowException): def __init__(self, instance, workflow_id, transition_id): self.instance = instance self.workflow_id = workflow_id self.transition_id = transition_id def __str__(self): return "Transition %s/%s unsupported for %r. Current state is %r." \ % (self.workflow_id, self.transition_id, self.instance, self.instance.getPortalObject().portal_workflow[self.workflow_id]
security.declarePublic('getDomainTreeMode') def getDomainTreeMode(self): return getattr(self, 'domain_tree_mode', 0) security.declarePublic('getReportTreeMode') def getReportTreeMode(self): return getattr(self, 'report_tree_mode', 0) security.declarePublic('getAnonymousSelectionKey') def getAnonymousSelectionKey(self): return md5(repr({k: v for k, v in self.__dict__.iteritems() if k != 'index'})).hexdigest() InitializeClass(Selection) allow_class(Selection) class DomainSelection(Acquisition.Implicit, Traversable, Persistent): """ A class to store a selection of domains which defines a report section. Do not use this class directly, but use selection_{domain,report} parameters in SQLCatalog API. """ security = ClassSecurityInfo() security.declareObjectPublic() def __init__(self, domain_dict = None): #LOG('DomainSelection', 0, '__init__ is called with %r' % (domain_dict,))
""" ERP5 Free Software ERP """ # Update ERP5 Globals from Products.ERP5Type.Utils import initializeProduct, updateGlobals import sys, Permissions this_module = sys.modules[__name__] document_classes = updateGlobals(this_module, globals(), permissions_module=Permissions) from Products.PythonScripts.Utility import allow_class from AccessControl import ModuleSecurityInfo import MovementGroup allow_class(MovementGroup) from Products.ERP5Type.Globals import package_home product_path = package_home(globals()) # Define object classes and tools from Tool import CategoryTool, SimulationTool, RuleTool, IdTool, TemplateTool,\ TestTool, DomainTool, AlarmTool, OrderTool, DeliveryTool,\ TrashTool, ContributionTool, NotificationTool, PasswordTool,\ GadgetTool, ContributionRegistryTool, IntrospectionTool,\ AcknowledgementTool, SolverTool, SolverProcessTool,\ RoundingTool, UrlRegistryTool, InterfaceTool,\ CertificateAuthorityTool, InotifyTool, TaskDistributionTool import ERP5Site from Document import PythonScript, SQLMethod object_classes = (
from zope import component from Products.CMFPlomino import interfaces from zope.interface import implements # TODO: support more of these: # from tablib import Databook, Dataset, detect, import_set, InvalidDatasetType, InvalidDimensions, UnsupportedFormat from tablib import Dataset from tablib import Databook from Products.PythonScripts.Utility import allow_module, allow_class allow_module('plomino.tablib') allow_class(Dataset) allow_class(Databook) def dataset(data, headers=None): """ `data` is a list of dicts. """ dataset = Dataset() dataset.dict = data if headers: dataset.headers = headers return dataset def databook(data): """ `data` is a tuple of datasets. """ return Databook(data) class PlominoTablibUtils:
# garantees and support are strongly adviced to contract a Free Software # Service Company # # This program is Free Software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # ############################################################################## """Exception Classes for ERP5Configurator""" # These classes are placed here so that they can be imported into TTW Python # scripts. To do so, add the following line to your Py script: # from Products.ERP5.Errors import DeferredCatalogError from Products.PythonScripts.Utility import allow_class from Products.CMFCore.WorkflowCore import WorkflowException class SMSGatewayError(Exception):pass allow_class(SMSGatewayError)
"""Exception Classes for Formulator""" # These classes are placed here so that they can be imported into TTW Python # scripts. To do so, add the following line to your Py script: # from Products.Formulator.Errors import ValidationError, FormValidationError from Products.PythonScripts.Utility import allow_class class FormValidationError(Exception): def __init__(self, errors, result): Exception.__init__(self,"Form Validation Error") self.errors = errors self.result = result allow_class(FormValidationError) class ValidationError(Exception): def __init__(self, error_key, field, error_text=None): Exception.__init__(self, error_key) self.error_key = error_key self.field_id = field.id self.field = field if error_text is not None: self.error_text = error_text else: self.error_text = field.get_error_message(error_key) allow_class(ValidationError)