Exemplo n.º 1
0
class entrypress_item(Implicit, NyProperties):
    """ """

    title = LocalProperty('title')
    description = LocalProperty('description')
    coverage = LocalProperty('coverage')
    keywords = LocalProperty('keywords')

    def __init__(self, title, description, coverage, keywords, sortorder,
        entry, releasedate, lang):
        """
        Constructor.
        """
        self.save_properties(title, description, coverage, keywords, sortorder,
            entry, releasedate, lang)
        NyProperties.__dict__['__init__'](self)

    def save_properties(self, title, description, coverage, keywords, sortorder,
        entry, releasedate, lang):
        """
        Save item properties.
        """
        self._setLocalPropValue('title', lang, title)
        self._setLocalPropValue('description', lang, description)
        self._setLocalPropValue('coverage', lang, coverage)
        self._setLocalPropValue('keywords', lang, keywords)
        self.sortorder = sortorder
        self.entry = entry
        self.releasedate = releasedate
Exemplo n.º 2
0
class questionnaire_item(Implicit, NyProperties):
    """ """

    title = LocalProperty('title')
    description = LocalProperty('description')
    coverage = LocalProperty('coverage')
    keywords = LocalProperty('keywords')

    def __init__(self, title, description, coverage, keywords, sortorder,
                 releasedate, expirationdate, lang):
        """
        Constructor.
        """
        self.save_properties(title, description, coverage, keywords, sortorder,
                             releasedate, expirationdate, lang)
        NyProperties.__dict__['__init__'](self)

    def save_properties(self,
                        title='',
                        description='',
                        coverage='',
                        keywords='',
                        sortorder=100,
                        releasedate=DateTime(),
                        expirationdate=DateTime(),
                        notify_owner=True,
                        notify_respondents='LET_THEM_CHOOSE_YES',
                        lang=None,
                        **kwargs):
        """
        Save item properties.
        """
        assert (notify_respondents
                in ('ALWAYS', 'NEVER', 'LET_THEM_CHOOSE_YES',
                    'LET_THEM_CHOOSE_NO'))
        self._setLocalPropValue('title', lang, title)
        self._setLocalPropValue('description', lang, description)
        self._setLocalPropValue('coverage', lang, coverage)
        self._setLocalPropValue('keywords', lang, keywords)
        self.sortorder = sortorder
        self.releasedate = releasedate
        self.expirationdate = expirationdate
        self.notify_owner = notify_owner
        self.notify_respondents = notify_respondents
        self.allow_overtime = int(kwargs.get('allow_overtime', '0'))
        self.allow_multiple_answers = int(
            kwargs.get('allow_multiple_answers', '0'))
        self.allow_drafts = int(kwargs.get('allow_drafts', '0'))
        self.allow_anonymous = int(kwargs.get('allow_anonymous', '0'))
        self.contributor = kwargs.get('contributor')
Exemplo n.º 3
0
    def createProperty(self, p_id, p_value, lang):
        """ Add a new property"""

        self.__dynamic_properties[p_id] = ''
        setattr(self, p_id, LocalProperty(p_id))
        self._setLocalPropValue(p_id, lang, p_value)
        self._p_changed = 1
Exemplo n.º 4
0
class ComboboxMatrixWidget(MatrixWidget):
    """ ComboboxMatrix Widget """

    meta_type = "Naaya Combobox Matrix Widget"
    meta_label = "Combobox matrix"
    meta_description = "Group of multiple choice questions with multiple answers per row"
    meta_sortorder = 502
    icon_filename = 'widgets/www/widget_comboboxmatrix.gif'

    _properties = MatrixWidget._properties + ()

    values = LocalProperty('values')

    # Constructor
    _constructors = (addComboboxMatrixWidget, )
    render_meth = PageTemplateFile('zpt/widget_comboboxmatrix.zpt', globals())

    def __init__(self, id, lang=None, **kwargs):
        MatrixWidget.__init__(self, id, lang, **kwargs)
        self.set_localproperty('values', 'lines', lang, [])

    def getDatamodel(self, form):
        """Get datamodel from form"""
        widget_id = self.getWidgetId()
        value = []
        for i in range(len(self.rows)):
            row_value = []
            for j in range(len(self.choices)):
                choice_value = form.get('%s_%d_%d' % (widget_id, i, j), None)
                if choice_value is not None:
                    choice_value = int(choice_value)
                row_value.append(choice_value)
            value.append(row_value)
        return value

    def validateDatamodel(self, value):
        """Validate datamodel"""
        if not self.required:
            return
        unanswered = [x for x in value if not x]
        if unanswered:
            raise WidgetError('Value required for "%s"' % self.title)

    def get_value(self, datamodel=None, **kwargs):
        """ Return a string with the data in this widget """
        if datamodel is None:
            return self._get_default_value()
        res = []
        for index, row_answers in enumerate(datamodel):
            title = self.rows[index]
            value = []
            if not row_answers:
                res.append('%s: -' % title)
                continue
            for answer in row_answers:
                value.append(self.values[answer])
            value = ', '.join(value)
            res.append('%s: %s' % (title, value))
        return '\n'.join(res)
Exemplo n.º 5
0
class MatrixWidget(Widget):
    """Abstract class"""

    # Local properties
    choices = LocalProperty('choices')
    rows = LocalProperty('rows')

    # macros
    matrix_render_meth = PageTemplateFile('zpt/widget_matrix', globals())

    def __init__(self, id, lang=None, **kwargs):
        Widget.__init__(self, id, lang, **kwargs)
        choices = kwargs.get('choices', [])
        self.set_localproperty('choices', 'lines', lang, choices)
        rows = kwargs.get('rows', [])
        self.set_localproperty('rows', 'lines', lang, rows)

    def getChoices(self, anyLangNonEmpty=False):
        """ """
        if anyLangNonEmpty and not self.choices:
            return self.getLocalAttribute('choices', langFallback=True)
        else:
            return self.choices
Exemplo n.º 6
0
class MultipleChoiceWidget(Widget):
    """Abstract class"""

    security = ClassSecurityInfo()

    # Local properties
    choices = LocalProperty('choices')

    # macros
    multiplechoice_render_meth = PageTemplateFile('zpt/widget_multiplechoice',
                                                  globals())

    def __init__(self, id, lang=None, **kwargs):
        self.set_localproperty('choices', 'lines', lang, [])
        Widget.__init__(self, id, lang, **kwargs)

    def getChoices(self, anyLangNonEmpty=False):
        """ """
        if anyLangNonEmpty and not self.choices:
            return self.getLocalAttribute('choices', langFallback=True)
        else:
            return self.choices
Exemplo n.º 7
0
class study_item(Implicit, NyProperties):
    """ """

    title = LocalProperty('title')
    description = LocalProperty('description')
    coverage = LocalProperty('coverage')
    keywords = LocalProperty('keywords')
    body = LocalProperty('body')
    toc_body = LocalProperty('toc_body')

    def __init__(self, title, description, coverage, keywords, sortorder, body,
                 topic, scope, toc_body, toc, releasedate, lang):
        """
        Constructor.
        """
        self.save_properties(title, description, coverage, keywords, sortorder,
                             body, topic, scope, toc_body, toc, releasedate,
                             lang)
        NyProperties.__dict__['__init__'](self)

    def save_properties(self, title, description, coverage, keywords,
                        sortorder, body, topic, scope, toc_body, toc,
                        releasedate, lang):
        """
        Save item properties.
        """
        self._setLocalPropValue('title', lang, title)
        self._setLocalPropValue('description', lang, description)
        self._setLocalPropValue('coverage', lang, coverage)
        self._setLocalPropValue('keywords', lang, keywords)
        self._setLocalPropValue('body', lang, body)
        self._setLocalPropValue('toc_body', lang, toc_body)
        self.topic = topic
        self.scope = scope
        self.sortorder = sortorder
        self.toc = toc
        self.releasedate = releasedate
Exemplo n.º 8
0
class mediafile_item(Implicit, NyContentData):
    """ """

    subtitle = LocalProperty('subtitle')
    startup_image = None
Exemplo n.º 9
0
class NyNetSite(NyAttributes, LocalPropertyManager, NyContainer, NyFeed):
    """ """

    meta_type = METATYPE_NYNETSITE
    icon = 'misc_/NaayaNetRepository/NyNetSite.gif'

    manage_options = (NyContainer.manage_options[0:2] +
                      ({
                          'label': 'Properties',
                          'action': 'manage_edit_html'
                      }, ) + NyContainer.manage_options[3:8])

    meta_types = ({
        'name': METATYPE_NYNETCHANNEL,
        'action': 'manage_addNyNetChannel_html'
    }, )
    all_meta_types = meta_types

    security = ClassSecurityInfo()

    security.declareProtected(view_management_screens,
                              'manage_addNyNetChannel_html')
    manage_addNyNetChannel_html = NyNetChannel.manage_addNyNetChannel_html

    security.declareProtected(PERMISSION_PUBLISH_OBJECTS, 'addNyNetChannel')
    addNyNetChannel = NyNetChannel.addNyNetChannel

    title = LocalProperty('title')
    description = LocalProperty('description')

    def __init__(self, id, title, description, url, lang):
        """ """
        self.id = id
        self._setLocalPropValue('title', lang, title)
        self._setLocalPropValue('description', lang, description)
        self.url = url
        self.langs = []
        NyFeed.__dict__['__init__'](self)

    security.declarePrivate('objectkeywords')

    def objectkeywords(self, lang):
        return u' '.join([
            self.getLocalProperty('title', lang),
            self.getLocalProperty('description', lang)
        ])

    #api
    def get_netsite_object(self):
        return self

    def get_netsite_path(self, p=0):
        return self.absolute_url(p)

    def get_netchannels(self):
        return self.objectValues(METATYPE_NYNETCHANNEL)

    def get_netsite_langs(self):
        #returns a comma separated string with languages labels
        try:
            return ', '.join(map(self.gl_get_language_name, self.langs))
        except:
            return ''

    def get_feed_url(self):
        #method from NyFeed
        return '%s/localchannels_rdf' % self.url

    def set_new_feed_url(self, new_url):
        #method from NyFeed
        pass

    #zmi actions
    security.declareProtected(view_management_screens, 'manageProperties')

    def manageProperties(self, title='', description='', url='', REQUEST=None):
        """ """
        if url.endswith('/'): url = url[:-1]
        lang = self.gl_get_selected_language()
        self._setLocalPropValue('title', lang, title)
        self._setLocalPropValue('description', lang, description)
        self.url = url
        self._p_changed = 1
        self.recatalogNyObject(self)
        if REQUEST: REQUEST.RESPONSE.redirect('manage_edit_html?save=ok')

    #site actions
    security.declareProtected(PERMISSION_PUBLISH_OBJECTS, 'saveProperties')

    def saveProperties(self,
                       title='',
                       description='',
                       url='',
                       lang=None,
                       REQUEST=None):
        """ """
        if url.endswith('/'): url = url[:-1]
        if lang is None: lang = self.gl_get_selected_language()
        self._setLocalPropValue('title', lang, title)
        self._setLocalPropValue('description', lang, description)
        self.url = url
        self._p_changed = 1
        self.recatalogNyObject(self)
        #update search capabilities
        self.update_search_capabilities()
        if REQUEST:
            self.setSessionInfoTrans(MESSAGE_SAVEDCHANGES,
                                     date=self.utGetTodayDate())
            REQUEST.RESPONSE.redirect('%s/edit_html?lang=%s' %
                                      (self.absolute_url(), lang))

    security.declareProtected(PERMISSION_PUBLISH_OBJECTS, 'deleteObjects')

    def deleteObjects(self, ids=None, REQUEST=None):
        """ """
        if ids is None: ids = []
        else: ids = self.utConvertToList(ids)
        try:
            self.manage_delObjects(ids)
        except:
            error = 1
        else:
            error = 0
        if REQUEST:
            if error: self.setSessionErrors(['Error while deleting data.'])
            else: self.setSessionInfo(['Item(s) deleted.'])
            REQUEST.RESPONSE.redirect('%s/index_html' % self.absolute_url())

    security.declareProtected(PERMISSION_PUBLISH_OBJECTS, 'update_netsite')

    def update_netsite(self, REQUEST=None):
        """ harvest and create channels """
        self.harvest_feed()
        if self.get_feed_bozo_exception() is not None:
            #some error occurred
            self.setSessionErrors([self.get_feed_bozo_exception()])
        else:
            #no errors
            #remove old channels
            self.deleteObjects(
                [x.id for x in self.objectValues() if x.manual == 0])
            #add channels
            for x in self.get_feed_items():
                id = PREFIX_NYNETCHANNEL + self.utGenRandomId(6)
                language, type, description, lang = None, None, '', None
                if x.has_key('dc_description'):
                    description = x['dc_description']
                if x.has_key('language'):
                    language = x['language'].encode('utf-8')
                elif x.has_key('dc_language'):
                    language = x['dc_language'].encode('utf-8')
                if x.has_key('type'): type = x['type'].encode('utf-8')
                elif x.has_key('dc_type'): type = x['dc_type'].encode('utf-8')
                #choose which language for the content
                #channel language if channel language is in the list of languages
                #selected language otherwise
                if language is not None:
                    if language in self.gl_get_languages():
                        lang = language
                #create channel
                self.addNyNetChannel(id, x['title'], description,
                                     x['link'].encode('utf-8'), language, type,
                                     0, lang)
                #harvest channel
                self._getOb(id).update_netchannel()
                #update search capabilities
                self.update_search_capabilities()
            self.setSessionInfoTrans(MESSAGE_SAVEDCHANGES,
                                     date=self.utGetTodayDate())
        if REQUEST:
            REQUEST.RESPONSE.redirect('%s/index_html' % self.absolute_url())

    security.declareProtected(PERMISSION_PUBLISH_OBJECTS,
                              'update_search_capabilities')

    def update_search_capabilities(self, REQUEST=None):
        """ """
        msg, err, res = '', '', None
        xconn = XMLRPCConnector(self.get_http_proxy())
        res = xconn(self.url, 'external_search_capabilities')
        if res is None:
            err = 'Cannot connect to the given URL.'
            if not hasattr(self, 'langs'):
                #update script for sites that don't have yet the 'langs' property set
                self.langs = []
                self._p_changed = 1
        else:
            self.langs = res
            self._p_changed = 1
            msg = MESSAGE_SAVEDCHANGES % self.utGetTodayDate()
        if REQUEST:
            if err != '': self.setSessionErrors([err])
            if msg != '': self.setSessionInfo([msg])
            REQUEST.RESPONSE.redirect('%s/index_html' % self.absolute_url())

    #zmi pages
    security.declareProtected(view_management_screens, 'manage_edit_html')
    manage_edit_html = PageTemplateFile('zpt/netsite_manage_edit', globals())

    #site pages
    security.declareProtected(view, 'index_html')
    index_html = PageTemplateFile('zpt/netsite_index', globals())

    security.declareProtected(PERMISSION_PUBLISH_OBJECTS, 'edit_html')
    edit_html = PageTemplateFile('zpt/netsite_edit', globals())

    security.declareProtected(PERMISSION_PUBLISH_OBJECTS,
                              'netchannel_add_html')
    netchannel_add_html = PageTemplateFile('zpt/netchannel_add', globals())
Exemplo n.º 10
0
class NyNetRepository(LocalPropertyManager, Folder):
    """ """

    meta_type = METATYPE_NYNETREPOSITORY
    icon = 'misc_/NaayaNetRepository/NyNetRepository.gif'

    manage_options = (
        Folder.manage_options[0:2]
        +
        (
            {'label': 'Properties', 'action': 'manage_edit_html'},
        )
        +
        Folder.manage_options[3:8]
    )

    meta_types = (
        {'name': METATYPE_NYNETSITE, 'action': 'manage_addNyNetSite_html'},
    )
    all_meta_types = meta_types

    security = ClassSecurityInfo()

    security.declareProtected(view_management_screens, 'manage_addNyNetSite_html')
    manage_addNyNetSite_html = NyNetSite.manage_addNyNetSite_html

    security.declareProtected(PERMISSION_PUBLISH_OBJECTS, 'addNyNetSite')
    addNyNetSite = NyNetSite.addNyNetSite

    title = LocalProperty('title')

    def __init__(self, id, title, lang):
        """ """
        self.id = id
        self._setLocalPropValue('title', lang, title)

    security.declarePrivate('loadDefaultData')
    def loadDefaultData(self):
        #create some indexes in the portal catalog
        catalog = self.getCatalogTool()
        try: catalog.addIndex('language', 'FieldIndex')
        except: pass
        try: catalog.addIndex('type', 'FieldIndex')
        except: pass
        #create a portlet
        portlets_ob = self.getPortletsTool()
        portlet_id = '%s%s' % (PREFIX_PORTLET, self.id)
        portlets_ob.addPortlet(portlet_id, self.title_or_id(), 99)
        portlet_ob = portlets_ob._getOb(portlet_id)
        content = self.futRead(join(NAAYANETREPOSITORY_PRODUCT_PATH, 'data', 'portlet_netrepository.zpt'), 'r')
        content = content.replace('PORTLET_NETREPOSITORY_ID', self.id)
        portlet_ob.pt_edit(text=content, content_type='text/html')

    #overwrite handlers
    def manage_beforeDelete(self, item, container):
        """
        This method is called, when the object is deleted.
        """
        Folder.inheritedAttribute('manage_beforeDelete')(self, item, container)
        self.delete_portlet_for_object(item)

    #api
    def get_netrepository_object(self): return self
    def get_netrepository_path(self, p=0): return self.absolute_url(p)
    def get_netsites(self): return self.objectValues(METATYPE_NYNETSITE)
    def get_sites(self):
        """ """
        r = []
        ra = r.append
        for netsite in self.objectValues(METATYPE_NYNETSITE):
            ra({'url': netsite.url, 'title': netsite.title, 'langs': netsite.langs})
        return r

    def search_channels(self, q='', l='', t=''):
        #search channels
        lang = self.gl_get_selected_language()
        if q == '': q = None
        if l == '': l = None
        if t == '': t = None
        return self.query_objects_ex(meta_type=METATYPE_NYNETCHANNEL, q=q, lang=lang, path='/'.join(self.getPhysicalPath()), language=l, type=t)

    #zmi actions
    security.declareProtected(view_management_screens, 'manageProperties')
    def manageProperties(self, title='', REQUEST=None):
        """ """
        lang = self.gl_get_selected_language()
        self._setLocalPropValue('title', lang, title)
        self._p_changed = 1
        if REQUEST: REQUEST.RESPONSE.redirect('manage_edit_html?save=ok')

    #site actions
    security.declareProtected(PERMISSION_PUBLISH_OBJECTS, 'saveProperties')
    def saveProperties(self, title='', lang=None, REQUEST=None):
        """ """
        if lang is None: lang = self.gl_get_selected_language()
        self._setLocalPropValue('title', lang, title)
        self._p_changed = 1
        if REQUEST:
            self.setSessionInfoTrans(MESSAGE_SAVEDCHANGES, date=self.utGetTodayDate())
            REQUEST.RESPONSE.redirect('%s/edit_html?lang=%s' % (self.absolute_url(), lang))

    security.declareProtected(PERMISSION_PUBLISH_OBJECTS, 'deleteObjects')
    def deleteObjects(self, ids=None, REQUEST=None):
        """ """
        if ids is None: ids = []
        else: ids = self.utConvertToList(ids)
        try: self.manage_delObjects(ids)
        except: self.setSessionErrors(['Error while deleting data.'])
        else: self.setSessionInfo(['Item(s) deleted.'])
        if REQUEST: REQUEST.RESPONSE.redirect('%s/index_html' % self.absolute_url())

    #zmi pages
    security.declareProtected(view_management_screens, 'manage_edit_html')
    manage_edit_html = PageTemplateFile('zpt/netrepository_manage_edit', globals())

    #site pages
    security.declareProtected(view, 'index_html')
    index_html = PageTemplateFile('zpt/netrepository_index', globals())

    security.declareProtected(PERMISSION_EDIT_OBJECTS, 'edit_html')
    edit_html = PageTemplateFile('zpt/netrepository_edit', globals())

    security.declareProtected(view, 'search_html')
    search_html = PageTemplateFile('zpt/netrepository_search', globals())

    security.declareProtected(PERMISSION_PUBLISH_OBJECTS, 'netsite_add_html')
    netsite_add_html = PageTemplateFile('zpt/netsite_add', globals())
Exemplo n.º 11
0
class NyConsultation(NyAttributes, Implicit, NyProperties, BTreeFolder2,
                     NyContainer, NyCheckControl, NyValidation, utils):
    """ """

    meta_type = METATYPE_OBJECT
    meta_label = LABEL_OBJECT

    all_meta_types = ()

    icon = 'misc_/NaayaContent/NyConsultation.gif'
    icon_marked = 'misc_/NaayaContent/NyConsultation_marked.gif'

    title = LocalProperty('title')
    description = LocalProperty('description')

    security = ClassSecurityInfo()

    edit_access = NyAccess(
        'edit_access', {
            PERMISSION_REVIEW_CONSULTATION: "Submit comments",
            PERMISSION_VIEW_CONSULTATION: "View consultation",
            PERMISSION_MANAGE_CONSULTATION: "Administer consultation",
        })

    def __init__(self, id, title, description, sortorder, start_date, end_date,
                 public_registration, allow_file, line_comments, contributor,
                 releasedate, lang):
        """ """
        self.id = id
        NyValidation.__dict__['__init__'](self)
        NyCheckControl.__dict__['__init__'](self)
        NyContainer.__dict__['__init__'](self)
        BTreeFolder2.__init__(self)
        self.contributor = contributor
        self.questions = {}
        try:
            del self.title
        except:
            pass
        self.save_properties(title, description, sortorder, start_date,
                             end_date, public_registration, allow_file,
                             line_comments, releasedate, lang)
        NyProperties.__dict__['__init__'](self)
        self.submitted = 1

    security.declarePrivate('save_properties')

    def save_properties(self, title, description, sortorder, start_date,
                        end_date, public_registration, allow_file,
                        line_comments, releasedate, lang):

        self._setLocalPropValue('title', lang, title)
        self._setLocalPropValue('description', lang, description)

        if not hasattr(self, 'imageContainer'):
            self.imageContainer = NyImageContainer(self, True)

        if start_date:
            self.start_date = self.utConvertStringToDateTimeObj(start_date)
        else:
            self.start_date = self.utGetTodayDate()

        if end_date:
            self.end_date = self.utConvertStringToDateTimeObj(end_date)
        else:
            self.end_date = self.utGetTodayDate()

        self.sortorder = sortorder
        self.releasedate = releasedate
        self.public_registration = public_registration
        self.allow_file = allow_file
        self.line_comments = line_comments

    security.declareProtected(PERMISSION_MANAGE_CONSULTATION, 'saveProperties')

    def saveProperties(self,
                       title='',
                       description='',
                       sortorder='',
                       start_date='',
                       end_date='',
                       public_registration='',
                       allow_file='',
                       line_comments='',
                       file='',
                       lang='',
                       REQUEST=None):
        """ """

        if not title:
            self.setSession('title', title)
            self.setSession('description', description)
            self.setSessionErrors(['The Title field must have a value.'])
            return REQUEST.RESPONSE.redirect('%s/edit_html?lang=%s' %
                                             (self.absolute_url(), lang))

        if file and not file.read():
            self.setSession('title', title)
            self.setSession('description', description)
            self.setSessionErrors(['File must not be empty'])
            return REQUEST.RESPONSE.redirect('%s/edit_html?lang=%s' %
                                             (self.absolute_url(), lang))

        exfile = self.get_exfile()

        if file and exfile:
            exfile.saveUpload(file=file, lang=lang)
            downloadfilename = file.filename
            exfile._setLocalPropValue('downloadfilename', lang,
                                      downloadfilename)
        elif file and not exfile:
            addNyExFile(self, title=title, file=file, lang=lang, source='file')

        releasedate = self.releasedate
        self.updateRequestRoleStatus(public_registration, lang)
        self.save_properties(title, description, sortorder, start_date,
                             end_date, public_registration, allow_file,
                             line_comments, releasedate, lang)

        if REQUEST:
            self.setSessionInfoTrans(MESSAGE_SAVEDCHANGES,
                                     date=self.utGetTodayDate())
            REQUEST.RESPONSE.redirect('%s/edit_html?lang=%s' %
                                      (self.absolute_url(), lang))

    security.declareProtected(PERMISSION_MANAGE_CONSULTATION,
                              'updateRequestRoleStatus')

    def updateRequestRoleStatus(self, public_registration, lang):
        if public_registration:
            self.updateDynamicProperties(
                self.processDynamicProperties(
                    METATYPE_OBJECT, {'show_contributor_request_role': 'on'}),
                lang)
        if not public_registration:
            self.updateDynamicProperties(
                self.processDynamicProperties(
                    METATYPE_OBJECT, {'show_contributor_request_role': ''}),
                lang)

    security.declareProtected(PERMISSION_MANAGE_CONSULTATION,
                              'checkReviewerRole')

    def checkReviewerRole(self):
        """
        Checks if the 'Reviewer' role exists,
        creates and adds review permissions if it doesn't exist
        """

        auth_tool = self.getAuthenticationTool()
        roles = auth_tool.list_all_roles()
        PERMISSION_GROUP = 'Review content'

        if 'Reviewer' not in roles:
            auth_tool.addRole('Reviewer', [PERMISSION_REVIEW_CONSULTATION])
        else:
            permission_add_role(self, PERMISSION_REVIEW_CONSULTATION,
                                'Reviewer')

        #give permissions to administrators
        admin_permissions = self.permissionsOfRole('Administrator')
        site = self.getSite()
        if PERMISSION_MANAGE_CONSULTATION not in admin_permissions:
            site.manage_permission(PERMISSION_MANAGE_CONSULTATION,
                                   ('Administrator', ),
                                   acquire=1)
            site.manage_permission(PERMISSION_VIEW_CONSULTATION,
                                   ('Administrator', ),
                                   acquire=1)
            site.manage_permission(PERMISSION_REVIEW_CONSULTATION,
                                   ('Administrator', ),
                                   acquire=1)

    ########################
    # Rate lists
    ########################
    manage_addRateList = manage_addRateList

    security.declareProtected(PERMISSION_MANAGE_CONSULTATION, 'default_rating')

    def default_rating(self):
        self.admin_addratelist('Relevancy', 'Relevancy', 'Relevancy')
        self.admin_additem('Relevancy', '1', 'Less relevant')
        self.admin_additem('Relevancy', '2', 'Average relevant')
        self.admin_additem('Relevancy', '3', 'Very relevant')

    security.declareProtected(PERMISSION_MANAGE_CONSULTATION, 'getRateValue')

    def getRateValue(self, review, rate):
        """ """
        try:
            return review.ratings[rate.title]
        except:
            return None

    security.declareProtected(PERMISSION_MANAGE_CONSULTATION, 'getRateLists')

    def getRateLists(self):
        return self.objectValues('Rate Item')

    security.declareProtected(PERMISSION_MANAGE_CONSULTATION,
                              'getRateListById')

    def getRateListById(self, p_id):
        #return the selection list with the given id
        try:
            ob = self._getOb(p_id)
        except:
            ob = None
        if ob is not None:
            if ob.meta_type != 'Rate Item': ob = None
        return ob

    security.declareProtected(PERMISSION_MANAGE_CONSULTATION,
                              'admin_deleteratelist')

    def admin_deleteratelist(self, ids=[], REQUEST=None):
        """ """
        self.manage_delObjects(self.utConvertToList(ids))
        if REQUEST:
            self.setSessionInfoTrans(MESSAGE_SAVEDCHANGES,
                                     date=self.utGetTodayDate())
            REQUEST.RESPONSE.redirect('%s/admin_ratelists_html' %
                                      self.absolute_url())

    security.declareProtected(PERMISSION_MANAGE_CONSULTATION,
                              'admin_addratelist')

    def admin_addratelist(self, id='', title='', description='', REQUEST=None):
        """ """
        self.manage_addRateList(id, title, description)
        if REQUEST:
            self.setSessionInfoTrans(MESSAGE_SAVEDCHANGES,
                                     date=self.utGetTodayDate())
            REQUEST.RESPONSE.redirect('%s/admin_ratelists_html' %
                                      self.absolute_url())

    security.declareProtected(PERMISSION_MANAGE_CONSULTATION,
                              'admin_editratelist')

    def admin_editratelist(self,
                           id='',
                           title='',
                           description='',
                           REQUEST=None):
        """ """
        ob = self.getRateListById(id)
        if ob is not None:
            ob.manageProperties(title, description)
        if REQUEST:
            self.setSessionInfoTrans(MESSAGE_SAVEDCHANGES,
                                     date=self.utGetTodayDate())
            REQUEST.RESPONSE.redirect('%s/admin_ratelist_html?id=%s' %
                                      (self.absolute_url(), id))

    security.declareProtected(PERMISSION_MANAGE_CONSULTATION,
                              'admin_deleteitems')

    def admin_deleteitems(self, id='', ids=[], REQUEST=None):
        """ """
        ob = self.getRateListById(id)
        if ob is not None:
            ob.manage_delete_items(self.utConvertToList(ids))
        if REQUEST:
            self.setSessionInfoTrans(MESSAGE_SAVEDCHANGES,
                                     date=self.utGetTodayDate())
            REQUEST.RESPONSE.redirect('%s/admin_ratelist_html?id=%s' %
                                      (self.absolute_url(), id))

    security.declareProtected(PERMISSION_MANAGE_CONSULTATION, 'admin_additem')

    def admin_additem(self, id='', item='', title='', REQUEST=None):
        """ """
        ob = self.getRateListById(id)
        if ob is not None:
            ob.manage_add_item(item, title)
        if REQUEST:
            self.setSessionInfoTrans(MESSAGE_SAVEDCHANGES,
                                     date=self.utGetTodayDate())
            REQUEST.RESPONSE.redirect('%s/admin_ratelist_html?id=%s' %
                                      (self.absolute_url(), id))

    security.declareProtected(view, 'get_consultation')

    def get_consultation(self):
        """ Returns this object"""
        return self

    security.declareProtected(view, 'get_consultation_url')

    def get_consultation_url(self):
        """ Returns this object's url"""
        return self.absolute_url()

    security.declareProtected(view, 'get_exfile')

    def get_exfile(self):
        """ Returns the first ExFile in the Consultation, there should be only one. """

        try:
            exfile = self.objectValues(['Naaya Extended File'])[0]
        except IndexError:
            exfile = None

        return exfile

    security.declareProtected(view, 'get_exfile_url')

    def get_exfile_url(self, lang):
        """ Returns the exfile download url for the given language """
        try:
            return self.get_exfile().getEditDownloadUrl(lang)
        except:
            return '[no_file]'

    security.declareProtected(view, 'check_exfile_for_lang')

    def check_exfile_for_lang(self, lang):
        """ Checks if there is a file uploaded for the given language. """

        return self.get_exfile().getFileItem(lang).size > 0

    security.declareProtected(view, 'get_exfile_langs')

    def get_exfile_langs(self):
        """ Returns the languages for witch NyExFile contains files. """

        return [
            language for language in self.getSite().gl_get_languages_map()
            if self.check_exfile_for_lang(language['id'])
        ]

    security.declareProtected(view, 'get_start_date')

    def get_start_date(self):
        """ Returns the start date in dd/mm/yyyy string format. """

        return self.utConvertDateTimeObjToString(self.start_date)

    security.declareProtected(view, 'get_end_date')

    def get_end_date(self):
        """ Returns the end date in dd/mm/yyyy string format. """

        return self.utConvertDateTimeObjToString(self.end_date)

    security.declareProtected(view, 'get_days_left')

    def get_days_left(self):
        """ Returns the remaining days for the consultation or the number of days before it starts """

        today = self.utGetTodayDate().earliestTime()

        if self.start_date.lessThanEqualTo(today):
            return (1, int(str((self.end_date + 1) - today).split('.')[0]))
        else:
            return (0, int(str(self.start_date - today).split('.')[0]))

    security.declareProtected(view_management_screens, 'manage_options')

    def manage_options(self):
        """ """

        l_options = (NyContainer.manage_options[0], )
        l_options += ({
            'label': 'View',
            'action': 'index_html'
        }, ) + NyContainer.manage_options[3:8]
        return l_options

    security.declareProtected(view, 'check_contributor_review')

    def check_contributor_review(self, contributor='', REQUEST=None):
        """ Returns True if user already posted a comment """

        if not contributor and REQUEST:
            contributor = REQUEST.AUTHENTICATED_USER.getUserName()

        return contributor in [
            review.contributor
            for review in self.objectValues(['Consultation Review'])
        ]

    security.declareProtected(PERMISSION_REVIEW_CONSULTATION,
                              'addConsultationReview')

    def addConsultationReview(self,
                              contributor_name='',
                              file='',
                              REQUEST=None,
                              **kwargs):
        """ """

        contributor = REQUEST.AUTHENTICATED_USER.getUserName()

        if not contributor_name:
            self.setSession('contributor_name', contributor_name)
            self.setSessionErrors(['Fill in the name field.'])
            return REQUEST.RESPONSE.redirect(self.absolute_url() +
                                             '/review_add_html')

        if REQUEST:
            kwargs.update(REQUEST.form)

        if self.allow_file != '1':
            file = ''

        if self.line_comments != '1':
            kwargs['adt_comment'] = {}

        days = self.get_days_left()
        if days[0] == 1 and days[1] > 0 and self.get_exfile():
            if not self.check_contributor_review(contributor):
                addConsultationReviewItem(self, contributor, contributor_name,
                                          file, kwargs)
                return REQUEST.RESPONSE.redirect(self.absolute_url() +
                                                 '/review_add_html?status=ok')
            else:
                return REQUEST.RESPONSE.redirect(
                    self.absolute_url() + '/review_add_html?status=failed')
        elif days[0] == 1 and days[1] <= 0:
            return REQUEST.RESPONSE.redirect(self.absolute_url() +
                                             '/review_add_html?status=late')
        elif days[0] <= 0:
            return REQUEST.RESPONSE.redirect(self.absolute_url() +
                                             '/review_add_html?status=soon')
        else:
            return REQUEST.RESPONSE.redirect(self.absolute_url())

    def checkConsultationUser(self):
        """
        Checks if the user is logged in and has reviewer rights:
        0 if user is anonymous,
        1 if user has reviewer role
        2 if user doesn't have reviewer role
        """
        review_check = self.checkPermissionReviewConsultation()

        if self.isAnonymousUser(): return 0
        elif review_check: return 1
        elif not review_check: return 2

    def checkPermissionReviewConsultation(self):
        """
        Check for reviewing the Consultation.
        """
        return self.checkPermission(PERMISSION_REVIEW_CONSULTATION)

    def checkPermissionManageConsultation(self):
        """
        Check for managing the Consultation.
        """
        return self.checkPermission(PERMISSION_MANAGE_CONSULTATION)

    def checkPermissionViewConsultation(self):
        """
        Check for managing the Consultation.
        """
        return self.checkPermission(PERMISSION_VIEW_CONSULTATION)

    security.declareProtected(view, 'get_reviews')

    def get_reviews(self):
        """ Returns a list with all the Consultation Review objects """
        return self.objectValues(['Consultation Review'])

    def count_line_comments(self):
        """ Returns the total count of line comments in all reviews """

        reviews = self.get_reviews()
        count = 0
        if reviews:
            for review in reviews:
                if self.review_has_comments(review):
                    count = count + 1
        return count

    def count_additional_files(self):
        """ Returns the total count of additional files in all reviews """

        reviews = self.get_reviews()
        count = 0
        if reviews:
            for review in reviews:
                if review.size > 0:
                    count = count + 1
        return count

    def count_question_answers(self):
        """ Returns (question_id, answer_count) """

        reviews = self.get_reviews()
        questions = self.get_questions()
        count = {}

        for qid, q in questions:
            count[qid] = 0

        for review in reviews:
            for qid, answer in review.answers:
                if answer:
                    count[qid] = count[qid] + 1
        return count.items()

    security.declareProtected(PERMISSION_MANAGE_CONSULTATION, 'addQuestion')

    def addQuestion(self, question_body, lang, sortorder, REQUEST=None):
        """ """
        id = 'q%s' % self.utGenRandomId(4)

        try:
            sortorder = int(sortorder)
        except:
            sortorder = 100

        if not self.questions.has_key(id): id = id
        else: id = id + self.utGenRandomId()

        self.questions[id] = question_item(question_body, lang, sortorder)
        self._p_changed = 1
        return REQUEST.RESPONSE.redirect('%s/manage_questions_html' %
                                         (self.absolute_url(), ))

    security.declareProtected(PERMISSION_MANAGE_CONSULTATION,
                              'delete_question')

    def delete_question(self, qid, REQUEST=None):
        """ """
        del (self.questions[qid])
        self._p_changed = 1
        return REQUEST.RESPONSE.redirect('%s/manage_questions_html' %
                                         (self.absolute_url(), ))

    security.declareProtected(PERMISSION_MANAGE_CONSULTATION, 'edit_question')

    def edit_question(self, qid, question_body, lang, REQUEST=None):
        """ """
        self.questions[qid].save_properties(question_body, lang)
        self._p_changed = 1
        return REQUEST.RESPONSE.redirect('%s/question_edit_html?qid=%s' %
                                         (self.absolute_url(), qid))

    security.declareProtected(PERMISSION_REVIEW_CONSULTATION, 'get_questions')

    def get_questions(self):
        """ Returns the questions sorted by sortorder (question_id, question_item)"""
        question_items = self.questions.items()
        question_items.sort(lambda x, y: cmp(x[1].sortorder, y[1].sortorder))
        return question_items

    security.declareProtected(PERMISSION_MANAGE_CONSULTATION,
                              'getQuestionById')

    def getQuestionById(self, qid):
        """ Returns the question item for the given id"""
        return self.questions[qid]

    security.declareProtected(PERMISSION_MANAGE_CONSULTATION,
                              'changeSortorder')

    def changeSortorder(self, qid, sortorder):
        """ """
        self.getQuestionById(qid).set_sortorder(sortorder)
        self._p_changed = 1

    security.declareProtected(view, 'getQuestionBody')

    def getQuestionBody(self, qid, lang):
        """ Returns the question's body string for the specified language """
        return self.getQuestionById(qid).get_body(lang)

    security.declareProtected(view, 'getQuestionSortorder')

    def getQuestionSortorder(self, qid):
        """ """
        return self.getQuestionById(qid).get_sortorder()

    security.declareProtected(view, 'review_has_comments')

    def review_has_comments(self, review):
        """ Checks if the review has any line comments """
        try:
            return review.linecomments[0]['comment']
        except KeyError:
            return ''

    security.declareProtected(PERMISSION_MANAGE_CONSULTATION, 'comment_image')
    comment_image = ImageFile('www/consultation-comment.gif', globals())

    #Consultation statistics

    security.declareProtected(view, 'getRatingTitles')

    def getRatingTitles(self):
        """ """
        cns_ratings = [x.title for x in self.getRateLists()]
        return cns_ratings

    security.declareProtected(view, 'getQuestionsReviews')

    def getQuestionsReviews(self):
        """
        Returns a dictionary with question ids as keys and
        a list of reviews that answered to that question as values.
        {qid: [rating1, rating2, ]}
        """

        reviews = self.get_reviews()
        questions = self.get_questions()
        qs_rev = {}

        for qid, q in questions:
            qs_rev[qid] = []

        for review in reviews:
            for qid, answer in review.answers:
                if answer:
                    qs_rev[qid].append(review.getId())
        return qs_rev

    security.declareProtected(PERMISSION_VIEW_CONSULTATION, 'getReviewById')

    def getReviewById(self, rid):
        """ """
        reviews = self.get_reviews()
        for review in reviews:
            if review.getId() == rid:
                return review

    #reviews sorting
    security.declareProtected(PERMISSION_VIEW_CONSULTATION, 'sort_cns_reviews')

    def sort_cns_reviews(self, by='Date'):
        """ Selects whitch method to use for sorting """

        if by == 'Date':
            return self.utSortObjsListByMethod(self.get_reviews(),
                                               'get_review_date', 1)
        else:
            return self.get_reviews_sorted(by)

    security.declareProtected(PERMISSION_VIEW_CONSULTATION,
                              'get_reviews_sorted')

    def get_reviews_sorted(self, rating=''):
        """ Returns the list of reviews sorted by rating value for the given rating """

        if rating not in self.getRatingTitles():
            return self.sort_reviews_page()
        reviews = [x for x in self.get_reviews()]
        reviews.sort(lambda x, y: cmp(int(y.getRatings()[rating]),
                                      int(x.getRatings()[rating])))
        return reviews

    security.declareProtected(PERMISSION_VIEW_CONSULTATION,
                              'sort_reviews_page')

    def sort_reviews_page(self, by='Date', REQUEST=None):
        """ Open the reviews page sorted acording to 'by' """
        if REQUEST is not None:
            return REQUEST.RESPONSE.redirect('%s/reviews_index_html?by=%s' %
                                             (self.absolute_url(), by))

    #site pages

    security.declareProtected(PERMISSION_REVIEW_CONSULTATION, 'edit_review')

    def edit_review(self):
        """ """
        auth_user = self.REQUEST.AUTHENTICATED_USER.getUserName()
        for review in self.objectValues(['Consultation Review']):
            if review.contributor == auth_user:
                return self.REQUEST.RESPONSE.redirect('%s/edit_html' %
                                                      review.absolute_url())
        self.setSessionErrors(['You cannot edit that Review.'])
        return self.REQUEST.RESPONSE.redirect(self.absolute_url() +
                                              '/index_html')

    security.declareProtected(PERMISSION_MANAGE_CONSULTATION,
                              'question_edit_html')
    question_edit_html = PageTemplateFile('zpt/question_edit', globals())

    security.declareProtected(PERMISSION_MANAGE_CONSULTATION,
                              'admin_ratelist_html')
    admin_ratelist_html = PageTemplateFile('zpt/admin_ratelist', globals())

    security.declareProtected(PERMISSION_MANAGE_CONSULTATION,
                              'admin_ratelists_html')
    admin_ratelists_html = PageTemplateFile('zpt/admin_ratelists', globals())

    security.declareProtected(PERMISSION_REVIEW_CONSULTATION,
                              'review_add_html')
    review_add_html = PageTemplateFile('zpt/review_add', globals())

    security.declareProtected(PERMISSION_MANAGE_CONSULTATION,
                              'manage_questions_html')
    manage_questions_html = PageTemplateFile('zpt/manage_questions', globals())

    security.declareProtected(PERMISSION_VIEW_CONSULTATION,
                              'reviews_index_html')
    reviews_index_html = PageTemplateFile('zpt/reviews_index', globals())

    security.declareProtected(view, 'index_html')
    index_html = PageTemplateFile('zpt/consultation_index', globals())

    security.declareProtected(PERMISSION_MANAGE_CONSULTATION, 'edit_html')
    edit_html = PageTemplateFile('zpt/consultation_edit', globals())

    security.declareProtected(PERMISSION_MANAGE_CONSULTATION,
                              'view_statistics_html')
    view_statistics_html = PageTemplateFile('zpt/view_statistics', globals())

    security.declareProtected(PERMISSION_MANAGE_CONSULTATION,
                              'instructions_html')
    instructions_html = PageTemplateFile('zpt/instructions', globals())
Exemplo n.º 12
0
class NySimpleConsultation(NyAttributes, Implicit, NyProperties, BTreeFolder2,
                           NyContainer, NyCheckControl, NyValidation, utils):
    """ """

    meta_type = METATYPE_OBJECT
    meta_label = LABEL_OBJECT

    all_meta_types = ()

    icon = 'misc_/NaayaContent/NySimpleConsultation.gif'
    icon_marked = 'misc_/NaayaContent/NySimpleConsultation_marked.gif'

    title = LocalProperty('title')
    description = LocalProperty('description')

    security = ClassSecurityInfo()

    edit_access = NyAccess(
        'edit_access', {
            PERMISSION_REVIEW_SIMPLECONSULTATION: "Submit comments",
            PERMISSION_MANAGE_SIMPLECONSULTATION: "Administer consultation",
        })

    def __init__(self, id, title, description, sortorder, start_date, end_date,
                 public_registration, allow_file, contributor, releasedate,
                 lang):
        """ """
        self.id = id
        NyValidation.__dict__['__init__'](self)
        NyCheckControl.__dict__['__init__'](self)
        NyContainer.__dict__['__init__'](self)
        BTreeFolder2.__init__(self)
        self.contributor = contributor
        try:
            del self.title
        except:
            pass
        self.save_properties(title, description, sortorder, start_date,
                             end_date, public_registration, allow_file,
                             releasedate, lang)
        NyProperties.__dict__['__init__'](self)
        self.submitted = 1

    security.declarePrivate('save_properties')

    def save_properties(self, title, description, sortorder, start_date,
                        end_date, public_registration, allow_file, releasedate,
                        lang):

        self._setLocalPropValue('title', lang, title)
        self._setLocalPropValue('description', lang, description)

        if not hasattr(self, 'imageContainer'):
            self.imageContainer = NyImageContainer(self, True)

        if start_date:
            self.start_date = self.utConvertStringToDateTimeObj(start_date)
        else:
            self.start_date = self.utGetTodayDate()

        if end_date:
            self.end_date = self.utConvertStringToDateTimeObj(end_date)
        else:
            self.end_date = self.utGetTodayDate()

        try:
            self.sortorder = abs(int(sortorder))
        except:
            self.sortorder = DEFAULT_SORTORDER

        self.releasedate = releasedate
        self.public_registration = public_registration
        self.allow_file = allow_file

    security.declareProtected(PERMISSION_MANAGE_SIMPLECONSULTATION,
                              'saveProperties')

    def saveProperties(self,
                       title='',
                       description='',
                       sortorder='',
                       start_date='',
                       end_date='',
                       public_registration='',
                       allow_file='',
                       file='',
                       lang='',
                       REQUEST=None):
        """ """

        if not title:
            self.setSession('title', title)
            self.setSession('description', description)
            self.setSessionErrors(['The Title field must have a value.'])
            if REQUEST:
                return REQUEST.RESPONSE.redirect('%s/edit_html?lang=%s' %
                                                 (self.absolute_url(), lang))
            else:
                raise ValueError('The title field must have a value.')

        if file and not file.read():
            self.setSession('title', title)
            self.setSession('description', description)
            self.setSessionErrors(['File must not be empty'])
            return REQUEST.RESPONSE.redirect('%s/edit_html?lang=%s' %
                                             (self.absolute_url(), lang))

        exfile = self.get_exfile()

        if file and exfile:
            exfile.saveUpload(file=file, lang=lang)
            downloadfilename = file.filename
            exfile._setLocalPropValue('downloadfilename', lang,
                                      downloadfilename)
        elif file and not exfile:
            addNyExFile(self, title=title, file=file, lang=lang, source='file')

        releasedate = self.releasedate
        self.updateRequestRoleStatus(public_registration, lang)
        self.save_properties(title, description, sortorder, start_date,
                             end_date, public_registration, allow_file,
                             releasedate, lang)

        if REQUEST:
            self.setSessionInfoTrans(MESSAGE_SAVEDCHANGES,
                                     date=self.utGetTodayDate())
            REQUEST.RESPONSE.redirect('%s/edit_html?lang=%s' %
                                      (self.absolute_url(), lang))

    security.declareProtected(PERMISSION_MANAGE_SIMPLECONSULTATION,
                              'updateRequestRoleStatus')

    def updateRequestRoleStatus(self, public_registration, lang):
        """ Allow public registration for this consultation """
        if public_registration:
            self.updateDynamicProperties(
                self.processDynamicProperties(
                    METATYPE_OBJECT, {'show_contributor_request_role': 'on'}),
                lang)
        if not public_registration:
            self.updateDynamicProperties(
                self.processDynamicProperties(
                    METATYPE_OBJECT, {'show_contributor_request_role': ''}),
                lang)

    security.declareProtected(PERMISSION_MANAGE_SIMPLECONSULTATION,
                              'checkReviewerRole')

    def checkReviewerRole(self):
        """
        Checks if the 'Reviewer' role exists,
        creates and adds review permissions if it doesn't exist
        """

        auth_tool = self.getAuthenticationTool()
        roles = auth_tool.list_all_roles()
        PERMISSION_GROUP = 'Review content'

        if 'Reviewer' not in roles:
            auth_tool.addRole('Reviewer',
                              [PERMISSION_REVIEW_SIMPLECONSULTATION])
        else:
            permission_add_role(self, PERMISSION_REVIEW_SIMPLECONSULTATION,
                                'Reviewer')

        #give permissions to administrators
        admin_permissions = self.permissionsOfRole('Administrator')
        site = self.getSite()
        if PERMISSION_MANAGE_SIMPLECONSULTATION not in admin_permissions:
            site.manage_permission(PERMISSION_MANAGE_SIMPLECONSULTATION,
                                   ('Administrator', ),
                                   acquire=1)
            site.manage_permission(PERMISSION_REVIEW_SIMPLECONSULTATION,
                                   ('Administrator', ),
                                   acquire=1)

    security.declareProtected(view, 'get_exfile')

    def get_exfile(self):
        """ Returns the first ExFile in the Simple Consultation, there should be only one. """

        try:
            exfile = self.objectValues(['Naaya Extended File'])[0]
        except IndexError:
            exfile = None

        return exfile

    security.declareProtected(view, 'check_exfile_for_lang')

    def check_exfile_for_lang(self, lang):
        """ Checks if there is a file uploaded for the given language. """

        return self.get_exfile().getFileItem(lang).size > 0

    security.declareProtected(view, 'get_exfile_langs')

    def get_exfile_langs(self):
        """ Returns the languages for witch NyExFile contains files. """

        return [
            language for language in self.getSite().gl_get_languages_map()
            if self.check_exfile_for_lang(language['id'])
        ]

    security.declareProtected(view, 'get_start_date')

    def get_start_date(self):
        """ Returns the start date in dd/mm/yyyy string format. """

        return self.utConvertDateTimeObjToString(self.start_date)

    security.declareProtected(view, 'get_end_date')

    def get_end_date(self):
        """ Returns the end date in dd/mm/yyyy string format. """

        return self.utConvertDateTimeObjToString(self.end_date)

    security.declareProtected(view, 'get_days_left')

    def get_days_left(self):
        """ Returns the remaining days for the consultation or the number of days before it starts """

        today = self.utGetTodayDate().earliestTime()
        if not self.start_date or not self.end_date:
            return (1, 0)

        if self.start_date.lessThanEqualTo(today):
            return (1, int(str(self.end_date - today).split('.')[0]))
        else:
            return (0, int(str(self.start_date - today).split('.')[0]))

    security.declareProtected(view_management_screens, 'manage_options')

    def manage_options(self):
        """ """

        l_options = (NyContainer.manage_options[0], )
        l_options += ({
            'label': 'View',
            'action': 'index_html'
        }, ) + NyContainer.manage_options[3:8]
        return l_options

    security.declareProtected(view, 'check_contributor_comment')

    def check_contributor_comment(self, contributor='', REQUEST=None):
        """ Returns True if user already posted a comment """

        if not contributor and REQUEST:
            contributor = REQUEST.AUTHENTICATED_USER.getUserName()

        return contributor in [
            comment.contributor
            for comment in self.objectValues(['Simple Consultation Comment'])
        ]

    security.declareProtected(PERMISSION_REVIEW_SIMPLECONSULTATION,
                              'addComment')

    def addComment(self,
                   title='',
                   contributor_name='',
                   message='',
                   file='',
                   REQUEST=None):
        """ """

        if not title or not contributor_name or not message:
            self.setSession('title', title)
            self.setSession('contributor_name', contributor_name)
            self.setSession('message', message)
            self.setSessionErrors(['Fill in all mandatory fields.'])
            return REQUEST.RESPONSE.redirect(self.absolute_url() +
                                             '/add_simpleconsultation_comment')

        contributor = REQUEST.AUTHENTICATED_USER.getUserName()
        if not self.allow_file: file = ''
        days = self.get_days_left()

        if days[0] == 1 and days[1] > 0:
            if not self.check_contributor_comment(contributor):
                addSimpleConsultationComment(self, title, contributor,
                                             contributor_name, message, file,
                                             REQUEST)
            else:
                return REQUEST.RESPONSE.redirect(
                    self.absolute_url() +
                    '/add_simpleconsultation_comment?status=failed')
        elif days[0] == 1 and days[1] <= 0:
            return REQUEST.RESPONSE.redirect(
                self.absolute_url() +
                '/add_simpleconsultation_comment?status=late')
        elif days[0] <= 0:
            return REQUEST.RESPONSE.redirect(
                self.absolute_url() +
                '/add_simpleconsultation_comment?status=soon')

    def checkSimpleConsultationUser(self):
        """
        Checks if the user is logged in and has reviewer rights:
        0 if user is anonymous,
        1 if user has reviewer role
        2 if user doesn't have reviewer role
        """
        review_check = self.checkPermissionReviewSimpleConsultation()

        if self.isAnonymousUser(): return 0
        elif review_check: return 1
        elif not review_check: return 2

    #permissions
    def checkPermissionReviewSimpleConsultation(self):
        """
        Check for reviewing the Simple Consultation.
        """
        return self.checkPermission(PERMISSION_REVIEW_SIMPLECONSULTATION)

    def checkPermissionManageSimpleConsultation(self):
        """
        Check for managing the Simple Consultation.
        """
        return self.checkPermission(PERMISSION_MANAGE_SIMPLECONSULTATION)

    #zmi pages
    security.declareProtected(view_management_screens, 'manage_edit_html')
    manage_edit_html = PageTemplateFile('zpt/simpleconsultation_manage_edit',
                                        globals())

    #site pages
    security.declareProtected(view, 'index_html')
    index_html = PageTemplateFile('zpt/simpleconsultation_index', globals())

    security.declareProtected(PERMISSION_MANAGE_SIMPLECONSULTATION,
                              'edit_html')
    edit_html = PageTemplateFile('zpt/simpleconsultation_edit', globals())

    security.declareProtected(PERMISSION_REVIEW_SIMPLECONSULTATION,
                              'add_simpleconsultation_comment')
    add_simpleconsultation_comment = PageTemplateFile(
        'zpt/simpleconsultation_comment_add', globals())
Exemplo n.º 13
0
class BaseSurveyTemplate(Folder, LocalPropertyManager):
    """Survey Template"""

    manage_options = (
        {
            'label': 'Contents',
            'action': 'manage_main',
            'help': ('OFSP', 'ObjectManager_Contents.stx')
        },
        {
            'label': 'View',
            'action': 'index_html'
        },
        {
            'label': 'Properties',
            'action': 'manage_propertiesForm',
            'help': ('OFSP', 'Properties.stx')
        },
        {
            'label': 'Security',
            'action': 'manage_access',
            'help': ('OFSP', 'Security.stx')
        },
    )

    _properties = ()

    security = ClassSecurityInfo()

    title = LocalProperty('title')
    description = LocalProperty('description')

    def _get_meta_types_from_names(self, meta_type_names):
        """Return the meta_type objects for meta_type_names"""
        meta_types = []
        for meta_type in Products.meta_types:
            if meta_type['name'] in meta_type_names:
                meta_types.append(meta_type)
        return meta_types

    def get_widget_meta_types(self):
        """ """
        return self._get_meta_types_from_names(
            [w.meta_type for w in AVAILABLE_WIDGETS])

    def get_report_meta_types(self):
        """ """
        return self._get_meta_types_from_names([SurveyReport.meta_type])

    def all_meta_types(self, interfaces=None):
        """ What can you put inside me? """
        return (self.get_widget_meta_types() + self.get_report_meta_types() +
                self._get_meta_types_from_names(
                    ['Script (Python)', 'Page Template']) +
                [{
                    'name': "Naaya Survey Answer",
                    'action': 'base_questionnaire_add_html',
                    'permission': 'view',
                }])

    def __init__(self, id, lang=None, **kwargs):
        Folder.__init__(self, id=id)
        self.set_localproperty('title', 'string', lang)
        self.set_localproperty('description', 'text', lang)
        self.saveProperties(lang=lang, **kwargs)

    #
    # global methods used in naaya site context
    #
    def _object_add_language(self, language, **kwargs):
        for doc in self.objectValues():
            doc.add_language(language)

    def _object_del_language(self, language, **kwargs):
        for doc in self.objectValues():
            doc.del_language(language)

    #
    # Self edit methods
    #
    security.declarePrivate('saveProperties')

    def saveProperties(self, REQUEST=None, **kwargs):
        """Update properties"""
        if REQUEST:
            kwargs.update(REQUEST.form)
        lang = kwargs.get('lang', self.get_selected_language())
        local_properties = filter(
            None, [x.get('id', None) for x in self.getLocalProperties()])
        # Update localized properties
        for local_property in local_properties:
            prop_value = kwargs.get(local_property, '')
            self.set_localpropvalue(local_property, lang, prop_value)
        # Update non-localized properties
        kwargs = dict([(key, value) for key, value in kwargs.items()
                       if key not in local_properties])
        self.manage_changeProperties(**kwargs)
        if REQUEST:
            query = {'lang': lang}
            query = urlencode(query)
            REQUEST.RESPONSE.redirect('%s/edit_html?%s' %
                                      (self.absolute_url(), query))
        return True

    #
    # Widget read methods
    #
    security.declareProtected(view, 'getWidgetTypes')

    def getWidgetTypes(self):
        """What widgets can I add inside this?"""
        types = self.get_widget_meta_types()
        for widget_type in types:
            instance = widget_type.get('instance', None)
            widget_type.update({
                'meta_type':
                getattr(instance, 'meta_type', ''),
                'meta_label':
                getattr(instance, 'meta_label', ''),
                'meta_description':
                getattr(instance, 'meta_description', ''),
            })
        return types

    security.declareProtected(view, 'getWidgetTypesAsMatrix')

    def getWidgetTypesAsMatrix(self, cols=3):
        """ Return widget types as a matrix with cols columns"""
        widget_types = self.getWidgetTypes()
        rows = len(widget_types) / cols
        rows += len(widget_types) % cols and 1
        return [[x for i, x in enumerate(widget_types) if i / cols == j]
                for j in range(rows)]

    security.declareProtected(view, 'getWidget')

    def getWidget(self, widget_id='', default=None, **kwargs):
        """ Return widget by id"""
        if not widget_id:
            return default
        return self._getOb(widget_id, default)

    security.declareProtected(view, 'getWidgets')

    def getWidgets(self):
        """ """
        return self.objectValues([w.meta_type for w in AVAILABLE_WIDGETS])

    security.declareProtected(view, 'getSortedWidgets')

    def getSortedWidgets(self, sort_by='sortorder'):
        """ Return sorted widget"""
        return sort(self.getWidgets(), ((sort_by, 'cmp', 'asc'), ))

    security.declareProtected(view, 'getNonEmptyAttribute')

    def getNonEmptyAttribute(self, attr):
        """ Return the value of the first non empty <attr> local atribute."""
        return self.getLocalAttribute(attr, langFallback=True)

    #
    # Widget edit methods
    #
    security.declarePrivate('addWidget')

    def addWidget(self, REQUEST=None, title='', meta_type=None, **kwargs):
        """Add a widget.

            @param meta_type: metatype of the widget
        """
        err = []
        if not title:
            err.append('Field title is required')
        if not meta_type:
            err.append('Field type is required')

        if err:
            if REQUEST is None:
                raise ValueError('.'.join(err))
            self.setSessionErrorsTrans(err)
            self.setSession('title', title)
            self.setSession('meta_type', meta_type)
            return REQUEST.RESPONSE.redirect(REQUEST.HTTP_REFERER)

        widget_cls = WIDGETS[meta_type]
        return manage_addWidget(widget_cls,
                                self,
                                title=title,
                                REQUEST=REQUEST,
                                **kwargs)

    security.declarePrivate('deleteItems')

    def deleteItems(self, ids=[], REQUEST=None):
        """ Delete items (e.g. widgets, reports) by ids"""
        if not ids:
            self.setSessionErrorsTrans(
                'Please select one or more items to delete.')
        else:
            try:
                if isinstance(self._getOb(ids[0]), AVAILABLE_WIDGETS):
                    for widget_id in ids:
                        if (getattr(self._getOb(widget_id), 'locked', '')
                                and not self.checkPermission(
                                    'View Management Screens')):
                            raise Unauthorized

                    # if we're deleting questions, delete the
                    # corresponding statistics too
                    for report in self.getReports():
                        statistic_ids = [
                            stat.id for stat in report.getStatistics()
                            if stat.question.id in ids
                        ]
                        report.manage_delObjects(statistic_ids)
                self.manage_delObjects(ids)
            except Unauthorized:
                err = sys.exc_info()
                zLOG.LOG('Naaya Survey Tool',
                         zLOG.ERROR,
                         'Could not delete items',
                         error=err)
                self.setSessionErrorsTrans(
                    'You are not authorized to delete selected items.')
            except:
                err = sys.exc_info()
                zLOG.LOG('Naaya Survey Tool',
                         zLOG.ERROR,
                         'Could not delete items',
                         error=err)
                self.setSessionErrorsTrans('Error while deleting data.')
            else:
                self.setSessionInfoTrans('Item(s) deleted.')
        if REQUEST:
            return REQUEST.RESPONSE.redirect(REQUEST.HTTP_REFERER)

    security.declarePrivate('setSortOrder')

    def setSortOrder(self, REQUEST=None, **kwargs):
        """ Bulk update widgets sort order"""
        if REQUEST:
            kwargs.update(REQUEST.form)
        for key, value in kwargs.items():
            widget = self._getOb(key, None)
            if widget is None or not isinstance(widget, Widget):
                continue
            widget.saveProperties(sortorder=value)
        if REQUEST:
            self.setSessionInfoTrans(MESSAGE_SAVEDCHANGES,
                                     date=self.utGetTodayDate())
            return REQUEST.RESPONSE.redirect(REQUEST.HTTP_REFERER)
        return True

    #
    # Bulk widgets methods
    #
    security.declareProtected(view, 'render')

    def render(self, mode='view', datamodel={}, **kwargs):
        """Render widgets"""
        widgets = self.getSortedWidgets()
        return '\n'.join([
            widget.render(mode=mode,
                          datamodel=datamodel.get(widget.id, None),
                          **kwargs) for widget in widgets
        ])

    #
    # Reports
    #
    security.declareProtected(view, 'getReport')

    def getReport(self, report_id='', default=None, **kwargs):
        """ Return widget by id"""
        if not report_id:
            return default
        return self._getOb(report_id, default)

    security.declareProtected(view, 'getReports')

    def getReports(self):
        """ """
        return self.objectValues([SurveyReport.meta_type])

    security.declareProtected(view, 'getSortedReports')

    def getSortedReports(self, sort_by='title'):
        """ """
        return sort(self.getReports(), ((sort_by, 'cmp', 'asc'), ))

    security.declarePrivate('addReport')

    def addReport(self, title='', REQUEST=None, **kwargs):
        """Add a new report"""
        err = []
        if not title:
            err.append('Field title is required')

        if err:
            if REQUEST is None:
                raise ValueError('.'.join(err))
            self.setSessionErrorsTrans(err)
            self.setSession('title', title)
            return REQUEST.RESPONSE.redirect(REQUEST.HTTP_REFERER)

        report_id = manage_addSurveyReport(self, title=title, REQUEST=REQUEST)
        if REQUEST is not None:
            REQUEST.RESPONSE.redirect(REQUEST.HTTP_REFERER)
        return report_id

    security.declarePrivate('generateFullReport')

    def generateFullReport(self, title='', REQUEST=None):
        """Generate a full report"""
        if not title:
            if REQUEST is None:
                raise ValueError('Field title is required')
            self.setSessionErrorsTrans('Field title is required')
            return REQUEST.RESPONSE.redirect(REQUEST.HTTP_REFERER)

        report_id = manage_addSurveyReport(self, title=title)
        report = self._getOb(report_id)
        sortorder = 1
        for question in self.getSortedWidgets():
            stat_classes = []
            if isinstance(question, LabelWidget):
                pass
            elif isinstance(question, MultipleChoiceWidget):
                stat_classes.extend([
                    MultipleChoiceTabularStatistic,
                    MultipleChoiceCssBarChartStatistic,
                    MultipleChoiceGoogleBarChartStatistic,
                    MultipleChoicePieChartStatistic
                ])

            elif isinstance(question, ComboboxMatrixWidget):
                stat_classes.extend([ComboboxMatrixTabularStatistic])
            elif isinstance(question, MatrixWidget):
                stat_classes.extend(
                    [MatrixTabularStatistic, MatrixCssBarChartStatistic])

            elif isinstance(question, StringWidget) or isinstance(
                    question, TextAreaWidget):
                stat_classes.extend([TextAnswerListing])

            else:
                stat_classes.extend([SimpleTabularStatistic])

            for stat_class in stat_classes:
                manage_addStatistic(stat_class,
                                    report,
                                    question=question,
                                    sortorder=sortorder)
                sortorder += 1
        if REQUEST is not None:
            REQUEST.RESPONSE.redirect(REQUEST.HTTP_REFERER)
        return report_id

    #
    # Attachments
    #
    security.declareProtected(view, 'getAttachments')

    def getAttachments(self):
        """ """
        return self.objectValues([SurveyAttachment.meta_type])

    security.declareProtected(view, 'getReports')

    def getSortedAttachments(self, sort_by='title'):
        """ """
        return sort(self.getAttachments(), ((sort_by, 'cmp', 'asc'), ))

    security.declarePrivate('addAttachment')

    def addAttachment(self, title='', REQUEST=None, **kwargs):
        """Add an attachment"""
        result = addSurveyAttachment(self,
                                     title=title,
                                     REQUEST=REQUEST,
                                     **kwargs)
        if REQUEST:
            return REQUEST.RESPONSE.redirect(REQUEST.HTTP_REFERER)
        return result

    #
    # Macros
    #
    security.declareProtected(view, 'base_edit_attachments_html')
    base_edit_attachments_html = PageTemplateFile(
        'zpt/base_surveytemplate_edit_attachments', globals())

    security.declareProtected(view, 'base_edit_questions_html')
    base_edit_questions_html = PageTemplateFile(
        'zpt/base_surveytemplate_edit_questions', globals())

    security.declareProtected(view, 'base_edit_reports_html')
    base_edit_reports_html = PageTemplateFile(
        'zpt/base_surveytemplate_edit_reports', globals())
Exemplo n.º 14
0
class NyForum(NyRoleManager, NyPermissions, NyForumBase, Folder, utils,
              LocalPropertyManager):
    """ """
    interface.implements(INyForum)

    meta_type = METATYPE_NYFORUM
    meta_label = LABEL_NYFORUM
    icon = 'misc_/NaayaForum/NyForum.gif'
    icon_marked = 'misc_/NaayaForum/NyForum_marked.gif'
    topics_listing = 'Plain table'
    topics_ordering = 'Reverse: Chronological order'
    message_top = LocalProperty('message_top')
    message_outdated = LocalProperty('message_outdated')

    manage_options = (Folder.manage_options[0:2] +
                      ({
                          'label': 'Properties',
                          'action': 'manage_edit_html'
                      }, ) + Folder.manage_options[3:8])

    meta_types = ({
        'name': METATYPE_NYFORUMTOPIC,
        'action': 'manage_addNyForumTopic_html'
    }, )
    all_meta_types = meta_types

    security = ClassSecurityInfo()

    edit_access = NyAccess(
        'edit_access', {
            view: "Access content",
            PERMISSION_MODIFY_FORUMTOPIC: "Modify topic",
            PERMISSION_ADD_FORUMMESSAGE: "Add message",
            PERMISSION_MODIFY_FORUMMESSAGE: "Modify message",
        })

    #constructors
    security.declareProtected(view_management_screens,
                              'manage_addNyForumTopic_html')
    manage_addNyForumTopic_html = manage_addNyForumTopic_html

    security.declareProtected(PERMISSION_MODIFY_FORUMTOPIC, 'topic_add_html')
    topic_add_html = topic_add_html

    security.declareProtected(PERMISSION_MODIFY_FORUMTOPIC, 'addNyForumTopic')
    addNyForumTopic = addNyForumTopic

    def __init__(self, id, title, description, categories, file_max_size,
                 contributor):
        """ """
        self.id = id
        self.title = title
        self.description = description
        self.categories = categories
        self.file_max_size = file_max_size
        self.contributor = contributor
        NyForumBase.__dict__['__init__'](self)
        #make this object available for portal search engine
        self.submitted = 1
        self.approved = 1

    def loadDefaultData(self):
        """
        Sets default permissions
        """
        self.manage_permission(PERMISSION_ADD_FORUMMESSAGE, ['Anonymous'],
                               acquire=1)
        self.manage_permission(PERMISSION_MODIFY_FORUMTOPIC,
                               ['Administrator', 'Manager'],
                               acquire=1)
        self.manage_permission(PERMISSION_SKIP_CAPTCHA,
                               ['Administrator', 'Manager'],
                               acquire=1)

    def __setstate__(self, state):
        """
        For backwards compatibility.
        """
        NyForum.inheritedAttribute("__setstate__")(self, state)
        if not hasattr(self, 'file_max_size'):
            self.file_max_size = 0

    security.declarePrivate('_get_template')

    def _get_template(self, name):
        template = self._getOb('emailpt_%s' % name, None)
        if template is not None:
            return template.render_email

        template = email_templates.get(name, None)
        if template is not None:
            return template.render_email

        raise ValueError('template for %r not found' % name)

    #api
    def get_forum_object(self):
        return self

    def get_forum_path(self, p=0):
        return self.absolute_url(p)

    def get_forum_categories(self):
        return self.categories

    def get_topics(self):
        return self.objectValues(METATYPE_NYFORUMTOPIC)

    def count_topics(self):
        return len(self.objectIds(METATYPE_NYFORUMTOPIC))

    def getObjectsForValidation(self):
        return []

    def count_notok_objects(self):
        return 0

    def count_notchecked_objects(self):
        return 0

    security.declarePrivate('processIdentity')

    def processIdentity(self):
        """
        Returns information about the user who created the topic/message
        and the posting date.
        """
        return self.REQUEST.AUTHENTICATED_USER.getUserName(
        ), self.utGetTodayDate()

    security.declarePrivate('handleAttachmentUpload')

    def handleAttachmentUpload(self, ob, file):
        """
        Handle upload of a file. A B{File} object will be created inside
        the B{given} object.
        """
        if file != '':
            if hasattr(file, 'filename'):
                if file.filename != '':
                    if file.filename.find('\\') != -1:
                        id = file.filename.split('\\')[-1]
                    else:
                        id = file.filename
                    #check file size
                    id = self.utSlugify(id)
                    if len(file.read()
                           ) <= self.file_max_size or self.file_max_size == 0:
                        ob.manage_addFile(id=id, file=file)

    def can_be_seen(self):
        """
        Indicates if the current user has access to the current forum.
        """
        return self.checkPermission(view)

    def has_restrictions(self):
        """
        Indicates if this folder has restrictions for the current user.
        """
        return not self.acquiredRolesAreUsedBy(view)

    def get_roles_with_access(self):
        """
        Returns a list of roles that have access to this forum.
        """
        r = []
        ra = r.append
        for x in self.rolesOfPermission(view):
            if x['selected'] and x['name'] not in [
                    'Administrator', 'Anonymous', 'Manager', 'Owner'
            ]:
                ra(x['name'])
        return r

    security.declarePublic('getPublishedFolders')

    def getPublishedFolders(self):
        if not self.checkPermissionView():
            return []
        return self.objectValues(METATYPE_NYFORUMTOPIC)

    def getPublishedObjects(self):
        return []

    def getObjects(self):
        return self.getPublishedFolders()

    def getPendingFolders(self):
        return []

    def getFolders(self):
        return self.getPublishedFolders()

    def hasContent(self):
        return (len(self.getObjects()) > 0)

    def get_sort_options(self):
        """ return a maping of sorting options"""
        return [['Subject', 'subject', False],
                ['Access type', 'access', False], ['Status', 'status', False],
                ['Author', 'author', False],
                ['Number of replies', 'count_messages', False],
                ['Number of views', 'views', False],
                ['Chronological order', 'last_message', False],
                ['Reverse: Subject', 'subject', True],
                ['Reverse: Access type', 'access', True],
                ['Reverse: Status', 'status', True],
                ['Reverse: Author', 'author', True],
                ['Reverse: Number of replies', 'count_messages', True],
                ['Reverse: Number of views', 'views', True],
                ['Reverse: Chronological order', 'last_message', True]]

    security.declareProtected(view, 'checkTopicsPermissions')

    def checkTopicsPermissions(self):
        """
        This function is called on the forum index and it checkes whether or not
        to display the various buttons on that form.
        Returns in a list of tuples: which buttons should be visible,
        a list of topics, sorted reversed by the date of the last post.
        """
        REQUEST = self.REQUEST
        skey = REQUEST.get('skey', None)
        rkey = None
        if skey is None:
            for option in self.get_sort_options():
                if self.topics_ordering == option[0]:
                    skey = option[1]
                    rkey = option[2]
        if rkey is None:
            rkey = REQUEST.get('rkey')
            if not rkey:
                rkey = False
            else:
                rkey = rkey not in ['0', 'False']
        if self.topics_listing == 'Plain table':
            topics = {'Plain table': []}
        else:
            topics = {}
            for category in self.categories:
                topics[category] = []
        btn_select, btn_delete, can_operate = 0, 0, 0
        # btn_select - if there is at least one permisson to delete or copy an object
        # btn_delete - if there is at least one permisson to delete an object
        for x in self.objectValues(METATYPE_NYFORUMTOPIC):
            del_permission = x.checkPermissionModifyForumTopic()
            edit_permission = x.checkPermissionModifyForumTopic()
            if del_permission: btn_select = 1
            if del_permission: btn_delete = 1
            if edit_permission: can_operate = 1
            if self.topics_listing == 'Plain table':
                topics['Plain table'].append(
                    (del_permission, edit_permission, x))
            else:
                if x.category in topics.keys():
                    topics[x.category].append(
                        (del_permission, edit_permission, x))
                elif 'Other' in topics.keys():
                    topics['Other'].append(
                        (del_permission, edit_permission, x))
                else:
                    topics['Other'] = [(del_permission, edit_permission, x)]
        can_operate = can_operate or btn_select
        for topics_category in topics.values():
            if skey == 'subject':
                topics_category.sort(key=lambda x: x[2].title_or_id().lower(),
                                     reverse=rkey)
            elif skey == 'access':
                topics_category.sort(key=lambda x: x[2].access_type(),
                                     reverse=rkey)
            elif skey == 'status':
                topics_category.sort(key=lambda x: x[2].is_topic_opened(),
                                     reverse=rkey)
            elif skey == 'views':
                topics_category.sort(
                    key=lambda x: self.getTopicHits(topic=x[2].id),
                    reverse=rkey)
            elif skey == 'last_message':
                topics_category.sort(
                    key=lambda x: x[2].get_last_message().postdate,
                    reverse=rkey)
            else:
                try:
                    topics_category.sort(key=lambda x: getattr(x[2], skey),
                                         reverse=rkey)
                except AttributeError:
                    #This means the sort key was wrong (manually altered)
                    pass
        return btn_select, btn_delete, can_operate, topics, skey, rkey

    def checkPermissionSkipCaptcha(self):
        return getSecurityManager().checkPermission('Naaya - Skip Captcha',
                                                    self)

    #zmi actions
    security.declareProtected(view_management_screens, 'manageProperties')

    def manageProperties(self,
                         title='',
                         description='',
                         categories='',
                         file_max_size='',
                         topics_listing='',
                         topics_ordering='',
                         REQUEST=None):
        """ """
        contributor = self.REQUEST.AUTHENTICATED_USER.getUserName()
        self.contributor = contributor
        self.title = title
        self.description = description
        self.categories = self.utConvertLinesToList(categories)
        self.file_max_size = abs(int(file_max_size))
        self.topics_listing = topics_listing
        self.topics_ordering = topics_ordering
        self._p_changed = 1
        if REQUEST: REQUEST.RESPONSE.redirect('manage_edit_html?save=ok')

    #zmi actions
    security.declareProtected(PERMISSION_ADD_FORUM, 'saveProperties')

    def saveProperties(self,
                       title='',
                       description='',
                       categories='',
                       file_max_size='',
                       topics_listing='',
                       topics_ordering='',
                       message_top='',
                       message_outdated='',
                       alphabetic_categories=None,
                       REQUEST=None):
        """ """
        contributor = self.REQUEST.AUTHENTICATED_USER.getUserName()
        self.contributor = contributor
        self.title = title
        self.description = description
        self.categories = self.utConvertLinesToList(categories)
        self.file_max_size = abs(int(file_max_size))
        self.topics_listing = topics_listing
        self.topics_ordering = topics_ordering
        lang = self.gl_get_selected_language()
        self._setLocalPropValue('message_top', lang, message_top)
        self._setLocalPropValue('message_outdated', lang, message_outdated)
        self.alphabetic_categories = alphabetic_categories
        self._p_changed = 1
        if REQUEST:
            self.setSessionInfoTrans(MESSAGE_SAVEDCHANGES,
                                     date=self.utGetTodayDate())
            REQUEST.RESPONSE.redirect('edit_html?save=ok')

    #site actions
    security.declareProtected(PERMISSION_MODIFY_FORUMTOPIC, 'deleteTopics')

    def deleteTopics(self, ids='', REQUEST=None):
        """ """
        try:
            self.manage_delObjects(self.utConvertToList(ids))
        except:
            self.setSessionErrorsTrans('Error while deleting data.')
        else:
            self.setSessionInfoTrans('Topic(s) deleted.')
        if REQUEST:
            REQUEST.RESPONSE.redirect('%s/index_html' % self.absolute_url())

    #
    # Statistics
    #
    security.declarePrivate("_getStatisticsContainerCursor")

    def _getStatisticsContainerCursor(self):
        """ Create statistics container if it doesn't exists and return it
        """
        stats_container = getattr(self, STATISTICS_CONTAINER, None)
        if stats_container is None:
            # do DB was ever created
            cursor = None
        else:
            try:
                cursor = stats_container.cursor()
            except naaya.sql.DbMissing:
                # DB was removed
                cursor = None

        if cursor is None:
            stats_container = naaya.sql.new_db()
            setattr(self, STATISTICS_CONTAINER, stats_container)
            table = ("CREATE TABLE HITS"
                     "(id INTEGER PRIMARY KEY ASC AUTOINCREMENT")
            for (col, val) in STATISTICS_COLUMNS.items():
                table += ", " + col + " " + val
            table += ")"
            cursor = stats_container.cursor()
            cursor.execute(table)

        return cursor

    def _removeStatisticsContainer(self):
        """ Remove statistics container if exists
        """
        stats_container = getattr(self, STATISTICS_CONTAINER, None)
        if stats_container is not None:
            if hasattr(stats_container, 'drop'):
                stats_container.drop()
            delattr(self, STATISTICS_CONTAINER)

    security.declareProtected(view, 'getTopicHits')

    def getTopicHits(self, topic):
        """ Returns statistics for given topic
        """
        cursor = self._getStatisticsContainerCursor()
        cursor.execute("SELECT hits from HITS where topic=?", (topic, ))
        res = cursor.fetchone()
        if not res:
            cursor.execute("INSERT into HITS(topic) values(?)", (topic, ))
            return 0
        else:
            return res[0]

    security.declarePrivate('setTopicHits')

    def setTopicHits(self, topic, how_many=1):
        hits = self.getTopicHits(topic) + how_many
        cursor = self._getStatisticsContainerCursor()
        cursor.execute("UPDATE HITS set hits=? where topic=?", (hits, topic))

    security.declareProtected(view, 'updateTopicHits')

    def updateTopicHits(self, topic):
        """ Update hits for topic
        """
        self.setTopicHits(topic, 1)

    security.declareProtected(view, 'removeTopicHits')

    def removeTopicHits(self, topic):
        """ Remove hits record for topic
        """
        cursor = self._getStatisticsContainerCursor()
        cursor.execute("DELETE FROM HITS where topic=?", (topic, ))

    security.declareProtected(view, 'hasVersion')

    def hasVersion(self):
        """ """
        return False

    security.declarePublic('export_this')

    def export_this(self, folderish=0):
        """ """
        return ''

    security.declareProtected(view, 'get_categories')

    def get_categories(self):
        """ return categories, sorted if the option is set on the forum
        """
        if getattr(self, 'alphabetic_categories', None):
            return sorted(self.categories)
        return self.categories

    #zmi pages
    security.declareProtected(view_management_screens, 'manage_edit_html')
    manage_edit_html = PageTemplateFile('zpt/forum_manage_edit', globals())

    #site pages
    security.declareProtected(view, 'index_html')
    index_html = NaayaPageTemplateFile('zpt/forum_index', globals(),
                                       'forum_index')

    security.declareProtected(view, 'messages_feed')
    messages_feed = messages_feed

    security.declareProtected(PERMISSION_ADD_FORUM, 'edit_html')
    edit_html = PageTemplateFile('zpt/forum_edit', globals())

    security.declareProtected(PERMISSION_ADD_FORUM, 'forum_add_html')
    forum_add_html = PageTemplateFile('zpt/forum_add', globals())
Exemplo n.º 15
0
class NyNetChannel(NyAttributes, LocalPropertyManager, NyItem, NyFeed):
    """ """

    meta_type = METATYPE_NYNETCHANNEL
    icon = 'misc_/NaayaNetRepository/NyNetChannel.gif'

    manage_options = (({
        'label': 'Properties',
        'action': 'manage_edit_html'
    }, ) + NyItem.manage_options)

    security = ClassSecurityInfo()

    title = LocalProperty('title')
    description = LocalProperty('description')

    def __init__(self, id, title, description, url, language, type, manual,
                 lang):
        """ """
        self.id = id
        self._setLocalPropValue('title', lang, title)
        self._setLocalPropValue('description', lang, description)
        self.url = url
        self.language = language
        self.type = type
        self.manual = manual
        NyFeed.__dict__['__init__'](self)

    security.declarePrivate('objectkeywords')

    def objectkeywords(self, lang):
        return u' '.join([
            self.getLocalProperty('title', lang),
            self.getLocalProperty('description', lang)
        ])

    #api
    def get_netchannel_object(self):
        return self

    def get_netchannel_path(self, p=0):
        return self.absolute_url(p)

    def get_feed_url(self):
        #method from NyFeed
        return self.url

    def set_new_feed_url(self, new_url):
        #method from NyFeed
        self.url = new_url
        self._p_changed = 1

    #zmi actions
    security.declareProtected(view_management_screens, 'manageProperties')

    def manageProperties(self,
                         title='',
                         description='',
                         url='',
                         language=None,
                         type=None,
                         REQUEST=None):
        """ """
        lang = self.gl_get_selected_language()
        if language is None: language = lang
        self._setLocalPropValue('title', lang, title)
        self._setLocalPropValue('description', lang, description)
        self.url = url
        self.language = language
        self.type = type
        self._p_changed = 1
        self.recatalogNyObject(self)
        if REQUEST: REQUEST.RESPONSE.redirect('manage_edit_html?save=ok')

    #site actions
    security.declareProtected(PERMISSION_PUBLISH_OBJECTS, 'saveProperties')

    def saveProperties(self,
                       title='',
                       description='',
                       url='',
                       language=None,
                       type=None,
                       lang=None,
                       REQUEST=None):
        """ """
        if lang is None: lang = self.gl_get_selected_language()
        if language is None: language = lang
        self._setLocalPropValue('title', lang, title)
        self._setLocalPropValue('description', lang, description)
        self.url = url
        self.language = language
        self.type = type
        self._p_changed = 1
        self.recatalogNyObject(self)
        if REQUEST:
            self.setSessionInfoTrans(MESSAGE_SAVEDCHANGES,
                                     date=self.utGetTodayDate())
            REQUEST.RESPONSE.redirect('%s/edit_html?lang=%s' %
                                      (self.absolute_url(), lang))

    security.declareProtected(PERMISSION_PUBLISH_OBJECTS, 'update_netchannel')

    def update_netchannel(self, REQUEST=None):
        """ """
        self.harvest_feed()
        if REQUEST:
            if self.get_feed_bozo_exception() is not None:
                self.setSessionErrors([self.get_feed_bozo_exception()])
            else:
                self.setSessionInfoTrans(MESSAGE_SAVEDCHANGES,
                                         date=self.utGetTodayDate())
            REQUEST.RESPONSE.redirect('%s/index_html' % self.absolute_url())

    #zmi pages
    security.declareProtected(view_management_screens, 'manage_edit_html')
    manage_edit_html = PageTemplateFile('zpt/netchannel_manage_edit',
                                        globals())

    #site pages
    security.declareProtected(view, 'index_html')
    index_html = PageTemplateFile('zpt/netchannel_index', globals())

    security.declareProtected(PERMISSION_PUBLISH_OBJECTS, 'edit_html')
    edit_html = PageTemplateFile('zpt/netchannel_edit', globals())
Exemplo n.º 16
0
class Widget(Folder, LocalPropertyManager):
    """ Abstract class for widget
    """
    meta_type = 'Naaya Widget'
    meta_sortorder = 100  # used to sort the list of available widget types

    security = ClassSecurityInfo()

    # Subobjects
    all_meta_types = ()

    # ZMI Tabs
    manage_options = (
        {
            'label': 'Properties',
            'action': 'manage_propertiesForm',
            'help': ('OFSP', 'Properties.stx')
        },
        {
            'label': 'Contents',
            'action': 'manage_main',
            'help': ('OFSP', 'ObjectManager_Contents.stx')
        },
    )

    # Properties
    _properties = (
        {
            'id': 'sortorder',
            'type': 'int',
            'mode': 'w',
            'label': 'Sort order'
        },
        {
            'id': 'required',
            'type': 'boolean',
            'mode': 'w',
            'label': 'Required widget'
        },
    )

    sortorder = 100
    required = False
    localized = False

    # Local properties
    title = LocalProperty('title')
    tooltips = LocalProperty('tooltips')

    common_render_meth = PageTemplateFile('widgets/zpt/widget_common',
                                          globals())

    def __init__(self, id, lang=None, **kwargs):
        Folder.__init__(self, id=id)
        self.set_localproperty('title', 'string', lang)
        self.set_localproperty('tooltips', 'text', lang)
        self.saveProperties(lang=lang, **kwargs)

    security.declarePublic('getWidgetId')

    def getWidgetId(self):
        """ Returns widget id"""
        return self.getId()

    security.declareProtected(PERMISSION_EDIT_OBJECTS, 'saveProperties')

    def saveProperties(self, REQUEST=None, **kwargs):
        """ Update widget properties"""
        if REQUEST:
            kwargs.update(REQUEST.form)
        local_properties = self.getLocalProperties()
        local_properties = filter(
            None, [x.get('id', None) for x in local_properties])
        # Update local properties
        lang = kwargs.get('lang', self.get_selected_language())
        for local_property in local_properties:
            if not kwargs.has_key(local_property):
                continue
            prop_value = kwargs.get(local_property, '')

            # Strip empty values:
            if type(prop_value) in (str, unicode):
                prop_value = prop_value.strip()
            # Filter/strip empty values
            if type(prop_value) in (list, tuple):
                prop_value = [x.strip() for x in prop_value if x.strip()]
            if type(prop_value) == tuple:
                prop_value = tuple(prop_value)
            self.set_localpropvalue(local_property, lang, prop_value)
        # Update non local properties
        kwargs = dict([(key, value) for key, value in kwargs.items()
                       if key not in local_properties])
        self.manage_changeProperties(**kwargs)
        if REQUEST:
            self.setSessionInfoTrans(MESSAGE_SAVEDCHANGES,
                                     date=self.utGetTodayDate())
            return REQUEST.RESPONSE.redirect(REQUEST.HTTP_REFERER)

    def _get_default_value(self, **kwargs):
        return '-'

    #
    # To be implemented or ovewritten (if needed) by widget concrete classes.
    #
    def isEmptyDatamodel(self, value):
        return value is None

    def validateDatamodel(self, value):
        """Validate datamodel"""
        if self.required and self.isEmptyDatamodel(value):
            raise WidgetError('Value required for "%s"' % self.title)

    def prepare(self, datamodel, **kwargs):
        """ Prepare value to be stored according with widget type"""
        pass

    security.declareProtected(view, 'render')

    def render(self, mode, datamodel=None, **kwargs):
        """Render widget according with given mode"""

        from naaya.content.bfile.NyBlobFile import NyBlobFile
        if isinstance(datamodel, NyBlobFile):
            datamodel.aq_parent = datamodel.aq_parent.__of__(self.aq_parent)
            kwargs['parent'] = datamodel.aq_parent

        assert (mode in ('view', 'edit', 'manage'))
        return self.render_meth(mode=mode, datamodel=datamodel, **kwargs)

    security.declareProtected(view, 'get_value')

    def get_value(self, datamodel=None, **kwargs):
        """ Return a string with the data in this widget """
        if datamodel is None:
            return ''
        if isinstance(datamodel, dict):
            lang = self.gl_get_selected_language()
            return datamodel[lang]
        return datamodel

    security.declareProtected(PERMISSION_EDIT_OBJECTS, 'edit')
    edit = PageTemplateFile('zpt/edit_widget', globals())

    security.declareProtected(PERMISSION_EDIT_OBJECTS, 'edit_html')

    def edit_html(self):
        """ """
        if getattr(self, 'locked',
                   '') and not self.checkPermission('View Management Screens'):
            raise Unauthorized
        local_properties = self.getLocalProperties()
        local_properties = filter(
            None, [x.get('id', None) for x in local_properties])
        lang = self.get_selected_language()
        other_languages = [
            language for language in self.gl_get_languages()
            if language != lang
        ]
        if 'choices' in local_properties:
            choices = self.getLocalAttribute('choices', lang)
            for language in other_languages:
                other_choices = len(self.getLocalAttribute(
                    'choices', language))
                if (len(choices) != other_choices and other_choices):
                    errors = self.getSessionErrors() or []
                    errors.append(
                        'This question has a different '
                        'number of choices (%s) in %s. Reports cannot be generated '
                        'until this is corrected.' %
                        (other_choices, self.gl_get_language_name(language)))
                    self.setSessionErrorsTrans(errors)
        return self.edit()

    security.declareProtected(PERMISSION_EDIT_OBJECTS, 'preview_html')
    preview_html = PageTemplateFile('zpt/preview_widget', globals())

    security.declareProtected(PERMISSION_EDIT_OBJECTS, 'index_html')
    index_html = preview_html

    def getNonEmptyAttribute(self, attrName):
        """ Return the value of the first non empty <attrName> local atribute."""
        return self.getLocalAttribute(attrName, langFallback=True)
Exemplo n.º 17
0
class SurveyReport(Folder, LocalPropertyManager):
    """Survey Report"""

    meta_type = 'Naaya Survey Report'

    manage_options=(
        {'label':'Contents', 'action':'manage_main',
         'help':('OFSP','ObjectManager_Contents.stx')},
        {'label':'View', 'action':'index_html'},
        {'label':'Security', 'action':'manage_access',
         'help':('OFSP', 'Security.stx')},
        )

    _constructors = (manage_addSurveyReport,)

    _properties=()

    icon = 'misc_/NaayaSurvey/NySurveyReport.gif'

    security = ClassSecurityInfo()

    title = LocalProperty('title')
    description = LocalProperty('description')

    def __init__(self, id, lang=None, **kwargs):
        Folder.__init__(self, id=id)
        self.set_localproperty('title', 'string', lang)
        self.set_localproperty('description', 'text', lang)
        self.saveProperties(lang=lang, **kwargs)

    #
    # global methods used in naaya site context
    #
    def _object_add_language(self, language, **kwargs):
        for doc in self.objectValues():
            doc.add_language(language)

    def _object_del_language(self, language, **kwargs):
        for doc in self.objectValues():
            doc.del_language(language)

    #
    # Self edit methods
    #
    security.declareProtected(PERMISSION_EDIT_OBJECTS, 'saveProperties')
    def saveProperties(self, REQUEST=None, **kwargs):
        """Update properties"""
        if REQUEST:
            kwargs.update(REQUEST.form)
        local_properties = self.getLocalProperties()
        local_properties = filter(None, [x.get('id', None) for x in local_properties])
        # Update local properties
        lang = kwargs.get('lang', self.get_selected_language())
        for local_property in local_properties:
            prop_value = kwargs.get(local_property, '')
            self.set_localpropvalue(local_property, lang, prop_value)
        kwargs = dict([(key, value) for key, value in kwargs.items()
                       if key not in local_properties])
        self.manage_changeProperties(**kwargs)
        if REQUEST:
            query = {'lang': lang}
            query = urlencode(query)
            REQUEST.RESPONSE.redirect('%s/edit_html?%s' % (self.absolute_url(), query))
        return True

    security.declareProtected(view, 'getStatistics')
    def getStatistics(self):
        """Return the statistics"""
        return self.objectValues()

    #security.declareProtected(view, 'getSortedStatistics')
    security.declarePublic('getSortedStatistics')
    def getSortedStatistics(self, sort_by='sortorder'):
        """Return the statistics in sorted order"""
        return sort(self.getStatistics(), ((sort_by, 'cmp', 'asc'), ))

    security.declareProtected(PERMISSION_EDIT_OBJECTS, 'deleteStatistics')
    def addStatistic(self, REQUEST, question=None, meta_type=None):
        """Add a statistic for question.

            @param question: id of the question
            @param meta_type: metatype of the statistic
        """
        err = []
        if not question:
            err.append('Please select a question')
        if not meta_type:
            err.append('Please select a statistic type')
        if err:
            self.setSessionErrorsTrans(err)
            return REQUEST.RESPONSE.redirect(REQUEST.HTTP_REFERER)

        statistic_cls = STATISTICS[meta_type]
        question = self.getWidget(question)
        try:
            return manage_addStatistic(statistic_cls,
                                       self,
                                       genObjectId(question.title),
                                       question=question,
                                       REQUEST=REQUEST)
        except TypeError:
            if not REQUEST:
                raise
            err = sys.exc_info()
            LOG('NaayaSurvey.statistics.manage_addStatistic', DEBUG,
                'Error creating statistic %s for question %s' % (statistic_cls, question.absolute_url()), error=err)
            self.setSessionErrorsTrans('"${meta_label}" can\'t be used for question "${title}"',
                meta_label=statistic_cls.meta_label, title=question.title)
            return REQUEST.RESPONSE.redirect(REQUEST.HTTP_REFERER)

    security.declareProtected(PERMISSION_EDIT_OBJECTS, 'deleteStatistics')
    def deleteStatistics(self, ids=[], REQUEST=None):
        """ Delete statistics by ids"""
        if not ids:
            self.setSessionErrorsTrans('Please select one or more items to delete.')
        else:
            try: self.manage_delObjects(ids)
            except: self.setSessionErrorsTrans('Error while deleting data.')
            else: self.setSessionInfoTrans('Item(s) deleted.')
        REQUEST.RESPONSE.redirect('%s/index_html' % self.absolute_url())

    security.declareProtected(PERMISSION_EDIT_OBJECTS, 'setSortOrder')
    def setSortOrder(self, order={}, REQUEST=None):
        """Set the order of the statistics"""
        if REQUEST:
            order.update(REQUEST.form)
        for id, neworder in order.items():
            ob = self._getOb(id, None)
            if id not in self.objectIds():
                continue
            ob.sortorder = neworder
        if REQUEST:
            self.setSessionInfoTrans(MESSAGE_SAVEDCHANGES, date=self.utGetTodayDate())
            return REQUEST.RESPONSE.redirect(REQUEST.HTTP_REFERER)

    def getAvailableStatistics(self):
        """Return the available statistics"""
        return statistics.AVAILABLE_STATISTICS

    security.declareProtected(PERMISSION_EDIT_OBJECTS, 'index_html')
    index_html = PageTemplateFile('zpt/surveyreport_index', globals())

    security.declareProtected(view, 'edit_html')
    edit_html = PageTemplateFile('zpt/surveyreport_edit', globals())

    security.declareProtected(view, 'view_report_html')
    view_report_html = PageTemplateFile('zpt/surveyreport_view_report', globals())
Exemplo n.º 18
0
class semnews_item(Implicit, NyContentData, NyFSContainer):
    """ """
    meta_type = METATYPE_OBJECT
    file_link_local = LocalProperty('file_link_local')
Exemplo n.º 19
0
class SemideRegistration(LocalPropertyManager, Folder):
    """ Main class of the meeting registration"""

    meta_type = 'Semide Registration'
    product_name = 'SemideRegistration'

    security = ClassSecurityInfo()

    title = LocalProperty('title')
    conference_details = LocalProperty('conference_details')
    introduction = LocalProperty('introduction')

    manage_options = (Folder.manage_options[:1] +
                      ({
                          'label': 'Reload registration forms',
                          'action': 'reloadRegistrationForms'
                      }, ) + Folder.manage_options[2:])
    security.declareProtected(view, 'index_html')
    index_html = PageTemplateFile('zpt/registration/index', globals())

    security.declareProtected(view_management_screens, '_edit_html')
    _edit_html = PageTemplateFile('zpt/registration/edit', globals())

    security.declarePublic('registration_form')
    registration_form = PageTemplateFile('zpt/registration/registration',
                                         globals())

    security.declarePublic('registration_press_form')
    registration_press_form = PageTemplateFile(
        'zpt/registration/registration_press', globals())

    security.declarePublic('view_participant')
    view_participant = PageTemplateFile('zpt/participant/view_participant',
                                        globals())

    security.declarePublic('edit_participant')
    edit_participant = PageTemplateFile('zpt/participant/edit_participant',
                                        globals())

    security.declarePublic('menu_buttons')
    menu_buttons = PageTemplateFile('zpt/menu_buttons', globals())

    security.declareProtected(view_management_screens, 'participants')
    participants = PageTemplateFile('zpt/registration/participants', globals())

    security.declareProtected(view_management_screens, 'participants_press')
    participants_press = PageTemplateFile(
        'zpt/registration/participants_press', globals())

    def __init__(self, id, title, conference_details, administrative_email,
                 start_date, end_date, introduction, lang):
        """ constructor """
        self.id = id
        self.save_properties(title, conference_details, administrative_email,
                             start_date, end_date, introduction, lang)

    security.declareProtected(view_management_screens, 'loadDefaultContent')

    def loadDefaultContent(self):
        """ load default content such as: email templates """
        from TemplatesManager import manage_addTemplatesManager
        manage_addTemplatesManager(self)
        self._loadRegistrationForms()

    security.declarePrivate('_loadRegistrationForms')

    def _loadRegistrationForms(self):
        """ load registration forms """

    security.declarePrivate('_deleteRegistrationForms')

    def _deleteRegistrationForms(self):
        try:
            self.manage_delObjects([
                'registration_form', 'registration_press_form', 'menu_buttons',
                'view_participant', 'edit_participant'
            ])
        except:
            pass

    security.declareProtected(view_management_screens, 'save_properties')

    def save_properties(self, title, conference_details, administrative_email,
                        start_date, end_date, introduction, lang):
        """ save properties """
        self._setLocalPropValue('title', lang, title)
        self._setLocalPropValue('conference_details', lang, conference_details)
        self._setLocalPropValue('introduction', lang, introduction)
        self.administrative_email = administrative_email
        self.start_date = str2date(start_date)
        self.end_date = str2date(end_date)

    security.declareProtected(view_management_screens,
                              'reloadRegistrationForms')

    def reloadRegistrationForms(self, REQUEST=None):
        """ reload registration forms """
        self._deleteRegistrationForms()
        self._loadRegistrationForms()
        if REQUEST:
            return self.manage_main(self, REQUEST, update_menu=1)

    security.declareProtected(view, 'registration_html')

    def registration_html(self, REQUEST):
        """ registration form """
        submit = REQUEST.form.get('submit', '')
        if submit:
            form_valid = form_validation(constants.PART_MANDATORY_FIELDS,
                                         constants.DATE_FIELDS,
                                         constants.TIME_FIELDS, REQUEST)
            if form_valid:
                lang = self.gl_get_selected_language()
                registration_no = naaya_utils.genRandomId(10)
                cleaned_data = REQUEST.form
                del cleaned_data['submit']
                ob = BaseParticipant(registration_no, **cleaned_data)
                self._setObject(registration_no, ob)
                participant = self._getOb(registration_no, None)
                if participant:
                    #save the authentication token on session
                    REQUEST.SESSION.set('authentication_id', registration_no)
                    REQUEST.SESSION.set(
                        'authentication_name',
                        self.unicode2UTF8(participant.last_name))

                    #send notifications
                    values = {
                        'registration_edit_link':
                        participant.absolute_url(),
                        'conference_title':
                        self.unicode2UTF8(self.title),
                        'conference_details':
                        self.unicode2UTF8(self.conference_details),
                        'website_team':
                        self.unicode2UTF8(self.site_title),
                        'registration_number':
                        registration_no,
                        'last_name':
                        self.unicode2UTF8(participant.last_name)
                    }
                    self.send_registration_notification(
                        participant.email, 'Event registration',
                        self.getEmailTemplate('user_registration_html', lang) %
                        values,
                        self.getEmailTemplate('user_registration_text', lang) %
                        values)
                    self.send_registration_notification(
                        self.administrative_email, 'Event registration',
                        self.getEmailTemplate('admin_registration_html',
                                              'en') % values,
                        self.getEmailTemplate('admin_registration_text', 'en')
                        % values)

                    #redirect to profile page
                    return REQUEST.RESPONSE.redirect(
                        participant.absolute_url())
        return self.registration_form(REQUEST)

    security.declareProtected(view, 'registration_press_html')

    def registration_press_html(self, REQUEST):
        """ registration form """
        submit = REQUEST.form.get('submit', '')
        if submit:
            form_valid = form_validation(constants.PRESS_MANDATORY_FIELDS,
                                         constants.DATE_FIELDS,
                                         constants.TIME_FIELDS, REQUEST)
            if form_valid:
                lang = self.gl_get_selected_language()
                registration_no = naaya_utils.genRandomId(10)
                cleaned_data = REQUEST.form
                del cleaned_data['submit']
                ob = SemidePress(registration_no, **cleaned_data)
                self._setObject(registration_no, ob)
                press = self._getOb(registration_no, None)
                if press:
                    #save the authentication token on session
                    REQUEST.SESSION.set('authentication_id', registration_no)
                    REQUEST.SESSION.set('authentication_name',
                                        self.unicode2UTF8(press.last_name))

                    #send notifications
                    values = {
                        'registration_edit_link':
                        press.absolute_url(),
                        'conference_title':
                        self.unicode2UTF8(self.title),
                        'conference_details':
                        self.unicode2UTF8(self.conference_details),
                        'website_team':
                        self.unicode2UTF8(self.site_title),
                        'registration_number':
                        registration_no,
                        'last_name':
                        self.unicode2UTF8(press.last_name)
                    }
                    self.send_registration_notification(
                        press.email, 'Event registration',
                        self.getEmailTemplate('user_registration_html', lang) %
                        values,
                        self.getEmailTemplate('user_registration_text', lang) %
                        values)
                    self.send_registration_notification(
                        self.administrative_email, 'Event registration',
                        self.getEmailTemplate('admin_registration_html',
                                              'en') % values,
                        self.getEmailTemplate('admin_registration_text', 'en')
                        % values)

                    return REQUEST.RESPONSE.redirect(press.absolute_url())
        return self.registration_press_form(REQUEST)

    security.declarePrivate('getEmailTemplate')

    def getEmailTemplate(self, id, lang='en'):
        """ get email template """
        lang_dir = self.email_templates._getOb(lang, None)
        if lang_dir is None:  #maybe arabic?
            lang_dir = self.email_templates._getOb('en', None)
        email_template = lang_dir._getOb(id)
        return self.unicode2UTF8(email_template.document_src())

    #XXX: security?
    def registrationOpened(self):
        """ check if the registration is opend to the public """
        now = time.localtime()
        if now >= self.start_date:
            return True
        return False

    #XXX: security?
    def registrationNotClosed(self):
        """ check if the registration is opend to the public """
        now = time.localtime()
        from datetime import date, timedelta
        end_date = date(*self.end_date[0:3]) + timedelta(days=1)
        end_date = end_date.timetuple()[0:3] + self.end_date[3:]
        if now < end_date:
            return True
        return False

    security.declareProtected(view_management_screens, 'edit_html')

    def edit_html(self, REQUEST):
        """ edit properties """
        submit = REQUEST.form.get('edit-submit', '')
        if submit:
            if registration_validation(REQUEST):
                cleaned_data = REQUEST.form
                del cleaned_data['edit-submit']
                self.save_properties(**cleaned_data)
        return self._edit_html(REQUEST)

    security.declarePrivate('send_registration_notification')

    def send_registration_notification(self, email, title, email_html,
                                       email_txt):
        """ send a notification when a folder is added / edited / commented"""
        send_mail(msg_from=constants.NO_REPLY_MAIL,
                  msg_to=self.utConvertToList(email),
                  msg_subject='%s - Registration added / edited' % title,
                  msg_body=self.unicode2UTF8(email_html),
                  msg_body_text=self.unicode2UTF8(email_txt),
                  smtp_host=constants.SMTP_HOST,
                  smtp_port=constants.SMTP_PORT)

    security.declareProtected(view_management_screens, 'exportParticipants')

    def exportParticipants(self, REQUEST=None, RESPONSE=None):
        """ exports the participants list in CSV format """
        data = [('Registration date', 'Registration number',
                 'Official delegation of', 'Participant type', 'First name',
                 'Name', 'Gender', 'Position', 'Work address', 'City',
                 'Postal code', 'Country', 'Phone number', 'Mobile number',
                 'Email', 'Fax number', 'Passport number',
                 'Language(s) spoken', 'Date of arrival', 'Time of arrival',
                 'Arrival flight number', 'Arrival flight company',
                 'Date of departure', 'Time of departure',
                 'Departure flight number', 'Departure flight company',
                 'Special requests', 'Medical requirements', 'Special diet',
                 'Participation in the 12/04 event',
                 'Participation in the 14/04 activity')]
        data_app = data.append
        for part in self.getParticipants(skey='registration_date',
                                         rkey=1,
                                         is_journalist=False):
            if part.arrival_date:
                arrival_date = self.formatDate(part.arrival_date)
            else:
                arrival_date = 'n/a'
            if part.departure_date:
                departure_date = self.formatDate(part.departure_date)
            else:
                departure_date = 'n/a'
            if part.extra_event_1:
                extra_event_1 = 'Yes'
            else:
                extra_event_1 = 'No'
            if part.extra_event_2:
                extra_event_2 = 'Yes'
            else:
                extra_event_2 = 'No'
            data_app((self.formatDate(part.registration_date), part.id,
                      self.unicode2UTF8(part.delegation_of),
                      self.getRefTreeTitle(part.participant_type),
                      self.unicode2UTF8(part.first_name),
                      self.unicode2UTF8(part.last_name),
                      self.unicode2UTF8(part.gender),
                      self.unicode2UTF8(part.position),
                      self.unicode2UTF8(part.work_address).replace(
                          '\r\n',
                          ' ').replace('\n',
                                       ' '), self.unicode2UTF8(part.city),
                      self.unicode2UTF8(part.postal_code),
                      self.unicode2UTF8(part.country),
                      self.unicode2UTF8(part.phone_number),
                      self.unicode2UTF8(part.mobile_number), part.email,
                      self.unicode2UTF8(part.fax_number),
                      self.unicode2UTF8(part.passport_no),
                      self.unicode2UTF8(part.languages), arrival_date,
                      part.arrival_time,
                      self.unicode2UTF8(part.arrival_flight_number),
                      self.unicode2UTF8(part.arrival_flight_company),
                      departure_date, part.departure_time,
                      self.unicode2UTF8(part.departure_flight_number),
                      self.unicode2UTF8(part.departure_flight_company),
                      self.unicode2UTF8(part.special_requests),
                      self.unicode2UTF8(part.medical_requirements),
                      self.unicode2UTF8(part.special_diet), extra_event_1,
                      extra_event_2))

        return self.create_csv(data,
                               filename='participants.csv',
                               RESPONSE=REQUEST.RESPONSE)

    security.declareProtected(view_management_screens, 'exportPress')

    def exportPress(self, REQUEST=None, RESPONSE=None):
        """ exports the press participants list in CSV format """
        data = [
            ('Registration date', 'Registration number', 'First name', 'Name',
             'Country', 'Media name', 'Type of media',
             'Description of equipment used', 'Your position',
             'Passport number', 'Expiry date of the passport', 'Email address',
             'Phone number', 'Fax number', 'Mobile phone', 'Date of arrival',
             'Arriving from', 'Flight number', 'Time of arrival',
             'Date of departure', 'Flight number', 'Time of departure')
        ]
        data_app = data.append
        for part in self.getParticipants(skey='registration_date',
                                         rkey=1,
                                         is_journalist=True):
            if part.arrival_date:
                arrival_date = self.formatDate(part.arrival_date)
            else:
                arrival_date = 'n/a'
            if part.departure_date:
                departure_date = self.formatDate(part.departure_date)
            else:
                departure_date = 'n/a'
            data_app(
                (self.formatDate(part.registration_date), part.id,
                 self.unicode2UTF8(part.first_name),
                 self.unicode2UTF8(part.last_name),
                 self.unicode2UTF8(part.country),
                 self.unicode2UTF8(part.media_name),
                 self.unicode2UTF8(part.media_type),
                 self.unicode2UTF8(part.media_description).replace(
                     '\r\n',
                     ' ').replace('\n',
                                  ' '), self.unicode2UTF8(part.media_position),
                 self.unicode2UTF8(part.passport_no),
                 self.unicode2UTF8(part.passport_expire), part.email,
                 self.unicode2UTF8(part.phone_number),
                 self.unicode2UTF8(part.fax_number),
                 self.unicode2UTF8(part.mobile_number), arrival_date,
                 self.unicode2UTF8(part.arrival_from),
                 self.unicode2UTF8(part.arrival_flight), part.arrival_time,
                 departure_date, self.unicode2UTF8(part.departure_flight),
                 part.departure_time))
        return self.create_csv(data,
                               filename='press_participants.csv',
                               RESPONSE=REQUEST.RESPONSE)

    security.declarePrivate('create_csv')

    def create_csv(self, data, filename, RESPONSE):
        tmp_name = tmpfile(data)
        content = open(str(tmp_name)).read()
        RESPONSE.setHeader('Content-Type', 'text/csv')
        RESPONSE.setHeader('Content-Disposition',
                           'attachment; filename=%s' % filename)
        return content

    security.declareProtected(view_management_screens, 'getParticipants')

    def getParticipants(self, skey, rkey, is_journalist):
        """ Returns the list of participants """
        if is_journalist:
            meta_type = 'Semide Press Participant'
        else:
            meta_type = 'Semide Participant'
        participants = [(self.unicode2UTF8(getattr(p, skey)), p)
                        for p in self.objectValues(meta_type)]
        participants.sort()
        if rkey:
            participants.reverse()
        return [p for (key, p) in participants]

    security.declareProtected(view_management_screens, 'deleteParticipants')

    def deleteParticipants(self, ids=[], REQUEST=None):
        """ Deletes selected participants """
        ids = self.utConvertToList(ids)
        self.manage_delObjects(ids)
        return REQUEST.RESPONSE.redirect(REQUEST.HTTP_REFERER)

    security.declarePublic('canManageParticipants')

    def canManageParticipants(self):
        """ Check the permissions to edit/delete participants """
        return checkPermission(view_management_screens, self)

    security.declarePublic('getRegistrationTitle')

    def getRegistrationTitle(self):
        """ """
        return self.title

    security.declarePublic('getConferenceDetails')

    def getConferenceDetails(self):
        """ """
        return self.conference_details

    #internal
    def formatDate(self, sdate, format='%d/%m/%Y'):
        if sdate:
            return time.strftime(format, sdate)
        return None

    def unicode2UTF8(self, s):
        if isinstance(s, unicode):
            return s.encode('utf-8')
        return s

    def getPropertyValue(self, id, lang=None):
        """ Returns a property value in the specified language. """
        if lang is None: lang = self.gl_get_selected_language()
        return self.getLocalProperty(id, lang)

    security.declareProtected(view, 'getCountryList')

    def getCountryList(self):
        """ """
        catalog = self.glossary_coverage.getGlossaryCatalog()
        brains = catalog(meta_type='Naaya Glossary Element',
                         sort_on='id',
                         sort_order='ascending')
        #if there are several glossaries, countries can get duplicated, so remove duplicates:
        all_countries_list = self.__getObjects(catalog, brains)
        country_list = {}
        for country in all_countries_list:
            country_list[country.id] = country
        return self.utSortObjsListByAttr(country_list.values(), 'id', False)

    def __getObjects(self, catalog, p_brains):
        """ """
        try:
            return map(
                catalog.getobject,
                map(getattr, p_brains, ('data_record_id_', ) * len(p_brains)))
        except:
            return []

    def hasVersion(self):
        """ """
        return None

    def getRefTree(self, ref_tree_id):
        """ """
        return self.getPortletsTool().getRefTreeById(ref_tree_id)

    def getRefTreeNodes(self, ref_tree_id='conference_participant_types'):
        """ """
        ref_tree = self.getRefTree(ref_tree_id)
        nodes = ref_tree.get_tree_nodes()
        return [(node.id, node.title) for node in nodes]

    def getRefTreeTitle(self,
                        node_id,
                        ref_tree_id='conference_participant_types'):
        """ """
        ref_tree = self.getRefTree(ref_tree_id)
        for node in ref_tree.get_tree_nodes():
            if node.id == node_id:
                return node.title
        return None

    security.declareProtected(view, 'getDelegations')

    def getDelegations(self, meta_type='Semide Participant'):
        """ """
        return json.dumps(
            [ob.delegation_of for ob in self.objectValues(meta_type)])
Exemplo n.º 20
0
class HTMLPortlet(LocalPropertyManager, Folder):
    """ """

    meta_type = METATYPE_HTMLPORTLET
    icon = 'misc_/NaayaCore/HTMLPortlet.gif'

    manage_options = (({
        'label': 'Properties Ex',
        'action': 'manage_properties_html'
    }, ) + (Folder.manage_options[0], ) + Folder.manage_options[3:])

    def all_meta_types(self, interfaces=None):
        """ """
        y = []
        additional_meta_types = ['Image', 'File']
        for x in Products.meta_types:
            if x['name'] in additional_meta_types:
                y.append(x)
        return y

    security = ClassSecurityInfo()

    title = LocalProperty('title')
    body = LocalProperty('body')

    def __init__(self, id, title, body, portlettype, lang):
        #constructor
        self.id = id
        self._setLocalPropValue('title', lang, title)
        self._setLocalPropValue('body', lang, body)
        self.portlettype = portlettype
        self.template = ZopePageTemplate('', HTML_PORTLET_TEMPLATE,
                                         'text/html')

    def __call__(self, context={}, *args):
        """ """
        if not context.has_key('args'):
            context['args'] = args
        context['skin_files_path'] = self.getLayoutTool().getSkinFilesPath()
        wrappedTemplate = self.template.__of__(self)
        context['here'] = self
        return wrappedTemplate.pt_render(extra_context=context)

    def get_type_label(self):
        #returns the label for the portlet type
        return PORTLETS_TYPES[self.portlettype]

    #zmi actions
    security.declareProtected(view_management_screens,
                              'manage_properties_html')

    def manage_properties(self, title='', body='', lang=None, REQUEST=None):
        """ """
        if lang is None: lang = self.gl_get_selected_language()
        self._setLocalPropValue('title', lang, title)
        self._setLocalPropValue('body', lang, body)
        self._p_changed = 1
        if REQUEST: REQUEST.RESPONSE.redirect('manage_properties_html?save=ok')

    #zmi pages
    security.declareProtected(view_management_screens,
                              'manage_properties_html')
    manage_properties_html = PageTemplateFile(
        'zpt/htmlportlet_manage_properties', globals())
Exemplo n.º 21
0
class NySemThematicDir(NyFolder):
    """ """
    meta_type = METATYPE_OBJECT
    meta_label = LABEL_OBJECT
    icon = 'misc_/NaayaContent/NySemThematicDir.gif'
    icon_marked = 'misc_/NaayaContent/NySemThematicDir_marked.gif'

    security = ClassSecurityInfo()

    criteria_keywords = LocalProperty('criteria_keywords')

    def all_meta_types(self, interfaces=None):
        """ What can you put inside me? """
        #filter meta types
        l = list(
            filter(
                lambda x: x['name'] in [
                    METATYPE_FOLDER, METATYPE_NYURL, METATYPE_NYEXFILE,
                    METATYPE_NYDOCUMENT
                ], Products.meta_types))
        #handle uninstalled pluggable meta_types
        pluggable_meta_types = self.get_pluggable_metatypes()
        pluggable_installed_meta_types = self.get_pluggable_installed_meta_types(
        )
        t = copy(l)
        for x in t:
            if (x['name'] in pluggable_meta_types) and (
                    x['name'] not in pluggable_installed_meta_types):
                l.remove(x)
        return l

    def __init__(self,
                 id='',
                 title='',
                 description='',
                 coverage='',
                 keywords='',
                 criteria_keywords='',
                 sortorder='',
                 publicinterface='',
                 maintainer_email='',
                 contributor='',
                 folder_meta_types='',
                 releasedate='',
                 criteria_date='',
                 themes='',
                 lang=''):
        NyFolder.__dict__['__init__'](self, id, title, description, coverage,
                                      keywords, sortorder, publicinterface,
                                      maintainer_email, contributor,
                                      folder_meta_types, releasedate, lang)
        self.themes = themes
        self.criteria_date = criteria_date
        self._setLocalPropValue('criteria_keywords', lang, criteria_keywords)

    security.declarePrivate('export_this_tag_custom')

    def export_this_tag_custom(self):
        meta_types = FolderMetaTypes(self).get_values()
        return 'custom_index="%s" maintainer_email="%s" folder_meta_types="%s" themes="%s" criteria_date="%s"' % \
            (self.utXmlEncode(self.compute_custom_index_value()),
                self.utXmlEncode(self.maintainer_email),
                self.utXmlEncode(','.join(meta_types)),
                self.utXmlEncode(self.themes),
                self.utXmlEncode(self.criteria_date))

    security.declarePrivate('export_this_body_custom')

    def export_this_body_custom(self):
        r = []
        ra = r.append
        for l in self.gl_get_languages():
            ra('<criteria_keywords lang="%s"><![CDATA[%s]]></criteria_keywords>'
               %
               (l, self.utToUtf8(self.getLocalProperty('criteria_keywords',
                                                       l))))
        return ''.join(r)

    #zmi actions
    security.declareProtected(view_management_screens, 'manageProperties')

    def manageProperties(self, REQUEST=None, **kwargs):
        """ """

    #site actions
    security.declareProtected(PERMISSION_EDIT_OBJECTS, 'saveProperties')

    def saveProperties(self, REQUEST=None, **kwargs):
        """ """

    security.declareProtected(PERMISSION_EDIT_OBJECTS, 'edit_html')

    def edit_html(self, REQUEST=None, RESPONSE=None):
        """ """
        return self.getFormsTool().getContent({'here': self},
                                              'semthematicdir_edit')

    #site pages
    security.declareProtected(view, 'index_html')

    def index_html(self, REQUEST=None, RESPONSE=None):
        """ """
        return self.getFormsTool().getContent({'here': self},
                                              'semthematicdir_index')

    def hasVersion(self):
        """
        Checks if the object is locked.
        @return:
            - B{TRUE/1} if true
            - B{FALSE/0} otherwise
        """
        return 0

    def format_results(self, p_objects=[], skey='', rkey='', ps_start=''):
        """Return sorted events"""
        results = []
        res_per_page = 10
        try:
            ps_start = int(ps_start)
        except:
            ps_start = 0
        try:
            rkey = int(rkey)
        except:
            rkey = 0

        if skey == 'date':
            p_objects.sort(lambda x, y: cmp(y.bobobase_modification_time(),
                                            x.bobobase_modification_time()))
            results.extend(p_objects)
        else:
            l_objects = self.utSortObjsByLocaleAttr(
                p_objects, skey, rkey, self.gl_get_selected_language())
            results.extend(l_objects)

        #batch related
        batch_obj = batch_utils(res_per_page, len(results), ps_start)
        if len(results) > 0:
            paging_informations = batch_obj.butGetPagingInformations()
        else:
            paging_informations = (-1, 0, 0, -1, -1, 0, res_per_page, [0])
        return (paging_informations,
                (1, 1, results[paging_informations[0]:paging_informations[1]]))

    security.declareProtected(view, 'getThDirPortletsData')

    def getThDirPortletsData(self, skey='', rkey='', ps_start=''):
        """
        Returns a list of news, events, projects and all the rest of the object types
        """
        #return nothing if no themes were selected
        if self.themes == [''] and self.criteria_keywords == '':
            return [[], [], [], []]
        #query the thesaurus for concepts
        lang = self.gl_get_selected_language()
        th_list = self.themes
        added_any_word = False
        portal_thesaurus = self.getPortalThesaurus()
        l_allconcepts = {}
        l_additional_concepts = {}
        for lang in self.gl_get_languages():
            l_allconcepts[lang] = []
            l_additional_concepts[lang] = []
            if th_list != ['']:
                for theme_id in th_list:
                    terms_list = []
                    for k in portal_thesaurus.getThemeConcept(theme_id, lang):
                        if k.concept_name: terms_list.append(k.concept_name)
                    if terms_list != ['']:
                        added_any_word = True
                        l_allconcepts[lang].extend(terms_list)
            l_additional = self.getLocalProperty('criteria_keywords', lang)
            l_additional_list = [
                x.strip() for x in l_additional.split(',') if x.strip() != ''
            ]
            l_additional_concepts[lang].extend(l_additional_list)
            if l_additional_list != ['']:
                l_allconcepts[lang].extend(l_additional_list)
                added_any_word = True

        if added_any_word:
            ThesaurusData = self.getThDirPortletsDataSpecific
            l_news = ThesaurusData(l_allconcepts,
                                   l_additional_concepts,
                                   p_news=1,
                                   p_amount=5)
            l_events = ThesaurusData(l_allconcepts,
                                     l_additional_concepts,
                                     p_events=1,
                                     p_amount=5)
            l_projects = ThesaurusData(l_allconcepts,
                                       l_additional_concepts,
                                       p_projects=1,
                                       p_amount=0)

            l_rest = ThesaurusData(l_allconcepts,
                                   l_additional_concepts,
                                   p_amount=0)
            l_rest = self.format_results(l_rest, skey, rkey, ps_start)

            return [l_news, l_events, l_projects, l_rest]
        else:
            return [[], [], [], []]

    security.declareProtected(view, 'getThDirPortletsData')

    def getThDirPortletsDataSpecific(
        self,
        p_allconcepts,
        p_additional_list,
        p_news=0,
        p_events=0,
        p_projects=0,
        p_amount=0,
    ):
        """
        Returns a list of specific object type
        """
        results = []
        l_meta = []
        l_meta_sbj = []
        lang = self.gl_get_selected_language()
        obs_with_subject = [METATYPE_NYSEMDOCUMENT, METATYPE_NYSEMMULTIMEDIA, METATYPE_NYSEMTEXTLAWS, \
                            METATYPE_NYSEMNEWS, METATYPE_NYSEMEVENT, METATYPE_NYSEMPROJECT]

        #decide the searchable metatypes
        if p_news:
            l_meta.append(METATYPE_NYSEMNEWS)
        elif p_events:
            l_meta.append(METATYPE_NYSEMEVENT)
        elif p_projects:
            l_meta.append(METATYPE_NYSEMPROJECT)
        else:
            l_meta.extend(self.get_pluggable_installed_meta_types())
            l_meta.append(METATYPE_FOLDER)
            l_meta.remove(METATYPE_NYSEMNEWS)
            l_meta.remove(METATYPE_NYSEMEVENT)
            l_meta.remove(METATYPE_NYSEMPROJECT)
            l_meta.remove(self.meta_type)

        for k in l_meta:
            if k in obs_with_subject:
                l_meta_sbj.append(k)
                l_meta.remove(k)

        res = []
        #search for objects with subject property
        query = {}
        if l_meta_sbj:
            if self.themes != ['']:
                for th in self.themes:
                    expr = 'self.getCatalogedObjects(meta_type=l_meta_sbj, approved=1, resource_subject=th, releasedate=self.criteria_date, releasedate_range=\'min\')'
                    res.extend(eval(expr))

        #search for objects without subject property
        query = {}
        if l_meta:
            for lang in self.gl_get_languages():
                if len(p_allconcepts[lang]):
                    #split the lists of concepts
                    l_nos = range(0, len(p_allconcepts[lang]), 100)
                    l_nos2 = l_nos[:]
                    l_nos2.remove(0)
                    l_nos2.append(len(p_allconcepts[lang]) + 1)
                    l_nos2 = [x - 1 for x in l_nos2]
                    l_concepts = {}
                    l_concepts[lang] = [
                        p_allconcepts[lang][l_nos[i]:l_nos2[i]]
                        for i in range(len(l_nos))
                    ]

                    for sub_list in l_concepts[lang]:
                        query[lang] = ' or '.join([
                            '"%s"' % self.utStrEscapeForSearch(x)
                            for x in sub_list
                        ])
                        expr = 'self.getCatalogedObjects(meta_type=l_meta, approved=1, objectkeywords_%s=query[\'%s\'], releasedate=self.criteria_date, releasedate_range=\'min\')' % (
                            lang, lang)
                        res.extend(eval(expr))

        #search after additional keywords
        query = {}
        all_meta = []
        all_meta.extend(l_meta_sbj)
        all_meta.extend(l_meta)
        for l_meta in all_meta:
            for lang in self.gl_get_languages():
                if p_additional_list[lang]:
                    query[lang] = ' or '.join([
                        '"%s"' % self.utStrEscapeForSearch(x)
                        for x in p_additional_list[lang]
                    ])
                    expr = 'self.getCatalogedObjects(meta_type=l_meta, approved=1, objectkeywords_%s=query[\'%s\'], releasedate=self.criteria_date, releasedate_range=\'min\')' % (
                        lang, lang)
                    res.extend(eval(expr))

        results = self.utEliminateDuplicatesByURL(res)

        if p_amount:
            results.sort(lambda x, y: cmp(y.bobobase_modification_time(),
                                          x.bobobase_modification_time()))
            return results[:p_amount]
        return results

    #zmi pages
    security.declareProtected(view_management_screens, 'manage_edit_html')
    manage_edit_html = PageTemplateFile('zpt/semthematicdir_manage_edit',
                                        globals())

    #    security.declareProtected(view_management_screens, 'manage_folder_subobjects_html')
    #    manage_folder_subobjects_html = PageTemplateFile('zpt/semthematicdir_manage_subobjects', globals())

    security.declarePrivate('setReleaseDate')

    def setCriteriaDate(self, criteria_date):
        """
        Set the release date of the current object.
        @param releasedate: the date
        @type releasedate: DateTime
        """
        self.criteria_date = self.utGetDate(criteria_date)
        self._p_changed = 1

    #utils
    def utSortObjsByLocaleAttr(self, p_list, p_attr, p_desc=1, p_locale=''):
        """Sort a list of objects by an attribute values based on locale"""
        if not p_locale:
            #normal sorting
            l_len = len(p_list)
            l_temp = map(None, map(getattr, p_list, (p_attr, ) * l_len),
                         xrange(l_len), p_list)
            l_temp.sort()
            if p_desc: l_temp.reverse()
            return map(operator.getitem, l_temp, (-1, ) * l_len)
        else:
            #locale sorting based
            try:
                default_locale = locale.setlocale(locale.LC_ALL)

                try:
                    #try to set for NT, WIN operating systems
                    locale.setlocale(locale.LC_ALL, p_locale)
                except:
                    #try to set for other operating system
                    if p_locale == 'ar': p_locale = 'ar_DZ'
                    else: p_locale = '%s_%s' % (p_locale, p_locale.upper())
                    locale.setlocale(locale.LC_ALL, p_locale)

                #sorting
                l_len = len(p_list)
                l_temp = map(None, map(getattr, p_list, (p_attr, ) * l_len),
                             xrange(l_len), p_list)
                l_temp.sort(lambda x, y: locale.strcoll(x[0], y[0]))
                if p_desc: l_temp.reverse()

                locale.setlocale(locale.LC_ALL, default_locale)
                return map(operator.getitem, l_temp, (-1, ) * l_len)
            except:
                #in case of failure make a normal sorting
                locale.setlocale(locale.LC_ALL, default_locale)
                return self.utSortObjsByLocaleAttr(p_list, p_attr, p_desc)