Esempio n. 1
0
    def __call__(self):
        data = super(CastleSettingsAdapter, self).__call__()

        if api.user.is_anonymous():
            return data

        folder = self.context
        if not IDexterityContainer.providedBy(folder):
            folder = aq_parent(folder)
        required_upload_fields = self.registry.get(
            'castle.required_file_upload_fields', []) or []
        data.update({
            'data-available-slots':
            json.dumps(self.get_available_slot_tiles()),
            'data-required-file-upload-fields':
            json.dumps(required_upload_fields),
            'data-google-maps-api-key':
            self.registry.get('castle.google_maps_api_key', '') or '',
            'data-folder-url':
            folder.absolute_url()
        })

        show_tour = False
        user = api.user.get_current()
        viewed = user.getProperty('tours_viewed', [])
        if ('all' not in viewed and set(viewed) != set([
                'welcome', 'dashboard', 'foldercontents', 'addcontentinitial',
                'addcontentadd', 'editpage'
        ])):
            show_tour = True

        if show_tour and not api.env.test_mode():
            data['data-show-tour'] = json.dumps({'viewed': viewed})

        folder = self.context
        if not ISiteRoot.providedBy(
                folder) and not IDexterityContainer.providedBy(folder):
            folder = aq_parent(folder)
        site_path = self.site.getPhysicalPath()
        folder_path = folder.getPhysicalPath()
        data['data-base-path'] = '/' + '/'.join(folder_path[len(site_path):])

        real_context = self.context
        if ISiteRoot.providedBy(real_context):
            # we're at site root but actually kind of want context front page
            try:
                real_context = real_context[getDefaultPage(real_context)]
            except (AttributeError, KeyError):
                pass
        if IDashboard.providedBy(real_context):
            real_context = self.site

        transform = theming.getTransform(real_context, self.request)
        if transform is not None:
            data['data-site-layout'] = transform.get_layout_name(real_context)

        data['data-site-default'] = getDefaultPage(self.site) or 'front-page'

        return data
def object_modified(obj, event):
    (modif, names) = _check_modified_fieldname(obj, event)
    if not modif:
        return
    (fti_config, fti) = fti_configuration(obj)
    if not fti_config:
        return

    # We have to reindex sub objects security when a localrolefield is modified
    if IDexterityContainer.providedBy(obj):
        obj.reindexObjectSecurity(skip_self=True)

    # We have to update related objects
    state = get_state(obj)
    # First we remove previous rel annotation for this uid
    if 'static_config' in fti_config:
        related_annot_removal(obj, state, fti_config['static_config'])
    for name in names:
        if name not in fti_config:
            continue
        related_annot_removal(obj, state, fti_config[name])
    # Second we add related roles annotations
    if 'static_config' in fti_config:
        lr_related_role_addition(obj, state, fti_config)
    for name in names:
        if name not in fti_config:
            continue
        related_role_addition(obj, state, fti_config[name], name)
Esempio n. 3
0
    def get(self):
        available = dict([(t.value, t.title)
                          for t in AvailableSiteLayouts(self.context)])
        applied = 'index.html'
        applied_context = getSite()

        context = self.context
        adapted = context_adapted = ILayoutAware(context)
        selected = adapted.pageSiteLayout
        if selected is None:
            context = aq_parent(context)
            while not ISiteRoot.providedBy(context):
                adapted = ILayoutAware(context, None)
                if adapted and adapted.sectionSiteLayout:
                    selected = adapted.sectionSiteLayout
                    break
                context = aq_parent(context)

        if selected:
            applied = selected
            applied_context = context

        return {
            'success': True,
            'available': available,
            'applied': applied,
            'context': utils.get_path(self.context),
            'applied_context': utils.get_path(applied_context),
            'page_layout': context_adapted.pageSiteLayout,
            'section_layout': context_adapted.sectionSiteLayout,
            'folder': IDexterityContainer.providedBy(self.context)
        }
Esempio n. 4
0
def assign_ids(context, tree):
    uid_handler = getToolByName(context, "portal_uidhandler")
    todo = collections.deque([(None, tree)])
    while todo:
        (parent, item) = todo.popleft()
        uid_handler.register(item)
        if INameFromUniqueId.providedBy(item):
            if parent is not None:
                contents = parent.ZopeFind(parent, search_sub=1)
                ids = [int(child[1].id) for child in contents]
            else:
                ids = None
            old_id = item.id
            new_id = get_next_id(context, ids)
            item._setId(new_id)
            if parent is not None:
                # We need to reset the child in its folder to make sure
                # the folder knows of the new id.
                position = parent.getObjectPosition(old_id)
                del parent[old_id]
                parent._setObject(new_id, item, suppress_events=True)
                parent.moveObjectToPosition(new_id, position, True)
        if IDexterityContainer.providedBy(item):
            for gc in item.values():
                todo.append((item, aq_base(gc)))
Esempio n. 5
0
def walk(node):
    for idx, sub_node in node.ZopeFind(node, search_sub=0):
        if ISurvey.providedBy(sub_node):
            yield sub_node
        if IDexterityContainer.providedBy(sub_node):
            for sub_sub_node in walk(sub_node):
                yield sub_sub_node
Esempio n. 6
0
def object_modified(obj, event):
    (modif, names) = _check_modified_fieldname(obj, event)
    if not modif:
        return
    (fti_config, fti) = fti_configuration(obj)
    if not fti_config:
        return

    # We have to reindex sub objects security when a localrolefield is modified
    if IDexterityContainer.providedBy(obj):
        obj.reindexObjectSecurity(skip_self=True)

    # We have to update related objects
    state = get_state(obj)
    # First we remove previous rel annotation for this uid
    if 'static_config' in fti_config:
        related_annot_removal(obj, state, fti_config['static_config'])
    for name in names:
        if name not in fti_config:
            continue
        related_annot_removal(obj, state, fti_config[name])
    # Second we add related roles annotations
    if 'static_config' in fti_config:
        lr_related_role_addition(obj, state, fti_config)
    for name in names:
        if name not in fti_config:
            continue
        related_role_addition(obj, state, fti_config[name], name)
Esempio n. 7
0
    def get_items(self, field='target'):
        target_object = self.get_target_object(field)

        if ICollection.providedBy(target_object):
            return [x for x in target_object.queryCatalog(batch=False)]

        elif IDexterityContainer.providedBy(target_object):
            # Folder Contents
            listing = aq_inner(target_object).restrictedTraverse(
                '@@folderListing', None)

            if listing is None:
                return []

            _ = listing(batch=False)

            # Exclude default page
            _id = target_object.getDefaultPage()

            if _id:
                _ = [x for x in _ if _id != x.getId()]

                # If the box for hiding items that are excluded
                # from navigation is checked, filter them out.
                if self.get_valid_value('exclude_navigation'):
                    _ = [x for x in _ if not x.exclude_from_nav]

            return _
Esempio n. 8
0
    def __call__(self, published_only=False, filter_uids=[]):

        catalog = getToolByName(self.context, 'portal_catalog')
        # First check if there is a flat for a nested folder structure
        is_folderish = False
        for brain in catalog(
            {'path': '/'.join(self.context.getPhysicalPath())}):
            obj = brain.getObject()
            if obj == self.context:
                continue
            if HAVE_DEXTERITY:
                if (IATFolder.providedBy(obj)
                        or IDexterityContainer.providedBy(obj)):
                    is_folderish = True
                    break
            else:
                if IATFolder.providedBy(obj):
                    is_folderish = True
                    break

        if is_folderish:
            return NestedHTMLView(request=self.request,
                                  context=self.context)(published_only,
                                                        filter_uids)
        else:
            return FlatHTMLView(request=self.request,
                                context=self.context)(published_only,
                                                      filter_uids)
Esempio n. 9
0
 def paste_available(self):
     if not IDexterityContainer.providedBy(self.toolbar.real_context):
         return False
     try:
         return self.toolbar.folder.cb_dataValid()
     except AttributeError:
         return True
     return False
Esempio n. 10
0
def _get_children(obj):
    result = []
    if not IDexterityContainer.providedBy(obj):
        return result
    for child in obj.listFolderContents():
        result.append(child)
        result.extend(_get_children(child))
    return result
Esempio n. 11
0
 def get_section(self):
     section = None
     context = self.context
     while not IPloneSiteRoot.providedBy(context):
         section = context
         context = aq_parent(context)
     if section is not None and IDexterityContainer.providedBy(section):
         return section
Esempio n. 12
0
 def getTargetFolder(self):
     target_folder = getattr(self.calendar, 'target_folder', None)
     if target_folder:
         addContext = self.portal.unrestrictedTraverse('/' + self.portal.id + target_folder)
     elif IATFolder.providedBy(self.context) or IDexterityContainer.providedBy(self.context):
         addContext = self.context
     else:
         addContext = aq_parent(aq_inner(self.context))
     return addContext.absolute_url()
Esempio n. 13
0
 def getTargetFolder(self):
     target_folder = getattr(self.calendar, 'target_folder', None)
     if target_folder:
         addContext = self.portal.unrestrictedTraverse('/' + self.portal.id + target_folder)
     elif IATFolder.providedBy(self.context) or IDexterityContainer.providedBy(self.context):
         addContext = self.context
     else:
         addContext = aq_parent(aq_inner(self.context))
     return addContext.absolute_url()
Esempio n. 14
0
    def get_addable_types(self):
        """Return menu item entries in a TAL-friendly form."""
        data = {
            'types': [],
            'templates': []
        }
        idnormalizer = queryUtility(IIDNormalizer)

        constraints = ISelectableConstrainTypes(self.folder, None)
        data['canConstrainTypes'] = False
        if constraints is not None:
            if constraints.canSetConstrainTypes() and \
                    constraints.getDefaultAddableTypes():
                data.update({
                    'canConstrainTypes': True,
                    'constrainUrl': '%s/folder_constraintypes_form' % (
                        self.folder.absolute_url(),)
                })

        site_path = '/'.join(self.site.getPhysicalPath())
        context = self.real_context
        if not IDexterityContainer.providedBy(context):
            context = aq_parent(context)
        folder_path = '/'.join(context.getPhysicalPath())[len(site_path):]
        if not folder_path:
            folder_path = '/'

        for t in self.folder.allowedContentTypes():
            typeId = t.getId()
            data['types'].append({
                'id': typeId,
                'safeId': idnormalizer.normalize(typeId),
                'title': t.Title(),
                'description': t.Description(),
                'folderPath': folder_path
            })

        try:
            site_templates = self.folder.template_list

            for t in site_templates:
                typeId = t.getId()
                data['templates'].append({
                    'id': typeId,
                    'safeId': idnormalizer.normalize(typeId),
                    'title': t.Title(),
                    'description': t.Description(),
                    'folderPath': folder_path
                })
        except AttributeError:
            pass

        return data
def collector(folder, level=1, published_only=False, html=[], filter_uids=[]):

    utils = getToolByName(folder, 'plone_utils')
    wf_tool = getToolByName(folder, 'portal_workflow')

    for brain in folder.getFolderContents({'sort_on' : 'getObjPositionInParent'}):
        obj = brain.getObject()
        LOG.info('Introspecting %s' % obj.absolute_url(1))
        view = obj.restrictedTraverse('@@asHTML', None)

        if view is not None:
            pt = utils.normalizeString(obj.portal_type)
            review_state = wf_tool.getInfoFor(obj, 'review_state')
            if published_only and review_state not in ['published']:
                continue

            is_folderish = False
            if HAVE_DEXTERITY:
                if (IATFolder.providedBy(obj) or IDexterityContainer.providedBy(obj)) and not IArchiveFolder.providedBy(obj):
                    is_folderish = True
            else:
                if IATFolder.providedBy(obj) and not IArchiveFolder.providedBy(obj):
                    is_folderish = True

            if is_folderish:
                html.append('<div class="mode-nested level-%d document-boundary portal-type-folder review-state-%s" path="%s" id="doc-id-%s" document_id="%s" review_state="%s" level="%d" uid="%s">\n' % 
                            (level, review_state, obj.absolute_url(1), obj.getId(), obj.getId(), review_state, level, obj.UID()))
                if IATFolder.providedBy(obj):
                    folder_title = obj.Title()
                    folder_descr = obj.Description()
                else:
                    folder_title = obj.title # Dexterity
                    folder_descr = obj.description
                html.append('<h%d class="title">%s</h%d>' % (level, folder_title, level))
                html.append('<div class="description">%s</div>' % folder_descr)
                collector(obj, level+1, published_only, html)
                html.append('</div>')

            else:
                html.append('<div class="level-%d document-boundary portal-type-%s review-state-%s" path="%s" id="doc-id-%s" document_id="%s" review_state="%s" level="%d" uid="%s">\n' % 
                            (level, pt, review_state, obj.absolute_url(1), obj.getId(), obj.getId(), review_state, level, obj.UID()))
                html.append('<div class="contentinfo">')
                html.append('<div><a class="editlink" href="%s/edit">Edit</a></div>' % obj.absolute_url())
                try:
                    html.append('<div class="review-state">%s</div>' % wf_tool.getInfoFor(obj, 'review_state'))
                except WorkflowException:
                    pass
                html.append('</div>')
                html.append(view())
                html.append('</div>')
        else :
            LOG.warn('No @@asHTML view found for %s' % obj.absolute_url(1))
Esempio n. 16
0
def object(ob):
    state = api.content.get_state(obj=ob, default=None)
    if state is not None and state != 'private':
        try:
            api.content.transition(obj=ob, to_state='private')
        except api.exc.InvalidParameterError:
            pass

    alsoProvides(ob, ITrashed)

    ob.setModificationDate()
    ob.reindexObject(idxs=['trashed', 'object_provides', 'modified'])
    if IDexterityContainer.providedBy(ob):
        tasks.trash_tree.delay(ob)
Esempio n. 17
0
        def collect_objects(folder, level=0, items=[]):
            """ Collect all related subobjects """
            for brain in folder.getFolderContents({'sort_on' : 'getObjPositionInParent'}):
                obj = brain.getObject()

                if IPPContent.providedBy(obj):
                    items.append(dict(obj=obj, level=level))
                else:
                    LOG.warn('IPPContent not provided by %s' % obj.absolute_url(1))

                if HAVE_DEXTERITY:
                    if (IATFolder.providedBy(obj) or IDexterityContainer.providedBy(obj)) and not IArchiveFolder.providedBy(obj):
                        collect_objects(obj, level+1, items)
                else:
                    if IATFolder.providedBy(obj) and not IArchiveFolder.providedBy(obj):
                        collect_objects(obj, level+1, items)
Esempio n. 18
0
def updateContainer(container, layout, ptypes):
    container.unindexObject()
    container.setLayout(layout)
    if IExcludeFromNavigation.providedBy(container):
        container.exclude_from_nav = True
    else:
        container.setExcludeFromNav(True)

    aspect = ISelectableConstrainTypes(container)
    addable = aspect.getImmediatelyAddableTypes()
    for ptype in ptypes:
        if ptype not in addable:
            aspect.setConstrainTypesMode(1)  # select manually
        if IDexterityContainer.providedBy(container):
            #bypass check for available types
            container.immediately_addable_types = ptypes
        else:
            aspect.setImmediatelyAddableTypes(ptypes)
def updateHistoryContainer(obj):
    obj.unindexObject()
    obj.setLayout("collective_history_view")
    if IExcludeFromNavigation.providedBy(obj):
        obj.exclude_from_nav = True
    else:
        obj.setExcludeFromNav(True)

    aspect = ISelectableConstrainTypes(obj)
    addable = aspect.getImmediatelyAddableTypes()
    if "collective.history.useraction" not in addable:
        aspect.setConstrainTypesMode(1)  # select manually
        types = ["collective.history.useraction"]
        if IDexterityContainer.providedBy(obj):
            #bypass check for available types
            obj.immediately_addable_types = types
        else:
            aspect.setImmediatelyAddableTypes(types)
Esempio n. 20
0
def assign_ids(context, tree):
    uid_handler = getToolByName(context, 'portal_uidhandler')
    todo = collections.deque([(None, tree)])
    while todo:
        (parent, item) = todo.popleft()
        uid_handler.register(item)
        if INameFromUniqueId.providedBy(item):
            old_id = item.id
            new_id = get_next_id(context)
            item._setId(new_id)
            if parent is not None:
                # We need to reset the child in its folder to make sure
                # the folder knows of the new id.
                position = parent.getObjectPosition(old_id)
                del parent[old_id]
                parent._setObject(new_id, item, suppress_events=True)
                parent.moveObjectToPosition(new_id, position, True)
        if IDexterityContainer.providedBy(item):
            for gc in item.values():
                todo.append((item, aq_base(gc)))
Esempio n. 21
0
        def collect_objects(folder, level=0, items=[]):
            """ Collect all related subobjects """
            for brain in folder.getFolderContents(
                {'sort_on': 'getObjPositionInParent'}):
                obj = brain.getObject()

                if IPPContent.providedBy(obj):
                    items.append(dict(obj=obj, level=level))
                else:
                    LOG.warn('IPPContent not provided by %s' %
                             obj.absolute_url(1))

                if HAVE_DEXTERITY:
                    if (IATFolder.providedBy(obj)
                            or IDexterityContainer.providedBy(obj)
                        ) and not IArchiveFolder.providedBy(obj):
                        collect_objects(obj, level + 1, items)
                else:
                    if IATFolder.providedBy(
                            obj) and not IArchiveFolder.providedBy(obj):
                        collect_objects(obj, level + 1, items)
Esempio n. 22
0
    def __call__(self, published_only=False, filter_uids=[]):

        catalog = getToolByName(self.context, 'portal_catalog')
        # First check if there is a flat for a nested folder structure
        is_folderish = False
        for brain in catalog({'path' : '/'.join(self.context.getPhysicalPath())}):
            obj = brain.getObject()
            if obj == self.context:
                continue
            if HAVE_DEXTERITY:
                if (IATFolder.providedBy(obj) or IDexterityContainer.providedBy(obj)):
                    is_folderish = True
                    break
            else:
                if IATFolder.providedBy(obj):
                    is_folderish = True
                    break

        if is_folderish:
            return NestedHTMLView(request=self.request, context=self.context)(published_only, filter_uids)
        else:
            return FlatHTMLView(request=self.request, context=self.context)(published_only, filter_uids)
Esempio n. 23
0
    def render(self):
        currentValues = self.value or {}
        criteria = self.getCriteria()
        html = ''
        for fieldid, selectedItems in [(a['i'], a.get('v')) for a in criteria]:
            index = self.context.portal_atct.getIndex(fieldid)
            fieldname = index.friendlyName or index.index
            if selectedItems:
                html += '<br/><b>%s</b><br/><table>' % (fieldname)
                if isinstance(selectedItems, unicode):
                    selectedItems = [selectedItems]
                for item in selectedItems:
                    name = safe_unicode(item)
                    item = str(component.queryUtility(IURLNormalizer).normalize(name))
                    value = ''
                    if fieldid in currentValues \
                      and item in currentValues[fieldid]:
                        value = currentValues[fieldid][item]

                    html += """<tr><td>%s&nbsp;</td><td>
                    <input type="text" size="10" name="%s:record" value="%s"
                           class="colorinput" style="background-color:%s;" />
                    </td></tr>""" % (
                        name,
                        self.name+'.'+fieldid+'.'+item,
                        value, value)

                html+='</table>'
        calendar = ISolgemaFullcalendarProperties(self.context, None)
        gcalSourcesAttr = getattr(calendar, 'gcalSources', '')
        if gcalSourcesAttr != None:
            gcalSources = gcalSourcesAttr.split('\n')
            if gcalSources:
                html += '<br/><b>%s</b><br/><table>' % (_('Google Calendar Sources'))
                fieldid = 'gcalSources'
                for i in range(len(gcalSources)):
                    url = gcalSources[i]
                    item = 'source'+str(i)
                    value = ''
                    if fieldid in currentValues \
                        and item in currentValues[fieldid]:
                        value = currentValues[fieldid][item]

                    html += """<tr><td><span title="%s">%s</span>&nbsp;</td></td><td>
                        <input type="text" size="10" name="%s:record" value="%s"
                               class="colorinput" style="background-color:%s;" />
                        </td></tr>""" % (
                            str(url),
                            'Source '+str(i+1),
                            self.name+'.'+fieldid+'.'+item,
                            value, value)
                html+='</table>'
        availableSubFolders = getattr(calendar, 'availableSubFolders', [])
        if (IATFolder.providedBy(self.context) or IDexterityContainer.providedBy(self.context)) and availableSubFolders:
            html += '<br/><b>%s</b><br/><table>' % (_('Sub-Folders'))
            fieldid = 'subFolders'
            for folderId in availableSubFolders:
                value = ''
                if fieldid in currentValues \
                    and folderId in currentValues[fieldid]:
                    value = currentValues[fieldid][folderId]

                html += """<tr><td><span title="%s">%s</span>&nbsp;</td></td><td>
                    <input type="text" size="10" name="%s:record" value="%s"
                           class="colorinput" style="background-color:%s;" />
                    </td></tr>""" % (
                        folderId,
                        folderId,
                        self.name+'.'+fieldid+'.'+folderId,
                        value, value)
            html+='</table>'

        return html
Esempio n. 24
0
            def recursive_reindex(self, obj):
                for child_obj in obj.listFolderContents():
                    child_obj.reindexObject()

                    if IDexterityContainer.providedBy(child_obj):
                        self.recursive_reindex(child_obj)
Esempio n. 25
0
 def is_folderish(self):
     return IDexterityContainer.providedBy(self.real_context)
Esempio n. 26
0
def collector(folder, level=1, published_only=False, html=[], filter_uids=[]):

    utils = getToolByName(folder, 'plone_utils')
    wf_tool = getToolByName(folder, 'portal_workflow')

    for brain in folder.getFolderContents(
        {'sort_on': 'getObjPositionInParent'}):
        obj = brain.getObject()
        LOG.info('Introspecting %s' % obj.absolute_url(1))
        view = obj.restrictedTraverse('@@asHTML', None)

        if view is not None:
            pt = utils.normalizeString(obj.portal_type)
            review_state = wf_tool.getInfoFor(obj, 'review_state')
            if published_only and review_state not in ['published']:
                continue

            is_folderish = False
            if HAVE_DEXTERITY:
                if (IATFolder.providedBy(obj)
                        or IDexterityContainer.providedBy(obj)
                    ) and not IArchiveFolder.providedBy(obj):
                    is_folderish = True
            else:
                if IATFolder.providedBy(
                        obj) and not IArchiveFolder.providedBy(obj):
                    is_folderish = True

            if is_folderish:
                html.append(
                    '<div class="mode-nested level-%d document-boundary portal-type-folder review-state-%s" path="%s" id="doc-id-%s" document_id="%s" review_state="%s" level="%d" uid="%s">\n'
                    % (level, review_state, obj.absolute_url(1), obj.getId(),
                       obj.getId(), review_state, level, obj.UID()))
                if IATFolder.providedBy(obj):
                    folder_title = obj.Title()
                    folder_descr = obj.Description()
                else:
                    folder_title = obj.title  # Dexterity
                    folder_descr = obj.description
                html.append('<h%d class="title">%s</h%d>' %
                            (level, folder_title, level))
                html.append('<div class="description">%s</div>' % folder_descr)
                collector(obj, level + 1, published_only, html)
                html.append('</div>')

            else:
                html.append(
                    '<div class="level-%d document-boundary portal-type-%s review-state-%s" path="%s" id="doc-id-%s" document_id="%s" review_state="%s" level="%d" uid="%s">\n'
                    %
                    (level, pt, review_state, obj.absolute_url(1), obj.getId(),
                     obj.getId(), review_state, level, obj.UID()))
                html.append('<div class="contentinfo">')
                html.append(
                    '<div><a class="editlink" href="%s/edit">Edit</a></div>' %
                    obj.absolute_url())
                try:
                    html.append('<div class="review-state">%s</div>' %
                                wf_tool.getInfoFor(obj, 'review_state'))
                except WorkflowException:
                    pass
                html.append('</div>')
                html.append(view())
                html.append('</div>')
        else:
            LOG.warn('No @@asHTML view found for %s' % obj.absolute_url(1))
Esempio n. 27
0
def restore(ob):
    noLongerProvides(ob, ITrashed)
    ob.reindexObject(idxs=['trashed', 'object_provides'])
    if IDexterityContainer.providedBy(ob):
        tasks.trash_tree.delay(ob)
Esempio n. 28
0
            def recursive_reindex(self, obj):
                for child_obj in obj.listFolderContents():
                    child_obj.reindexObject()

                    if IDexterityContainer.providedBy(child_obj):
                        self.recursive_reindex(child_obj)
 def is_folderish(self):
     return IDexterityContainer.providedBy(self.real_context)