def set(self, instance, value, **kwargs): """ """ if value is None: ObjectField.set(self, instance, value, **kwargs) return if self.multiValued and not isinstance(value, (list, tuple)): value = value, elif not self.multiValued and isinstance(value, (list, tuple)): if len(value) > 1: raise ValueError( "Multiple values given for single valued field %r" % self) value = value[0] intid_tool = getUtility(IIntIds) #convert objects to intids if necessary if self.multiValued: result = [] for v in value: if isinstance(v, (basestring, int)): result.append(RelationValue(int(v))) else: result.append(RelationValue(intid_tool.getId(v))) else: if isinstance(value, (basestring, int)): result = RelationValue(int(value)) else: result = RelationValue(intid_tool.getId(value)) ObjectField.set(self, instance, result, **kwargs)
def set(self, instance, value, **kwargs): """ Check if value is an actual Money value. If not, attempt to convert it to one; otherwise, set to None. Assign all properties passed as kwargs to object. field.set( Money(10, 'ZAR') ) field.set( money_instance ) """ if value is not None: if type(value) in STRING_TYPES: cur, value = parseString(decode(value, instance)) if self.use_global_currency: cur = self.getGlobalCurrency() else: if cur is None: cur = self.getDefaultCurrency(instance) value = Money(value, cur) assert isinstance( value, Money), ('value must be Money instance. value == %s' % value) ObjectField.set(self, instance, value, **kwargs)
def set(self, instance, value, **kwargs): if not isinstance(value, PythonScript): s = self._seperator body = "%s\n%s%s\n%s%s" % (self.header, s, value, s, self.footer) script = PythonScript(self.getName()) script.ZPythonScript_edit('**options', body) value = script ObjectField.set(self, instance, value, **kwargs)
def get(self, instance, **kwargs): value = ObjectField.get(self, instance, **kwargs) if type(value) in types.StringTypes: # migration from TextField zpt = ZopePageTemplate(self.getName()) ObjectField.set(self, instance, zpt, **kwargs) value = ObjectField.get(self, instance, **kwargs) return value.pt_render(extra_context={'options': kwargs})
def set(self, instance, value, **kwargs): """ test""" #log("Set: value = %s, specific=%s" % (value, kwargs.get('specific','wer'))) if value == 'specific': if kwargs.has_key('specific'): value = kwargs['specific'] else: value = 'latest' ObjectField.set(self, instance, value, **kwargs)
def _render_output_html(self): """ Return rendered newsletter with header+body+footer (raw html). """ enl = self.getNewsletter() # get out_template from ENL object and render it in context of issue out_template_pt_field = enl.getField('out_template_pt') ObjectField.set(out_template_pt_field, self, ZopePageTemplate( out_template_pt_field.getName(), enl.getRawOut_template_pt())) output_html = safe_portal_encoding(self.out_template_pt.pt_render()) output_html = compactify(output_html, filter_tags=False) return output_html
def get(self, instance, **kwargs): value = ObjectField.get(self, instance, **kwargs) if type(value) in types.StringTypes: # migration from TextField zpt = ZopePageTemplate(self.getName()) ObjectField.set(self, instance, zpt, **kwargs) value = ObjectField.get(self, instance, **kwargs) if config.CATCH_RENDER_ERRORS: try: return value.pt_render(extra_context={'options': kwargs}) except Exception, e: return _(u"zpt_field_render_error", default=u'<div class="error">An error occured while rendering this field</div>')
def _render_output_html(self): """ Return rendered newsletter with header+body+footer (raw html). """ enl = self.getNewsletter() props = getToolByName(self, "portal_properties").site_properties charset = props.getProperty("default_charset") # get out_template from ENL object and render it in context of issue out_template_pt_field = enl.getField('out_template_pt') ObjectField.set(out_template_pt_field, self, ZopePageTemplate( out_template_pt_field.getName(), enl.getRawOut_template_pt())) output_html = safe_portal_encoding(self.out_template_pt.pt_render()) return output_html
def set(self, instance, value, **kwargs): """ If passed-in value is a string, split at line breaks and remove leading and trailing white space before storing in object with rest of properties. """ __traceback_info__ = value, type(value) if type(value) == type(''): value = value.split('\n') value = [v.strip() for v in value if v.strip()] #Uniquify and remove None from list value=filter(None,dict(map(None,value,[None])).keys()) value.sort(lambda x,y: cmp(x.lower(),y.lower())) ObjectField.set(self, instance, value, **kwargs)
def _render_output_html(self): """ Return rendered newsletter with header+body+footer (raw html). """ enl = self.getNewsletter() # get out_template from ENL object and render it in context of issue out_template_pt_field = enl.getField('out_template_pt') ObjectField.set( out_template_pt_field, self, ZopePageTemplate(out_template_pt_field.getName(), enl.getRawOut_template_pt())) output_html = safe_portal_encoding(self.out_template_pt.pt_render()) output_html = compactify(output_html, filter_tags=False) return output_html
def _render_output_html(self): """ Return rendered newsletter with header+body+footer (raw html). """ enl = self.getNewsletter() props = getToolByName(self, "portal_properties").site_properties charset = props.getProperty("default_charset") # get out_template from ENL object and render it in context of issue out_template_pt_field = enl.getField('out_template_pt') ObjectField.set( out_template_pt_field, self, ZopePageTemplate(out_template_pt_field.getName(), enl.getRawOut_template_pt())) output_html = safe_portal_encoding(self.out_template_pt.pt_render()) return output_html
def set(self, instance, value, **kwargs): """ Check if value is an actual FixedPoint value. If not, attempt to convert it to one; Raise an error if value is a float. Assign all properties passed as kwargs to object. field.set( FixedPoint(10)) field.set( FixedPointInstance) """ assert type(value) != type(0.00) if not value is None and not isinstance(value, FixedPoint): value = FixedPoint(value) ObjectField.set(self, instance, value, **kwargs)
def Vocabulary(self, content_instance=None): #If we have a method providing the list of types go with it, #it can always pull allowed_types if it needs to (not that we #pass the field name) value = ObjectField.Vocabulary(self, content_instance) if value: return value results = [] catalog = getToolByName(content_instance, 'portal_catalog') try: ws_path = content_instance.workspacePath() except AttributeError: ws_path = "/" if self.allowed_types: # we trust that all allowed_types are properly referencable and cataloged results = catalog(Type=self.allowed_types, path=ws_path) else: keys = catalog.uniqueValuesFor('UID') results = catalog(UID=keys, path=ws_path) #... but this should never happen results = [(r, r.getObject()) for r in results] value = [(r.UID, obj and (str(obj.Title().strip()) or \ str(obj.getId()).strip()) or \ log('Field %r: Object at %r could not be found' % \ (self.getName(), r.getURL())) or \ r.Title or r.UID) for r, obj in results] if not self.required: value.insert(0, ('', '<no reference>')) return DisplayList(value)
def _render_output_html(self): """ Return rendered newsletter with header+body+footer (raw html). """ # get out_template from ENL object and render it in context of issue out_template_pt_field = self.enl.getField('out_template_pt') # and here we create a write on read, but we do not need to persist it: transaction.commit() ObjectField.set( out_template_pt_field, self.issue, ZopePageTemplate(out_template_pt_field.getName(), self.enl.getRawOut_template_pt())) output_html = safe_portal_encoding( self.issue.out_template_pt.pt_render()) transaction.abort() # output_html = compactify(output_html, filter_tags=False) return output_html
def set(self, instance, value, **kwargs): """ Tests if all elements in value are numbers and save them as minutes. @see ObjectField.set """ result = [] for item in value: if self.required or item: m = re.match('^(\d\d)[.:]?(\d\d)$', item.strip()) result.append((int(m.group(1)) * 60 ) + int(m.group(2))) else: result = [] break ObjectField.set(self, instance, result, **kwargs)
def getRaw(self, instance, **kwargs): body = ObjectField.get(self, instance, **kwargs).body() p1 = body.find(self._seperator) if p1 == -1: # no seperator: we return the whole body return body else: p1 = p1 + len(self._seperator) p2 = body.find(self._seperator, p1) return body[p1:p2]
def validate_required(self, instance, value, errors): """ Tests if all elements in value are not None. If one is None a error message will be returned. @see ObjectField.validate_required """ result = True for item in value: if not item: result = False break return ObjectField.validate_required(self, instance, result, errors)
def set(self, instance, value, **kwargs): """ Check if value is an actual Money value. If not, attempt to convert it to one; otherwise, set to None. Assign all properties passed as kwargs to object. field.set( Money(10, 'ZAR') ) field.set( money_instance ) """ if value is not None: if type(value) in STRING_TYPES: cur, value = parseString(decode(value, instance)) if self.use_global_currency: cur = self.getGlobalCurrency() else: if cur is None: cur = self.getDefaultCurrency(instance) value = Money(value, cur) assert isinstance(value, Money), ( 'value must be Money instance. value == %s' % value) ObjectField.set(self, instance, value, **kwargs)
def getRaw(self, instance, aslist=False, **kwargs): """Return the list of UIDs referenced under this fields relationship """ objects = [] uids = ObjectField.get(self, instance, **kwargs) if uids is None: uids = [] if not self.multiValued and not aslist: if uids: uids = uids[0] else: uids = None return uids
def get(self, instance, aslist=False, **kwargs): """ """ res = ObjectField.get(self, instance, **kwargs) if res is None: return res if self.multiValued: resolved = [] for rel in res: resolved.append(rel.to_object) else: resolved = res.to_object if aslist: resolved = [resolved] return resolved
def get(self, instance, aslist=False, **kwargs): objects = [] rc = getToolByName(instance, REFERENCE_CATALOG) uids = ObjectField.get(self, instance, **kwargs) if uids is None: uids = [] for uid in uids: if uid: objects.append(rc.lookupObject(uid)) if objects: if not self.multiValued: return objects[0] else: return objects return []
def get(self, instance, **kwargs): dtml = ObjectField.get(self, instance, **kwargs) if not kwargs.has_key('client'): kwargs['client'] = instance value = dtml(**kwargs) return value
def getRaw(self, instance, **kwargs): dtml = ObjectField.get(self, instance, **kwargs) if getattr(dtml, 'read', _marker) is not _marker: return dtml.read() else: return dtml
def set(self, instance, value, **kwargs): if not isinstance(value, ZopePageTemplate): zpt = ZopePageTemplate(self.getName()) zpt.write(value) value = zpt ObjectField.set(self, instance, value, **kwargs)
def getDefault(self, instance): value = ObjectField.getDefault(self, instance) zpt = ZopePageTemplate(self.getName()) zpt.write(value) return zpt.__of__(instance)
def getRaw(self, instance, **kwargs): zpt = ObjectField.get(self, instance, **kwargs) return zpt.read()
def getRaw(self, instance, **kwargs): zpt = ObjectField.get(self, instance, **kwargs) if getattr(zpt, 'read', _marker) is not _marker: return zpt.read() else: return zpt
class ECQResult(ATCTContent, HistoryAwareMixin): """A quiz result.""" """ This class contains all the candidate-specific information for an ECQuiz. They are: questionResults: A dictionary that contains all the information concerning a single question, e. g. the suggested answer, the answer given by the candidate, the grade. The keys are the UIDs of the question. questionContainerIds: A list of the IDs of the 'ECQAbstractGroup' instances that the candidate saw. questionUIDs: A list of IDs of the questions that the candidate saw in their quiz. Unfortunately 'questionResults.keys()' cannot be used since it does not preserve the order of the UIDs. timeStart: The time when the candidate first saw the quiz. timeFinish: The time when the candidate submitted their quiz. """ schema = ATContentTypeSchema.copy() + Schema(( ObjectField( 'questionResults', read_permission=PERMISSION_RESULT_READ, default={}, ), ObjectField( 'possiblePointsCache', read_permission=PERMISSION_RESULT_READ, default={}, ), ObjectField( 'candidatePointsCache', read_permission=PERMISSION_RESULT_READ, default={}, ), ObjectField( 'questionContainerIds', read_permission=PERMISSION_RESULT_READ, default=[], ), ObjectField( 'questionUIDs', read_permission=PERMISSION_RESULT_READ, default=[], ), DateTimeField( 'timeStart', read_permission=PERMISSION_RESULT_READ, ), DateTimeField( 'timeFinish', read_permission=PERMISSION_RESULT_READ, default=None, ), IntegerField( 'currentPageNum', read_permission=PERMISSION_RESULT_READ, write_permission=PERMISSION_RESULT_WRITE, default=0, ), ), ) # Don't list this type in the portal navigation. navigation_exclude = True security = ClassSecurityInfo() security.declarePrivate('getQR') def getQR(self, caller, question, dontThrow=False): questionUID = question.UID() qrs = self.getQuestionResults() retVal = qrs.get(questionUID, None) if (retVal is not None) or dontThrow: return retVal else: txt = "%s() called for questionUID not in self.questionUIDs\n" \ "questionUID: %s\n" \ "self.questionUIDs: %s" \ % (caller, repr(questionUID), repr(self.getQuestionUIDs())) log(txt) raise Exception(txt) security.declarePrivate('storeQR') def storeQR(self, question, result): qrs = self.getQuestionResults() qrs[question.UID()] = result # Instead of saving "qrs" directly, save a copy of it, # "dict(qrs)". If we don't do that, there is a chance that # Zope will return an old, cached value the next time # "self.getQuestionResults()" is called because it *thinks* # the cached dictionary is the same as the stored one because # the memory location didn't change. self.setQuestionResults(dict(qrs)) security.declarePrivate('setSuggestedAnswer') def setSuggestedAnswer(self, question, suggestedAnswer): """ Saves the suggested answer values to a question the candidate was asked. @param suggestedAnswer The value or list of values of the answer suggested to the candidate. @param question The question that the answer belongs to. @param questionContainerId The ID of the question container that contains the question. """ # The list 'questionContainerIds' is neccessary because # 'self.questionResults.keys()' does not return the # questionUIDs in the order they were added. questionContainerId = getParent(question).getId() questionUID = question.UID() questionContainerIds = self.getQuestionContainerIds() if questionContainerId not in questionContainerIds: self.setQuestionContainerIds(questionContainerIds + [questionContainerId]) questionUIDs = self.getQuestionUIDs() if questionUID not in questionUIDs: self.setQuestionUIDs(questionUIDs + [questionUID]) qr = QuestionResult(suggestedAnswer) self.storeQR(question, qr) security.declareProtected(PERMISSION_RESULT_READ, 'getSuggestedAnswer') def getSuggestedAnswer(self, question): """ Returns the suggested answer values for a question the candidate was asked. With the standard question and answer types this will be a list of IDs of answer objects. """ qr = self.getQR("getAnswer", question) return qr.getSuggestedAnswer() security.declareProtected(PERMISSION_RESULT_READ, 'getCandidateAnswer') def getCandidateAnswer(self, question): """ Returns the candidate's answer to the question. If this question was not part of their quiz, an exception will be raised. """ qr = self.getQR("getCandidateAnswer", question) return qr.getCandidateAnswer() security.declareProtected(PERMISSION_RESULT_WRITE, 'setCandidateAnswer') def setCandidateAnswer(self, question, answerValue): """ Saves the candidate's answer to a question. @param answerValue The value or list of values of the answer(s) the candidate gave. With the standard question and answer types this will be the ID (list of IDs) of the answer(s) the candidate selected. """ qr = self.getQR("setCandidateAnswer", question) qr.setCandidateAnswer(answerValue) self.storeQR(question, qr) security.declareProtected(PERMISSION_RESULT_WRITE, 'unsetCandidateAnswer') def unsetCandidateAnswer(self, question): """ Removes the candidate's answer to a question. @param answerValue The value or list of values of the belongs to. """ qr = self.getQR("unsetCandidateAnswer", question) qr.unsetCandidateAnswer() self.storeQR(question, qr) ## Points caching: start # Points for an individual question security.declareProtected(PERMISSION_RESULT_READ, 'getCachedQuestionPoints') def getCachedQuestionPoints(self, question): """ """ qr = self.getQR("getCachedQuestionPoints", question) return qr.cachedPoints security.declareProtected(PERMISSION_RESULT_WRITE, 'setCachedQuestionPoints') def setCachedQuestionPoints(self, question, value): """ """ qr = self.getQR("setCachedQuestionPoints", question) qr.cachedPoints = value self.storeQR(question, qr) # Tutor-assigned points for an individual question security.declareProtected(PERMISSION_GRADE, 'setTutorPoints') def getTutorPoints(self, question): """ """ qr = self.getQR("getTutorPoints", question) return qr.tutorPoints security.declareProtected(PERMISSION_GRADE, 'setTutorPoints') def setTutorPoints(self, question, value): """ """ qr = self.getQR("setTutorPoints", question) qr.tutorPoints = value self.storeQR(question, qr) # clear related cache info test = getParent(question) if test.portal_type == ECQGroup.portal_type: questionGroup = test test = getParent(questionGroup) else: questionGroup = None self.setCachedCandidatePoints(test, None) #log("%s: CachedCandidatePoints: %s" % (str(self), str(test))) if questionGroup: self.setCachedCandidatePoints(questionGroup, None) #log("%s: CachedCandidatePoints: %s" % (str(self), # str(questionGroup))) #log("") security.declareProtected(PERMISSION_GRADE, 'unsetTutorPoints') def unsetTutorPoints(self, question): """ """ self.setTutorPoints(question, None) # this also clears any # related caches # Retract to "pending" because the result can't be "graded" if # some grades are missing userId = self.portal_membership.getAuthenticatedMember().getId() comment = "Retracted by %s: tutor grades were deleted" % userId self.tryWorkflowAction('retract_pending', ignoreErrors=True, comment=comment) # Possible points for a question group security.declareProtected(PERMISSION_RESULT_READ, 'getCachedPossiblePoints') def getCachedPossiblePoints(self, questionGroup): """ """ cache = self.getPossiblePointsCache() return cache.get(questionGroup.UID(), None) security.declareProtected(PERMISSION_RESULT_WRITE, 'setCachedPossiblePoints') def setCachedPossiblePoints(self, questionGroup, value): """ """ cache = self.getPossiblePointsCache() cache[questionGroup.UID()] = value self.setPossiblePointsCache(dict(cache)) # Achieved points for a question group security.declareProtected(PERMISSION_RESULT_READ, 'getCachedCandidatePoints') def getCachedCandidatePoints(self, questionGroup): """ """ cache = self.getCandidatePointsCache() return cache.get(questionGroup.UID(), None) security.declareProtected(PERMISSION_RESULT_WRITE, 'setCachedCandidatePoints') def setCachedCandidatePoints(self, questionGroup, value): """ """ cache = self.getCandidatePointsCache() cache[questionGroup.UID()] = value self.setCandidatePointsCache(dict(cache)) # Delete all cached points security.declarePrivate('unsetAllCachedPoints') def unsetAllCachedPoints(self): # Delete cached points for the questions qrs = self.getQuestionResults() for qr in qrs.values(): qr.cachedPoints = None self.setQuestionResults(dict(qrs)) # Delete the caches for possible and candidate points in a # question group self.setPossiblePointsCache({}) self.setCandidatePointsCache({}) #log("%s: deleted all cached points" % (str(self))) # Clear all cached points related to the question [question], # i. e. clear cache for possible and achieved (candidate) points # for the question and the question group and the test that # contain this question security.declarePrivate('unsetCachedQuestionPoints') def unsetCachedQuestionPoints(self, question): """ """ if self.getQR("", question, dontThrow=True) is not None: test = getParent(question) if test.portal_type == ECQGroup.portal_type: questionGroup = test test = getParent(questionGroup) else: questionGroup = None self.setCachedQuestionPoints(question, None) #log("%s: CachedQuestionPoints: %s" % (str(self), str(question))) self.setCachedPossiblePoints(test, None) #log("%s: CachedPossiblePoints: %s" % (str(self), str(test))) self.setCachedCandidatePoints(test, None) #log("%s: CachedCandidatePoints: %s" % (str(self), str(test))) if questionGroup: self.setCachedPossiblePoints(questionGroup, None) #log("%s: CachedPossiblePoints: %s" % (str(self), # str(questionGroup))) self.setCachedCandidatePoints(questionGroup, None) #log("%s: CachedCandidatePoints: %s" % (str(self), # str(questionGroup))) #log("") ## Points caching: end security.declareProtected(PERMISSION_RESULT_READ, 'haveCandidateAnswer') def haveCandidateAnswer(self, question): qr = self.getQR("haveCandidateAnswer", question) return qr.haveCandidateAnswer() security.declareProtected(PERMISSION_RESULT_WRITE, 'startWatch') def startWatch(self, question): qr = self.getQR("startWatch", question) if not qr.isWatchRunning(): qr.addTimeStart(datetime.now()) #log("startWatch: %s" % str(question)) self.storeQR(question, qr) makeTransactionUnundoable() security.declareProtected(PERMISSION_RESULT_WRITE, 'stopWatch') def stopWatch(self, question): qr = self.getQR("stopWatch", question) if qr.isWatchRunning(): #log("stopWatch: %s" % str(question)) qr.addTimeFinish(datetime.now()) self.storeQR(question, qr) security.declareProtected(PERMISSION_RESULT_READ, 'isWatchRunning') def isWatchRunning(self, question): qr = self.getQR("isWatchRunning", question) return qr.isWatchRunning() security.declareProtected(PERMISSION_RESULT_READ, 'getTimeSpent') def getTimeSpent(self, question): """@return A Python timedelta object.""" qr = self.getQR("getTimeSpent", question) return qr.getTimeSpent() security.declareProtected(PERMISSION_RESULT_READ, 'getSetCount') def getSetCount(self, question): """@return The number of times the candidate changed his answer.""" qr = self.getQR("getTimeSpent", question) return qr.getSetCount() security.declarePublic('getWorkflowState') def getWorkflowState(self): """Determine the Plone workflow state.""" wtool = self.portal_workflow wf = wtool.getWorkflowsFor(self)[0] return wf.getInfoFor(self, 'review_state', '') security.declarePublic('hasState') def hasState(self, state): return self.getWorkflowState() == state security.declarePrivate('tryWorkflowAction') def tryWorkflowAction(self, action, ignoreErrors=False, comment=None): wtool = self.portal_workflow wf = wtool.getWorkflowsFor(self)[0] if wf.isActionSupported(self, action): if comment is None: userId = getSecurityManager().getUser().getId() comment = 'State changed by ' + userId wtool.doActionFor(self, action, comment=comment) elif not ignoreErrors: raise TypeError('Unsupported workflow action %s for object %s.' % (repr(action), repr(self))) security.declarePublic('isGradable') def isGradable(self): mcTest = getParent(self) return mcTest.isTutorGraded(self) and \ (self.getWorkflowState() in ("pending", "graded",)) security.declareProtected(PERMISSION_RESULT_WRITE, 'submit') def submit(self): self.setTimeFinish(DateTime()) mcTest = getParent(self) results = mcTest.contentValues(filter={ 'Creator': self.Creator(), 'portal_type': self.portal_type, }) for res in results: # determine workflow action: submit for self and supersede # for all the others if res == self: if mcTest.isTutorGraded(self): action = 'submit_pending' else: action = 'submit_graded' commentAction = 'Submitted' else: action = 'supersede' commentAction = 'Superseded' # execute the action comment = '%s by %s' % (commentAction, self.Creator()) res.tryWorkflowAction(action, ignoreErrors=True, comment=comment) security.declarePublic('isNewer') def isNewer(self, other): return self.getTimeStart() > other.getTimeStart() security.declarePublic('isMoreFinal') def isMoreFinal(self, other): STATES = [ 'unsubmitted', 'superseded', 'pending', 'graded', #'invalid', ] indexes = [STATES.index(o.getWorkflowState()) for o in self, other] return indexes[0] > indexes[1] security.declarePrivate('getViewerNames') def getViewerNames(self): """ Get the names of the users and/or groups which have the local role ROLE_RESULT_VIEWER. This allows reviewers to quickly check who may view an assignment. @return list of user and/or group names """ principalIds = self.users_with_local_role(ROLE_RESULT_VIEWER) names = [] for id in principalIds: if self.portal_groups.getGroupById(id): names.append( self.portal_groups.getGroupById(id).getGroupName()) else: names.append(self.ecq_tool.getFullNameById(id)) return names security.declarePublic('getIndicators') def getIndicators(self): """ Returns a list of dictionaries which contain information necessary to display the indicator icons. """ retVal = [] user = self.portal_membership.getAuthenticatedMember() isOwner = user.has_role(['Owner', 'Reviewer', 'Manager'], self) isGrader = self.userIsGrader(user) viewers = self.getViewerNames() if viewers: if isOwner: retVal.append({ 'src': 'ec_shared.png', 'alt': 'Released', 'alt_msgid': 'label_released', 'title': '; '.join(viewers), }) elif isGrader: retVal.append({ 'src': 'ec_shared.png', 'alt': 'Released', 'alt_msgid': 'label_released', 'title': 'These quiz results have been released for viewing.', 'title_msgid': 'tooltip_released_icon', }) # if self.feedback: # feedback = str(self.feedback) # title = re.sub('[\r\n]+', ' ', feedback)[0:76] # retVal.append({'icon':'comment.png', # 'alt':'Feedback', # 'alt_msgid':'label_feedback', # 'title':title, # }) # if isGrader and hasattr(self, 'remarks') and self.remarks: # remarks = str(self.remarks) # title = re.sub('[\r\n]+', ' ', remarks)[0:76] # retVal.append({'icon':'ecab_remarks.png', # 'alt':'Remarks', # 'alt_msgid':'label_remarks', # 'title':title, # }) return retVal security.declarePublic('translateIndicators') def translateIndicators(self, indicators): # Translate [alt] and [title] for d in indicators: for k_msgid, k_msg in (( 'alt_msgid', 'alt', ), ( 'title_msgid', 'title', )): msgid = d.get(k_msgid, None) if msgid is not None: msg = d[k_msg] d[k_msg] = self.translate(msgid=k_msg, domain=I18N_DOMAIN, default=msg) d.pop(k_msgid) return indicators
def getRaw(self, instance, **kwargs): dtml = ObjectField.get(self, instance, **kwargs) return dtml.read()
def get(self, instance, **kwargs): zpt = ObjectField.get(self, instance, **kwargs) return zpt.pt_render(extra_context={'options': kwargs})
def set(self, instance, value, **kwargs): if value is None: value = () if not isinstance(value, (ListType, TupleType)): value = value, elif not self.multiValued and len(value) > 1: raise ValueError, \ "Multiple values given for single valued field %r" % self # Convert objects to uids if necessary. Compute new references # as well. original_uids = [] if not kwargs.get('_initializing_'): original_uids = self.getRaw(instance, aslist=True) new_uids = [] uids = [] for v in value: if type(v) in STRING_TYPES: uid = v else: uid = v.UID() # Update lists if uid not in original_uids: new_uids.append(uid) if uid not in uids: uids.append(uid) ObjectField.set(self, instance, uids) if not self.set_backreference or kwargs.get('backref'): return # Maintain back references if kwargs.get('_initializing_'): return # Compute removed references removed_uids = set(original_uids) - set(uids) # Scan the target portal type for a field with a matching # relationship backref_field_map = {} def get_backref_field(ob): def filter_function(f): return (f.type in ('reference', 'simplereference')) \ and (f.relationship == self.relationship) portal_type = ob.portal_type field = None if backref_field_map.has_key(self.relationship): field = backref_field_map[self.relationship] else: fields = ob.Schema().filterFields(filter_function) if fields: field = fields[0] backref_field_map[self.relationship] = field return field rc = getToolByName(instance, REFERENCE_CATALOG) # Set new back references for uid in new_uids: ob = rc.lookupObject(uid) field = get_backref_field(ob) if field is not None: field.set( ob, list(field.getRaw(ob, aslist=True) + [instance.UID()]), backref=True, ) # Remove old back references for uid in removed_uids: ob = rc.lookupObject(uid) field = get_backref_field(ob) if field is not None: field.set( ob, list( set(field.getRaw(ob, aslist=True)) - set([instance.UID()])), backref=True, )
def set(self, instance, value, **kwargs): if not isinstance(value, DTMLMethod): dtml = DTMLMethod(self.getName()) dtml.munge(value) value = dtml ObjectField.set(self, instance, value, **kwargs)
def getDefault(self, instance): value = ObjectField.getDefault(self, instance) script = PythonScript(self.getName()) script.ZPythonScript_edit('**options', value) return script.__of__(instance)
def get(self, instance, **kwargs): script = ObjectField.get(self, instance, **kwargs) return script(**kwargs)
def getDefault(self, instance): value = ObjectField.getDefault(self, instance) dtml = DTMLMethod(self.getName()) dtml.munge(value) return dtml.__of__(instance)
def set(self, instance, value, **kwargs): if value is None: value = () if not isinstance(value, (ListType, TupleType)): value = value, elif not self.multiValued and len(value) > 1: raise ValueError, \ "Multiple values given for single valued field %r" % self # Convert objects to uids if necessary. Compute new references # as well. original_uids = [] if not kwargs.get('_initializing_'): original_uids = self.getRaw(instance, aslist=True) new_uids = [] uids = [] for v in value: if type(v) in STRING_TYPES: uid = v else: uid = v.UID() # Update lists if uid not in original_uids: new_uids.append(uid) if uid not in uids: uids.append(uid) ObjectField.set(self, instance, uids) if not self.set_backreference or kwargs.get('backref'): return # Maintain back references if kwargs.get('_initializing_'): return # Compute removed references removed_uids = set(original_uids) - set(uids) # Scan the target portal type for a field with a matching # relationship backref_field_map = {} def get_backref_field(ob): def filter_function(f): return (f.type in ('reference', 'simplereference')) \ and (f.relationship == self.relationship) portal_type = ob.portal_type field = None if backref_field_map.has_key(self.relationship): field = backref_field_map[self.relationship] else: fields = ob.Schema().filterFields(filter_function) if fields: field = fields[0] backref_field_map[self.relationship] = field return field rc = getToolByName(instance, REFERENCE_CATALOG) # Set new back references for uid in new_uids: ob = rc.lookupObject(uid) field = get_backref_field(ob) if field is not None: field.set( ob, list(field.getRaw(ob, aslist=True)+[instance.UID()]), backref=True, ) # Remove old back references for uid in removed_uids: ob = rc.lookupObject(uid) field = get_backref_field(ob) if field is not None: field.set( ob, list(set(field.getRaw(ob, aslist=True)) - set([instance.UID()])), backref=True, )