def create_subobjects(self, context, total=0, types=None): request = self.request amount = int(request.get('amount', 3)) if types is None: base = aq_base(context) if IBaseContent.providedBy(base): types = [] if hasattr(base, 'constrainTypesMode') and base.constrainTypesMode: types = context.locallyAllowedTypes elif IDexterityContent.providedBy(base): fti = getUtility(IDexterityFTI, name=context.portal_type) types = fti.filter_content_types and fti.allowed_content_types if not types: msg = _('Either restrict the addable types in this folder or ' \ 'provide a type argument.') addStatusMessage(request, msg) return total else: msg = _("The context doesn't provide IBaseContent or " "IDexterityContent. It might be a Plone Site object, " "but either way, I haven't gotten around to dealing with " "it. Why don't you jump in and help?") addStatusMessage(request, msg) return total for portal_type in types: if portal_type in ['File', 'Image', 'Folder']: continue for n in range(0, amount): obj = self.create_object(context, portal_type) total += 1 if request.get('recurse'): total = self.create_subobjects(obj, total=total, types=None) return total
def unsubscribe(self): """init """ pn = getToolByName(self, "portal_notification") subscriptions = pn._subscriptions sub_keys = subscriptions.keys() variables = self.request.form for userid in variables.keys(): paths = variables[userid] for path in paths: if path == "all": for existing_path in sub_keys: self.deleteUserOnPath(subscriptions, userid, existing_path) else: if path in sub_keys: self.deleteUserOnPath(subscriptions, userid, path) addStatusMessage(self.request, "User(s) unsubscribed successfully", type='info') url = "%s/notification_controlpanel" % self.context.absolute_url() self.request.RESPONSE.redirect(url)
def __call__(self): request = self.request form = request.form CheckAuthenticator(form) if form.get('submitted'): # Validate form submission csvfile = form.get('csvfile') data = csvfile.read() lines = data.splitlines() filename = csvfile.filename if not csvfile: addStatusMessage(request, _("No file selected")) return self.template() if len(lines) < 3: addStatusMessage(request, _("Too few lines in CSV file")) return self.template() # Create the arimport object arimport = _createObjectByType("ARImport", self.context, tmpID()) arimport.processForm() arimport.setTitle(self.mkTitle(filename)) arimport.schema['OriginalFile'].set(arimport, data) # Save all fields from the file into the arimport schema arimport.save_header_data() arimport.save_sample_data() # immediate batch creation if required arimport.create_or_reference_batch() # Attempt first validation try: workflow = getToolByName(self.context, 'portal_workflow') workflow.doActionFor(arimport, 'validate') except WorkflowException: self.request.response.redirect(arimport.absolute_url() + "/edit") else: return self.template()
def workflow_before_validate(self): """This function transposes values from the provided file into the ARImport object's fields, and checks for invalid values. If errors are found: - Validation transition is aborted. - Errors are stored on object and displayed to user. """ # Re-set the errors on this ARImport each time validation is attempted. # When errors are detected they are immediately appended to this field. self.setErrors([]) self.validate_headers() self.validate_samples() if self.getErrors(): addStatusMessage(self.REQUEST, _p('Validation errors.'), 'error') transaction.commit() self.REQUEST.response.write( '<script>document.location.href="%s/edit"</script>' % ( self.absolute_url())) self.REQUEST.response.write( '<script>document.location.href="%s/view"</script>' % ( self.absolute_url()))
def __call__(self): self.processed = False self.errors = {} start_time = self.context.ZopeTime().timeTime() if not self.request.form.get('form.submitted'): return self.template() # fetch value from request input_encoding = self.request.form.get('input_encoding', 'utf-8') span_of_search = self.request.form.get('span_of_search', None) format = self.request.form.get('format', 'bib') # process source filename = None source = self.request.form.get('up_text') if not source: upfile = self.request.form.get('file') filename = upfile and getattr(upfile, 'filename', None) if not filename: self.errors['file'] = _(u'You must import a file or enter a' ' text.') addStatusMessage(self.request, _(u"Please correct the indicated errors.")) return self.template() source = upfile.read() if not source or not isinstance(source, basestring): msg = "Could not read the file '%s'." % filename self.errors['file'] = msg addStatusMessage(self.request, _(unicode(msg))) return self.template() # skip DOS line breaks source = source.replace('\r', '') # get parsed entries from the Bibliography Tool bibtool = getToolByName(self.context, 'portal_bibliography') try: entries = bibtool.getEntries(source, format, filename, input_encoding=input_encoding) except ImportParseError: msg = """%s Parser's 'checkFormat' and guessing the format""" \ """ from the file name '%s' failed.""" % (format, filename) self.errors['format'] = msg addStatusMessage(self.request, _(unicode(msg))) return self.template() except UnicodeError: msg = """The choosen input encoding does not match the real """ \ """encoding of your input data in order to convert it to """\ """unicode internally.""" self.errors['input_encoding'] = msg addStatusMessage(self.request, _(unicode(msg))) return self.template() except RuntimeError, e: addStatusMessage(self.request, _(unicode(e))) return self.template()
def save(self, action): data, errors = self.extractData() if errors: self.status = '\n'.join([error.error.__str__() for error in errors]) return annotations = IAnnotations(self.context) annotations['slc.facetedcalendar.facets'] = data['facets'] addStatusMessage(self.request, _('Filters Saved'), type='info') self.request.response.redirect('/'.join(self.context.getPhysicalPath()))
def save_confirmation(self, action): data, errors = self.extractData() if errors: self.status = '\n'.join([error.error.__str__() for error in errors]) return context = aq_inner(self.context) utils.save_confirmation(context, data['attending']) addStatusMessage(self.request, "Thank you for confirming.", type='info') self.request.response.redirect(self.context.REQUEST.get('URL'))
def workflow_before_validate(self): """This function transposes values from the provided file into the ARImport object's fields, and checks for invalid values. If errors are found: - Validation transition is aborted. - Errors are stored on object and displayed to user. """ # Re-set the errors on this ARImport each time validation is attempted. # When errors are detected they are immediately appended to this field. if not self.getClient(): #Modified from ProcessForm only return self.setErrors([]) def item_empty(gridrow, key): if not gridrow.get(key, False): return True return len(gridrow[key]) == 0 row_nr = 0 for gridrow in self.getSampleData(): row_nr += 1 for key in ('SamplingDate', 'Priority', 'Strain', 'ClientStateLicenseID'): if item_empty(gridrow, key): self.error("Row %s: %s is required" % (row_nr, key)) samplingDate = gridrow['SamplingDate'] try: new = DateTime(samplingDate) ulocalized_time(new, long_format=True, time_only=False, context=self) except: self.error("Row %s: SamplingDate format must be 2017-06-21" % row_nr) sampler = gridrow['Sampler'] if not sampler: gridrow['Sampler'] = '' self.validate_headers() self.validate_samples() if self.getErrors() and self.getErrors() != (): addStatusMessage(self.REQUEST, _p('Validation errors.'), 'error') transaction.commit() self.REQUEST.response.write( '<script>document.location.href="%s/edit"</script>' % (self.absolute_url())) self.REQUEST.response.write( '<script>document.location.href="%s/view"</script>' % (self.absolute_url()))
def email_all(self, action): data, errors = self.extractData() if errors: self.status = '\n'.join([error.error.__str__() for error in errors]) return data = utils.save_attendees(self.context, data) utils.email_recipients(self.context, data) addStatusMessage(self.request, "Attendees have been saved and notified", type='info') self.request.response.redirect(self.context.REQUEST.get('URL'))
def create_subobjects(root, context, data, total=0): amount = int(data.get('amount', 3)) types = data.get('portal_type') if types is None: base = aq_base(context) if IBaseContent.providedBy(base): types = [] if hasattr(base, 'constrainTypesMode') and base.constrainTypesMode: types = context.locallyAllowedTypes elif IDexterityContent.providedBy(base): fti = component.getUtility(IDexterityFTI, name=context.portal_type) types = fti.filter_content_types and fti.allowed_content_types if not types: msg = _('Either restrict the addable types in this folder or ' \ 'provide a type argument.') addStatusMessage(context.request, msg) return total else: msg = _("The context doesn't provide IBaseContent or " "IDexterityContent. It might be a Plone Site object, " "but either way, I haven't gotten around to dealing with " "it. Why don't you jump in and help?") addStatusMessage(context.request, msg) return total recurse = False if data.get('recurse', None) not in [None, '0', 'False', False]: depth = 0 node = context while IUUID(node) != IUUID(root): depth += 1 node = node.aq_parent if depth < data.get('recursion_depth'): recurse = True for portal_type in types: for n in range(0, amount): obj = create_object(context, portal_type, data) total += 1 if not IObjectManager.providedBy(obj): continue if recurse: if shasattr(obj, 'getLocallyAllowedTypes'): data['portal_type'] = \ list(obj.getLocallyAllowedTypes()) elif shasattr(obj, 'allowedContentTypes'): data['portal_type'] = \ [t.id for t in obj.allowedContentTypes()] total = create_subobjects(root, obj, data, total) return total
def create(self, action): data, errors = self.extractData() if errors: self.status = '\n'.join([error.error.__str__() for error in errors]) return context = aq_inner(self.context) total = create_subobjects(context, context, data, 0) addStatusMessage( self.request, 'Successfully created %d dummy objects.' % total, type='info') self.request.response.redirect(self.context.REQUEST.get('URL'))
def add_url(self, action): data, errors = self.extractData() if errors: self.status = "\n".join([error.error.__str__() for error in errors]) return urls = [] if data.has_key("calendar_urls"): urls = [v.strip() for v in data["calendar_urls"].split()] annotations = IAnnotations(self.context) annotations["slc.calendarfetcher-urls"] = urls addStatusMessage(self.request, "URLs Saved", type="info") self.request.response.redirect(self.context.REQUEST.get("URL"))
def create(self, action): data, errors = self.extractData() if errors: self.status = '\n'.join([ error.error.__str__() for error in errors]) return context = aq_inner(self.context) total = create_subobjects(context, context, data, 0) addStatusMessage( self.request, _(u'Successfully created %d dummy objects.') % total, type='info') self.request.response.redirect(self.context.REQUEST.get('URL'))
def email_new(self, action): data, errors = self.extractData() if errors: self.status = '\n'.join([error.error.__str__() for error in errors]) return context = aq_inner(self.context) new_attendees = utils.get_new_attendees(context, data) utils.save_attendees(context, data) utils.email_recipients(context, new_attendees) if new_attendees['internal_attendees'] or \ new_attendees['external_attendees']: addStatusMessage(self.request, "The new attendees have been added and notified.", type='info') self.request.response.redirect(self.context.REQUEST.get('URL'))
def add_and_refresh(self, action): data, errors = self.extractData() if errors: self.status = _("Please correct the following errors before saving the form") return if data.has_key("calendar_urls"): urls = [v for v in data["calendar_urls"].split()] utils.fetch_calendars(self.context, self.request, urls) else: urls = [] annotations = IAnnotations(self.context) annotations["slc.calendarfetcher-urls"] = urls addStatusMessage(self.request, "URLs Saved", type="info") self.request.response.redirect(self.context.REQUEST.get("URL"))
def invokeFactory(self, type_name=None, id=None, RESPONSE=None, base_impl=False, *args, **kw): """invoke the factory""" if base_impl: return super(Specification, self).invokeFactory( type_name, id, RESPONSE, *args, **kw) factory_name = 'factory_' + type_name factory = getattr(self, factory_name, None) if not factory: return super(Specification, self).invokeFactory( type_name, id, RESPONSE, *args, **kw) try: res = factory() except ValueError, e: request = self.REQUEST addStatusMessage(request, e, type='error') raise
def fetch_calendars(context, request, urls): messages = [] title = context.Title() for url in urls: view = zope.component.queryMultiAdapter((context, request), name='import.html', default=None ) try: message = view.import_from_url(url) except HTTPError, e: msg = "Received a '404 Not Found' error for %s" % url addStatusMessage(request, msg, type='error') else: msg = '%s from %s' % (message, url) addStatusMessage(request, msg, type='info') messages.append(msg)
def __call__(self, **kw): """ type: string - The portal_type of the content type to create amount: integer - The amount of objects to create ul: bool - Add unordered lists. ol: bool - Add numbered lists. dl: bool - Add description lists. bq: bool - Add blockquotes. code: bool - Add code samples. link: bool - Add links. prude: bool - Prude version. headers: bool - Add headers. allcaps: bool - Use ALL CAPS. decorate: bool - Add bold, italic and marked text. publish: bool - Should the objects be published recurse: bool - Should objects be created recursively? parnum: integer - The number of paragraphs to generate. (NOT USED) length: short, medium, long, verylong - The average length of a paragraph (NOT USED) """ request = self.request context = aq_inner(self.context) types = self.request.get('type') if isinstance(types, str): types = [types] # There are some formatting options that we want enabled by default. If # the user didn't specify them in the URL, we add them here. for key, default in OPTIONS.items(): if not request.has_key(key): request.set(key, default) total = create_subobjects(context, request, 0, types) addStatusMessage(request, _('%d objects successfully created' % total)) return request.RESPONSE.redirect('/'.join(context.getPhysicalPath()))
def users_from_csv(self): """Import users/groups from csv.""" csvfile = self.REQUEST.form['csv_users'] if not csvfile: return 'Please provide a csv structure file !' else: members, groups, errors = getUsersandGroups(csvfile) if errors: status_message = _(u'You have erors in your csvfile !', default=u'You have erors in your csvfile !') else: setUpMembers(self, members) setUpGroups(self, groups) status_message = _(u'Users and groups succesfully imported', default=u'Users and groups succesfully imported') addStatusMessage(self.REQUEST, status_message) # and redirect him to the fine location next_url = self.portal_url() self.REQUEST.RESPONSE.redirect(next_url) return self.REQUEST.RESPONSE
def create_subobjects(self, context, total=0, types=None): request = self.request amount = int(request.get('amount', 3)) if types is None: base = aq_base(context) if IBaseContent.providedBy(base): types = [] if hasattr(base, 'constrainTypesMode') and base.constrainTypesMode: types = context.locallyAllowedTypes elif IDexterityContent.providedBy(base): fti = getUtility(IDexterityFTI, name=context.portal_type) types = fti.filter_content_types and fti.allowed_content_types if not types: msg = _('Either restrict the addable types in this folder or ' \ 'provide a type argument.') addStatusMessage(request, msg) return total else: msg = _( "The context doesn't provide IBaseContent or " "IDexterityContent. It might be a Plone Site object, " "but either way, I haven't gotten around to dealing with " "it. Why don't you jump in and help?") addStatusMessage(request, msg) return total for portal_type in types: if portal_type in ['File', 'Image', 'Folder']: continue for n in range(0, amount): obj = self.create_object(context, portal_type) total += 1 if request.get('recurse'): total = self.create_subobjects(obj, total=total, types=None) return total
def invokeFactory(self, type_name=None, id=None, RESPONSE=None, base_impl=False, *args, **kw): """invoke the factory""" if base_impl: return super(Specification, self).invokeFactory(type_name, id, RESPONSE, *args, **kw) factory_name = 'factory_' + type_name factory = getattr(self, factory_name, None) if not factory: return super(Specification, self).invokeFactory(type_name, id, RESPONSE, *args, **kw) try: res = factory() except ValueError, e: request = self.REQUEST addStatusMessage(request, e, type='error') raise
def __call__(self, **kw): """ type: string - The portal_type of the content type to create amount: integer - The amount of objects to create ul: bool - Add unordered lists. ol: bool - Add numbered lists. dl: bool - Add description lists. bq: bool - Add blockquotes. code: bool - Add code samples. link: bool - Add links. prude: bool - Prude version. headers: bool - Add headers. allcaps: bool - Use ALL CAPS. decorate: bool - Add bold, italic and marked text. publish: bool - Should the objects be published recurse: bool - Should objects be created recursively? parnum: integer - The number of paragraphs to generate. (NOT USED) length: short, medium, long, verylong - The average length of a paragraph (NOT USED) """ request = self.request context = aq_inner(self.context) types = self.request.get('type') if isinstance(types, str): types = [types] total = self.create_subobjects(context, 0, types) addStatusMessage(request, _('%d objects successfully created' % total)) return request.RESPONSE.redirect('/'.join(context.getPhysicalPath()))
def structure_from_csv(self): """Import structure/content via csvrepliacta.""" csvfile = self.REQUEST.form['csv_structure'] if not csvfile: return 'Please provide a csv structure file !' else: import transaction import os from zope.interface import alsoProvides, noLongerProvides from Products.csvreplicata.interfaces import ICSVReplicable, \ Icsvreplicata from pgolf.tma.config import getImportOptionsFromIni import_settings, default_transition = getImportOptionsFromIni() import foo # are we in zopetestcase ? # if not we have to install temorarly csvreplicata just to import # structure else it's installed via base_setup zopetestcase = (('ZOPE_TESTCASE' in os.environ) or ('ZOPETESTCASE' in os.environ)) portal_quickinstaller = self.portal_quickinstaller has_csvreplicata = portal_quickinstaller.\ isProductInstalled('csvreplicata') if not zopetestcase and not has_csvreplicata: #install temporarly csvreplicata if not used by policy. portal_quickinstaller.installProduct('csvreplicata') transaction.savepoint() #provide ICSVReplicable to plonesite alsoProvides(self, ICSVReplicable) csvreplicatatool = self.portal_csvreplicatatool # save existents user settings if has_csvreplicata: old_replicabletypes_settings = csvreplicatatool.replicabletypes # register Structure replicabletypes csvreplicatatool.replicabletypes = import_settings # now import replicator = Icsvreplicata(self) replicator.csvimport(csvfile, datetimeformat='%d/%m/%Y', wf_transition=default_transition) # restore replicabletypes user settings if has_csvreplicata : csvreplicatatool.replicabletypes = old_replicabletypes_settings #remove ICSVReplicable interface for self noLongerProvides(self, ICSVReplicable) #uninistall csvreplicata if not used by policy if not zopetestcase and not has_csvreplicata: portal_quickinstaller.uninstallProducts(['csvreplicata']) status_message = _(u'structure succesfully imported', default=u'structure succesfully imported') addStatusMessage(self.REQUEST, status_message) # and redirect him to the fine location next_url = self.portal_url() self.REQUEST.RESPONSE.redirect(next_url) return self.REQUEST.RESPONSE
if next or previous: s_names = [s for s in schemata.keys() if s != 'metadata'] if previous: s_names.reverse() next_schemata = None try: index = s_names.index(fieldset) except ValueError: raise 'Non-existing fieldset: %s' % fieldset else: index += 1 if index < len(s_names): next_schemata = s_names[index] addStatusMessage(REQUEST, portal_status_message) return state.set(status='next_schemata', context=new_context, fieldset=next_schemata) if next_schemata != None: addStatusMessage(REQUEST, portal_status_message) return state.set(status='next_schemata', context=new_context, fieldset=next_schemata) else: raise 'Unable to find next field set after %s' % fieldset env = state.kwargs reference_source_url = env.get('reference_source_url') if reference_source_url is not None:
from Products.PythonScripts.standard import url_quote, urlencode from Products.Archetypes.utils import addStatusMessage portal = context.portal_url.getPortalObject() pm = portal.portal_membership myFolder = pm.getHomeFolder() if not myFolder: portal_status_message = "You must be logged in to create a Homecoming team." addStatusMessage(context.REQUEST, portal_status_message) kw = { 'came_from': context.absolute_url() + "/createTeam", } context.REQUEST.RESPONSE.redirect(portal.absolute_url() + "/login_form?" + urlencode(kw)) else: new_id = myFolder.generateUniqueId('HomecomingTeam') newTeam = myFolder.invokeFactory('HomecomingTeam', new_id) newTeamURL = myFolder.absolute_url() + '/' + newTeam redirect_to = newTeamURL + '/edit' portal_status_message = "A new team has been created. You must give it a name and fill out the names and email addresses of its members. Please make sure you enter correct email addresses." addStatusMessage(context.REQUEST, portal_status_message) ploneVersion = portal.portal_migration.getInstanceVersionTuple() #portal_status_message += " (Plone version is %s)" % str(ploneVersion) if ploneVersion[0] == 2 and ploneVersion[1] == 1: last_referer = newTeamURL + '/object_delete' else: last_referer = newTeamURL + '/delete_confirmation' kw = {
def create_subobjects(root, context, data, total=0): amount = int(data.get('amount', 3)) types = data.get('portal_type') request = getRequest() depth = 0 node = context if not IPloneSiteRoot.providedBy(root): while IUUID(node) != IUUID(root): depth += 1 node = node.aq_parent else: while not IPloneSiteRoot.providedBy(node): depth += 1 node = node.aq_parent if types is None or depth > 0: base = aq_base(context) if IBaseContent.providedBy(base): types = [] if hasattr(base, 'constrainTypesMode') and base.constrainTypesMode: types = context.locallyAllowedTypes elif IDexterityContent.providedBy(base): fti = component.getUtility(IDexterityFTI, name=context.portal_type) types = fti.filter_content_types and fti.allowed_content_types if not types: msg = _('Either restrict the addable types in this folder ' 'or provide a type argument.') addStatusMessage(request, msg) return total else: msg = _("The context doesn't provide IBaseContent or " "IDexterityContent. It might be a Plone Site object, " "but either way, I haven't gotten around to dealing with " "it. Why don't you jump in and help?") addStatusMessage(request, msg) return total recurse = False if data.get('recurse', None) not in [None, '0', 'False', False] and \ depth < data.get('recursion_depth'): recurse = True for portal_type in types: for n in range(0, amount): obj = create_object(context, portal_type, data) total += 1 if not IObjectManager.providedBy(obj): continue if recurse: if not data.get('recurse_same_ptypes', False): if shasattr(obj, 'getLocallyAllowedTypes'): data['portal_type'] = \ list(obj.getLocallyAllowedTypes()) elif shasattr(obj, 'allowedContentTypes'): data['portal_type'] = \ [t.id for t in obj.allowedContentTypes()] total = create_subobjects(root, obj, data, total) return total
## Script (Python) "rejectAnonymous" ##bind container=container ##bind context=context ##bind namespace= ##bind script=script ##bind subpath=traverse_subpath ##parameters= ##title= ## from Products.Archetypes import PloneMessageFactory as _ from Products.Archetypes.utils import addStatusMessage if context.portal_membership.isAnonymousUser(): url = '%s/login_form' % context.portal_url() addStatusMessage(REQUEST, _(u'You must sign in first.'), type='info') RESPONSE=context.REQUEST.RESPONSE return RESPONSE.redirect(url) return True
from Products.PythonScripts.standard import url_quote, urlencode from Products.Archetypes.utils import addStatusMessage portal=context.portal_url.getPortalObject() pm=portal.portal_membership myFolder=pm.getHomeFolder() if not myFolder: portal_status_message = "You must be logged in to create a Homecoming team." addStatusMessage(context.REQUEST, portal_status_message) kw = { 'came_from' : context.absolute_url() + "/createTeam", } context.REQUEST.RESPONSE.redirect(portal.absolute_url() + "/login_form?" + urlencode (kw)) else: new_id = myFolder.generateUniqueId('HomecomingTeam') newTeam = myFolder.invokeFactory('HomecomingTeam', new_id) newTeamURL = myFolder.absolute_url() + '/' + newTeam redirect_to = newTeamURL + '/edit' portal_status_message="A new team has been created. You must give it a name and fill out the names and email addresses of its members. Please make sure you enter correct email addresses." addStatusMessage(context.REQUEST, portal_status_message) ploneVersion = portal.portal_migration.getInstanceVersionTuple() #portal_status_message += " (Plone version is %s)" % str(ploneVersion) if ploneVersion[0] == 2 and ploneVersion[1] == 1: last_referer = newTeamURL + '/object_delete' else: last_referer = newTeamURL + '/delete_confirmation' kw = { 'last_referer':last_referer,
class ImportView(BrowserView): template = ViewPageTemplateFile('import.pt') def __call__(self): self.processed = False self.errors = {} start_time = self.context.ZopeTime().timeTime() if not self.request.form.get('form.submitted'): return self.template() # fetch value from request input_encoding = self.request.form.get('input_encoding', 'utf-8') span_of_search = self.request.form.get('span_of_search', None) format = self.request.form.get('format', 'bib') # process source filename = None source = self.request.form.get('up_text') if not source: upfile = self.request.form.get('file') filename = upfile and getattr(upfile, 'filename', None) if not filename: self.errors['file'] = _(u'You must import a file or enter a' ' text.') addStatusMessage(self.request, _(u"Please correct the indicated errors.")) return self.template() source = upfile.read() if not source or not isinstance(source, basestring): msg = "Could not read the file '%s'." % filename self.errors['file'] = msg addStatusMessage(self.request, _(unicode(msg))) return self.template() # skip DOS line breaks source = source.replace('\r', '') # get parsed entries from the Bibliography Tool bibtool = getToolByName(self.context, 'portal_bibliography') try: entries = bibtool.getEntries(source, format, filename, input_encoding=input_encoding) except ImportParseError: msg = """%s Parser's 'checkFormat' and guessing the format""" \ """ from the file name '%s' failed.""" % (format, filename) self.errors['format'] = msg addStatusMessage(self.request, _(unicode(msg))) return self.template() except UnicodeError: msg = """The choosen input encoding does not match the real """ \ """encoding of your input data in order to convert it to """\ """unicode internally.""" self.errors['input_encoding'] = msg addStatusMessage(self.request, _(unicode(msg))) return self.template() except RuntimeError, e: addStatusMessage(self.request, _(unicode(e))) return self.template() # debug message if entries is not a python list if not entries or not isinstance(entries, (list, tuple)): msg = "There must be something wrong with the parser" addStatusMessage(self.request, _(unicode(msg))) return self.template() # start building the report mtool = getToolByName(self.context, 'portal_membership') member = mtool.getAuthenticatedMember() fullname = member.getProperty('fullname', None) if fullname: username = '******' % (_encode(fullname), _encode(member.getId())) else: username = _encode(member.getId()) tmp_report = '[%s] Imported by %s' % (self.context.ZopeTime(), username) if filename is not None: tmp_report += ' from file %s' % _encode(filename) tmp_report += ':\n\n' # process import for each entry processedEntries = 0 importErrors = 0 logger.info('Start import of %s raw entries.' % len(entries)) counter = 0 for entry in entries: counter += 1 count = '#%05i: ' % counter logger.info(count + 'processing entry') # Workaround for #36 where an entry represents # an error from parser instead of a dict containing # importable data if isinstance(entry, basestring): msg = 'Entry could not be parsed! %s' % _encode(entry) upload = (msg, 'error') logger.error(count + msg) elif entry.get('title'): logger.info(count + 'Normal processing') upload = self.context.processSingleImport( entry, span_of_search=span_of_search) else: formated = '; '.join([ '%s=%s' % (key, entry[key]) for key in sorted(entry.keys()) if key == key.lower() ]) upload = ('Found entry without title: %s\n' % formated, 'error') logger.error(count + upload[0]) if upload[1] == 'ok': processedEntries += 1 else: importErrors += 1 state, msg = _encode(upload[1].upper()), _encode(upload[0]) tmp_report += '%s: %s\n' % (state, msg) self.context.logImportReport(tmp_report) self.processed = True # set the portal status message up msg = "Processed %i entries. There were %i errors. "\ "Import processed in %f seconds. See import report below." \ % (processedEntries, importErrors, self.context.ZopeTime().timeTime() - start_time) logger.info(msg) addStatusMessage(self.request, _(unicode(msg))) return self.template()
'reference_focus':reference_source_field, } return state.set(**kwargs) if state.errors: errors = state.errors s_items = [(s, schemata[s].keys()) for s in schemata.keys()] fields = [] portal_status_message = "Please correct the indicated errors." for s, f_names in s_items: for f_name in f_names: fields.append((s, f_name)) for s_name, f_name in fields: if errors.has_key(f_name): REQUEST.set('fieldset', s_name) addStatusMessage(REQUEST, portal_status_message, type="error") return state.set( status='failure', context=new_context,) if not state.errors: from Products.Archetypes.utils import transaction_note transaction_note('Edited %s %s at %s' % (new_context.meta_type, new_context.title_or_id(), new_context.absolute_url())) return state.set(status='success', context=new_context, )
## Script (Python) "rejectAnonymous" ##bind container=container ##bind context=context ##bind namespace= ##bind script=script ##bind subpath=traverse_subpath ##parameters= ##title= ## from Products.Archetypes import PloneMessageFactory as _ from Products.Archetypes.utils import addStatusMessage if context.portal_membership.isAnonymousUser(): url = '%s/login_form' % context.portal_url() addStatusMessage(REQUEST, _(u'You must sign in first.'), type='info') RESPONSE = context.REQUEST.RESPONSE return RESPONSE.redirect(url) return True