Example #1
0
    def handleSave(self, action):
        data, errors = self.extractData()
        if errors:
            self.status = self.formErrorsMessage
            return

        typeName = self.tileType.__name__

        # Traverse to a new tile in the context, with no data
        tile = self.context.restrictedTraverse('@@%s/%s' % (
            typeName,
            self.tileId,
        ))

        dataManager = ITileDataManager(tile)
        dataManager.set(data)

        # Look up the URL - we need to do this after we've set the data to
        # correctly account for transient tiles
        tileURL = absoluteURL(tile, self.request)
        contextURL = absoluteURL(tile.context, self.request)
        tileRelativeURL = tileURL

        if tileURL.startswith(contextURL):
            tileRelativeURL = '.' + tileURL[len(contextURL):]

        notify(ObjectModifiedEvent(tile))

        # Get the tile URL, possibly with encoded data
        IStatusMessage(self.request).addStatusMessage(_(u"Tile saved", ),
                                                      type=u'info')

        self.request.response.redirect(tileURL)
    def handleAdd(self, action):

        data, errors = self.extractData()
        if errors:
            self.status = self.formErrorsMessage
            return

        typeName = self.tileType.__name__

        # Traverse to a new tile in the context, with no data
        tile = self.context.restrictedTraverse(
            '@@%s/%s' % (typeName, self.tileId,))

        dataManager = ITileDataManager(tile)
        content = {}
        applyChanges(self, content, data)
        dataManager.set(content)

        # Look up the URL - we need to do this after we've set the data to
        # correctly account for transient tiles
        tileURL = absoluteURL(tile, self.request)
        contextURL = absoluteURL(tile.context, self.request)

        notify(ObjectCreatedEvent(tile))
        notify(ObjectAddedEvent(tile, self.context, self.tileId))

        IStatusMessage(self.request).addStatusMessage(
                _(u"Tile created at ${url}",
                  mapping={'url': tileURL}),
                type=u'info',
            )

        self.request.response.redirect(contextURL)
Example #3
0
    def handleSave(self, action):
        data, errors = self.extractData()
        if errors:
            self.status = self.formErrorsMessage
            return

        typeName = self.tileType.__name__

        # Traverse to a new tile in the context, with no data
        tile = self.context.restrictedTraverse('@@%s/%s' % (typeName, self.tileId,))

        dataManager = ITileDataManager(tile)
        dataManager.set(data)

        # Look up the URL - we need to do this after we've set the data to
        # correctly account for transient tiles
        tileURL = absoluteURL(tile, self.request)
        contextURL = absoluteURL(tile.context, self.request)
        tileRelativeURL = tileURL

        if tileURL.startswith(contextURL):
            tileRelativeURL = '.' + tileURL[len(contextURL):]

        notify(ObjectModifiedEvent(tile))

        # Get the tile URL, possibly with encoded data
        IStatusMessage(self.request).addStatusMessage(_(u"Tile saved",), type=u'info')

        self.request.response.redirect(tileURL)
Example #4
0
def unconsumedURL(context, request):
    url = absoluteURL(context, request)
    consumed = request.annotations.get(CONSUMED_ANNOTATION_KEY)
    if not consumed:
        return url
    inserts = []
    for obj, names in consumed:
        if obj is context:
            # only calculate once
            objURL = url
        else:
            objURL = absoluteURL(obj, request)
        if not url.startswith(objURL):
            # we are further down
            break
        names = '/' + '/'.join(map(_encode, names))
        inserts.append((len(objURL), names))

    offset = 0
    for i, s in inserts:
        oi = i + offset
        pre = url[:oi]
        post = url[oi:]
        url = pre + s + post
        offset += len(s)
    return url
Example #5
0
    def initialize(self):
        self.pillar = self.context.pillar
        self.person = self.context.person

        self.label = "Information shared with %s" % self.person.displayname
        self.page_title = "%s" % self.person.displayname
        self.sharing_service = getUtility(IService, 'sharing')

        self._loadSharedArtifacts()

        cache = IJSONRequestCache(self.request)
        request = get_current_web_service_request()
        branch_data = self._build_branch_template_data(self.branches, request)
        bug_data = self._build_bug_template_data(self.bugtasks, request)
        spec_data = self._build_specification_template_data(
            self.specifications, request)
        grantee_data = {
            'displayname': self.person.displayname,
            'self_link': absoluteURL(self.person, request)
        }
        pillar_data = {'self_link': absoluteURL(self.pillar, request)}
        cache.objects['grantee'] = grantee_data
        cache.objects['pillar'] = pillar_data
        cache.objects['bugs'] = bug_data
        cache.objects['branches'] = branch_data
        cache.objects['specifications'] = spec_data
Example #6
0
 def test_view_data_model(self):
     # Test that the json request cache contains the view data model.
     pillarperson = self.getPillarPerson()
     view = create_initialized_view(pillarperson, '+index')
     bugtask = list(view.bugtasks)[0]
     bug = bugtask.bug
     cache = IJSONRequestCache(view.request)
     request = get_current_web_service_request()
     self.assertEqual({
         'self_link': absoluteURL(pillarperson.person, request),
         'displayname': pillarperson.person.displayname
     }, cache.objects.get('grantee'))
     self.assertEqual({
         'self_link': absoluteURL(pillarperson.pillar, request),
     }, cache.objects.get('pillar'))
     self.assertEqual({
         'bug_id': bug.id,
         'bug_summary': bug.title,
         'bug_importance': bugtask.importance.title.lower(),
         'information_type': bug.information_type.title,
         'web_link': canonical_url(
             bugtask, path_only_if_possible=True),
         'self_link': absoluteURL(bug, request),
     }, cache.objects.get('bugs')[0])
     if self.pillar_type == 'product':
         branch = list(view.branches)[0]
         self.assertEqual({
             'branch_id': branch.id,
             'branch_name': branch.unique_name,
             'information_type': branch.information_type.title,
             'web_link': canonical_url(branch, path_only_if_possible=True),
             'self_link': absoluteURL(branch, request),
         }, cache.objects.get('branches')[0])
Example #7
0
    def update(self):
        """Read and validate form data, and update model if necessary.

        Also choose the correct template to render.
        """
        self.field_errors = []
        self.template = self.select_template

        if 'CANCEL' in self.request:
            self.request.response.redirect(
                absoluteURL(self.context, self.request))
            return

        if 'date' in self.request:
            try:
                self.date = parse_date(self.request['date'])
            except ValueError:
                self.error = _("Invalid date. Please use YYYY-MM-DD format.")
            else:
                self.term = getTermForDate(self.date)
                if self.term is None:
                    self.error = _("The date does not belong to any term.")
                    self.date = None

        if self.date:
            self.template = self.form_template

        if self.date and 'SUBMIT' in self.request:
            replacements = self.extractMeetings()
            if self.field_errors:
                self.error = self.field_error_message
            else:
                self.updateExceptions(replacements)
                self.request.response.redirect(
                    absoluteURL(self.context, self.request))
Example #8
0
    def update(self):
        """Read and validate form data, and update model if necessary.

        Also choose the correct template to render.
        """
        self.field_errors = []
        self.template = self.select_template

        if 'CANCEL' in self.request:
            self.request.response.redirect(
                absoluteURL(self.context, self.request))
            return

        if 'date' in self.request:
            try:
                self.date = parse_date(self.request['date'])
            except ValueError:
                self.error = _("Invalid date. Please use YYYY-MM-DD format.")
            else:
                self.term = getTermForDate(self.date)
                if self.term is None:
                    self.error = _("The date does not belong to any term.")
                    self.date = None

        if self.date:
            self.template = self.form_template

        if self.date and 'SUBMIT' in self.request:
            replacements = self.extractMeetings()
            if self.field_errors:
                self.error = self.field_error_message
            else:
                self.updateExceptions(replacements)
                self.request.response.redirect(
                    absoluteURL(self.context, self.request))
Example #9
0
    def initialize(self):
        self.pillar = self.context.pillar
        self.person = self.context.person

        self.label = "Information shared with %s" % self.person.displayname
        self.page_title = "%s" % self.person.displayname
        self.sharing_service = getUtility(IService, 'sharing')

        self._loadSharedArtifacts()

        cache = IJSONRequestCache(self.request)
        request = get_current_web_service_request()
        branch_data = self._build_branch_template_data(self.branches, request)
        bug_data = self._build_bug_template_data(self.bugtasks, request)
        spec_data = self._build_specification_template_data(
            self.specifications, request)
        grantee_data = {
            'displayname': self.person.displayname,
            'self_link': absoluteURL(self.person, request)
        }
        pillar_data = {
            'self_link': absoluteURL(self.pillar, request)
        }
        cache.objects['grantee'] = grantee_data
        cache.objects['pillar'] = pillar_data
        cache.objects['bugs'] = bug_data
        cache.objects['branches'] = branch_data
        cache.objects['specifications'] = spec_data
Example #10
0
 def jsonGranteeData(self, grant_permissions):
     """See `ISharingService`."""
     result = []
     request = get_current_web_service_request()
     browser_request = IWebBrowserOriginatingRequest(request)
     # We need to precache icon and validity information for the batch.
     grantee_ids = [grantee[0].id for grantee in grant_permissions]
     list(getUtility(IPersonSet).getPrecachedPersonsFromIDs(
         grantee_ids, need_icon=True, need_validity=True))
     for (grantee, permissions, shared_artifact_types) in grant_permissions:
         some_things_shared = len(shared_artifact_types) > 0
         grantee_permissions = {}
         for (policy, permission) in permissions.iteritems():
             grantee_permissions[policy.type.name] = permission.name
         shared_artifact_type_names = [
             info_type.name for info_type in shared_artifact_types]
         display_api = ObjectImageDisplayAPI(grantee)
         icon_url = display_api.custom_icon_url()
         sprite_css = display_api.sprite_css()
         result.append({
             'name': grantee.name,
             'icon_url': icon_url,
             'sprite_css': sprite_css,
             'display_name': grantee.displayname,
             'self_link': absoluteURL(grantee, request),
             'web_link': absoluteURL(grantee, browser_request),
             'permissions': grantee_permissions,
             'shared_artifact_types': shared_artifact_type_names,
             'shared_items_exist': some_things_shared})
     return result
Example #11
0
def unconsumedURL(context, request):
    url = absoluteURL(context, request)
    consumed = request.annotations.get(CONSUMED_ANNOTATION_KEY)
    if not consumed:
        return url
    inserts = []
    for obj, names in consumed:
        if obj is context:
            # only calculate once
            objURL = url
        else:
            objURL = absoluteURL(obj, request)
        if not url.startswith(objURL):
            # we are further down
            break
        names = '/' + '/'.join(map(_encode, names))
        inserts.append((len(objURL), names))

    offset = 0
    for i, s in inserts:
        oi = i + offset
        pre = url[:oi]
        post = url[oi:]
        url = pre + s + post
        offset += len(s)
    return url
Example #12
0
    def handleAdd(self, action):

        data, errors = self.extractData()
        if errors:
            self.status = self.formErrorsMessage
            return

        typeName = self.tileType.__name__

        context = self.context

        # Look up if our context supports tiles, if not
        # pick default view instead
        if not ILayoutAware(context, None):
            default_page_view = getMultiAdapter((context, self.request),
                                                name='default_page')
            default_page = default_page_view.getDefaultPage()
            context = default_page and context[default_page] or context
            context = ILayoutAware(context, None)

        # Traverse to a new tile in the context, with no data
        tile = context.restrictedTraverse(
            '@@%s/%s' % (typeName, self.tileId,))

        dataManager = ITileDataManager(tile)
        dataManager.set(data)

        # Look up the URL - we need to do this after we've set the data to
        # correctly account for transient tiles
        tileURL = absoluteURL(tile, self.request)
        contextURL = absoluteURL(tile.context, self.request)
        tileRelativeURL = tileURL

        if tileURL.startswith(contextURL):
            tileRelativeURL = '.' + tileURL[len(contextURL):]

        notify(ObjectCreatedEvent(tile))
        notify(ObjectAddedEvent(tile, self.context, self.tileId))

        IStatusMessage(self.request).addStatusMessage(
                _(u"Tile created at ${url}",
                  mapping={'url': tileURL}),
                type=u'info',
            )

        # Calculate the edit URL and append some data in a JSON structure,
        # to help the UI know what to do.

        url = getEditTileURL(tile, self.request)

        tileDataJson = {}
        tileDataJson['action'] = "save"
        tileDataJson['mode'] = "add"
        tileDataJson['url'] = tileRelativeURL
        tileDataJson['tile_type'] = typeName
        tileDataJson['id'] = tile.id

        url = appendJSONData(url, 'tiledata', tileDataJson)
        self.request.response.redirect(url)
Example #13
0
 def handleBack(self, action):
     context = self.context.context
     quote = lambda x:urllib.quote(x.encode("utf-8"))
     self.request.response.redirect(
         u"%s/select_group?context=%s&title=%s" % (
             absoluteURL(hooks.getSiteManager(), self.request),
             absoluteURL(context, self.request),
             quote(IZopeDublinCore(context).title or context.__name__)))
Example #14
0
 def handleBack(self, action):
     context = self.context.context
     quote = lambda x: urllib.quote(x.encode("utf-8"))
     self.request.response.redirect(
         u"%s/select_group?context=%s&title=%s" %
         (absoluteURL(hooks.getSiteManager(),
                      self.request), absoluteURL(context, self.request),
          quote(IZopeDublinCore(context).title or context.__name__)))
Example #15
0
    def values(self):
        site = hooks.getSite()

        yield {'title': u"SITE",
               'url': absoluteURL(site, self.request),
               'nesting': 0}

        for x in site.values():
            yield {'title': IZopeDublinCore(x).title or x.__name__,
                   'url': absoluteURL(x, self.request),
                   'nesting': 1}
Example #16
0
 def handle_cancel_action(self, action):
     person = IPerson(self.request.principal, None)
     if person is None:
         worksheet = self.context._getDefaultWorksheet()
     else:
         worksheet = self.context.getCurrentWorksheet(person)
     if worksheet is None:
         url = absoluteURL(self.context.__parent__, self.request)
     else:
         url = absoluteURL(worksheet, self.request) + '/gradebook'
     self.request.response.redirect(url)
Example #17
0
 def handle_submit_(self, action):
     app = ISchoolToolApplication(None)
     persons = app['persons']
     username = self.request.get('username', '')
     person = persons.get(username, None)
     if person is not None:
         url = absoluteURL(person, self.request)
     else:
         url = absoluteURL(app, self.request)
     self.request.response.redirect(url)
     self.ajax_settings['dialog'] = 'close'
Example #18
0
 def handle_submit_(self, action):
     app = ISchoolToolApplication(None)
     persons = app['persons']
     username = self.request.get('username', '')
     person = persons.get(username, None)
     if person is not None:
         url = absoluteURL(person, self.request)
     else:
         url = absoluteURL(app, self.request)
     self.request.response.redirect(url)
     self.ajax_settings['dialog'] = 'close'
Example #19
0
 def update(self):
     prefix = 'setting.'
     self.status = None
     if 'UPDATE_SUBMIT' in self.request:
         for setting in self.settings():
             val = self.request.get(prefix + setting.key, 'False')
             setting.setValue(bool(val != 'False'))
         url = absoluteURL(self.context, self.request) + '/security.html'
         self.request.response.redirect(url)
     elif 'CANCEL' in self.request:
         url = absoluteURL(self.context, self.request) + '/security.html'
         self.request.response.redirect(url)
 def __call__(self):
     interaction = zope.security.management.getInteraction()
     canChangeStatus = interaction.checkPermission(
         'quotationtool.editorial.ChangeEditorialStatus', self.context)
     if canChangeStatus:
         self.request.response.redirect(
             absoluteURL(self.context, self.request) +
             u"/@@changeEditorialStatus.html")
     else:
         self.request.response.redirect(
             absoluteURL(self.context, self.request) +
             u"/@@revisionHistory.html")
Example #21
0
 def nextURL(self):
     if 'person_id' in self.request:
         person_id = self.request['person_id']
         app = ISchoolToolApplication(None)
         persons = app['persons']
         if person_id in persons:
             return absoluteURL(persons[person_id], self.request)
     base_url = absoluteURL(self.context.__parent__, self.request)
     return "%s/@@manage_contacts.html?%s" % (
         base_url,
         urllib.urlencode([('SEARCH_TITLE',
                            self.context.last_name.encode("utf-8"))]))
Example #22
0
 def update(self):
     prefix = 'setting.'
     self.status = None
     if 'UPDATE_SUBMIT' in self.request:
         for setting in self.settings():
             val = self.request.get(prefix + setting.key, 'False')
             setting.setValue(bool(val != 'False'))
         url = absoluteURL(self.context, self.request) + '/security.html'
         self.request.response.redirect(url)
     elif 'CANCEL' in self.request:
         url = absoluteURL(self.context, self.request) + '/security.html'
         self.request.response.redirect(url)
Example #23
0
 def nextURL(self):
     if 'person_id' in self.request:
         person_id = self.request['person_id']
         app = ISchoolToolApplication(None)
         persons = app['persons']
         if person_id in persons:
             return absoluteURL(persons[person_id], self.request)
     base_url = absoluteURL(self.context.__parent__, self.request)
     return "%s/@@manage_contacts.html?%s" % (
         base_url,
         urllib.urlencode(
             [('SEARCH_TITLE', self.context.last_name.encode("utf-8"))]))
Example #24
0
 def getSections(self):
     person = schooltool.person.interfaces.IPerson(self.request.principal)
     instructor_of = schooltool.course.interfaces.IInstructor(person).sections()
     for section in instructor_of:
         url = absoluteURL(section, self.request)
         url += '/gradebook'
         title = '%s %s' % (list(section.courses)[0].title, section.title)
         yield {'url': url, 'title': title}
     learner_of = schooltool.course.interfaces.ILearner(person).sections()
     for section in learner_of:
         url = absoluteURL(section, self.request)
         url += '/mygrades'
         title = '%s %s' % (list(section.courses)[0].title, section.title)
         yield {'url': url, 'title': title}
Example #25
0
    def values(self):
        site = hooks.getSite()

        yield {
            'title': u"SITE",
            'url': absoluteURL(site, self.request),
            'nesting': 0
        }

        for x in site.values():
            yield {
                'title': IZopeDublinCore(x).title or x.__name__,
                'url': absoluteURL(x, self.request),
                'nesting': 1
            }
Example #26
0
 def getSections(self):
     person = schooltool.person.interfaces.IPerson(self.request.principal)
     instructor_of = schooltool.course.interfaces.IInstructor(
         person).sections()
     for section in instructor_of:
         url = absoluteURL(section, self.request)
         url += '/gradebook'
         title = '%s %s' % (list(section.courses)[0].title, section.title)
         yield {'url': url, 'title': title}
     learner_of = schooltool.course.interfaces.ILearner(person).sections()
     for section in learner_of:
         url = absoluteURL(section, self.request)
         url += '/mygrades'
         title = '%s %s' % (list(section.courses)[0].title, section.title)
         yield {'url': url, 'title': title}
Example #27
0
    def testBasicContext_unicode(self):
        #Tests so that AbsoluteURL handle unicode names as well
        request = TestRequest()
        root = Root()
        root.__name__ = u'\u0439'

        content = contained(TrivialContent(), root, name=u'\u0442')
        content = contained(TrivialContent(), content, name=u'\u0435')
        content = contained(TrivialContent(), content, name=u'\u0441')
        view = getMultiAdapter((content, request), name='absolute_url')
        self.assertEqual(str(view),
                         'http://127.0.0.1/%D0%B9/%D1%82/%D0%B5/%D1%81')
        self.assertEqual(view(),
                         'http://127.0.0.1/%D0%B9/%D1%82/%D0%B5/%D1%81')
        self.assertEqual(view.__unicode__(),
                         u'http://127.0.0.1/\u0439/\u0442/\u0435/\u0441')
        self.assertEqual(absoluteURL(content, request),
                         'http://127.0.0.1/%D0%B9/%D1%82/%D0%B5/%D1%81')

        breadcrumbs = view.breadcrumbs()
        self.assertEqual(breadcrumbs,
                         ({'name':  '', 'url': 'http://127.0.0.1'},
                          {'name': u'\u0439', 'url': 'http://127.0.0.1/%D0%B9'},
                          {'name': u'\u0442',
                           'url': 'http://127.0.0.1/%D0%B9/%D1%82'},
                          {'name': u'\u0435',
                           'url': 'http://127.0.0.1/%D0%B9/%D1%82/%D0%B5'},
                          {'name': u'\u0441',
                           'url':
                           'http://127.0.0.1/%D0%B9/%D1%82/%D0%B5/%D1%81'},
                         ))
Example #28
0
 def __str__(self):
     if IContainmentRoot.providedBy(self.context):
         return ''
     name = self.context.__name__
     url = absoluteURL(getParent(self.context), self.request)
     url += '/' + name
     return url
Example #29
0
 def update(self):
     if 'DONE' in self.request:
         url = absoluteURL(self.context, self.request)
         self.request.response.redirect(url)
     elif 'form-submitted' in self.request:
         for demo in self.context.values():
             name = 'delete.%s' % demo.__name__
             if name in self.request:
                 del self.context[demo.__name__]
                 return
         old_pos, new_pos = 0, 0, False
         for demo in self.context.values():
             old_pos += 1
             name = getName(demo)
             if 'pos.' + name not in self.request:
                 continue
             new_pos = int(self.request['pos.' + name])
             if new_pos != old_pos:
                 break
         old_pos, new_pos = old_pos - 1, new_pos - 1
         keys = list(self.context.keys())
         moving = keys[old_pos]
         keys.remove(moving)
         keys.insert(new_pos, moving)
         self.context.updateOrder(keys)
Example #30
0
    def handleSave(self, action):
        data, errors = self.extractData()
        if errors:
            self.status = self.formErrorsMessage
            return

        typeName = self.tileType.__name__

        # Traverse to a new tile in the context, with no data
        tile = self.context.restrictedTraverse('@@%s/%s' % (typeName, self.tileId,))

        dataManager = ITileDataManager(tile)
        # We need to check first for existing content in order to not loose
        # fields that weren't sent with the form.
        old_data = dataManager.get()
        for item in data:
            if data[item] is not None:
                old_data[item] = data[item]

        dataManager.set(old_data)

        # Look up the URL - we need to do this after we've set the data to
        # correctly account for transient tiles
        tileURL = absoluteURL(tile, self.request)
        notify(ObjectModifiedEvent(tile))

        # Get the tile URL, possibly with encoded data
        IStatusMessage(self.request).addStatusMessage(_(u"Tile saved",), type=u'info')

        self.request.response.redirect(tileURL)
Example #31
0
 def url(self):
     link = self.link
     if not link:
         return None
     courses = ICourseContainer(self.schoolyear)
     return "%s/%s" % (absoluteURL(courses, self.request),
                       self.link)
Example #32
0
 def table(self):
     result = []
     for demo in list(self.context.values()):
         classname = demo.__class__.__name__
         class_key = classname[:classname.find('FieldDescription')]
         field_type = self.types.get(class_key, '')
         limit_keys = demo.limit_keys
         if limit_keys is None:
             limit_keys = []
         result.append({
             'title':
             demo.title,
             'url':
             '%s/edit.html' % absoluteURL(demo, self.request),
             'id':
             demo.name,
             'type':
             field_type,
             'required':
             demo.required,
             'limited':
             bool(limit_keys),
             'groups': [(key[0] in limit_keys) for key in self.keys],
         })
     return result
Example #33
0
    def testBasicContext_unicode(self):
        # Tests so that AbsoluteURL handle unicode names as well
        request = TestRequest()
        root = Root()
        root.__name__ = u"\u0439"

        content = contained(TrivialContent(), root, name=u"\u0442")
        content = contained(TrivialContent(), content, name=u"\u0435")
        content = contained(TrivialContent(), content, name=u"\u0441")
        view = getMultiAdapter((content, request), name="absolute_url")
        self.assertEqual(str(view), "http://127.0.0.1/%D0%B9/%D1%82/%D0%B5/%D1%81")
        self.assertEqual(view(), "http://127.0.0.1/%D0%B9/%D1%82/%D0%B5/%D1%81")
        self.assertEqual(unicode(view), u"http://127.0.0.1/\u0439/\u0442/\u0435/\u0441")
        self.assertEqual(absoluteURL(content, request), "http://127.0.0.1/%D0%B9/%D1%82/%D0%B5/%D1%81")

        breadcrumbs = view.breadcrumbs()
        self.assertEqual(
            breadcrumbs,
            (
                {"name": "", "url": "http://127.0.0.1"},
                {"name": u"\u0439", "url": "http://127.0.0.1/%D0%B9"},
                {"name": u"\u0442", "url": "http://127.0.0.1/%D0%B9/%D1%82"},
                {"name": u"\u0435", "url": "http://127.0.0.1/%D0%B9/%D1%82/%D0%B5"},
                {"name": u"\u0441", "url": "http://127.0.0.1/%D0%B9/%D1%82/%D0%B5/%D1%81"},
            ),
        )
Example #34
0
 def render(self, *args, **kw):
     # XXX: risky:
     if self.timetable is None:
         self.timetable = self.createAndAdd()
     self.request.response.redirect(
         absoluteURL(self.timetable, self.request))
     return ''
Example #35
0
    def handleAdd(self, action):

        data, errors = self.extractData()
        if errors:
            self.status = self.formErrorsMessage
            return

        typeName = self.tileType.__name__

        generator = getUtility(IUUIDGenerator)
        tileId = generator()

        # Traverse to a new tile in the context, with no data
        tile = self.context.restrictedTraverse(
            '@@%s/%s' % (typeName, tileId,))

        dataManager = ITileDataManager(tile)
        new_data = {}
        form.applyChanges(self, new_data, data)
        dataManager.set(new_data)

        # Look up the URL - we need to do this after we've set the data to
        # correctly account for transient tiles
        tileURL = absoluteURL(tile, self.request)

        notify(ObjectCreatedEvent(tile))
        notify(ObjectAddedEvent(tile, self.context, tileId))
        logger.debug(u"Tile created at {0}".format(tileURL))

        try:
            url = self.nextURL(tile)
        except NotImplementedError:
            url = tileURL

        self.request.response.redirect(url)
Example #36
0
 def handleDelete(self, action):
     url = '%s/delete.html?delete.%s&CONFIRM' % (
         absoluteURL(self.context.__parent__, self.request),
         self.context.__name__.encode('utf-8'))
     self.request.response.redirect(url)
     # We never have errors, so just close the dialog.
     self.ajax_settings['dialog'] = 'close'
Example #37
0
 def update(self):
     if 'DONE' in self.request:
         url = absoluteURL(self.context, self.request)
         self.request.response.redirect(url)
     elif 'form-submitted' in self.request:
         for demo in self.context.values():
             name = 'delete.%s' % demo.__name__
             if name in self.request:
                 del self.context[demo.__name__]
                 return
         old_pos, new_pos = 0, 0, False
         for demo in self.context.values():
             old_pos += 1
             name = getName(demo)
             if 'pos.'+name not in self.request:
                 continue
             new_pos = int(self.request['pos.'+name])
             if new_pos != old_pos:
                 break
         old_pos, new_pos = old_pos-1, new_pos-1
         keys = list(self.context.keys())
         moving = keys[old_pos]
         keys.remove(moving)
         keys.insert(new_pos,moving)
         self.context.updateOrder(keys)
Example #38
0
    def testBasicContext_unicode(self):
        #Tests so that AbsoluteURL handle unicode names as well
        request = TestRequest()
        root = Root()
        root.__name__ = u'\u0439'

        content = contained(TrivialContent(), root, name=u'\u0442')
        content = contained(TrivialContent(), content, name=u'\u0435')
        content = contained(TrivialContent(), content, name=u'\u0441')
        view = getMultiAdapter((content, request), name='absolute_url')
        self.assertEqual(str(view),
                         'http://127.0.0.1/%D0%B9/%D1%82/%D0%B5/%D1%81')
        self.assertEqual(view(),
                         'http://127.0.0.1/%D0%B9/%D1%82/%D0%B5/%D1%81')
        self.assertEqual(view.__unicode__(),
                         u'http://127.0.0.1/\u0439/\u0442/\u0435/\u0441')
        self.assertEqual(absoluteURL(content, request),
                         'http://127.0.0.1/%D0%B9/%D1%82/%D0%B5/%D1%81')

        breadcrumbs = view.breadcrumbs()
        self.assertEqual(breadcrumbs,
                         ({'name':  '', 'url': 'http://127.0.0.1'},
                          {'name': u'\u0439', 'url': 'http://127.0.0.1/%D0%B9'},
                          {'name': u'\u0442',
                           'url': 'http://127.0.0.1/%D0%B9/%D1%82'},
                          {'name': u'\u0435',
                           'url': 'http://127.0.0.1/%D0%B9/%D1%82/%D0%B5'},
                          {'name': u'\u0441',
                           'url':
                           'http://127.0.0.1/%D0%B9/%D1%82/%D0%B5/%D1%81'},
                          ))
Example #39
0
def password_reset_request(event):
    user = get_profile(event.principal_id, "basic")
    f = open_file('mail/password_reset_request.tmpl', __file__)

    site = hooks.getSite()
    site_url = absoluteURL(site, event.req)
    page_link = u'%s/password_reset' % site_url
    full_link = u'%s?login=%s&code=%s' % (page_link, event.login, event.code)
    dc = IZopeDublinCore(site)

    data = {'name': user.name,
            'code': event.code,
            'page_link': page_link,
            'full_link': full_link,
            'site_title': dc.title,
            'site_url': site_url}

    message = Template(file=f, searchList=[data])

    subject = u'Password reset request'
    send_mail(message,
              subject,
              user.email,
              subtype='html',
              from_header=dc.title,
              to_header=user.name)
    def lockroot(self):
        if interfaces.IIndirectToken.providedBy(self.token):
            root = self.token.roottoken.context
        else:
            root = self.token.context

        return absoluteURL(root, self.request)
Example #41
0
 def handleApply(self, action):
     super(FlourishGroupEditView, self).handleApply.func(self, action)
     # XXX: hacky sucessful submit check
     if (self.status == self.successMessage or
         self.status == self.noChangesMessage):
         url = absoluteURL(self.context, self.request)
         self.request.response.redirect(url)
Example #42
0
 def __str__(self):
     if IContainmentRoot.providedBy(self.context):
         return ''
     name = self.context.__name__
     url = absoluteURL(getParent(self.context), self.request)
     url += '/' + name
     return url
Example #43
0
    def handleAdd(self, action):

        data, errors = self.extractData()
        if errors:
            self.status = self.formErrorsMessage
            return

        typeName = self.tileType.__name__

        generator = getUtility(IUUIDGenerator)
        tileId = generator()

        # Traverse to a new tile in the context, with no data
        tile = self.context.restrictedTraverse('@@%s/%s' % (
            typeName,
            tileId,
        ))

        dataManager = ITileDataManager(tile)
        dataManager.set(data)

        # Look up the URL - we need to do this after we've set the data to
        # correctly account for transient tiles
        tileURL = absoluteURL(tile, self.request)

        notify(ObjectCreatedEvent(tile))
        notify(ObjectAddedEvent(tile, self.context, tileId))

        self.request.response.redirect(tileURL)
Example #44
0
 def nextURL(self):
     link = flourish.content.queryContentProvider(self.context,
                                                  self.request, self,
                                                  'done_link')
     if link is not None:
         return link.url
     return absoluteURL(self.context.__parent__, self.request)
Example #45
0
    def action(self, type_name='', id=''):
        if not type_name:
            raise UserError(_(u"You must select the type of object to add."))

        if type_name.startswith('@@'):
            type_name = type_name[2:]

        if '/' in type_name:
            view_name = type_name.split('/', 1)[0]
        else:
            view_name = type_name

        if queryMultiAdapter((self, self.request),
                             name=view_name) is not None:
            url = "%s/%s=%s" % (
                absoluteURL(self, self.request), type_name, id)
            self.request.response.redirect(url)
            return

        if not self.contentName:
            self.contentName = id

        factory = getUtility(IFactory, type_name)
        content = factory()

        notify(ObjectCreatedEvent(content))

        self.add(content)
        self.request.response.redirect(self.nextURL())
    def handleCancel(self, action):
        api.portal.show_message(
            _(u'Tile configuration cancelled.'), self.request, type='info')

        contextURL = absoluteURL(self.context, self.request)
        layoutURL = '{0}/layoutedit'.format(contextURL)
        self.request.response.redirect(layoutURL)
Example #47
0
    def handleSave(self, action):
        data, errors = self.extractData()
        if errors:
            self.status = self.formErrorsMessage
            return

        typeName = self.tileType.__name__

        # Traverse to a new tile in the context, with no data
        tile = self.context.restrictedTraverse(
            '@@%s/%s' % (typeName, self.tileId,))

        dataManager = ITileDataManager(tile)
        dataManager.set(data)

        # Look up the URL - we need to do this after we've set the data to
        # correctly account for transient tiles
        tileURL = absoluteURL(tile, self.request)

        notify(ObjectModifiedEvent(tile))
        logger.debug(u"Tile edited at {0}".format(tileURL))

        try:
            url = self.nextURL(tile)
        except NotImplementedError:
            url = tileURL

        self.request.response.redirect(url)
    def handleSave(self, action):
        data, errors = self.extractData()
        if errors:
            self.status = self.formErrorsMessage
            return

        # Traverse to a new tile in the context, with no data
        typeName = self.tileType.__name__
        tile = self.context.restrictedTraverse('@@{0}/{1}'.format(
            typeName, self.tileId))
        tile_conf_adapter = getMultiAdapter((self.context, self.request, tile),
                                            ITilesConfigurationScreen)
        tile_conf_adapter.set_configuration(data)

        # notify about modification
        notify(ObjectModifiedEvent(self.context))
        api.portal.show_message(_(u'Tile configuration saved.'),
                                self.request,
                                type='info')

        # Look up the URL - We need to redirect to the layout view, since
        # there's the only way from where a user would access the configuration
        contextURL = absoluteURL(tile.context, self.request)
        layoutURL = '{0}/layoutedit'.format(contextURL)
        self.request.response.redirect(layoutURL)
Example #49
0
    def _update(self):
        """ Run updater
        """
        url = self.context.url
        etag = self.context.etag or None
        updated = self.context.updated
        if not isinstance(updated, datetime):
            updated = None
        else:
            updated = updated.timetuple()

        data = feedparser.parse(url, etag=etag, modified=updated)
        # No change
        if data.get('status', None) == 304:
            return "No changes made until last update"

        if data.get('etag', None):
            self.context.etag = etag

        last_updated = data.get('modified', None)
        if isinstance(last_updated, time.struct_time) and len(last_updated) >= 6:
            args = last_updated[:6] + (0, utc)
            self.context.updated = datetime(*args)
        else:
            self.context.updated = datetime.now(bucharest)

        for entry in data.get('entries', ()):
            self.add_newsitem(entry)

        return '%s\t%s\tUPDATED' % (
            datetime.now(bucharest).strftime('%d-%m-%Y %H:%M'),
            absoluteURL(self.context, self.request)
        )
Example #50
0
    def handle_signin(self, **data):
        """signin button and signin action
        """
        # create the people
        people = People()
        self.applyData(people, **data)
        # check the login is not taken
        if people.login in self.peoplelist:
            msg = _(u'This username already exists: %s')
            SessionMessageSource().send(
                translate(msg, context=self.request) % people.login)
            return self.redirect('signin')

        # generate a weak but nice password
        password = u''.join([
            choice([
                'z', 'r', 't', 'p', 'q', 's', 'd', 'f', 'g', 'h', 'j', 'k',
                'l', 'm', 'w', 'x', 'c', 'v', 'b', 'n'
            ]) + choice(['a', 'e', 'i', 'o', 'u', 'y']) for i in range(4)
        ])
        people.password = password

        # send an email with the password
        site = grok.getSite()
        email = _(u'''Content-Type: text/plain; charset=UTF-8
Subject: your account for %s

Dear %s %s,

Thanks for your account!
You can connect to %s with the following informations:

%s

     login : %s
     password : %s''')

        url = absoluteURL(site, self.request)

        if ('HTTP_X_FORWARDED_SCHEME' in self.request
                and 'HTTP_X_FORWARDED_SERVER' in self.request):
            url = (self.request['HTTP_X_FORWARDED_SCHEME'] + '://' +
                   self.request['HTTP_X_FORWARDED_SERVER'])

        email = translate(email, context=self.request) % (
            site.name, people.firstname, people.lastname, site.name, url,
            people.login, password)
        mailer = getUtility(IMailDelivery, 'afpy.barcamp')
        if 'nomail' not in self.request:
            mailer.send('*****@*****.**', people.email.encode('utf-8'),
                        email.encode('utf-8'))

        # add the user
        self.peoplelist[people.login] = people

        # grant him the Member role
        prm = IPrincipalRoleManager(grok.getSite())
        prm.assignRoleToPrincipal('afpy.barcamp.Member', people.login)

        self.redirect('confirmation')
    def handleSave(self, action):
        data, errors = self.extractData()
        if errors:
            self.status = self.formErrorsMessage
            return

        typeName = self.tileType.__name__

        # Traverse to a new tile in the context, with no data
        tile = self.context.restrictedTraverse('@@%s/%s' % (typeName, self.tileId,))

        tile_conf_adapter = getMultiAdapter((self.context, self.request, tile),
                                            ITilesConfigurationScreen)

        tile_conf_adapter.set_configuration(data)

        #dataManager = ITileDataManager(tile)
        #dataManager.set(data)

        # Look up the URL - We need to redirect to the layout view, since
        # there's the only way from where a user would access the configuration
        contextURL = absoluteURL(tile.context, self.request)

        layoutURL = '%s/layoutedit' % contextURL

        notify(ObjectModifiedEvent(tile))

        # Get the tile URL, possibly with encoded data
        IStatusMessage(self.request).addStatusMessage(_(u"Tile configuration saved.",), type=u'info')

        self.request.response.redirect(layoutURL)
Example #52
0
    def action(self, type_name='', id=''):
        if not type_name:
            raise UserError(_(u"You must select the type of object to add."))

        if type_name.startswith('@@'):
            type_name = type_name[2:]

        if '/' in type_name:
            view_name = type_name.split('/', 1)[0]
        else:
            view_name = type_name

        if queryMultiAdapter((self, self.request), name=view_name) is not None:
            url = "%s/%s=%s" % (absoluteURL(self, self.request), type_name, id)
            self.request.response.redirect(url)
            return

        if not self.contentName:
            self.contentName = id

        factory = getUtility(IFactory, type_name)
        content = factory()

        notify(ObjectCreatedEvent(content))

        self.add(content)
        self.request.response.redirect(self.nextURL())
Example #53
0
    def handleSave(self, action):
        data, errors = self.extractData()
        if errors:
            self.status = self.formErrorsMessage
            return

        # Traverse to a new tile in the context, with no data
        typeName = self.tileType.__name__
        tile = self.context.restrictedTraverse('@@{0}/{1}'.format(typeName, self.tileId))

        # We need to check first for existing content in order not not loose
        # fields that weren't sent with the form
        dataManager = ITileDataManager(tile)
        old_data = dataManager.get()
        for item in data:
            old_data[item] = data[item]
        dataManager.set(old_data)

        # notify about modification
        notify(ObjectModifiedEvent(tile))
        api.portal.show_message(_(u'Tile saved'), self.request, type='info')

        # Look up the URL - we need to do this after we've set the data to
        # correctly account for transient tiles
        tileURL = absoluteURL(tile, self.request)
        self.request.response.redirect(tileURL)