예제 #1
0
def getParentsFromContextToObject(context, obj):
    """Returns a list starting with the given context's parent followed by
    each of its parents till we reach the object.

    If the child object is not a child of the parent a empty list
    will return.
    """
    # this is a very bad situation. The context could be a NotFound error.
    # Such NotFound objects provide a LocationProxy with the site as parent
    # even if we don't allow the site in our possible parent chain. So skip it.
    if zope.publisher.interfaces.INotFound.providedBy(context):
        return []

    if not isChildOf(context, obj):
        return []
    
    if sameProxiedObjects(context, obj):
        return []

    parents = []
    w = context

    while 1:
        w = w.__parent__
        if sameProxiedObjects(w, obj):
            parents.append(w)
            break
        if w is None:
            break
        
        parents.append(w)

    return parents
예제 #2
0
    def start_imap_service(self):
        """
        Starts imap service.
        """
        from leap.bitmask.config import flags

        logger.debug('Starting imap service')
        leap_assert(sameProxiedObjects(self._soledad, None)
                    is not True,
                    "We need a non-null soledad for initializing imap service")
        leap_assert(sameProxiedObjects(self._keymanager, None)
                    is not True,
                    "We need a non-null keymanager for initializing imap "
                    "service")

        offline = flags.OFFLINE
        self.imap_service, self.imap_port, \
            self.imap_factory = imap.start_imap_service(
                self._soledad,
                self._keymanager,
                userid=self.userid,
                offline=offline)

        if offline is False:
            logger.debug("Starting loop")
            self.imap_service.start_loop()
예제 #3
0
 def renderCells(self, schedule, day, item):
     if sameProxiedObjects(schedule, self.context.periods):
         period = item
         return (period.title,
                 self.activityTitle(period.activity_type) or '')
     if sameProxiedObjects(schedule, self.context.time_slots):
         slot = item
         return (format_time_range(slot.tstart, slot.duration),
                 self.activityTitle(slot.activity_type) or '')
     return None
예제 #4
0
    def breadcrumbs(self):
        context = self.context
        request = self.request

        # We do this here do maintain the rule that we must be wrapped
        context = ILocation(context, context)
        container = getattr(context, '__parent__', None)
        if container is None:
            raise TypeError(_insufficientContext)

        if sameProxiedObjects(context, request.getVirtualHostRoot()) or \
               isinstance(context, Exception):
            return ({'name':'', 'url': self.request.getApplicationURL()}, )

        base = tuple(zope.component.getMultiAdapter(
                (container, request), IAbsoluteURL).breadcrumbs())

        name = getattr(context, '__name__', None)
        if name is None:
            raise TypeError(_insufficientContext)

        if name:
            base += ({'name': name,
                      'url': ("%s/%s" % (base[-1]['url'],
                                         urllib.quote(name.encode('utf-8'),
                                                      _safe)))
                      }, )

        return base
예제 #5
0
 def __str__(self):
     target = removeSecurityProxy(self.context).__target__
     vhostroot = self.request.getVirtualHostRoot()
     if sameProxiedObjects(vhostroot, target):
         return str(AbsoluteURL(target, self.request))
     log.debug("ProxyAwareAbsoluteURL.__str__: %s [%s]", vhostroot, target)
     return super(ProxyAwareAbsoluteURL, self).__str__()
예제 #6
0
    def upperContainer(self):
        request = self.request
        vhr = request.getVirtualHostRoot()
        parent = getattr(self.context, '__parent__', None)

        while True:
            if (parent is None or
                sameProxiedObjects(parent, vhr) or
                IContainmentRoot.providedBy(parent)):
                return None

            if IContentContainer.providedBy(parent):
                url = absoluteURL(parent, request)

                if checkPermission('zojax.ModifyContent', parent):
                    return '%s/@@context.html' % url

                viewName = queryMultiAdapter(
                    (parent, request),
                    IContentViewView
                )
                if viewName:
                    return '%s/%s' % (url, viewName.name)

                return '%s/' % url
            else:
                parent = getattr(parent, '__parent__', None)
예제 #7
0
    def add_container_menu_items(self, context, container):
        request = self.request

        _url = url.absoluteURL(container, request)

        if IReadContainer.providedBy(container):
            #XXX should be the same in all containers ?
            container = proxy.removeSecurityProxy(container)
            for name, item in container.items():
                if context is None:
                    selected = False
                else:
                    selected = url.same_path_names(context.__name__, name)
                item = proxy.removeSecurityProxy(item)
                if IDCDescriptiveProperties.providedBy(item):
                    title = item.title
                else:
                    props = IDCDescriptiveProperties(item)
                    title = props.title
                # only items with valid title
                if title is not None:
                    self.items.append(
                        url.get_menu_item_descriptor(title, selected, _url,
                                                     name))
        default_view_name = queryDefaultViewName(container, self.request)
        default_view = component.queryMultiAdapter((container, self.request),
                                                   name=default_view_name)
        if hasattr(default_view, "title") and default_view.title is not None:
            self.items.insert(
                0,
                url.get_menu_item_descriptor(
                    default_view.title,
                    sameProxiedObjects(container, self.context), _url))
예제 #8
0
    def get_all_docs(self, _type=fields.TYPE_FLAGS_VAL):
        """
        Get all documents for the selected mailbox of the
        passed type. By default, it returns the flag docs.

        If you want acess to the content, use __iter__ instead

        :return: a list of u1db documents
        :rtype: list of SoledadDocument
        """
        if _type not in fields.__dict__.values():
            raise TypeError("Wrong type passed to get_all_docs")

        if sameProxiedObjects(self._soledad, None):
            logger.warning('Tried to get messages but soledad is None!')
            return []

        all_docs = [doc for doc in self._soledad.get_from_index(
            fields.TYPE_MBOX_IDX,
            _type, self.mbox)]

        # inneficient, but first let's grok it and then
        # let's worry about efficiency.
        # XXX FIXINDEX -- should implement order by in soledad
        # FIXME ----------------------------------------------
        return sorted(all_docs, key=lambda item: item.content['uid'])
예제 #9
0
    def breadcrumbs(self):
        context = self.context
        request = self.request

        # We do this here do maintain the rule that we must be wrapped
        context = ILocation(context, context)
        container = getattr(context, '__parent__', None)
        if container is None:
            raise TypeError(_insufficientContext)

        if sameProxiedObjects(context, request.getVirtualHostRoot()) or \
               isinstance(context, Exception):
            return ({'name': '', 'url': self.request.getApplicationURL()}, )

        base = tuple(
            zope.component.getMultiAdapter((container, request),
                                           IAbsoluteURL).breadcrumbs())

        name = getattr(context, '__name__', None)
        if name is None:
            raise TypeError(_insufficientContext)

        if name:
            base += ({
                'name':
                name,
                'url': ("%s/%s" %
                        (base[-1]['url'], quote(name.encode('utf-8'), _safe)))
            }, )

        return base
예제 #10
0
 def add_container_menu_items(self, context, container):
     request = self.request
     
     _url = url.absoluteURL(container, request)
     
     if IReadContainer.providedBy(container):
         #XXX should be the same in all containers ?
         container=proxy.removeSecurityProxy(container)
         for name, item in container.items():
             if context is None:
                 selected = False
             else:
                 selected = url.same_path_names(context.__name__, name)
             item = proxy.removeSecurityProxy(item)
             if IDCDescriptiveProperties.providedBy(item):
                 title = item.title
             else:
                 props = IDCDescriptiveProperties(item)
                 title = props.title
             # only items with valid title
             if title is not None:
                 self.items.append(url.get_menu_item_descriptor(
                         title, selected, _url, name))
     default_view_name = queryDefaultViewName(container, self.request)
     default_view = component.queryMultiAdapter(
         (container, self.request), name=default_view_name)
     if hasattr(default_view, "title") and default_view.title is not None:
         self.items.insert(0, url.get_menu_item_descriptor(
                 default_view.title, 
                 sameProxiedObjects(container, self.context), 
                 _url))
예제 #11
0
def contained(obj, parent=None, name=None):
    """An implementation of zope.app.container.contained.contained
    that doesn't generate events, for internal use.

    copied from SQLOS / z3c.zalchemy
    """
    if (parent is None):
        raise TypeError('Must provide a parent')

    if not IContained.providedBy(obj):
        if ILocation.providedBy(obj):
            interface.directlyProvides(obj, IContained,
                                       interface.directlyProvidedBy(obj))
        else:
            obj = ContainedProxy(obj)

    oldparent = obj.__parent__
    oldname = obj.__name__

    if (oldparent is None) or not (oldparent is parent
                                   or sameProxiedObjects(oldparent, parent)):
        obj.__parent__ = parent

    if oldname != name and name is not None:
        obj.__name__ = name

    return obj
예제 #12
0
    def isAvailable(self):
        if super(ErrorConfiglet, self).isAvailable():
            sm = IComponentLookup(getUtility(IErrorReportingUtility))
            if sameProxiedObjects(sm, getSite().getSiteManager()) or \
                IFolder.providedBy(getSite().__parent__):
                return True

        return False
예제 #13
0
    def isInstalled(self):
        sm = getSiteManager()

        auth = sm.getUtility(IAuthentication)
        if not IPluggableAuthentication.providedBy(auth):
            return False

        return sameProxiedObjects(IComponentLookup(auth), sm)
예제 #14
0
파일: term.py 프로젝트: l1ph0x/schooltool-2
def validateTermsForOverlap(sy, dr, term):
    overlapping_terms = []
    for other_term in sy.values():
        if (not sameProxiedObjects(other_term, term)
                and dr.overlaps(IDateRange(other_term))):
            overlapping_terms.append(other_term)
            if overlapping_terms:
                raise TermOverlapError(term, overlapping_terms)
예제 #15
0
 def visible(self):
     if not checkPermission("schooltool.edit", self.container):
         return False
     authenticated = IPerson(self.request.principal, None)
     target = IPerson(self.context, None)
     if sameProxiedObjects(authenticated, target):
         return False
     return True
예제 #16
0
 def visible(self):
     if not checkPermission("schooltool.edit", self.container):
         return False
     authenticated = IPerson(self.request.principal, None)
     target = IPerson(self.context, None)
     if sameProxiedObjects(authenticated, target):
         return False
     return True
예제 #17
0
 def listTerms(self):
     first, last = self.terms
     result = [first]
     next = getNextTerm(first)
     while (next is not None and not sameProxiedObjects(result[-1], next)):
         result.append(next)
         next = getNextTerm(next)
     return result
예제 #18
0
def validateTermsForOverlap(sy, dr, term):
    overlapping_terms = []
    for other_term in sy.values():
        if (not sameProxiedObjects(other_term, term) and
            dr.overlaps(IDateRange(other_term))):
            overlapping_terms.append(other_term)
            if overlapping_terms:
                raise TermOverlapError(term,
                                       overlapping_terms)
예제 #19
0
 def __call__(self):
     app = ISchoolToolApplication(None)
     # XXX: extremely nasty loop through all schedules.
     schedule_containers = app[SCHEDULES_KEY]
     for container in schedule_containers.values():
         for schedule in container.values():
             if (interfaces.ISelectedPeriodsSchedule.providedBy(schedule) and
                 sameProxiedObjects(schedule.timetable, self.object)):
                 del container[schedule.__name__]
예제 #20
0
def validateScholYearsForOverlap(syc, dr, schoolyear):
    overlapping_schoolyears = []
    for other_schoolyear in syc.values():
        if (not sameProxiedObjects(other_schoolyear, schoolyear) and
            dr.overlaps(IDateRange(other_schoolyear))):
            overlapping_schoolyears.append(other_schoolyear)
            if overlapping_schoolyears:
                raise SchoolYearOverlapError(schoolyear,
                                             overlapping_schoolyears)
 def listTerms(self):
     first, last = self.terms
     result = [first]
     next = getNextTerm(first)
     while (next is not None and
            not sameProxiedObjects(result[-1], next)):
         result.append(next)
         next = getNextTerm(next)
     return result
예제 #22
0
    def updateSection(self,
                      section,
                      term,
                      course,
                      instructor,
                      periods,
                      dry_run=True):
        """Create a section.

        `periods` is a list of tuples (day_id, period_id).

        A title is generated from the titles of `course` and `instructor`.
        If an existing section with the same title is found, it is used instead
        of creating a new one.

        The created section is returned, or None if dry_run is True.
        """
        if dry_run:
            return None

        # Establish links to course and to teacher
        for c in list(section.courses):
            if c is not course:
                section.remove(c)
        if course not in section.courses:
            section.courses.add(course)
        for i in list(section.instructors):
            if i is not instructor:
                section.instructor.remove(i)
        if instructor not in section.instructors:
            section.instructors.add(instructor)

        timetable_container = ITimetableContainer(self.schoolyear)
        timetables = [timetable_container[ttid] for ttid in sorted(periods)]
        schedules = IScheduleContainer(section)
        for timetable in timetables:
            selected = periods[timetable.__name__]
            schedule = None
            for s in schedules.values():
                if sameProxiedObjects(s.timetable, timetable):
                    schedule = s
                    break
            if schedule is None:
                schedule = SelectedPeriodsSchedule(timetable,
                                                   term.first,
                                                   term.last,
                                                   title=timetable.title,
                                                   timezone=timetable.timezone)
                for period in selected:
                    schedule.addPeriod(period)
                schedules[timetable.__name__] = schedule
            else:
                for period in schedule.periods:
                    if period not in selected:
                        schedule.removePeriod(period)
                for period in selected:
                    schedule.addPeriod(period)
예제 #23
0
def validateScholYearsForOverlap(syc, dr, schoolyear):
    overlapping_schoolyears = []
    for other_schoolyear in syc.values():
        if (not sameProxiedObjects(other_schoolyear, schoolyear)
                and dr.overlaps(IDateRange(other_schoolyear))):
            overlapping_schoolyears.append(other_schoolyear)
            if overlapping_schoolyears:
                raise SchoolYearOverlapError(schoolyear,
                                             overlapping_schoolyears)
예제 #24
0
 def renderCells(self, schedule, day, item):
     timetable = self.context.timetable
     if sameProxiedObjects(schedule, timetable.periods):
         if self.context.hasPeriod(item):
             return (item.title,
                     self.owner.title)
         else:
             return (item.title, '')
     return None
예제 #25
0
    def __call__(self):
        if (self.event.first is None or self.event.second is None):
            return  # unlinking sections

        first_term = ITerm(self.event.first)
        second_term = ITerm(self.event.second)
        if sameProxiedObjects(first_term, second_term):
            raise InvalidSectionLinkException(
                _("Cannot link sections in same term"))

        if not sameProxiedObjects(ISchoolYear(first_term),
                                  ISchoolYear(second_term)):
            raise InvalidSectionLinkException(
                _("Cannot link sections in different school years"))

        if not sameProxiedObjects(getNextTerm(first_term), second_term):
            raise InvalidSectionLinkException(
                _("Sections must be in consecutive terms"))
예제 #26
0
    def isInstalled(self):
        container = queryUtility(ISessionDataContainer)
        if container is not None:
            if container.__class__ == PersistentSessionDataContainer and \
                    sameProxiedObjects(
                IComponentLookup(container), getSiteManager()):
                return True

        return False
예제 #27
0
    def add_container_menu_items(self, context, container):
        request = self.request
        # add a menu item for each user workspace, if we are in an
        # IWorkspaceSectionLayer
        # !+ if user is logged in or if request.layer_data

        if (interfaces.IWorkspaceSectionLayer.providedBy(request)
                or interfaces.IWorkspaceSchedulingSectionLayer.providedBy(
                    request)):
            try:
                workspaces = IAnnotations(request)["layer_data"].get(
                    "workspaces")
            except:
                workspaces = []
            log.info("%s got user workspaces: %s" % (self, workspaces))
            base_url_path = "/workspace"
            for workspace in workspaces:
                log.info("appending menu item for user workspace: %s" %
                         str(workspace))
                self.items.append(
                    url.get_menu_item_descriptor(
                        workspace.full_name,
                        pos_action_in_url(
                            "/workspace/obj-%s" % workspace.group_id,
                            request.getURL()), base_url_path,
                        "obj-%s" % workspace.group_id))

        _url = url.absoluteURL(container, request)

        if IReadContainer.providedBy(container):
            #XXX should be the same in all containers ?
            container = proxy.removeSecurityProxy(container)
            for name, item in container.items():
                if context is None:
                    selected = False
                else:
                    selected = url.same_path_names(context.__name__, name)
                item = proxy.removeSecurityProxy(item)
                if IDCDescriptiveProperties.providedBy(item):
                    title = item.title
                else:
                    props = IDCDescriptiveProperties(item)
                    title = props.title
                # only items with valid title
                if title is not None:
                    self.items.append(
                        url.get_menu_item_descriptor(title, selected, _url,
                                                     name))
        default_view_name = queryDefaultViewName(container, self.request)
        default_view = component.queryMultiAdapter((container, self.request),
                                                   name=default_view_name)
        if hasattr(default_view, "title") and default_view.title is not None:
            self.items.insert(
                0,
                url.get_menu_item_descriptor(
                    default_view.title,
                    sameProxiedObjects(container, self.context), _url))
예제 #28
0
    def isInstalled(self):
        container = queryUtility(ISessionDataContainer)
        if container is not None:
            if isinstance(container, MemCachedSessionDataContainer) and \
                    sameProxiedObjects(
                IComponentLookup(container), getSiteManager()):
                return True

        return False
예제 #29
0
 def __call__(self):
     app = ISchoolToolApplication(None)
     # XXX: extremely nasty loop through all schedules.
     schedule_containers = app[SCHEDULES_KEY]
     for container in schedule_containers.values():
         for schedule in container.values():
             if (interfaces.ISelectedPeriodsSchedule.providedBy(schedule)
                     and sameProxiedObjects(schedule.timetable,
                                            self.object)):
                 del container[schedule.__name__]
예제 #30
0
    def __call__(self):
        if (self.event.first is None or
            self.event.second is None):
            return # unlinking sections

        first_term = ITerm(self.event.first)
        second_term = ITerm(self.event.second)
        if sameProxiedObjects(first_term, second_term):
            raise InvalidSectionLinkException(
                _("Cannot link sections in same term"))

        if not sameProxiedObjects(ISchoolYear(first_term),
                                  ISchoolYear(second_term)):
            raise InvalidSectionLinkException(
                _("Cannot link sections in different school years"))

        if not sameProxiedObjects(getNextTerm(first_term), second_term):
            raise InvalidSectionLinkException(
                _("Sections must be in consecutive terms"))
예제 #31
0
    def start_imap_service(self):
        """
        Starts imap service.
        """
        logger.debug('Starting imap service')
        leap_assert(sameProxiedObjects(self._soledad, None)
                    is not True,
                    "We need a non-null soledad for initializing imap service")
        leap_assert(sameProxiedObjects(self._keymanager, None)
                    is not True,
                    "We need a non-null keymanager for initializing imap "
                    "service")

        self.imap_service, self.imap_port, \
            self.imap_factory = imap.start_imap_service(
                self._soledad,
                self._keymanager,
                userid=self.userid)
        self.imap_service.start_loop()
    def __init__(self, user, keymanager, soledad):
        """
        :param user: the current logged in user.
        :type user: unicode
        :param keymanager: the existing keymanager instance
        :type keymanager: KeyManager
        :param soledad: a loaded instance of Soledad
        :type soledad: Soledad
        """
        QtGui.QWidget.__init__(self)

        self.ui = Ui_AdvancedKeyManagement()
        self.ui.setupUi(self)

        # XXX: Temporarily disable the key import.
        self.ui.pbImportKeys.setVisible(False)

        # if Soledad is not started yet
        if sameProxiedObjects(soledad, None):
            self.ui.gbMyKeyPair.setEnabled(False)
            self.ui.gbStoredPublicKeys.setEnabled(False)
            msg = self.tr("<span style='color:#0000FF;'>NOTE</span>: "
                          "To use this, you need to enable/start {0}.")
            msg = msg.format(get_service_display_name(MX_SERVICE))
            self.ui.lblStatus.setText(msg)
            return
        # XXX: since import is disabled this is no longer a dangerous feature.
        # else:
        #     msg = self.tr(
        #         "<span style='color:#ff0000;'>WARNING</span>:<br>"
        #         "This is an experimental feature, you can lose access to "
        #         "existing e-mails.")
        #     self.ui.lblStatus.setText(msg)

        self._keymanager = keymanager
        self._soledad = soledad

        self._key = keymanager.get_key(user, openpgp.OpenPGPKey)
        self._key_priv = keymanager.get_key(
            user, openpgp.OpenPGPKey, private=True)

        # show current key information
        self.ui.leUser.setText(user)
        self.ui.leKeyID.setText(self._key.key_id)
        self.ui.leFingerprint.setText(self._key.fingerprint)

        # set up connections
        self.ui.pbImportKeys.clicked.connect(self._import_keys)
        self.ui.pbExportKeys.clicked.connect(self._export_keys)

        # Stretch columns to content
        self.ui.twPublicKeys.horizontalHeader().setResizeMode(
            0, QtGui.QHeaderView.Stretch)

        self._list_keys()
예제 #33
0
 def add(self, principal, bug, *args):
     if sameProxiedObjects(principal, self.person):
         collection = self.personal
     else:
         assert principal.is_team, (principal, self.person)
         if principal.id in self.administrated_team_ids:
             collection = self.as_team_admin
         else:
             collection = self.as_team_member
     self._add_item_to_collection(
         collection, principal, bug, *args)
 def add(self, principal, bug, *args):
     if sameProxiedObjects(principal, self.person):
         collection = self.personal
     else:
         assert principal.is_team, (principal, self.person)
         if principal.id in self.administrated_team_ids:
             collection = self.as_team_admin
         else:
             collection = self.as_team_member
     self._add_item_to_collection(
         collection, principal, bug, *args)
예제 #35
0
    def add_container_menu_items(self, context, container):
        request = self.request
        # add a menu item for each user workspace, if we are in an
        # IWorkspaceSectionLayer
        # !+ if user is logged in or if request.layer_data
        if interfaces.IWorkspaceSectionLayer.providedBy(request):
            try:
                workspaces = IAnnotations(request)["layer_data"].get(
                    "workspaces")
            except:
                workspaces = []
            log.info("%s got user workspaces: %s" % (self, workspaces))
            base_url_path = "/workspace"
            for workspace in workspaces:
                log.info("appending menu item for user workspace: %s" %
                         str(workspace))
                self.items.append(
                    url.get_menu_item_descriptor(
                        workspace.full_name,
                        pos_action_in_url(
                            "/workspace/obj-%s" % workspace.group_id,
                            request.getURL()), base_url_path,
                        "obj-%s" % workspace.group_id))

        _url = url.absoluteURL(container, request)

        if IReadContainer.providedBy(container):
            #XXX should be the same in all containers ?
            container = proxy.removeSecurityProxy(container)
            for name, item in container.items():
                if context is None:
                    selected = False
                else:
                    selected = url.same_path_names(context.__name__, name)
                item = proxy.removeSecurityProxy(item)
                if IDCDescriptiveProperties.providedBy(item):
                    title = item.title
                else:
                    props = IDCDescriptiveProperties(item)
                    title = props.title
                # only items with valid title
                if title is not None:
                    self.items.append(
                        url.get_menu_item_descriptor(title, selected, _url,
                                                     name))
        default_view_name = queryDefaultViewName(container, self.request)
        default_view = component.queryMultiAdapter((container, self.request),
                                                   name=default_view_name)
        if hasattr(default_view, "title") and default_view.title is not None:
            self.items.insert(
                0,
                url.get_menu_item_descriptor(
                    default_view.title,
                    sameProxiedObjects(container, self.context), _url))
예제 #36
0
 def renderCells(self, schedule, day, item):
     timetable = self.context.timetable
     if sameProxiedObjects(schedule, timetable.periods):
         checked = self.context.hasPeriod(item)
         key = self.getPeriodKey(day, item)
         checkbox = """
           <input class="activity" type="checkbox"
                  id="%(key)s" name="%(key)s"
                  value="%(key)s"%(checked)s></input>""" % {
             'key': key,
             'checked': checked and ' checked="checked"' or ''}
         label = """
           <label class="period" for="%(key)s">%(title)s</label>""" % {
             'key': key, 'title': item.title or ''}
         return (checkbox, label)
     if sameProxiedObjects(schedule, timetable.time_slots):
         slot = item
         return (format_time_range(slot.tstart, slot.duration),
                 self.activityTitle(slot.activity_type) or '')
     return None
예제 #37
0
 def _getCurrentOwnerId(self):
     settings = self._rolemanager.getPrincipalsForRole(OWNER_ROLE)
     principals = [
         principal_id for (principal_id, setting) in settings
         if sameProxiedObjects(setting, Allow)
     ]
     if not principals:
         return None
     if len(principals) > 1:
         raise RuntimeError(
             'Object has multiple owners. This should not happen')
     return principals[0]
예제 #38
0
 def __call__(self):
     app = ISchoolToolApplication(None)
     # XXX: extremely nasty loop through all schedules.
     schedule_containers = app[SCHEDULES_KEY]
     for container in schedule_containers.values():
         notify_container = False
         for schedule in container.values():
             if (interfaces.ISelectedPeriodsSchedule.providedBy(schedule) and
                 sameProxiedObjects(schedule.timetable, self.object)):
                 notify_container = True
         if notify_container:
             zope.lifecycleevent.modified(container)
예제 #39
0
 def iterOriginalMeetings(self, date, until_date=None):
     if until_date is None:
         until_date = date
     meetings = []
     for schedule in self.values():
         if not sameProxiedObjects(schedule.__parent__, self):
             # We are likely in the process of deleting/moving
             # this schedule.  Ignore.
             continue
         tt_meetings = iterMeetingsInTimezone(
             schedule, self.timezone, date, until_date=until_date)
         meetings.extend(list(tt_meetings))
     return sorted(meetings, key=lambda m: m.dtstart)
예제 #40
0
    def __str__(self):
        context = self.context
        request = self.request

        if sameProxiedObjects(context, request.getVirtualHostRoot()):
            return request.getApplicationURL()

        url = request.getApplicationURL()
        name = getattr(context, '__name__', None)
        if name:
            url += '/' + quote(name.encode('utf-8'), _safe)

        return url
예제 #41
0
    def __str__(self):
        context = self.context
        request = self.request

        if sameProxiedObjects(context, request.getVirtualHostRoot()):
            return request.getApplicationURL()

        url = request.getApplicationURL()
        name = getattr(context, "__name__", None)
        if name:
            url += "/" + urllib.quote(name.encode("utf-8"), _safe)

        return url
예제 #42
0
    def reply(self, title, text, message):
        oid = message['In-Reply-To'].split('@', 1)[0].split('.', 1)[0][1:]
        try:
            topic = getUtility(IIntIds).getObject(int(oid))
        except:
            return

        if not sameProxiedObjects(topic.__parent__, self.context):
            return

        if checkPermission('zojax.forum.AddMessage', topic):
            ct = getUtility(IContentType, 'forum.message').__bind__(topic)
            ct.add(ct.create(title=title, text=text))
예제 #43
0
 def __call__(self):
     app = ISchoolToolApplication(None)
     # XXX: extremely nasty loop through all schedules.
     schedule_containers = app[SCHEDULES_KEY]
     for container in schedule_containers.values():
         notify_container = False
         for schedule in container.values():
             if (interfaces.ISelectedPeriodsSchedule.providedBy(schedule)
                     and sameProxiedObjects(schedule.timetable,
                                            self.object)):
                 notify_container = True
         if notify_container:
             zope.lifecycleevent.modified(container)
예제 #44
0
def getParentsFromContextToObject(context, obj):
    """Returns a list starting with the given context's parent followed by
    each of its parents till we reach the object.

    """
    if sameProxiedObjects(context, obj):
        return []

    parents = []
    w = context

    while 1:
        w = w.__parent__
        if sameProxiedObjects(w, obj):
            parents.append(w)
            break
        if w is None:
            break

        parents.append(w)

    return parents
예제 #45
0
 def iterOriginalMeetings(self, date, until_date=None):
     if until_date is None:
         until_date = date
     meetings = []
     for schedule in self.values():
         if not sameProxiedObjects(schedule.__parent__, self):
             # We are likely in the process of deleting/moving
             # this schedule.  Ignore.
             continue
         tt_meetings = iterMeetingsInTimezone(schedule,
                                              self.timezone,
                                              date,
                                              until_date=until_date)
         meetings.extend(list(tt_meetings))
     return sorted(meetings, key=lambda m: m.dtstart)
예제 #46
0
    def test_oauth_access_token_for_retrieves_existing_token(self):
        # If there's already a token for a
        # user/consumer key/permission/context, it's retrieved.
        person = self.factory.makePerson()
        self.assertEquals(person.oauth_access_tokens.count(), 0)
        access_token = oauth_access_token_for(
            self.consumer.key, person, OAuthPermission.WRITE_PUBLIC,
            self.context)
        self.assertEquals(person.oauth_access_tokens.count(), 1)

        access_token_2 = oauth_access_token_for(
            access_token.consumer.key, access_token.person,
            access_token.permission, access_token.context)
        self.assertEquals(person.oauth_access_tokens.count(), 1)
        self.assertTrue(sameProxiedObjects(access_token, access_token_2))
예제 #47
0
    def breadcrumbs(self):
        context = self.context
        request = self.request

        if sameProxiedObjects(context, request.getVirtualHostRoot()):
            return ({'name': '', 'url': self.request.getApplicationURL()}, )

        base = ({'name': '', 'url': self.request.getApplicationURL()}, )

        name = getattr(context, '__name__', None)
        if name:
            base += ({'name': name,
                      'url': ("%s/%s" % (base[-1]['url'],
                                         quote(name.encode('utf-8'), _safe)))
                      }, )

        return base
예제 #48
0
 def send(self, sender=None, recipients=None):
     self.sender = sender
     if recipients is not None:
         self.recipients = recipients
     self.updated_on = self.utcnow
     app = ISchoolToolApplication(None)
     messages = IMessageContainer(app)
     if self.__name__:
         if (self.__name__ in messages):
             if (sameProxiedObjects(messages[self.__name__], self)):
                 return  # already sent
             del messages[self.__name__]
         messages[self.__name__] = self
     else:
         name_chooser = INameChooser(messages)
         name = name_chooser.chooseName('', self)
         messages[name] = self
예제 #49
0
    def load_and_sync_soledad(self, uuid=None, offline=False):
        """
        Once everthing is in the right place, we instantiate and sync
        Soledad

        :param uuid: the uuid of the user, used in offline mode.
        :type uuid: unicode, or None.
        :param offline: whether to instantiate soledad for offline use.
        :type offline: bool
        """
        local_param = self._get_soledad_local_params(uuid, offline)
        remote_param = self._get_soledad_server_params(uuid, offline)

        secrets_path, local_db_path, token = local_param
        server_url, cert_file = remote_param

        try:
            self._do_soledad_init(uuid, secrets_path, local_db_path,
                                  server_url, cert_file, token)
        except SoledadInitError:
            # re-raise the exceptions from try_init,
            # we're currently handling the retries from the
            # soledad-launcher in the gui.
            raise

        leap_assert(not sameProxiedObjects(self._soledad, None),
                    "Null soledad, error while initializing")

        if flags.OFFLINE:
            self._init_keymanager(self._address, token)
        else:
            try:
                address = make_address(self._user,
                                       self._provider_config.get_domain())
                self._init_keymanager(address, token)
                self._keymanager.get_key(address,
                                         openpgp.OpenPGPKey,
                                         private=True,
                                         fetch_remote=False)
                d = threads.deferToThread(self._do_soledad_sync)
                d.addErrback(self._soledad_sync_errback)
            except KeyNotFound:
                logger.debug("Key not found. Generating key for %s" %
                             (address, ))
                self._do_soledad_sync()
예제 #50
0
 def importAllTimetables(self):
     if not self.shouldImportAllTimetables():
         return
     oldTimetables = ITimetableContainer(self.activeSchoolyear)
     newTimetables = ITimetableContainer(self.newSchoolyear)
     chooser = INameChooser(newTimetables)
     app = ISchoolToolApplication(None)
     tzname = IApplicationPreferences(app).timezone
     for schooltt in oldTimetables.values():
         newSchooltt = Timetable(self.newSchoolyear.first,
                                 self.newSchoolyear.last,
                                 title=schooltt.title,
                                 timezone=tzname)
         name = chooser.chooseName(schooltt.__name__, newSchooltt)
         newTimetables[name] = newSchooltt
         self.setUpTimetable(newSchooltt, schooltt)
         if (oldTimetables.default is not None
                 and sameProxiedObjects(oldTimetables.default, schooltt)):
             newTimetables.default = newSchooltt
예제 #51
0
    def add_zcml_menu_items(self, container):
        """Add the list of ZCML menu items (if any) for this top-level 
        container. Top-level section given by container may define a menu 
        in ZCML with naming convention: <container_name>_navigation. 
        """
        # !+ turn this into a utility
        zcml_menu_name_template = "%s_navigation"
        try:
            menu_name = zcml_menu_name_template % container.__name__
            menu = component.getUtility(IBrowserMenu, name=menu_name)
            items = menu.getMenuItems(container, self.request)
        except (Exception, ):
            debug.log_exc(sys.exc_info(), log_handler=log.debug)
            return []

        # OK, do any necessary post-processing of each menu item
        local_url = url.absoluteURL(container, self.request)
        site_url = url.absoluteURL(getSite(), self.request)
        request_url = self.request.getURL()
        default_view_name = queryDefaultViewName(container, self.request)
        selection = None
        for item in sorted(items,
                           key=lambda item: item["action"],
                           reverse=True):
            action = item["action"]
            if default_view_name == action.lstrip("@@"):
                _url = local_url
                if selection is None:
                    selected = sameProxiedObjects(container, self.context)
            else:
                _url = make_absolute(action, local_url, site_url)
                if selection is None:
                    selected = pos_action_in_url(action, request_url)
            item["url"] = _url
            item["selected"] = selected and u"selected" or u""
            if selected:
                # self is marker
                selection = self
                selected = False
            self.items.append(item)
예제 #52
0
    def _load_soledad_online(self, uuid, secrets_path, local_db_path,
                             server_url, cert_file, token):
        syncable = True
        try:
            self._do_soledad_init(uuid, secrets_path, local_db_path,
                                  server_url, cert_file, token, syncable)
        except SoledadInitError as e:
            # re-raise the exceptions from try_init,
            # we're currently handling the retries from the
            # soledad-launcher in the gui.
            return defer.fail(e)

        leap_assert(not sameProxiedObjects(self._soledad, None),
                    "Null soledad, error while initializing")

        address = make_address(self._user, self._provider_config.get_domain())
        syncer = Syncer(self._soledad, self._signaler)

        d = self._init_keymanager(address, token)
        d.addCallback(lambda _: syncer.sync())
        d.addErrback(self._soledad_sync_errback)
        return d
예제 #53
0
def applyStackConsumers(context, request):
    if CONSUMED_ANNOTATION_KEY not in request.annotations:
        request.annotations[CONSUMED_ANNOTATION_KEY] = []
        request.annotations[CONSUMERS_ANNOTATION_KEY] = []
    else:
        for obj, consumed in request.annotations[CONSUMED_ANNOTATION_KEY]:
            if sameProxiedObjects(obj, context):
                return
    orgStack = request.getTraversalStack()
    cons = [cons for name, cons in getStackConsumers(context, request)]
    newStack = request.getTraversalStack()
    if newStack != orgStack:
        consumed = request.annotations[CONSUMED_ANNOTATION_KEY]
        numItems = len(orgStack) - len(newStack)
        vhStack = VHStack(request)
        vhStack.prepare()
        stack = request.getTraversalStack()
        items = orgStack[len(stack):len(stack) + numItems]
        vhStack.reset()
        items.reverse()
        consumed.append((context, items))
    request.annotations[CONSUMERS_ANNOTATION_KEY].extend(cons)
예제 #54
0
    def getCalendars(self):
        """Get a list of calendars to display.

        Yields tuples (calendar, color1, color2).
        """

        owner = self.context.__parent__

        user = IPerson(self.request.principal, None)
        if (user is not None and sameProxiedObjects(user, owner)):
            return

        instructs = list(
            getRelatedObjects(owner, URISection, rel_type=URIInstruction))
        member_of = list(
            getRelatedObjects(owner, URIGroup, rel_type=URIMembership))

        for obj in instructs + member_of:
            if IHaveSchedule.providedBy(obj):
                cal = ISchoolToolCalendar(obj, None)
                if cal is not None:
                    yield (ISchoolToolCalendar(obj), '#9db8d2', '#7590ae')