Пример #1
0
def html_results(self, query):
    """html results, used for in the edit screen of a collection,
       used in the live update results"""
    item_count = 30
    if hasattr(self.context, 'item_count'):
        item_count = self.context.item_count

    options = dict(original_context=self.context)
    results = self(query, sort_on=self.request.get('sort_on', None),
                   sort_order=self.request.get('sort_order', None),
                   limit=self.request.get('limit', 1000))

    lang_res = []
    for res in results:
        if hasattr(res, 'language'):
            if res.language == pref_lang():
                lang_res.append(res)
        else:
            if res.Language() == pref_lang():
                lang_res.append(res)

    results = IContentListing(lang_res)
    return getMultiAdapter(
        (results, self.request),
        name='display_query_results'
    )(**options)
Пример #2
0
 def _data(self):
     context = aq_inner(self.context)
     catalog = getToolByName(context, 'portal_catalog')
     limit = self.data.count
     state = ['published', 'intranet']
     results = catalog(portal_type=('News Item', 'Link'),
                       review_state=state,
                       is_important=True,
                       Language=pref_lang(),
                       sort_on="getObjPositionInParent",
                       sort_limit=limit,
                       path=self.get_current_path_news())
     results = [a for a in results]
     important = len(results)
     if important < limit:
         results2 = catalog(portal_type=('News Item', 'Link'),
                            review_state=state,
                            is_important=False,
                            Language=pref_lang(),
                            sort_on=('Date'),
                            sort_order='reverse',
                            path=self.get_current_path_news())
         results3 = []
         for brain in results2:
             results3.append(brain)
             if len(results3) == limit - important:
                 break
         return results + results3
     else:
         return results
Пример #3
0
 def _data(self):
     context = aq_inner(self.context)
     catalog = getToolByName(context, 'portal_catalog')
     limit = self.data.count
     state = ['published', 'intranet']
     importants = catalog(portal_type=('News Item', 'Link'),
                          review_state=state,
                          is_important=True,
                          Language=pref_lang(),
                          sort_on="getObjPositionInParent",
                          sort_limit=limit,
                          path=self.get_current_path_news())
     importants = [a for a in importants]
     important = len(importants)
     if important < limit:
         normals = catalog(portal_type=('News Item', 'Link'),
                           review_state=state,
                           is_important=False,
                           Language=pref_lang(),
                           sort_on=('Date'),
                           sort_order='reverse',
                           path=self.get_current_path_news())
         normals_limit = []
         path_folder_news = self.all_news_link()
         for brain in normals:
             brain_url = brain.getURL()
             brain_type = brain.Type
             if brain_type == 'Link' and brain_url.startswith(path_folder_news) or brain_type == 'News Item':
                 normals_limit.append(brain)
             if len(normals_limit) == limit - important:
                 break
         return importants + normals_limit
     else:
         return importants
Пример #4
0
 def getLogosFooter(self):
     catalog = api.portal.get_tool(name='portal_catalog')
     lang = utils.pref_lang()
     return catalog.searchResults(portal_type='Logos_Footer',
                                  review_state=['published', 'intranet'],
                                  Language=lang,
                                  sort_on='getObjPositionInParent')
Пример #5
0
    def menuPrincipal(self):
        """ returns folders (menu-principal)"""
        urltool = getToolByName(self.context, 'portal_url')
        portal_catalog = getToolByName(self.context, 'portal_catalog')
        # Obtain all folders in first level "published" o "visible"
        lang = pref_lang()
        servei = self.get_servei()
        subpath = servei.id
        path = urltool.getPortalPath() + '/' + lang + '/' + subpath

        folders = portal_catalog.searchResults(
            portal_type=self.allowed_section_types,
            path=dict(query=path, depth=1),
            sort_on='getObjPositionInParent')
        results = []
        for fold in folders:
            if (fold.portal_type in self.allowed_section_types):
                if fold.exclude_from_nav is not True:
                    results.append(
                        dict(name=fold.Title,
                             url=fold.getURL(),
                             id=fold.getId,
                             description=fold.Description,
                             review_state=fold.review_state))

        return results
Пример #6
0
    def quicklinks(self):
        """ Return de quicklinks for language
        """
        lang = pref_lang()
        registry = getUtility(IRegistry)
        settings = registry.forInterface(IUlearnControlPanelSettings, check=False)

        text = None
        if settings.quicklinks_literal is not None:
            for item in settings.quicklinks_literal:
                if lang in item['language']:
                    text = item['text']
                    break

        items = []
        if settings.quicklinks_table is not None:
            for item in settings.quicklinks_table:
                if lang in item['language']:
                    items.append(item)

        if len(items) > 0:
            quicklinks_show = True
        else:
            quicklinks_show = False

        dades = {'quicklinks_literal': text,
                 'quicklinks_icon': settings.quicklinks_icon,
                 'quicklinks_table': items,
                 'quicklinks_show': quicklinks_show,
                 }

        return dades
Пример #7
0
    def _data(self):
        context = aq_inner(self.context)
        catalog = getToolByName(context, 'portal_catalog')
        limit = self.data.count
        state = self.data.state

        now = localized_now()
        tomorrow = date.today() + timedelta(1)
        yesterday = date.today() - timedelta(1)

        results = catalog(portal_type='Event',
                          review_state=state,
                          end={'query': now,
                               'range': 'min'},
                          start={'query': [yesterday, tomorrow],
                                 'range': 'min:max'},
                          Language=pref_lang(),
                          sort_on='start',
                          sort_limit=limit)[:limit]
        count = len(results)
        if count < limit:
            results2 = catalog(portal_type=('Event'),
                               review_state=state,
                               end={'query': now,
                                    'range': 'min'},
                               start={'query': yesterday,
                                      'range': 'max'},
                               Language=pref_lang(),
                               sort_on='start',
                               sort_limit=limit - count)[:limit - count]
            count = len(results + results2)
            if count < limit:
                results3 = catalog(portal_type=('Event'),
                                   review_state=state,
                                   end={'query': now,
                                        'range': 'min'
                                        },
                                   start={'query': tomorrow,
                                          'range': 'min'},
                                   Language=pref_lang(),
                                   sort_on='start',
                                   sort_limit=limit - count)[:limit - count]
                return results + results2 + results3
            else:
                return results + results2
        else:
            return results
Пример #8
0
    def rss_news_link(self):
        pc = api.portal.get_tool('portal_catalog')
        news_folder = pc.searchResults(object_provides=INewsFolder.__identifier__,
                                       Language=pref_lang())

        if news_folder:
            return '%s%s' % (news_folder[0].getURL(), '/aggregator/RSS')
        else:
            return ''
Пример #9
0
 def get_current_path_news(self):
     lang = pref_lang()
     root_path = '/'.join(api.portal.get().getPhysicalPath())
     if lang == 'ca':
         return root_path+'/'+lang+'/noticies'
     elif lang == 'es':
         return root_path+'/'+lang+'/noticias'
     elif lang == 'en':
         return root_path+'/'+lang+'/news'
Пример #10
0
    def getHomepage(self):
        page = {}
        context = aq_inner(self.context)
        pc = getToolByName(context, 'portal_catalog')
        result = pc.searchResults(object_provides=IHomePage.__identifier__,
                                  Language=pref_lang())
        page['body'] = result[0].CookedBody()

        return page
Пример #11
0
    def getHomepage(self):
        page = {}
        context = aq_inner(self.context)
        pc = getToolByName(context, 'portal_catalog')
        result = pc.searchResults(object_provides=IHomePage.__identifier__,
                                  Language=pref_lang())
        page['body'] = result[0].CookedBody()

        return page
Пример #12
0
 def published_events_items(self):
     pc = api.portal.get_tool('portal_catalog')
     results = pc.searchResults(portal_type='Event',
                                Language=pref_lang(),
                                start={'query': DateTime(),
                                       'range': 'max'},
                                sort_on='start',
                                sort_order='reverse')
     return results
Пример #13
0
    def all_news_link(self):
        portal = api.portal.get()
        pc = api.portal.get_tool('portal_catalog')
        news_folder = pc.searchResults(object_provides=INewsFolder.__identifier__,
                                       Language=pref_lang())

        if news_folder:
            return '%s' % news_folder[0].getURL()
        else:
            return '%s/news_listing' % portal.absolute_url()
Пример #14
0
 def getPortletContainer(self):
     context = aq_inner(self.context)
     pc = getToolByName(context, 'portal_catalog')
     result = pc.searchResults(object_provides=IHomePage.__identifier__,
                               Language=pref_lang())
     if result:
         # Return the object without forcing a getObject()
         return getattr(context, result[0].id, context)
     else:
         # If this happens, it's bad. Implemented as a fallback
         return context
Пример #15
0
    def getHomepage(self):
        page = {}
        pc = api.portal.get_tool('portal_catalog')
        result = pc.searchResults(object_provides=IHomePage.__identifier__,
                                  Language=pref_lang())
        if not result:
            page['body'] = ''
        else:
            page['body'] = result[0].getObject().text.output

        return page
Пример #16
0
    def image_tag(self):
        lang = pref_lang()
        options = {
            "ca":
            """
                        <script type="text/javascript">
                            var RecaptchaOptions = {
                                    custom_translations : {
                                            instructions_visual : "Escriu les dues paraules:",
                                            instructions_audio : "Transcriu el que sentis:",
                                            play_again : "Torna a escoltar l'\u00e0udio",
                                            cant_hear_this : "Descarrega la pista en MP3",
                                            visual_challenge : "Modalitat visual",
                                            audio_challenge : "Modalitat auditiva",
                                            refresh_btn : "Demana dues noves paraules",
                                            help_btn : "Ajuda",
                                            incorrect_try_again : "Incorrecte. Torna-ho a provar.",
                                    },
                                    lang : '%s',
                                    theme : 'clean'
                                };
                        </script>
                        """ % lang,
            "es":
            """
                        <script type="text/javascript">
                            var RecaptchaOptions = {
                                    lang : '%s',
                                    theme : 'clean'
                            };
                        </script>
                        """ % lang,
            "en":
            """
                        <script type="text/javascript">
                            var RecaptchaOptions = {
                                    lang : '%s',
                                    theme : 'clean'
                            };
                        </script>
                        """ % lang
        }

        if not self.settings.public_key:
            raise ValueError(
                'No recaptcha public key configured. Go to path/to/site/@@recaptcha-settings to configure.'
            )
        use_ssl = self.request['SERVER_URL'].startswith('https://')
        error = IRecaptchaInfo(self.request).error
        return options.get(lang, '') + displayhtml(
            self.settings.public_key, use_ssl=use_ssl, error=error)
Пример #17
0
    def getPortletContainer(self):
        context = aq_inner(self.context)
        container = context

        # Portlet container will be in the context,
        # Except in the portal root, when we look for an alternative
        if IPloneSiteRoot.providedBy(self.context):
            pc = getToolByName(context, 'portal_catalog')
            result = pc.searchResults(object_provides=IHomePage.__identifier__,
                                      Language=pref_lang())
            if result:
                # Return the object without forcing a getObject()
                container = getattr(context, result[0].id, context)
        return container
Пример #18
0
 def is_visible(self):
     """ This method lookup for the physical welcome page and checks if the
         user has the permission to view it. If it doesn't raises an
         unauthorized (login)
     """
     portal = api.portal.get()
     pc = api.portal.get_tool('portal_catalog')
     result = pc.unrestrictedSearchResults(object_provides=IHomePage.__identifier__,
                                           Language=pref_lang())
     if result:
         portal.restrictedTraverse(result[0].getPath())
         return True
     else:
         return False
Пример #19
0
    def getPortletContainer(self):
        context = aq_inner(self.context)
        container = context

        # Portlet container will be in the context,
        # Except in the portal root, when we look for an alternative
        if IPloneSiteRoot.providedBy(self.context):
            pc = getToolByName(context, 'portal_catalog')
            result = pc.searchResults(object_provides=IHomePage.__identifier__,
                                      Language=pref_lang())
            if result:
                # Return the object without forcing a getObject()
                container = getattr(context, result[0].id, context)

        return container
Пример #20
0
 def _data(self):
     context = aq_inner(self.context)
     catalog = getToolByName(context, 'portal_catalog')
     state = ['published', 'intranet']
     results = catalog(portal_type=('News Item'),
                       review_state=state,
                       is_important=True,
                       Language=pref_lang(),
                       sort_on="getObjPositionInParent")
     results = [a for a in results]
     results2 = catalog(portal_type=('News Item', 'Link'),
                        review_state=state,
                        is_important=False,
                        Language=pref_lang(),
                        sort_on=('Date'),
                        sort_order='reverse')
     results3 = []
     path_folder_news = self.all_news_link()
     for brain in results2:
         brain_url = brain.getURL()
         brain_type = brain.Type
         if brain_type == 'Link' and brain_url.startswith(path_folder_news) or brain_type == 'News Item':
             results3.append(brain)
     return results + results3
Пример #21
0
    def getURLPremsa(self):
        url = ''
        idioma = utils.pref_lang()
        if idioma == 'en':
            url = 'https://upc.edu/en/press-room'

        elif idioma == 'ca':
            url = 'https://upc.edu/ca/sala-de-premsa'

        elif idioma == 'es':
            url = 'https://upc.edu/es/sala-de-prensa'

        else:
            url = 'https://upc.edu/ca/sala-de-premsa'

        return url
Пример #22
0
    def getUrlRSSPremsa(self):
        url = ''
        idioma = utils.pref_lang()

        if idioma == 'en':
            url = 'https://upc.edu/en/press-room/upc-today/RSS'

        elif idioma == 'ca':
            url = 'https://upc.edu/ca/sala-de-premsa/actualitat-upc/RSS'

        elif idioma == 'es':
            url = 'https://upc.edu/es/sala-de-prensa/actualidad-upc/RSS'

        else:
            url = 'https://upc.edu/ca/sala-de-premsa/actualitat-upc/RSS'

        return url
Пример #23
0
    def getPortletContainer(self):
        context = aq_inner(self.context)
        container = context

        # Portlet container will be in the context,
        # Except in the portal root, when we look for an alternative
        if INavigationRoot.providedBy(self.context):
            pc = getToolByName(context, 'portal_catalog')
            # Add the use case of mixin types of IHomepages. The main ones of a
            # non PAM-enabled site and the possible inner ones.
            result = pc.searchResults(object_provides=IHomePage.__identifier__,
                                      portal_type='Document',
                                      Language=pref_lang())
            if result:
                # Return the object without forcing a getObject()
                container = getattr(context, result[0].id, context)

        return container
Пример #24
0
    def image_tag(self):
        lang = pref_lang()
        options = {"ca": """
                        <script type="text/javascript">
                            var RecaptchaOptions = {
                                    custom_translations : {
                                            instructions_visual : "Escriu les dues paraules:",
                                            instructions_audio : "Transcriu el que sentis:",
                                            play_again : "Torna a escoltar l'\u00e0udio",
                                            cant_hear_this : "Descarrega la pista en MP3",
                                            visual_challenge : "Modalitat visual",
                                            audio_challenge : "Modalitat auditiva",
                                            refresh_btn : "Demana dues noves paraules",
                                            help_btn : "Ajuda",
                                            incorrect_try_again : "Incorrecte. Torna-ho a provar.",
                                    },
                                    lang : '%s',
                                    theme : 'clean'
                                };
                        </script>
                        """ % lang,
                   "es": """
                        <script type="text/javascript">
                            var RecaptchaOptions = {
                                    lang : '%s',
                                    theme : 'clean'
                            };
                        </script>
                        """ % lang,
                   "en": """
                        <script type="text/javascript">
                            var RecaptchaOptions = {
                                    lang : '%s',
                                    theme : 'clean'
                            };
                        </script>
                        """ % lang
        }

        if not self.settings.public_key:
            raise ValueError('No recaptcha public key configured. Go to path/to/site/@@recaptcha-settings to configure.')
        use_ssl = self.request['SERVER_URL'].startswith('https://')
        error = IRecaptchaInfo(self.request).error
        return options.get(lang, '') + displayhtml(self.settings.public_key, use_ssl=use_ssl, error=error)
Пример #25
0
    def menu(self):
        """ returns subfolders (submenus) for the dropdown in navbar"""
        urltool = getToolByName(self.context, 'portal_url')
        portal_catalog = getToolByName(self.context, 'portal_catalog')
        # Obtain all folders in first level "published" o "visible"
        lang = pref_lang()
        servei = self.get_servei()
        subpath = servei.id
        path = urltool.getPortalPath() + '/' + lang + '/' + subpath
        folders = portal_catalog.searchResults(portal_type=self.allowed_section_types,
                                               path=dict(query=path, depth=1),
                                               sort_on='getObjPositionInParent')

        subfolders = {}
        for fold in folders:
            if (fold.portal_type in self.allowed_section_types):
                if fold.exclude_from_nav is not True:
                    subfolders[fold.getId] = self.SubMenu(fold.getPath())
        return subfolders
Пример #26
0
    def getPortletContainerPath(self):
        context = aq_inner(self.context)

        container_url = context.absolute_url()

        # Portlet container will be in the context,
        # Except in the portal root, when we look for an alternative
        if INavigationRoot.providedBy(self.context):
            pc = getToolByName(context, 'portal_catalog')
            # Add the use case of mixin types of IHomepages. The main ones of a
            # non PAM-enabled site and the possible inner ones.
            result = pc.searchResults(object_provides=IHomePage.__identifier__,
                                      portal_type='Document',
                                      Language=pref_lang())

            if result:
                # Return the object without forcing a getObject()
                container_url = result[0].getURL()

        return container_url
Пример #27
0
    def menu(self):
        """ returns subfolders (submenus) for the dropdown in navbar"""
        urltool = getToolByName(self.context, 'portal_url')
        portal_catalog = getToolByName(self.context, 'portal_catalog')
        # Obtain all folders in first level "published" o "visible"
        lang = pref_lang()
        servei = self.get_servei()
        subpath = servei.id
        path = urltool.getPortalPath() + '/' + lang + '/' + subpath
        folders = portal_catalog.searchResults(
            portal_type=self.allowed_section_types,
            path=dict(query=path, depth=1),
            sort_on='getObjPositionInParent')

        subfolders = {}
        for fold in folders:
            if (fold.portal_type in self.allowed_section_types):
                if fold.exclude_from_nav is not True:
                    subfolders[fold.getId] = self.SubMenu(fold.getPath())
        return subfolders
Пример #28
0
    def get_people_literal(self):
        literal = api.portal.get_registry_record(name='ulearn.core.controlpanel.IUlearnControlPanelSettings.people_literal')
        lang = pref_lang()

        if lang == 'ca' and literal == 'persones':
            literal = 'Persones'
        elif lang == 'es' and literal == 'persones':
            literal = 'Personas'
        elif lang == 'en' and literal == 'persones':
            literal = 'People'

        if lang == 'ca' and literal == 'participants':
            literal = 'Participants'
        elif lang == 'es' and literal == 'participants':
            literal = 'Participantes'
        elif lang == 'en' and literal == 'participants':
            literal = 'Participants'

        if literal == 'thinnkers':
            literal = 'Thinnkers'

        return literal
Пример #29
0
    def menuPrincipal(self):
        """ returns folders (menu-principal)"""
        urltool = getToolByName(self.context, 'portal_url')
        portal_catalog = getToolByName(self.context, 'portal_catalog')
        # Obtain all folders in first level "published" o "visible"
        lang = pref_lang()
        servei = self.get_servei()
        subpath = servei.id
        path = urltool.getPortalPath() + '/' + lang + '/' + subpath

        folders = portal_catalog.searchResults(portal_type=self.allowed_section_types,
                                               path=dict(query=path, depth=1),
                                               sort_on='getObjPositionInParent')
        results = []
        for fold in folders:
            if (fold.portal_type in self.allowed_section_types):
                if fold.exclude_from_nav is not True:
                    results.append(dict(name=fold.Title,
                                        url=fold.getURL(),
                                        id=fold.getId,
                                        description=fold.Description))

        return results
Пример #30
0
    def getHTML(self):
        packet_type = self.getType()
        adapter = getAdapter(self.context, IpacketDefinition, packet_type)
        adapter.packet_fields.update({'lang': utils.pref_lang()})

        url = adapter.URL_schema
        portal_url = getToolByName(self.context, "portal_url")
        portal = portal_url.getPortalObject()
        url_portal_nginx = portal.absolute_url()  # url (per dns) del lloc
        try:
            url = self.get_absolute_url(url % adapter.packet_fields)
            # check url to avoid autoreference, removing http(s) and final slash
            link_url = re.findall('https?://(.*)', url)[0].strip('/')  # url del contingut netejada
            parent_url = re.findall('https?://(.*)', self.context.absolute_url())[0].strip('/')  # url del pare netejada
            root_url = re.findall('https?://(.*)', url_portal_nginx)[0].strip('/')  # url (per dns) del lloc netejada
            if link_url != parent_url:
                if link_url.startswith(root_url):
                    # link intern, search through the catalog
                    relative_path = '/' + re.findall(root_url + '(.*)', link_url)[0]
                    url_to_search = '/'.join(portal.getPhysicalPath()) + relative_path
                    raw_html = self.get_catalog_content(url_to_search)
                    charset = re.findall('charset=(.*)"', raw_html)
                    if len(charset) > 0:
                        clean_html = re.sub(r'[\n\r]?', r'', raw_html.encode(charset[0]))
                        doc = pq(clean_html)
                        match = re.search(r'This page does not exist', clean_html)
                        self.title = self.context.Title()  # titol per defecte
                        if not match:
                            if packet_type == 'contingut_genweb':
                                element = adapter.packet_fields['element']
                                if not element:
                                    element = "#content-core"
                            else:
                                element = "#content-nucli"
                            content = pq('<div/>').append(
                                doc(element).outerHtml()).html(method='html')
                            if not content:
                                content = _(u"ERROR. This element does not exist.") + " " + element
                        else:
                            content = _(u"ERROR: Unknown identifier. This page does not exist." + url)
                    else:
                        content = _(u"ERROR. Charset undefined")
                else:
                    # link extern, pyreq
                    raw_html = requests.get(url, timeout=5, verify=False)
                    charset = re.findall('charset=(.*)"', raw_html.content)
                    if len(charset) > 0:
                        clean_html = re.sub(r'[\n\r]?', r'', raw_html.content.decode(charset[0]))
                        doc = pq(clean_html)
                        match = re.search(r'This page does not exist', clean_html)
                        self.title = self.context.Title()  # titol per defecte
                        if not match:
                            if packet_type == 'contingut_genweb':
                                element = adapter.packet_fields['element']
                                if not element:
                                    element = "#content-core"
                            else:
                                element = "#content-nucli"
                            content = pq('<div/>').append(
                                doc(element).outerHtml()).html(method='html')
                            if not content:
                                content = _(u"ERROR. This element does not exist.") + " " + element
                        else:
                            content = _(u"ERROR: Unknown identifier. This page does not exist." + url)
                    else:
                        content = _(u"ERROR. Charset undefined")
            else:
                content = _(u"ERROR. Autoreference")
        except ReadTimeout:
            content = _(u"ERROR. There was a timeout while waiting for '{0}'".format(self.get_absolute_url(self.data.url)))
        except RequestException:
            content = _(u"ERROR. This URL does not exist.")
        except:
            content = _(u"ERROR. Unexpected exception.")

        self.content = content
Пример #31
0
    def render(self):
        # We set the parameters sent in livesearch using the old way.
        q = self.request['q']

        limit = 10
        path = None
        ploneUtils = getToolByName(self.context, 'plone_utils')
        portal_url = getToolByName(self.context, 'portal_url')()
        pretty_title_or_id = ploneUtils.pretty_title_or_id
        portalProperties = getToolByName(self.context, 'portal_properties')
        siteProperties = getattr(portalProperties, 'site_properties', None)
        useViewAction = []
        if siteProperties is not None:
            useViewAction = siteProperties.getProperty('typesUseViewActionInListings', [])

        # SIMPLE CONFIGURATION
        MAX_TITLE = 40
        MAX_DESCRIPTION = 80

        # generate a result set for the query
        catalog = self.context.portal_catalog

        friendly_types = ploneUtils.getUserFriendlyTypes()

        def quotestring(s):
            return '"%s"' % s

        def quote_bad_chars(s):
            bad_chars = ["(", ")"]
            for char in bad_chars:
                s = s.replace(char, quotestring(char))
            return s

        multispace = u'\u3000'.encode('utf-8')
        for char in ('?', '-', '+', '*', multispace):
            q = q.replace(char, ' ')
        r = q.split()
        r = " AND ".join(r)
        r = quote_bad_chars(r) + '*'
        searchterms = url_quote_plus(r)

        params = {'SearchableText': r,
                  'portal_type': friendly_types,
                  'sort_limit': limit + 1}

        if path is None:
            # useful for subsides
            params['path'] = getNavigationRoot(self.context)
        else:
            params['path'] = path

        params["Language"] = pref_lang()
        # search limit+1 results to know if limit is exceeded
        results = catalog(**params)

        REQUEST = self.context.REQUEST
        RESPONSE = REQUEST.RESPONSE
        RESPONSE.setHeader('Content-Type', 'application/json')

        label_show_all = _('label_show_all', default='Show all items')

        ts = getToolByName(self.context, 'translation_service')

        queryElements = []

        if results:
            # TODO: We have to build a JSON with the desired parameters.
            for result in results[:limit]:
                # Calculate icon replacing '.' per '-' as '.' in portal_types break CSS
                icon = result.portal_type.lower().replace(".", "-")
                itemUrl = result.getURL()
                if result.portal_type in useViewAction:
                    itemUrl += '/view'

                full_title = safe_unicode(pretty_title_or_id(result))
                if len(full_title) > MAX_TITLE:
                    display_title = ''.join((full_title[:MAX_TITLE], '...'))
                else:
                    display_title = full_title

                full_title = full_title.replace('"', '&quot;')

                display_description = safe_unicode(result.Description)
                if len(display_description) > MAX_DESCRIPTION:
                    display_description = ''.join(
                        (display_description[:MAX_DESCRIPTION], '...'))

                # We build the dictionary element with the desired parameters and we add it to the queryElements array.
                queryElement = {
                    'class': '',
                    'title': display_title,
                    'description': display_description,
                    'itemUrl': itemUrl,
                    'icon': icon}
                queryElements.append(queryElement)

        return json.dumps(queryElements)
Пример #32
0
    def render(self):
        # We set the parameters sent in livesearch using the old way.
        q = self.request["q"]

        limit = 10
        path = None

        ploneUtils = getToolByName(self.context, "plone_utils")
        portal_url = getToolByName(self.context, "portal_url")()
        pretty_title_or_id = ploneUtils.pretty_title_or_id
        portalProperties = getToolByName(self.context, "portal_properties")
        siteProperties = getattr(portalProperties, "site_properties", None)
        useViewAction = []
        if siteProperties is not None:
            useViewAction = siteProperties.getProperty("typesUseViewActionInListings", [])

        # SIMPLE CONFIGURATION
        MAX_TITLE = 40
        MAX_DESCRIPTION = 80

        # generate a result set for the query
        catalog = self.context.portal_catalog

        friendly_types = ploneUtils.getUserFriendlyTypes()

        def quotestring(s):
            return '"%s"' % s

        def quote_bad_chars(s):
            bad_chars = ["(", ")"]
            for char in bad_chars:
                s = s.replace(char, quotestring(char))
            return s

        multispace = u"\u3000".encode("utf-8")
        for char in ("?", "-", "+", "*", multispace):
            q = q.replace(char, " ")
        r = q.split()
        r = " AND ".join(r)
        r = quote_bad_chars(r) + "*"
        searchterms = url_quote_plus(r)

        params = {"SearchableText": r, "portal_type": friendly_types, "sort_limit": limit + 1}

        if path is None:
            # useful for subsides
            params["path"] = get_referer_path(self.context, self.request)
        else:
            params["path"] = path

        params["Language"] = pref_lang()
        # search limit+1 results to know if limit is exceeded
        results = catalog(**params)

        REQUEST = self.context.REQUEST
        RESPONSE = REQUEST.RESPONSE
        RESPONSE.setHeader("Content-Type", "application/json")

        label_show_all = _("label_show_all", default="Show all items")

        ts = getToolByName(self.context, "translation_service")

        queryElements = []

        if results:
            # TODO: We have to build a JSON with the desired parameters.
            for result in results[:limit]:
                # Calculate icon replacing '.' per '-' as '.' in portal_types break CSS
                icon = result.portal_type.lower().replace(".", "-")
                itemUrl = result.getURL()
                if result.portal_type in useViewAction:
                    itemUrl += "/view"

                full_title = safe_unicode(pretty_title_or_id(result))
                if len(full_title) > MAX_TITLE:
                    display_title = "".join((full_title[:MAX_TITLE], "..."))
                else:
                    display_title = full_title

                full_title = full_title.replace('"', "&quot;")

                display_description = safe_unicode(result.Description)
                if len(display_description) > MAX_DESCRIPTION:
                    display_description = "".join((display_description[:MAX_DESCRIPTION], "..."))

                # We build the dictionary element with the desired parameters and we add it to the queryElements array.
                queryElement = {
                    "class": "",
                    "title": display_title,
                    "description": display_description,
                    "itemUrl": itemUrl,
                    "icon": icon,
                }
                queryElements.append(queryElement)

            if len(results) > limit:
                # We have to add here an element to the JSON in case there is too many elements.
                searchquery = "/@@search?SearchableText=%s&path=%s" % (searchterms, params["path"])
                too_many_results = {
                    "class": "with-separator",
                    "title": ts.translate(label_show_all, context=REQUEST),
                    "description": "",
                    "itemUrl": portal_url + searchquery,
                    "icon": "",
                }
                queryElements.append(too_many_results)

        return json.dumps(queryElements)
Пример #33
0
    def all_events_link(self):
        pc = api.portal.get_tool('portal_catalog')
        events_folder = pc.searchResults(object_provides=IEventFolder.__identifier__, Language=pref_lang())

        if events_folder:
            return '%s' % events_folder[0].getURL()
        else:
            return ''
Пример #34
0
    def render(self):
        # We set the parameters sent in livesearch using the old way.
        q = self.request['q']
        cf = self.request['cf']
        limit = 10
        path = None
        if cf != '':
            path = cf
        ploneUtils = getToolByName(self.context, 'plone_utils')
        portal_url = getToolByName(self.context, 'portal_url')()
        pretty_title_or_id = ploneUtils.pretty_title_or_id
        portalProperties = getToolByName(self.context, 'portal_properties')
        siteProperties = getattr(portalProperties, 'site_properties', None)
        useViewAction = []
        if siteProperties is not None:
            useViewAction = siteProperties.getProperty('typesUseViewActionInListings', [])

        # SIMPLE CONFIGURATION
        MAX_TITLE = 40
        MAX_DESCRIPTION = 80

        # generate a result set for the query
        catalog = self.context.portal_catalog

        friendly_types = ploneUtils.getUserFriendlyTypes()

        def quotestring(s):
            return '"%s"' % s

        def quote_bad_chars(s):
            bad_chars = ["(", ")"]
            for char in bad_chars:
                s = s.replace(char, quotestring(char))
            return s

        multispace = u'\u3000'.encode('utf-8')
        for char in ('?', '-', '+', '*', multispace):
            q = q.replace(char, ' ')
        r = q.split()
        r = " AND ".join(r)
        r = quote_bad_chars(r) + '*'
        searchterms = url_quote_plus(r)

        params = {'SearchableText': r,
                  'portal_type': friendly_types,
                  'sort_limit': limit + 1}

        if path is None:
            # useful for subsides
            params['path'] = getNavigationRoot(self.context)
        else:
            params['path'] = path

        params["Language"] = pref_lang()
        # search limit+1 results to know if limit is exceeded
        results = catalog(**params)

        REQUEST = self.context.REQUEST
        RESPONSE = REQUEST.RESPONSE
        RESPONSE.setHeader('Content-Type', 'application/json')

        label_show_all = _('label_show_all', default='Show all items')

        ts = getToolByName(self.context, 'translation_service')

        queryElements = []

        if results:
            # TODO: We have to build a JSON with the desired parameters.
            for result in results[:limit]:
                # Calculate icon replacing '.' per '-' as '.' in portal_types break CSS
                icon = result.portal_type.lower().replace(".", "-")
                itemUrl = result.getURL()
                if result.portal_type in useViewAction:
                    itemUrl += '/view'

                full_title = safe_unicode(pretty_title_or_id(result))
                if len(full_title) > MAX_TITLE:
                    display_title = ''.join((full_title[:MAX_TITLE], '...'))
                else:
                    display_title = full_title

                full_title = full_title.replace('"', '&quot;')

                display_description = safe_unicode(result.Description)
                if len(display_description) > MAX_DESCRIPTION:
                    display_description = ''.join(
                        (display_description[:MAX_DESCRIPTION], '...'))

                # We build the dictionary element with the desired parameters and we add it to the queryElements array.
                queryElement = {'class': '', 'title': display_title, 'description': display_description, 'itemUrl': itemUrl, 'icon': icon}
                queryElements.append(queryElement)

            if len(results) > limit:
                # We have to add here an element to the JSON in case there is too many elements.
                searchquery = '/@@search?SearchableText=%s&path=%s' \
                    % (searchterms, params['path'])
                too_many_results = {'class': 'with-separator', 'title': ts.translate(label_show_all, context=REQUEST), 'description': '', 'itemUrl': portal_url + searchquery, 'icon': ''}
                queryElements.append(too_many_results)

        return json.dumps(queryElements)
Пример #35
0
    def getHTML(self):
        packet_type = self.getType()
        adapter = getAdapter(self.context, IpacketDefinition, packet_type)
        adapter.packet_fields.update({'lang': utils.pref_lang()})

        url = adapter.URL_schema
        portal_url = getToolByName(self.context, "portal_url")
        portal = portal_url.getPortalObject()
        url_portal_nginx = portal.absolute_url()  # url (per dns) del lloc
        try:
            url = self.get_absolute_url(url % adapter.packet_fields)
            # check url to avoid autoreference, removing http(s) and final slash
            link_url = re.findall('https?://(.*)', url)[0].strip(
                '/')  # url del contingut netejada
            parent_url = re.findall('https?://(.*)',
                                    self.context.absolute_url())[0].strip(
                                        '/')  # url del pare netejada
            root_url = re.findall('https?://(.*)', url_portal_nginx)[0].strip(
                '/')  # url (per dns) del lloc netejada
            if link_url != parent_url:
                if link_url.startswith(root_url):
                    # link intern, search through the catalog
                    relative_path = '/' + re.findall(root_url + '(.*)',
                                                     link_url)[0]
                    url_to_search = '/'.join(
                        portal.getPhysicalPath()) + relative_path
                    raw_html = self.get_catalog_content(url_to_search)
                    charset = re.findall('charset=(.*)"', raw_html)
                    if len(charset) > 0:
                        clean_html = re.sub(r'[\n\r]?', r'',
                                            raw_html.encode(charset[0]))
                        doc = pq(clean_html)
                        match = re.search(r'This page does not exist',
                                          clean_html)
                        self.title = self.context.Title()  # titol per defecte
                        if not match:
                            if packet_type == 'contingut_genweb':
                                element = adapter.packet_fields['element']
                                if not element:
                                    element = "#content-core"
                            else:
                                element = "#content-nucli"
                            content = pq('<div/>').append(
                                doc(element).outerHtml()).html(method='html')
                            if not content:
                                content = _(
                                    u"ERROR. This element does not exist."
                                ) + " " + element
                        else:
                            content = _(
                                u"ERROR: Unknown identifier. This page does not exist."
                                + url)
                    else:
                        content = _(u"ERROR. Charset undefined")
                else:
                    # link extern, pyreq
                    raw_html = requests.get(url, timeout=5, verify=False)
                    charset = re.findall('charset=(.*)"', raw_html.content)
                    if len(charset) > 0:
                        clean_html = re.sub(
                            r'[\n\r]?', r'',
                            raw_html.content.decode(charset[0]))
                        doc = pq(clean_html)
                        match = re.search(r'This page does not exist',
                                          clean_html)
                        self.title = self.context.Title()  # titol per defecte
                        if not match:
                            if packet_type == 'contingut_genweb':
                                element = adapter.packet_fields['element']
                                if not element:
                                    element = "#content-core"
                            else:
                                element = "#content-nucli"
                            content = pq('<div/>').append(
                                doc(element).outerHtml()).html(method='html')
                            if not content:
                                content = _(
                                    u"ERROR. This element does not exist."
                                ) + " " + element
                        else:
                            content = _(
                                u"ERROR: Unknown identifier. This page does not exist."
                                + url)
                    else:
                        content = _(u"ERROR. Charset undefined")
            else:
                content = _(u"ERROR. Autoreference")
        except ReadTimeout:
            content = _(
                u"ERROR. There was a timeout while waiting for '{0}'".format(
                    self.get_absolute_url(self.data.url)))
        except RequestException:
            content = _(u"ERROR. This URL does not exist.")
        except:
            content = _(u"ERROR. Unexpected exception.")

        self.content = content