def getCitationInfo(self):
        """ Gets the citation information """

        # Title
        title = self.context.title

        # Creators
        creator = ''
        index = 1
        
        names = [name.strip() for name in self.context.Creators()]
        
        for cr in names:
            if cr and '@' == cr[0]:
                creator += '%s, ' %cr[1:]
            else:
                inits = ''
                crs = []
                crs = cr.split(' ')
                for part in crs[:-1]:
                    inits += ' ' + part[0] + '.'   
                creator += crs[-1]
                if inits:
                    creator += "," + inits
                creator += ', '
                index += 1
            
        if creator:
            creator = creator[:-2]
            if creator:
                if creator[-1] != '.':
                    creator += '.'
         
        id = self.context.getId()
        portal_url = getToolByName(self.context, 'portal_url')
        portal_name = portal_url.getPortalObject().title
	# TODO: Adds support at format date on every languages at this string
        create_date = self.context.creation_date.strftime('%Y, %B %d')
        url = self.context.absolute_url()
        date = datetime.date.today().strftime('%B %d, %Y')
        
        ts = getToolByName(self.context, 'translation_service') 
        if creator:
            prompt_text = ts.translate(
                _(u"%s (%s). %s. Retrieved %s, from %s Web site: %s.")
            ) % (
                unicode_sanitize(creator),
                create_date,unicode_sanitize(title),
                date,unicode_sanitize(portal_name),url
            )
        else:
            prompt_text = ts.translate(
                _(u"%s. (%s). Retrieved %s, from %s Web site: %s.")
            ) % (
                unicode_sanitize(title),
                create_date,date,unicode_sanitize(portal_name),
                url
            )

        return prompt_text.replace('\'','\\\'').replace('\"','\\\'')
Beispiel #2
0
    def getGravatar(self, reply):
        purl = getToolByName(self.context, 'portal_url')
        default = purl() + '/defaultUser.gif' 
        email = ''

        creator = reply.Creator()
        if creator and not creator=='Anonymous User':
            mtool = getToolByName(self.context, "portal_membership")
            member = mtool.getMemberById(creator)
            email = member and member.getProperty('email','') or ''
            portrait = mtool.getPersonalPortrait(creator)
            if portrait.getId() != default_portrait:
                return portrait.absolute_url()
        else:
            email = reply.getProperty('email',d='')
        if not email:
            return default

        size = 40
        gravatar_url = "http://www.gravatar.com/avatar.php?"
        # construct the url
        gravatar_url += urllib.urlencode({'gravatar_id':md5.md5(email).hexdigest(), 
            'default':default, 'size':str(size)})

        return gravatar_url
Beispiel #3
0
def get_groups(username=None, user=None):
    """Get a list of groups that this user is a member of.

    Arguments ``username`` and ``user`` are mutually exclusive. You can either
    set one or the other, but not both.

    :param username: Username of the user for which to return groups.
    :type username: string
    :param user: User for which to return groups.
    :type user: MemberData object
    :returns: List of names of groups this user is a member of.
    :rtype: List of strings
    :Example: :ref:`get_groups_for_user_example`
    """
    if not username and not user:
        raise ValueError

    if username and user:
        raise ValueError

    site = getSite()

    if username:
        user = getToolByName(site, 'portal_membership').getMemberById(username)
    return getToolByName(site, 'portal_groups').getGroupsForPrincipal(user)
def write_folder_order(self):
    """ Write folder order
    """
    catalog = getToolByName(self, "portal_catalog")

    ttool = getToolByName(self, 'portal_types')
    cmf_meta_types = ttool.listContentTypes(by_metatype=1)


    images = catalog.searchResults(portal_type="Image")
    files = catalog.searchResults(portal_type="File")

    out = open("/tmp/out.pickle", "w")

    parents = set()
    for brain in images + files:
        path = brain.getPath()
        parent = path[:path.rfind('/')]
        parents.add(parent)

    result = {}
    for path in parents:
        logger.info("Recording %s", path)
        folder = self.restrictedTraverse(path)
        objs = folder.getFolderContents(full_objects=True)
        # objs = [o for o in folder.objectValues() if hasattr(o, 'meta_type')]
        ids = getCMFObjectsSubsetIds(objs, cmf_meta_types)
        result[path] = ids

    cPickle.dump(result, out)
    out.close()

    return "Done export"
Beispiel #5
0
    def update(self):
        if self.status:
            self._getStatus()
            return

        if self.projectId is not None:
            reference_catalog = getToolByName(
                self.context, 'reference_catalog'
            )
            self.project = reference_catalog.lookupObject(self.projectId)

        if self._action == 'GET' and self.projectId is None:
            self.catalog = getToolByName(self.context, 'portal_catalog')
            self._getProjects()

        if self._action == 'GET' and self.projectId is not None:
            self._getProject()

        if self._action == 'POST':
            self._updatePayload()
            self._createProject()

        if self._action == 'PUT':
            if self.project is None:
                raise ValueError("No project provided")
            self._updatePayload()
            self._updateProject()

        if self._action == 'DELETE':
            if self.project is None:
                raise ValueError("No project provided")
            self._deleteProject()
 def handleRebuild(self, action):
     catalog = getToolByName(self.context, 'portal_catalog')
     membrane_tool = getToolByName(self.context, 'membrane_tool')
     brains = catalog(portal_type="collective.rcse.member")
     for brain in brains:
         user = brain.getObject()
         membrane_tool.reindexObject(user)
    def getGravatar(self, reply):
        """ """
        purl = getToolByName(self.context, 'portal_url')
        mtool = getToolByName(self.context, 'portal_membership')
        portrait_url = purl() + '/defaultUser.gif'
        email = ''

        creator = reply.Creator()
        if creator and not creator == 'Anonymous User':
            mtool = getToolByName(self.context, "portal_membership")
            member = mtool.getMemberById(creator)
            email = member and member.getProperty('email', '') or ''
            mem_id = getattr(member, 'getId', lambda: 'Anonymous User')()
            portrait = mtool.getPersonalPortrait(mem_id)
            portrait_url = portrait.absolute_url()
        else:
            email = reply.getProperty('email', d='')

        if not email or not 'defaultUser.gif' in portrait_url:
            return portrait_url

        size = 40
        gravatar_url = "http://www.gravatar.com/avatar.php?"
        # construct the url
        gravatar_url += urllib.urlencode({
            'gravatar_id': md5.md5(email).hexdigest(),
            'default': portrait_url,
            'size': str(size)})
        return gravatar_url
def sendEmailNotification(obj):

    import pdb; pdb.set_trace()

    site = getSite()
    email_charset = getattr(obj, 'email_charset', 'utf-8')
    

    mail_template = site.unrestrictedTraverse('@@newinvitationnotification')
    mail_text = mail_template(invitation=obj,
                              charset=email_charset,
                              portal_url = site.absolute_url(),
                              request=obj.REQUEST
                              )

    try:
        host = getToolByName(obj, 'MailHost')
        # The ``immediate`` parameter causes an email to be sent immediately
        # (if any error is raised) rather than sent at the transaction
        # boundary or queued for later delivery.
        result = host.send(safe_unicode(mail_text), immediate=True)
        logger.info('Email queue returned %s' % str(result))
        comment = 'Invitation sent to %s. Mail host returned: %s' % (obj.recipient_email, str(result))
        workflow = getToolByName(site, "portal_workflow")
        workflow.doActionFor(obj, 'pend', comment=comment)
        new_state = workflow.getInfoFor(obj, 'review_state')
        logger.info("Object %s changed state to %s" % (obj.absolute_url_path(), new_state))
    except SMTPRecipientsRefused:
        # Don't disclose email address on failure
        raise SMTPRecipientsRefused('Recipient address rejected by server')
Beispiel #9
0
    def reorderObjects(self):
        object_id = self.request['id']
        position = self.request['position']

        if position.lower() == 'up':
            self.context.moveObjectsUp(object_id)

        if position.lower() == 'down':
            self.context.moveObjectsDown(object_id)

        if position.lower() == 'top':
            self.context.moveObjectsToTop(object_id)

        if position.lower() == 'bottom':
            self.context.moveObjectsToBottom(object_id)

        # order folder by field
        # id in this case is the field
        if position.lower() == 'ordered':
            self.context.orderObjects(object_id)

        cmfutils.getToolByName(
            self.context,
            'plone_utils').reindexOnReorder(
            self.context)
        return 1
Beispiel #10
0
def get_users(groupname=None, group=None):
    """Get all users or all users filtered by group.

    Arguments ``group`` and ``groupname`` are mutually exclusive.
    You can either set one or the other, but not both.

    :param groupname: Groupname of the group of which to return users. If set,
        only return users that are member of this group.
    :type username: string
    :param group: Group of which to return users.
        If set, only return users that are member of this group.
    :type group: GroupData object
    :returns: All users (optionlly filtered by group)
    :rtype: List of MemberData objects
    :Example: :ref:`user_get_all_users_example`,
        :ref:`user_get_groups_users_example`

    """

    if groupname and group:
        raise InvalidParameterError

    if groupname:
        group_tool = getToolByName(portal.get(), "portal_groups")
        group = group_tool.getGroupById(groupname)
        if not group:
            # XXX This should raise a custom plone.api exception
            raise ValueError

    portal_membership = getToolByName(portal.get(), "portal_membership")

    if group:
        return group.getGroupMembers()
    else:
        return portal_membership.listMembers()
Beispiel #11
0
    def submit_abuse_report(self):
        """ Send an email with the abuse report message and hide abuse report form.
        """
        errors = {}
        context = aq_inner(self.context)
        request = context.REQUEST
        portal = getToolByName(self.context, 'portal_url').getPortalObject()
        if hasattr(context, 'captcha_validator'):
            dummy_controller_state = ControllerState(
                                            id='comments.pt',
                                            context=context,
                                            button='submit',
                                            status='success',
                                            errors={},
                                            next_action=None,)
            # get the form controller
            controller = portal.portal_form_controller
            # send the validate script to the form controller with the dummy state object
            controller_state = controller.validate(dummy_controller_state, request, ['captcha_validator',])
            errors.update(controller_state.errors)

        message = request.get('message')
        if not message:
            errors.update({'message': 'Please provide a message'})

        mtool = getToolByName(self.context, "portal_membership")
        member = mtool.getAuthenticatedMember()
        comment_id = self.context.request.get('comment_id')
        ksscore = self.getCommandSet('core')
        if errors:
            html = self.macroContent('context/report_abuse_form/macros/form',
                                     errors=errors,
                                     show_form=True,
                                     tabindex=IndexIterator(),
                                     member=member,
                                     **request.form)
            node = ksscore.getHtmlIdSelector('span-reply-form-holder-%s' % comment_id)
            ksscore.replaceInnerHTML(node,  html)
            return self.render()

        # report_abuse(context, context, message, comment)
        manage_mails(context, self.context, 'report_abuse')

        html = self.macroContent('context/report_abuse_form/macros/form',
                                 tabindex=IndexIterator(),
                                 member=member,
                                 **request.form)
        node = ksscore.getHtmlIdSelector('span-reply-form-holder-%s' % comment_id)
        html = '<br/><span style="color:red">You have reported this comment for abuse.</span>'
        self.commands.addCommand('remove_abuse_report_form', 
                                 node, 
                                 comment_id=comment_id, 
                                 html=html)

        node = ksscore.getHtmlIdSelector('div-captcha-%s' % comment_id)
        html = self.macroContent('context/report_abuse_form/macros/captcha',
                                 **request.form)
        ksscore.replaceInnerHTML(node,  html)
        return self.render()
 def test_gtbn_funcglobals(self):
     from Products.CMFPlone.utils import getToolByName
     try:
         getToolByName(self.assertTrue, 'func_globals')['__builtins__']
     except TypeError:
         pass
     else:
         self.fail('getToolByName should block access to non CMF tools')
Beispiel #13
0
def upgrade_all_to_0003(context):
    # Install new package
    qi = getToolByName(context, 'portal_quickinstaller')
    qi.installProduct('collective.shibboleth')

    # Remove old portlet config by importing profile
    setup = getToolByName(context, 'portal_setup')
    return setup.runImportStepFromProfile(
        'profile-collective.aaf:upgrade_portlet', 'portlets')
def defaultlicensevocab(context):
    props = getToolByName(context, 'portal_properties')
    supp = props.content_licensing_properties.SupportedLicenses
    ts = getToolByName(context.context,'translation_service')
    licenses = []
    for x in supp:
        value = getattr(props.content_licensing_properties, x)[0]
        licenses.append((ts.translate(value), value))
    return SimpleVocabulary.fromItems(licenses)
    def __init__(self, context, request):
        super(GeoShapeForm, self).__init__(context, request)
        self.geomanager = IGeoManager(self.context)

        portal_url = getToolByName(self.context, "portal_url")
        portal = portal_url.getPortalObject()
        props_tool = getToolByName(portal, "portal_properties")
        site_props = getattr(props_tool, "site_properties")
        self.typesUseViewActionInListings = list(site_props.getProperty("typesUseViewActionInListings"))
Beispiel #16
0
def upgrade_0003_to_0004(context):
    """ Upgrade dependencies and reconfigure portlets.
    """
    qi = getToolByName(context, 'portal_quickinstaller')
    qi.upgradeProduct('collective.aaf')
    run_import_step(context, 'portlets')

    # Change language
    ltool = getToolByName(context, 'portal_languages')
    ltool.setDefaultLanguage('en-au')
Beispiel #17
0
 def addMultipleToOshmail(
         items=None, column=None, max=0, layout="", offset=0):
     for ob in items[:max]:
         alias = insertAlias(column, ob.UID)
         manager = IDynamicViewManager(alias)
         manager.setLayout(layout)
         for count in range(offset):
             column.moveObjectsUp(alias.id)
         cmfutils.getToolByName(
             self, 'plone_utils').reindexOnReorder(column)
def supportedvocab(context):
    props = getToolByName(context, 'portal_properties')
    supp = props.content_licensing_properties.AvailableLicenses
    ts = getToolByName(context.context,'translation_service')
    licenses = []
    for x in supp:
        value = getattr(props.content_licensing_properties, x)[0], x
        if 'Creative Commons License' == value[0]:
            value = (_(u'Creative Commons License Picker'), x)
	value = ts.translate(value[0]), value[1]
        licenses.append(value)
    return SimpleVocabulary.fromItems(licenses)
    def setUp(self):
        self.portal = self.layer['portal']
        self.request = self.layer['request']
        self.acl_users = getToolByName(self.portal, 'acl_users')
        self.regtool = getToolByName(self.portal, 'portal_registration')

        # add some users
        self.users = [self._add_user(username, fullname, location) \
                        for username, fullname, location in USERS]

        # mark request
        directlyProvides(self.request, IThemeSpecific)
Beispiel #20
0
 def __call__(self):
     mtr = getToolByName(self.portal, 'mimetypes_registry')
     cat = getToolByName(self.portal, 'portal_catalog')
     contenttypes = ['application/msword', 'application/octet-stream']
     query = {'portal_type': 'File', 'getContentType': contenttypes}
     for obj in self.objects(query, 'update Contenttype'):
         file_ = obj.getField('file').get(obj)
         mimetype = mtr.classify(file_.data, filename=file_.getFilename())
         if str(mimetype) != file_.getContentType():
             file_.setContentType(str(mimetype))
             cat.reindexObject(obj,
                               idxs=['getContentType'],
                               update_metadata=True
                               )
Beispiel #21
0
    def javascript_url(self):
        """Returns the URL to the javascript file (form.js) for embedding in
        the template. It also adds the date / time as parameter when
        portal_javscript is in debug mode.
        """
        url = getToolByName(self.context, 'portal_url')()
        url += '/++resource++tasktemplates.form.js'

        # debug mode on?
        jstool = getToolByName(self.context, 'portal_javascripts')
        if jstool.getDebugMode():
            url += '?now=' + str(datetime.now())

        return url
    def _importNode(self, node):
        """Import the object from the DOM node.
        """
        memberdata = getToolByName(self.context, 'portal_memberdata')
        pm = getToolByName(self.context, 'portal_membership')
        acl = getToolByName(self.context, 'acl_users')
        portal_groups = getToolByName(self.context, 'portal_groups')
        prop_map = getPropMap(memberdata)
        for usernode in node.getElementsByTagName('user'):
            userid = usernode.attributes['id'].value
            login = usernode.attributes['login'].value
            passwd = usernode.attributes['password'].value
            props = {}

            properties = usernode.getElementsByTagName('memberdata')[0]
            for propnode in properties.getElementsByTagName('property'):
                name = propnode.attributes['name'].value
                prop = prop_map[name]
                if prop['type'] == 'string':
                    value = propnode.attributes['value'].value
                elif prop['type'] == 'boolean':
                    value = propnode.attributes['value'].value
                    if value.lower() == 'true':
                        value = True
                    else:
                        value = False
                elif prop['type'] == 'date':
                    value = DateTime(propnode.attributes['value'].value)
                elif prop['type'] == 'float':
                    value = float(propnode.attributes['value'].value)
                elif prop['type'] == 'text':
                    if len(propnode.childNodes) == 0:
                        value = ''
                    else:
                        value = propnode.toxml()
            member = pm.getMemberById(userid)
            if member is None:
                acl._doAddUser(userid, passwd, (), None)
                member = pm.getMemberById(userid)
            member.setMemberProperties(props)

            self.context.updateUser(userid, login)
            self.context._user_passwords[userid] = passwd

            groupsnode = usernode.getElementsByTagName('groups')[0]
            existing_groups = portal_groups.getGroupsByUserId(userid)
            for groupnode in groupsnode.getElementsByTagName('group'):
                groupid = groupnode.attributes['id'].value
                if groupid not in existing_groups:
                    portal_groups.addPrincipalToGroup(userid, groupid)
Beispiel #23
0
    def unarchive(self, context, custom_message=None, initiator=None,
                  reason=None):
        """ Unarchive the object
        :param context: object which is going to be unarchived
        :param custom_message: Custom message explaining why the object was
               unarchived
        :param initiator: the user id or name which commissioned the archival
        :param reason: reason id for which the object was archived
        """
        noLongerProvides(context, IObjectArchived)

        now = DateTime()
        context.setExpirationDate(None)
        date = DateTime()

        wftool = getToolByName(context, 'portal_workflow')
        has_workflow = wftool.getChainFor(context)
        mtool = getToolByName(context, 'portal_membership')

        if not has_workflow:
            # NOP
            return

        state = wftool.getInfoFor(context, 'review_state')
        actor = mtool.getAuthenticatedMember().getId()

        if custom_message:
            reason += u" (%s)" % custom_message
        comments = (u"Unarchived by %(actor)s on %(date)s by request "
                    u"from %(initiator)s with reason: %(reason)s" % {
                        'actor': actor,
                        'initiator': initiator,
                        'reason': reason,
                        'date': date.ISO8601()
                    })

        for wfname in context.workflow_history.keys():
            history = context.workflow_history[wfname]
            history += ({
                            'action': 'UnArchive',
                            'review_state': state,
                            'actor': actor,
                            'comments': comments,
                            'time': now,
                        },)
            context.workflow_history[wfname] = history

        context.workflow_history._p_changed = True
        context.reindexObject()
        notify(ObjectModifiedEvent(context))
Beispiel #24
0
 def __call__(self, value, *args, **kwargs):
     if not value and isinstance(value, basestring):
         return False
     instance = kwargs['instance']
     cat = getToolByName(instance, 'portal_catalog')
     pmembership = getToolByName(instance, 'portal_membership')
     user = pmembership.getAuthenticatedMember()
     roles = user.getRoles()
     if 'Manager' in roles:
         return True
     for val in value:
         code = val.get('code')
         if val.get('orderindex_') == "template_row_marker":
             continue
         if not code:
             return "Validation failed, code cannot be empty"
         if not code.isdigit():
             return "Validation failed, code must contain only numbers"
         val_code = int(code or '0', base=10)
         val_set = val.get('set')
         val_id_code = '%s%s' % (val_set, code)
         res = cat(get_codes=val_id_code, sort_on='created',
                   sort_order='reverse', portal_type="Specification",
                   sort_limit=1)
         if not res:
             return True
         res_codes = res[0].get_codes
         code_value = 0
         res_code = 0
         for code in res_codes:
             if val_set in code:
                 if len(val_set) < len(code):
                     res_code = code.split(val_set)[-1]
                     code_value = int(res_code, base=10)
                     break
         if val_code == code_value:
             clim_obj = res[0].getObject()
             versions_view = clim_obj.restrictedTraverse('@@getVersions', '')
             if versions_view:
                 versions = versions_view.versions()
                 found_version = False
                 for version in versions:
                     if instance == version or instance == version.aq_parent:
                         found_version = True
                         break
                 if not found_version:
                     return ("Validation failed, you can only use the code "
                             "%s if related to %s" %
                             (res_code, versions[0].absolute_url()))
     return True
Beispiel #25
0
    def get_setcodes_map(self):
        """get secodes map"""

        result = {}

        catalog = getToolByName(self.context, 'portal_catalog')
        self.specifications = catalog.searchResults(portal_type='Specification')
        self.assessments = catalog.searchResults(portal_type='Assessment')
        self.factsheets = catalog.searchResults(
                             portal_type='IndicatorFactSheet')

        self.mtool = getToolByName(self.context, 'portal_membership')

        for spec in self.specifications:
            assessments = [(a, a.review_state)
                           for a in self.get_child_assessments(spec)]

            sets = [s['set'] for s in get_codes(spec.get_codes)] or ["none"]

            for st in sets:
                info = {
                        'spec':spec,
                        'manager_id':self._get_name(spec),
                        'state':spec.review_state,
                        'assessments':assessments,
                        }
                if st in result.keys():
                    result[st].append(info)
                else:
                    result[st] = [info]

        for fs in self.factsheets:
            sets = [ms['set'] for ms in get_codes(fs.get_codes)] or ["none"]

            for s in sets:
                info = {
                        'spec':fs,
                        'manager_id':'',
                        'state':fs.review_state,
                        'assessments':[],
                        }
                if s in result.keys():
                    result[s].append(info)
                else:
                    result[s] = [info]

        for k, v in result.items():
            v.sort(key=_get_code(k))

        return result
 def send(self):
     """ Send reminder mail
     """
     portal = self.context
     ct = getToolByName(portal, 'portal_catalog')
     wf = getToolByName(portal, 'portal_workflow')
     doActionFor = wf.doActionFor
     invalidTranslations = \
                [b.getObject() for b in ct(Language='all',
                                           lingua_state='invalid')]
     for translation in invalidTranslations:
         doActionFor(translation, 'notify_editors')
     logger.info('valentine.linguaflow: Notified editors about %d '
                 'invalidated translations', len(invalidTranslations))
Beispiel #27
0
def evolve(context):
    """ Migrate frequency_of_updates storage
    """

    catalog = getToolByName(context, 'portal_catalog')

    logger.info("Started migration of frequency_of_updates "
                "storage for Specifications")

    for b in catalog.searchResults(portal_type='Specification'):
        obj = b.getObject()
        field = obj.getField('frequency_of_updates')
        accessor = field.getEditAccessor(obj)
        value = accessor()
        freq_years = value.pop('frequency_years')
        freq_time_of_year = value.pop('time_of_year')


        if freq_years:
            frequency = [{'years_freq':freq_years,
                          'time_of_year':freq_time_of_year},]
        else:
            frequency = []

        value['frequency'] = frequency
        field.set(obj, value)
        logger.info("Migrated frequency_of_updates storage for %s",
                     obj.absolute_url())
Beispiel #28
0
 def install_additional_profiles(self):
     additional_profiles = self.config.get('additional_profiles')
     stool = getToolByName(self.site, 'portal_setup')
     if additional_profiles:
         for additional_profile in additional_profiles:
             stool.runAllImportStepsFromProfile(
                 'profile-%s' % additional_profile)
 def test_gtbn_faux_archetypes_tool(self):
     from Products.CMFCore.utils import FauxArchetypeTool
     from Products.CMFPlone.utils import getToolByName
     self.portal.portal_factory.archetype_tool = FauxArchetypeTool(
         self.portal.archetype_tool)
     self.assertEqual(self.portal.portal_factory.archetype_tool, getToolByName(
         self.portal.portal_factory, 'archetype_tool'))
Beispiel #30
0
 def results(self, object_name=None):
     """ Return a list of News Article brains inside the Periodical object.
     """
     catalog = getToolByName(self.context, 'portal_catalog')
     path = '/'.join(self.context.getPhysicalPath())
     brains = catalog(object_provides=INITF.__identifier__, path=path, sort_on='getObjPositionInParent')
     return brains
 def _is_user_admin(self):
     m_tool = getToolByName(self.context, 'portal_membership')
     member = m_tool.getAuthenticatedMember()
     if member:
         if member.has_role('Administrator') \
                 or member.has_role('Manager'):
             return True
     return False
def importUsers(context):
    site = context.getSite()
    acl = getToolByName(site, 'acl_users', None)
    users = acl.source_users
    body = context.readDataFile('users.xml')
    if body:
        importer = UsersXMLAdapter(users, context)
        importer.body = body
 def setUp(self):
     self.portal = self.layer['portal']
     self.request = self.layer['request']
     self.wftool = getToolByName(self.portal, 'portal_workflow')
     setRoles(self.portal, TEST_USER_ID, ['Manager'])
     alsoProvides(self.request, ITeamworkProductLayer)
     CreateContentFixtures(self, self.layer).create()
     self.test_member = CreateContentFixtures.TEST_MEMBER
Beispiel #34
0
def cleanup_assessmentparts(gstool):
    """ Cleanup AssessmentPart annotation that contains missing daviz info
    """
    portal = getToolByName(gstool, 'portal_url').getPortalObject()

    catalog = portal.portal_catalog
    res = catalog.searchResults(portal_type='AssessmentPart')
    uids_cat = getToolByName(portal, 'uid_catalog')

    logger.info("Starting cleanup of assessmentpart-daviz annotation")
    i = 0
    for b in res:
        obj = b.getObject()
        annot = obj.__annotations__.get('DAVIZ_CHARTS', {})

        for uid in annot.keys():
            brains = uids_cat.searchResults(UID=uid)
            if not brains:
                msg = "Couldn't find object for brain with UID %s, "\
                      "deleting from assessmentpart %s" % (uid,
                      obj.absolute_url())
                logger.info(msg)
                del annot[uid]
                annot._p_changed = True
                obj._p_changed = True
                i += 1
                continue

            daviz = brains[0].getObject()
            if daviz is None:   #brain does not lead to object?
                msg = "Couldn't find object for brain with UID %s, "\
                      "deleting from assessmentpart %s" % (uid,
                      obj.absolute_url())
                logger.info(msg)
                del annot[uid]
                annot._p_changed = True
                obj._p_changed = True
                i += 1

        if (i % 20) == 0:
            transaction.savepoint() #savepoint on every 20 changes

    transaction.commit()

    logger.info("End cleanup of assessmentpart-daviz annotation")
Beispiel #35
0
def get_came_from_url(context):
    """
    get the current session variable came_from
    """
    session_manager = getToolByName(context, 'session_data_manager')
    if not session_manager.hasSessionData():
        return None
    session = session_manager.getSessionData()
    return session.get('getpaid.camefrom', None)
Beispiel #36
0
    def get_adaptation_options(self):
        options = self.context.adaptationoptions or []

        cat = getToolByName(self.context, 'portal_catalog')
        res = []
        for v in options:
            res.extend(cat.searchResults(acemeasure_id=v))

        return res
Beispiel #37
0
 def _getStatus(self):
     """ Return state of the cirb_relex_project_workflow workflow """
     wtool = getToolByName(self.context, 'portal_workflow')
     workflow = wtool.getWorkflowById('cirb_relex_project_workflow')
     states = {
         state_id: state.title
         for state_id, state in workflow.states.items()
     }
     self._index = json.dumps(states)
    def isPlone42(self):

        try:
            site = getSite()
            migrationTool = getToolByName(site, 'portal_migration')
            versions = migrationTool.coreVersions()['Plone'].split('.')
            return versions[0] == '4' and versions[1] == '2'
        except:
            return False
 def getLicenseTitle(self, request):
     """ Returns the license name. For creative commons licenses, it explicitly appends the 
     CC license type  """
     ts = getToolByName(self.context, 'translation_service')
     license = self.clutil.getDefaultSiteLicense(request)
     if license[0] == 'Creative Commons License':
         return ts.translate(license[0]) + ' :: ' + license[1]
     else:
         return ts.translate(license[0])
Beispiel #40
0
    def __init__(self, context, request):
        super(GeoControlpanelForm, self).__init__(context, request)
        _subform = GeopointForm(self.context, self.request, self)
        self.ptool = getToolByName(self.context, 'plone_utils')
        _subform.level = self.level + 1

        self.subforms = [
            _subform,
        ]
def isPlone42(portal):
    migration_tool = getToolByName(portal, 'portal_migration')
    core_versions = migration_tool.coreVersions()
    plone = core_versions.get('Plone', '')
    if plone:
        versions = plone.split('.')
        return versions[0] == '4' and versions[1] == '2'

    return False
 def setUp(self):
     self.portal = self.layer['portal']
     self.user1 = api.user.get(username=TEST_USER_NAME)
     self.user2 = api.user.create(email='*****@*****.**',
                                  username='******').getUser()
     self.tool = getToolByName(self.portal, 'ploneintranet_notifications')
     self.msg_class_handler = getAdapter(self.portal,
                                         IMessageClassHandler,
                                         name='GLOBAL_NOTICE')
Beispiel #43
0
 def Description(self):
     """ Get description
     """
     convert = getToolByName(self, 'portal_transforms').convert
     text = convert('html_to_text', self.getDescription()).getData()
     try:
         text = text.decode('utf-8', 'replace')
     except UnicodeDecodeError, err:
         logger.info(err)
    def __call__(self):

        self.portal_properties = getUtility(
            IPropertiesTool
        )

        self.portal_catalog = getToolByName(
            self.context, 'portal_catalog'
        )

        # XXX: getUtility call does not work.
        self.membership_tool = getToolByName(
            self.context, 'portal_membership'
        )

        self.portal_state = getMultiAdapter(
            (self.context, self.request),
            name=u'plone_portal_state'
        )

        self.feedback_form = AuthorFeedbackForm(
            self.context, self.request
        )
        self.feedback_form.update()
        self.feedback_form.widgets["author"].mode = HIDDEN_MODE
        self.feedback_form.widgets["referer"].mode = HIDDEN_MODE
        self.feedback_form.widgets["author"].value = self.username
        self.feedback_form.widgets["referer"].value = self.request.get(
            'referer',
            self.request.get('HTTP_REFERER', 'unknown url')
        )

        registry = getUtility(IRegistry)
        security_settings = registry.forInterface(
            ISecuritySchema, prefix='plone')
        allow_anonymous_view_about = security_settings.allow_anon_views_about

        mail_settings = registry.forInterface(IMailSchema, prefix='plone')
        self.email_from_address = mail_settings.email_from_address

        if self.is_anonymous and not allow_anonymous_view_about:
            raise Unauthorized()

        return self.index()
Beispiel #45
0
    def test_default_site_layout_cache(self):
        # Clear cache if there
        if hasattr(self.portal, ATTR):
            delattr(self.portal, ATTR)

        resources = getToolByName(self.portal, 'portal_resources')
        resources._setOb('sitelayout', BTreeFolder2('sitelayout'))
        resources['sitelayout']._setOb('testlayout3',
                                       BTreeFolder2('testlayout3'))
        resources['sitelayout']['testlayout3']._setOb(
            'site.html',
            File(
                'site.html', 'site.html',
                StringIO(
                    '<html><head><title>ZODB test</title></head></html>')))

        self.registry[DEFAULT_SITE_LAYOUT_REGISTRY_KEY] = \
            '/++sitelayout++testlayout3/site.html'

        view = getMultiAdapter((
            self.portal,
            self.request,
        ),
                               name=u'default-site-layout')
        rendered = view()

        self.assertTrue(u"ZODB test" in rendered)

        resources['sitelayout']['testlayout3']._delOb('site.html')
        resources['sitelayout']['testlayout3']._setOb(
            'site.html',
            File(
                'site.html', 'site.html',
                StringIO(
                    '<html><head><title>Cache test</title></head></html>')))

        view = getMultiAdapter((
            self.portal,
            self.request,
        ),
                               name=u'default-site-layout')
        rendered = view()

        self.assertFalse(u"Cache test" in rendered)  # hidden by cache
        self.assertTrue(u"ZODB test" in rendered)

        self.assertEqual('/++sitelayout++testlayout3/site.html', view.layout)

        # Test cache is set
        self.assertTrue(hasattr(self.portal, ATTR))

        # Update cache
        for key in getattr(self.portal, ATTR):
            getattr(self.portal, ATTR)[key] = None

        self.assertIsNone(view.layout)  # because of cache
Beispiel #46
0
 def album_total_images(self, item):
     catalog = getToolByName(self.context, 'portal_catalog')
     path = '/'.join(item.getPhysicalPath())
     brains = catalog(Type='Image',
                      path={
                          'query': path,
                          'depth': 1
                      },
                      sort_on='getObjPositionInParent')
     return len(brains)
Beispiel #47
0
 def html_to_text(self, data):
     """
     Convert HTML formatted data to plain text.
     """
     ptrans = getToolByName(self, 'portal_transforms')
     transformed = ptrans.convertTo(
         'text/plain', data,
         mimetype='text/-x-web-intelligent'
     )
     return transformed.getData()
def importGroups(context):
    """Import actions tool.
    """
    site = context.getSite()
    acl = getToolByName(site, 'acl_users', None)
    groups = acl.source_groups
    body = context.readDataFile('groups.xml')
    if body:
        importer = GroupsXMLAdapter(groups, context)
        importer.body = body
Beispiel #49
0
 def results(self, b_size=10, b_start=0):
     catalog = getToolByName(self.context, 'portal_catalog')
     query, filters = self.get_filters(facets=PloneSearch.facets)
     search = PloneSearch(query, filters=filters)
     response = search.execute()
     self._facets = response.facets
     hits = [hit._d_['rid'] for hit in response.hits if 'rid' in hit._d_]
     brains = [IContentListingObject(catalog._catalog[rid]) for rid in hits]
     batch = Batch(brains, b_size, b_start)
     return batch
Beispiel #50
0
    def __init__(self, transmogrifier, name, options, previous):
        self.previous = previous

        context = transmogrifier.context
        catalog = getToolByName(context, 'portal_catalog')
        self.results = catalog(object_provides=IATNewsItem.__identifier__,
                               path='/'.join(context.getPhysicalPath()))

        # set up new object id suffix using generateUniqueId script from Plone
        self.tmp = '-tmp.%s' % context.generateUniqueId()
Beispiel #51
0
 def getOrganisationByUrl(self, url):
     """ get Organisation by given url
     """
     cat = getToolByName(self, 'portal_catalog')
     brains = cat.searchResults({
         'portal_type': 'Organisation',
         'getUrl': url
     })
     if brains:
         return brains[0]
    def getPloneVersion(self):
        """Returns plone version tuple."""

        self.pm = getToolByName(self.portal, 'portal_migration')
        try:
            version = versionTupleFromString(self.pm.getSoftwareVersion())
        except AttributeError:
            version = versionTupleFromString(self.pm.getFileSystemVersion())

        return version
Beispiel #53
0
 def run(self, resource, *args, **kwds):
     """ Change the rdf resource
     """
     catalog = getToolByName(self.context, "portal_catalog")
     indexer = getMultiAdapter((self.context, catalog), name="filetype")
     mimetypes = indexer()
     if not mimetypes:
         return
     setattr(resource, "dcterms_format", [(m, None) for m in mimetypes])
     resource.save()
     return resource
Beispiel #54
0
 def recursive_action(self, orig_obj, action, val):
     """ Recursive action
     """
     catalog = getToolByName(self.context, 'portal_catalog')
     query = {'path': '/'.join(orig_obj.getPhysicalPath())}
     brains = catalog.searchResults(query)
     for brain in brains:
         obj = brain.getObject()
         storage = IObjectArchivator(obj)
         logger.info("Object %s state is %s", obj.absolute_url(), action)
         getattr(storage, action)(obj, **val)
Beispiel #55
0
    def _get_brains(self, data_type=None):
        """ Return a list of brains inside the folder
        """
        catalog = getToolByName(self.context, 'portal_catalog')
        path = '/'.join(self.context.getPhysicalPath())
        brains = catalog(Type=data_type,
                         path={'query': path,
                               'depth': 1},
                         sort_on='getObjPositionInParent')

        return brains
Beispiel #56
0
def get_current():
    """Get the currently logged-in user.

    :returns: Currently logged-in user
    :rtype: MemberData object
    :raises:
        ValueError
    :Example: :ref:`user_get_current_example`
    """
    portal_membership = getToolByName(portal.get(), 'portal_membership')
    return portal_membership.getAuthenticatedMember()
Beispiel #57
0
def set_came_from_url(context):
    """
    Set a session variable for came_from to contexts url. Used to
    persist a context you may want to retrieve at subsequent point in
    the shopping process. For example: 'continue shopping' of the cart
    view will use it to locate where to return the user to if they
    elect to continue shopping.
    """
    session_manager = getToolByName(context, 'session_data_manager')
    session = session_manager.getSessionData()
    session['getpaid.camefrom'] = context.absolute_url()
Beispiel #58
0
def SearchableText_etherpad(context):
    view = etherpad_view.EtherpadView(context, getRequest())
    view.update()
    if view.etherpad is None:
        return indexers.SearchableText(context)
    text = indexers.SearchableText(context)
    transforms = getToolByName(context, 'portal_transforms')
    h = HTMLParser()
    value = h.unescape(str(view.content()))
    content = transforms.convertTo('text/plain', value, mimetype='text/html')
    return indexers._unicode_save_string_concat(text, content.getData())
Beispiel #59
0
def disable_language_switcher(portal):
    """Remove the use of language-switcher as default view for Plone Site"""
    tt = getToolByName(portal, 'portal_types')
    site = tt['Plone Site']
    methods = site.view_methods
    site.view_methods = [m for m in methods if m != 'language-switcher']
    if site.default_view == 'language-switcher':
        site.default_view = 'listing_view'

    log = getLogger('setuphandlers.disable_language_switcher')
    log.info('Language switcher disabled')
Beispiel #60
0
 def __call__(self, value, *args, **kwargs):
     cat = getToolByName(kwargs['instance'], 'portal_catalog')
     query = {'portal_type': 'PolicyDocumentReference'}
     brains = cat(**query)
     for brain in brains:
         obj = brain.getObject()
         if value == obj.getRemoteUrl() and \
           kwargs['instance'].UID() != obj.UID():
             return ("Validation failed, there is already an "
                     "Policy Document pointing to this URL.")
     return True