Beispiel #1
0
 def get_toc(self, html):
     toc = []
     content = BeautifulSoup(html, 'html.parser')
     for tag in content.findAll(TOC_TAGS):
         toc.append({
             'id': slugify(tag.string),
             'name': slugify(tag.name),
             'string': tag.string
         })
         tag['id'] = slugify(tag.string)
     return toc, content
Beispiel #2
0
    def new_page(self, cr, uid, name, template="website.default_page", ispage=True, context=None):
        context = context or {}
        imd = self.pool["ir.model.data"]
        view = self.pool["ir.ui.view"]
        template_module, template_name = template.split(".")

        # completely arbitrary max_length
        page_name = slugify(name, max_length=50)
        page_xmlid = "%s.%s" % (template_module, page_name)

        try:
            # existing page
            imd.get_object_reference(cr, uid, template_module, page_name)
        except ValueError:
            # new page
            _, template_id = imd.get_object_reference(cr, uid, template_module, template_name)

            page_id = view.copy(
                cr, uid, template_id, {"website_id": context.get("website_id"), "key": page_xmlid}, context=context
            )

            page = view.browse(cr, uid, page_id, context=context)

            page.write({"arch": page.arch.replace(template, page_xmlid), "name": page_name, "page": ispage})

        return page_xmlid
Beispiel #3
0
    def new_page(self, cr, uid, name, template='website.default_page', ispage=True, context=None):
        context = context or {}
        imd = self.pool['ir.model.data']
        view = self.pool['ir.ui.view']
        template_module, template_name = template.split('.')

        # completely arbitrary max_length
        page_name = slugify(name, max_length=50)
        page_xmlid = "%s.%s" % (template_module, page_name)

        try:
            # existing page
            imd.get_object_reference(cr, uid, template_module, page_name)
        except ValueError:
            # new page
            _, template_id = imd.get_object_reference(cr, uid, template_module, template_name)

            page_id = view.copy(cr, uid, template_id, {
                'website_id': context.get('website_id'),
                'key': page_xmlid
            }, context=context)

            page = view.browse(cr, uid, page_id, context=context)

            page.write({
                'arch': page.arch.replace(template, page_xmlid),
                'name': page_name,
                'page': ispage,
            })

        return page_xmlid
Beispiel #4
0
    def enumerate_pages(self):
        """
        For sitemap
        :return:
        """
        products = self.search([('website_published', '=', True)])
        for product in products:
            lastmod = False
            try:
                lastmod = datetime.strptime(product.write_date, "%Y-%m-%d %H:%M:%S").date().isoformat()
            except:
                pass

            slugname = slugify(product.name_ext or '').strip().strip('-')
            if not slugname:
                path = str(product.id)
            else:
                path = "%s-%d" % (slugname, product.id)

            page_pt = {'loc': '/shop/product/' + path, 'lastmod': lastmod, 'changefreq': 'weekly'}
            page_en = {'loc': '/en_US/shop/product/' + path, 'lastmod': lastmod, 'changefreq': 'weekly'}
            page_fr = {'loc': '/fr_FR/shop/product/' + path, 'lastmod': lastmod, 'changefreq': 'weekly'}
            yield page_pt
            yield page_en
            yield page_fr
Beispiel #5
0
def update_sequences_gallery(self, cr, uid, ids, field_gallery,
                             model_gallery_name):
    """ Actualiza los nombres de una galleria asociada a un object self
    en función de su sequencia """
    fs = _filestorage(cr)
    for obj in self.browse(cr, uid, ids):
        fix_images = []
        for image in getattr(obj, field_gallery):
            name_compute = image._compute_name_image(
                image.object_relation.name, image.sequence)
            if name_compute != image.name:
                image_path = os.path.join(fs, image.name)
                image._delete_thumbails(image_path)
                fix_images.append((image, name_compute))
                image.name = 'fix_{}_{}'.format(slugify(model_gallery_name),
                                                image.id)
                # rename
                path, file_name = os.path.split(image_path)
                new_image_path = os.path.join(path, image.name)
                try:
                    os.rename(image_path, new_image_path)
                except:
                    _log.exception(u"Error actualizando nombre gallery")
        if len(fix_images):
            for image, name_compute in fix_images:
                # rename
                new_image_path = os.path.join(fs, name_compute)
                try:
                    os.rename(os.path.join(path, image.name), new_image_path)
                except:
                    _log.exception(u"Error actualizando nombre gallery fixed")
                # write
                image.write({'name': name_compute})
Beispiel #6
0
def update_sequences_gallery(self, cr, uid, ids, field_gallery,
                             model_gallery_name):
    """ Actualiza los nombres de una galleria asociada a un object self
    en función de su sequencia """
    fs = _filestorage(cr)
    for obj in self.browse(cr, uid, ids):
        fix_images = []
        for image in getattr(obj, field_gallery):
            name_compute = image._compute_name_image(
                image.object_relation.name, image.sequence)
            if name_compute != image.name:
                image_path = os.path.join(fs, image.name)
                image._delete_thumbails(image_path)
                fix_images.append((image, name_compute))
                image.name = 'fix_{}_{}'.format(
                    slugify(model_gallery_name), image.id)
                # rename
                path, file_name = os.path.split(image_path)
                new_image_path = os.path.join(path, image.name)
                try:
                    os.rename(image_path, new_image_path)
                except:
                    _log.exception(u"Error actualizando nombre gallery")
        if len(fix_images):
            for image, name_compute in fix_images:
                # rename
                new_image_path = os.path.join(fs, name_compute)
                try:
                    os.rename(os.path.join(path, image.name), new_image_path)
                except:
                    _log.exception(u"Error actualizando nombre gallery fixed")
                # write
                image.write({'name': name_compute})
Beispiel #7
0
    def new_page(self, cr, uid, name, template='website.default_page', ispage=True, context=None):
        context = context or {}
        imd = self.pool['ir.model.data']
        view = self.pool['ir.ui.view']
        template_module, template_name = template.split('.')

        # completely arbitrary max_length
        page_name = slugify(name, max_length=50)
        page_xmlid = "%s.%s" % (template_module, page_name)

        try:
            # existing page
            imd.get_object_reference(cr, uid, template_module, page_name)
        except ValueError:
            # new page
            _, template_id = imd.get_object_reference(cr, uid, template_module, template_name)

            page_id = view.copy(cr, uid, template_id, {
                'website_id': context.get('website_id'),
                'key': page_xmlid
            }, context=context)

            page = view.browse(cr, uid, page_id, context=context)

            page.write({
                'arch': page.arch.replace(template, page_xmlid),
                'name': page_name,
                'page': ispage,
            })

        return page_xmlid
Beispiel #8
0
def slugify_friendly(s):
    # Well format slug: path/to/page.extension
    # Sample: woman/shoes/leather-boots.html
    # TODO: Keep final slug less than 2048 characters to be safe on IE

    path, extension = s[:s.rfind('.')], s[s.rfind('.'):]
    path_splits = [slugify(p or '') for p in path.split('/')]
    slug = '{}{}'.format('/'.join(path_splits), extension)

    # s = ustr(s)
    # if s[0] == u'/':
    #     s = s[1:]
    # if s[-1] == u'/':
    #     s = s[0:-1]

    # uni = unicodedata.normalize('NFKD', s).encode('ascii', 'ignore').decode(
    #     'ascii')
    # slug = re.sub('[\W_]', ' ', uni).strip().lower()
    # slug = re.sub('[-\s]+', '-', slug)

    # if len(slug) == len(s):
    #     pos = [m.start() for m in re.finditer('/', s)]
    #     if len(pos) == 0:
    #         return slug

    #     slug = list(slug)
    #     for i in pos:
    #         slug[i] = s[i]

    #     slug = u"".join(slug)
    #     if slug[0] == u'/':
    #         slug = slug[1:]

    return slug
Beispiel #9
0
 def new_page(self,
              cr,
              uid,
              name,
              template='website.default_page',
              ispage=True,
              context=None):
     res = super(website, self).new_page(cr,
                                         uid,
                                         name,
                                         template=template,
                                         ispage=ispage,
                                         context=context)
     page_name = slugify(name, max_length=50)
     ir_view = self.pool.get('ir.ui.view')
     view_id = ir_view.search(cr,
                              SUPERUSER_ID, [('name', '=', page_name)],
                              context=context)
     if view_id:
         view = ir_view.browse(cr, SUPERUSER_ID, view_id, context=context)
         arch = '<?xml version="1.0"?><t t-name="website.' + str(
             page_name
         ) + '"><t t-call="website.layout"> <div id="wrap" class="oe_structure oe_empty"><section class="page-title"><div class="container"><h1>' + str(
             page_name.capitalize()
         ) + '</h1><ul class="breadcrumb"><li><a href="/page/homepage">Home</a></li><li class="active">' + str(
             page_name.capitalize(
             )) + '</li></ul></div></section></div></t></t>'
         ir_view.write(cr,
                       SUPERUSER_ID,
                       view_id, {'arch': arch},
                       context=context)
     return res
Beispiel #10
0
def slugify_friendly(s):
    # TODO: Keep final slug less than 2048 characters to be safe on IE
    # Well formated slug: path/to/page.extension
    # Sample: woman/shoes/leather-boots.html
    path, extension = s[:s.rfind('.')], s[s.rfind('.'):]
    path_splits = [slugify(p or '') for p in path.split('/')]
    slug = '%s%s' % ('/'.join(path_splits), extension)

    return slug
Beispiel #11
0
 def _check_seo_url(self, vals, id=0):
     field = self._seo_url_field
     vals = vals or {}
     value = vals.get(field)
     if value:
         vals[field] = value = slugify(value)
         res = self.search([(field, '=', value), ('id', '!=', id)])
         if res:
             vals[field] = '%s-%s' % (vals[field], id)
     return vals
Beispiel #12
0
 def _compute_name_slug(self):
     self.name_slug = self.product_tmpl_id.name
     attributes = [
         attribute_value for attribute_value in self.attribute_value_ids
         if attribute_value.attribute_id.apply_to_images
     ]
     for attribute in attributes:
         self.name_slug += '-%s-%s' % (attribute.attribute_id.name,
                                       attribute.name)
     self.name_slug = slugify(self.name_slug)
Beispiel #13
0
	def to_url(self, value):
		if isinstance(value, orm.browse_record):
			# [(id, name)] = value.name_get()
			id, name = value.id, value.display_name
		else:
			# assume name_search result tuple
			id, name = value
		slugname = slugify(name or '').strip().strip('-')
		print(slugname)
		if not slugname:
			return str(id)
		return slugname
Beispiel #14
0
    def generate_name(self, product_id):
        """
        Generate an image name for the given property

        :param product_id: The real estate ID
        :type product_id: `product.product`
        :return: The name for the image
        :rtype: str
        """
        image_index = len(product_id.image_ids)
        name = slugify('%s-%d' % (product_id.name_ext, image_index + 1))
        return name
Beispiel #15
0
def get_name_product(product):
    logger.debug("Get name product {}".format(product._name))
    name = None

    if product._name == 'product.template':
        # producto por defecto y primera valor de cada variante que afecte
        # a la imagen
        # ====================================================================
        assert len(product.product_variant_ids) > 0, \
            u"El producto {} no tiene variantes".format(product)

        template = product
        product = product.product_variant_ids[0]  # producto por defecto
        name = slugify(template.name)

        # product.template
        #   - attribute_line_ids => product.attribute.line
        # product.attribute.line
        #   - attribute_id product.attribute
        #   - value_ids => product.attribute.value

        attributes_lines = [
            l for l in template.attribute_line_ids
            if l.attribute_id.affects_image
        ]

        for al in attributes_lines:
            av = al.value_ids[0]
            name += u'-{}-{}'.format(slugify(av.attribute_id.name),
                                     slugify(av.name))
    else:
        # valor de cada variante que afecta a la imagen
        # =============================================
        template = product.product_tmpl_id
        name = slugify(template.name)

        # product.product
        #   - attribute_value_ids => product.attribute.value
        # product.attribute.value
        #   - attribute_id => product.attribute

        attributes_values = [
            l for l in product.attribute_value_ids
            if l.attribute_id.affects_image
        ]

        for av in attributes_values:
            name += u'-{}-{}'.format(slugify(av.attribute_id.name),
                                     slugify(av.name))

    assert name is not None, \
        u"No se ha podido calcular el nombre de la imagen para {}" \
        .format(product)

    return name, slugify(template.name)
Beispiel #16
0
 def _compute_name_image(self, name=None, sequence=None):
     """
     Devuelve el nombre de la imagen en función del nombre del objecto
     y su sequencia
     """
     name = name or self.object_relation.name
     sequence = sequence or self.sequence
     if sequence > 1:
         name_file = u"{}-{}.jpg".format(slugify(name), sequence)
     else:
         name_file = u"{}.jpg".format(slugify(name))
     # comprobamos si existe ya una imagen con este nombre
     count = self.search_count([(self.object_relation_name, '!=',
                                 self.object_relation.id),
                                ('name', '=', name_file)])
     if count > 0:
         if sequence > 1:
             name_file = u"{}_{}-{}.jpg".format(slugify(name), count,
                                                sequence)
         else:
             name_file = u"{}_{}.jpg".format(slugify(name), count)
     return name_file
Beispiel #17
0
 def _compute_name_image(self, name=None, sequence=None):
     """
     Devuelve el nombre de la imagen en función del nombre del objecto
     y su sequencia
     """
     name = name or self.object_relation.name
     sequence = sequence or self.sequence
     if sequence > 1:
         name_file = u"{}-{}.jpg".format(slugify(name), sequence)
     else:
         name_file = u"{}.jpg".format(slugify(name))
     # comprobamos si existe ya una imagen con este nombre
     count = self.search_count(
         [(self.object_relation_name, '!=', self.object_relation.id),
          ('name', '=', name_file)])
     if count > 0:
         if sequence > 1:
             name_file = u"{}_{}-{}.jpg".format(slugify(name), count,
                                                sequence)
         else:
             name_file = u"{}_{}.jpg".format(slugify(name), count)
     return name_file
Beispiel #18
0
 def _compute_name_slug(self):
     # TODO: Incluir dependencia módulo ordenación attributos para
     # poder controlar los slugs de las variantes si hay más de un
     # atributo que afecta a la imagen
     self.name_slug = self.product_tmpl_id.name
     attributes = [
         attribute_value for attribute_value in self.attribute_value_ids
         if attribute_value.attribute_id.apply_to_images]
     for attribute in attributes:
         self.name_slug += '-%s-%s' % (
             attribute.attribute_id.name,
             attribute.name)
     self.name_slug = slugify(self.name_slug)
Beispiel #19
0
 def get_website_view(self):
     view = False
     if self.url:
         view = self.env['ir.ui.view'].find_by_seo_path(self.url)
         if not view:
             url_parts = self.url.split('/')
             xml_id = url_parts[-1]
             if '.' not in xml_id:
                 xml_id = 'website.%s' % xml_id
             view = self.env['ir.model.data'].xmlid_to_object(xml_id)
         if not view:
             xml_id = 'website.%s' % slugify(self.name)
             view = self.env['ir.model.data'].xmlid_to_object(xml_id)
     return view
    def new_page(self,
                 cr,
                 uid,
                 name,
                 template='website.default_page',
                 ispage=True,
                 context=None):
        context = context or {}
        imd = self.pool.get('ir.model.data')
        view = self.pool.get('ir.ui.view')
        template_module, template_name = template.split('.')

        # completely arbitrary max_length
        page_name = slugify(name, max_length=50)
        page_xmlid = "%s.%s" % (template_module, page_name)

        try:
            # existing page
            imd.get_object_reference(cr, uid, template_module, page_name)
        except ValueError:
            # new page
            _, template_id = imd.get_object_reference(cr, uid, template_module,
                                                      template_name)
            page_id = view.copy(cr, uid, template_id, context=context)
            page = view.browse(cr, uid, page_id, context=context)
            page.write({
                'arch': page.arch.replace(template, page_xmlid),
                'name': page_name,
                'page': ispage,
            })
            page1 = view.browse(cr, uid, page_id, context=context)
            arch = '<?xml version="1.0"?><t t-name="website.' + str(
                page_name) + '"><t t-call="website.layout"> \
                    <div id="wrap" class="oe_structure oe_empty"><div class="page-title"><div class="container">\
                    <h1>' + str(page_name.capitalize()) + '</h1> \
                    <ul class="breadcrumb"><li><a href="/page/homepage">Home</a>\
                    </li><li class="active">' + str(page_name.capitalize(
                )) + '</li></ul></div></div></div></t></t>'
            page1.write({'arch': arch})
            imd.create(cr,
                       uid, {
                           'name': page_name,
                           'module': template_module,
                           'model': 'ir.ui.view',
                           'res_id': page_id,
                           'noupdate': True
                       },
                       context=context)
        return page_xmlid
Beispiel #21
0
def get_name_product(product):
    logger.debug("Get name product {}".format(product._name))
    name = None

    if product._name == 'product.template':
        # producto por defecto y primera valor de cada variante que afecte
        # a la imagen
        # ====================================================================
        assert len(product.product_variant_ids) > 0, \
            u"El producto {} no tiene variantes".format(product)

        template = product
        product = product.product_variant_ids[0]  # producto por defecto
        name = slugify(template.name)

        # product.template
        #   - attribute_line_ids => product.attribute.line
        # product.attribute.line
        #   - attribute_id product.attribute
        #   - value_ids => product.attribute.value

        attributes_lines = [l for l in template.attribute_line_ids
                            if l.attribute_id.affects_image]

        for al in attributes_lines:
            av = al.value_ids[0]
            name += u'-{}-{}'.format(
                slugify(av.attribute_id.name), slugify(av.name))
    else:
        # valor de cada variante que afecta a la imagen
        # =============================================
        template = product.product_tmpl_id
        name = slugify(template.name)

        # product.product
        #   - attribute_value_ids => product.attribute.value
        # product.attribute.value
        #   - attribute_id => product.attribute

        attributes_values = [l for l in product.attribute_value_ids
                             if l.attribute_id.affects_image]

        for av in attributes_values:
            name += u'-{}-{}'.format(
                slugify(av.attribute_id.name), slugify(av.name))

    assert name is not None, \
        u"No se ha podido calcular el nombre de la imagen para {}" \
        .format(product)

    return name, slugify(template.name)
Beispiel #22
0
 def _inverse_image(self):
     fs = _filestorage(self.env.cr)
     name_file = self._compute_name_image()
     image_path = os.path.join(fs, name_file)
     if os.path.isfile(image_path):
         count = 1
         while not os.path.isfile(image_path):
             name = u"{}_{}".format(slugify(self.name), count)
             image_path = os.path.join(fs, name)
             count += 1
             name_file = name
         image_path = os.path.join(fs, name_file)
     # salvamos imagen
     img = Image.open(cStringIO.StringIO(base64.b64decode(self.image)))
     img.save(image_path)
     self.write({'name': name_file})
Beispiel #23
0
 def _inverse_image(self):
     fs = _filestorage(self.env.cr)
     name_file = self._compute_name_image()
     image_path = os.path.join(fs, name_file)
     if os.path.isfile(image_path):
         count = 1
         while not os.path.isfile(image_path):
             name = u"{}_{}".format(slugify(self.name), count)
             image_path = os.path.join(fs, name)
             count += 1
             name_file = name
         image_path = os.path.join(fs, name_file)
     # salvamos imagen
     img = Image.open(cStringIO.StringIO(base64.b64decode(self.image)))
     img.save(image_path)
     self.write({'name': name_file})
Beispiel #24
0
def slug(value):
    """Add seo url check in slug handling."""
    if isinstance(value, orm.browse_record):
        # if a seo url field exists in a record and it is not empty return it
        if 'seo_url' in value._fields and value.seo_url:
            return value.seo_url

        # [(id, name)] = value.name_get()
        id, name = value.id, value.display_name
    else:
        # assume name_search result tuple
        id, name = value
    slugname = slugify(name or '').strip().strip('-')
    if not slugname:
        return str(id)
    return "%s-%d" % (slugname, id)
    def new_page(self, cr, uid, name, template='website.default_page', ispage=True, context=None):
        context = context or {}
        imd = self.pool.get('ir.model.data')
        view = self.pool.get('ir.ui.view')
        template_module, template_name = template.split('.')

        # completely arbitrary max_length
        page_name = slugify(name, max_length=50)
        page_xmlid = "%s.%s" % (template_module, page_name)

        try:
            # existing page
            imd.get_object_reference(cr, uid, template_module, page_name)
        except ValueError:
            # new page
            _, template_id = imd.get_object_reference(cr, uid, template_module, template_name)
            page_id = view.copy(cr, uid, template_id, context=context)
            page = view.browse(cr, uid, page_id, context=context)
            page.write({
                'arch': page.arch.replace(template, page_xmlid),
                'name': page_name,
                'page': ispage,
            })
            page1=view.browse(cr, uid, page_id, context=context)
            arch='<?xml version="1.0"?><t t-name="website.'+str(page_name)+'"><t t-call="website.layout"> \
                    <div id="wrap" class="oe_structure oe_empty"><div class="page-title"><div class="container">\
                    <h1>'+str(page_name.capitalize())+'</h1> \
                    <ul class="breadcrumb"><li><a href="/page/homepage">Home</a>\
                    </li><li class="active">'+str(page_name.capitalize())+'</li></ul></div></div></div></t></t>'
            page1.write({'arch':arch})
            imd.create(cr, uid, {
                'name': page_name,
                'module': template_module,
                'model': 'ir.ui.view',
                'res_id': page_id,
                'noupdate': True
            }, context=context)
        return page_xmlid
Beispiel #26
0
 def _compute_city_slug(self):
     self.city_slug = slugify(self.city)
Beispiel #27
0
 def _compute_city_slug(self):
     self.city_slug = slugify(self.city)
Beispiel #28
0
 def test_spaces(self):
     self.assertEqual("spaces", slugify(u"   spaces   "))
Beispiel #29
0
    def blog_search_results(self, page=1, sorting='date', search='', **post):
        cr, uid, context = request.cr, request.uid, request.context

        blog_post_env = request.env['blog.post']
        p_blogs = blog_post_env.search([('displayAsCase', '=', False), ('website_published','=',True)], order='visits')
        popular_blogs = tuple(reversed(p_blogs))
        posts = ()
        
        values2 = {
                  'popular_blogs' : popular_blogs[0:3],
                  }
        
        if len(search)<self._min_search_len:
            return request.website.render("theme_aditim.blog_aggregator_page", values2)

        lang = request.context.get('lang')
        default_website_lang=request.website.default_lang_code[0:2]
        pages_use_translations= (default_website_lang!=lang[0:2])
        db_use_translations=(lang[0:2]!='en')

        # Check which modules are installed
        website_blog_installed = self._module_installed(cr, 'website_blog')
        website_partner_installed = self._module_installed(cr, 'website_partner')
        website_hr_recruitment_installed = self._module_installed(cr, 'website_hr_recruitment')
        website_sale_installed = self._module_installed(cr, 'website_sale')

        # Define search scope
        search_on_pages=self._search_on_pages or not (search_on_blogposts or search_on_comments or search_on_customers or search_on_jobs or search_on_products)
        search_on_blogposts=self._search_on_blogposts and website_blog_installed
        search_on_comments=self._search_on_comments and website_blog_installed
        search_on_customers=self._search_on_customers and website_partner_installed
        search_on_jobs=self._search_on_jobs and website_hr_recruitment_installed
        search_on_products=self._search_on_products and website_sale_installed
        case_sensitive=self._case_sensitive
        
        if not case_sensitive:
            search_lower=search.lower()

        url = "/search_results"
        sql_query=""


        # Check for other order criteria, if new order criteria added, add here
        if sorting=='date':
            sql_order_by='result_date desc'

        if search_on_blogposts:
            if sql_query:
                sql_query+=' UNION ALL '
            if db_use_translations:
                sql_query+="""
                  SELECT DISTINCT 'Blog post' as result_type, blp.id as result_id, blp.name as result_name,  'website_blog' as template_module, tr.value as template_source, blp.website_meta_description, blp.website_meta_title, blp.website_meta_keywords,  '/page/'||bl.name||'-'||bl.id|| '/post/' as result_path, '' as result_image, tr.lang as result_lang, '' as result_lang_text, blp.write_date as result_date --tr.value as result_lang_text generated more rows and not used afterwards
                  FROM ir_translation tr, blog_blog bl, blog_post blp
                  LEFT OUTER JOIN blog_post_blog_tag_rel tg_rel ON (tg_rel.blog_post_id=blp.id)
                  LEFT OUTER JOIN blog_tag tg ON (tg_rel.blog_tag_id=tg.id)
                  LEFT OUTER JOIN ir_translation tr2 ON (tr2.res_id=tg.id)
                  WHERE blp.blog_id=bl.id and tr.type='model' and tr.name='blog.post,content' and tr2.name='blog.tag,name'
                  and blp.website_published=true
                  and tr.res_id=blp.id and tr.lang='%s' """ % (lang)
                if case_sensitive:
                    sql_query+="""and ( tr.value ilike '%%%s%%' or tr2.value ilike '%%%s%%')""" % ( search, search)
                else:
                    sql_query+="""and ( lower(tr.value) ilike '%%%s%%' or lower(tr2.value) ilike '%%%s%%')""" % (search_lower, search_lower)
            else:
                sql_query+="""
                  SELECT DISTINCT 'Blog post' as result_type, blp.id as result_id, blp.name as result_name,  'website_blog' as template_module, blp.content as template_source, blp.website_meta_description, blp.website_meta_title, blp.website_meta_keywords, '/page/'||bl.name||'-'||bl.id|| '/post/' as result_path, '' as result_image, '%s' as result_lang, '' as result_lang_text, blp.write_date as result_date
                  FROM blog_blog bl, blog_post blp
                  LEFT OUTER JOIN blog_post_blog_tag_rel tg_rel ON (tg_rel.blog_post_id=blp.id)
                  LEFT OUTER JOIN blog_tag tg ON (tg_rel.blog_tag_id=tg.id)
                  WHERE blp.website_published=true and blp.blog_id=bl.id """ % (lang)
                if case_sensitive:
                    sql_query+="""and ( blp.content ilike '%%%s%%' or blp.website_meta_title ilike '%%%s%%' or blp.website_meta_keywords ilike '%%%s%%' or tg.name ilike '%%%s%%')""" % (search, search, search, search)
                else:
                    sql_query+="""and ( lower(blp.content) ilike '%%%s%%' or lower(blp.website_meta_title) ilike '%%%s%%' or lower(blp.website_meta_keywords) ilike '%%%s%%' or lower(tg.name) ilike '%%%s%%')""" % (search_lower, search_lower, search_lower, search_lower)


        if search_on_comments:
            if sql_query:
                sql_query+=' UNION ALL '

            sql_query+="""
                  SELECT DISTINCT 'Blog post comment' as result_type, blp.id as result_id, blp.name as result_name,  'website_blog' as template_module, ml.body as template_source, '' as website_meta_description, '' as website_meta_title, '' as website_meta_keywords, '/page/'||bl.name||'-'||bl.id|| '/post/' as result_path, '' as result_image, '' as result_lang, '' as result_lang_text, ml.write_date as result_date
                  FROM blog_blog bl, blog_post blp, mail_message ml
                  WHERE blp.website_published=true and ml.website_published=true and blp.blog_id=bl.id
                  and ml.res_id=blp.id and ml.model='blog.post' """
            if case_sensitive:
                sql_query+="""and ml.body ilike '%%%s%%'""" % (search)
            else:
                sql_query+="""and lower(ml.body) ilike '%%%s%%'""" % (search_lower)

        # Build query count
        if sql_query:
            sql_query_count="""SELECT count(distinct result_type||'-'||result_id  ) FROM ( %s ) as subquery""" % (sql_query)

        # Build query for results ordered
        if sql_query:
            limit=self._results_per_page
            offset=(page-1)*self._results_per_page
            sql_query_ordered="""SELECT distinct result_type, result_id, result_name,  template_module, template_source, website_meta_description, website_meta_title, website_meta_keywords, result_path, result_image, result_lang, result_lang_text, result_date
                                 FROM ( %s ) as subquery
                                 ORDER BY %s
                                 LIMIT %s
                                 OFFSET %s

                                 """ % (sql_query, sql_order_by, limit, offset)



        # Get results count for pager
        if sql_query_count:
            cr.execute(sql_query_count)
            results_count=cr.fetchone()[0] or 0

        url_args = {}
        if search:
            url_args['search'] = search
        if sorting:
            url_args['sorting'] = sorting
        pager = request.website.pager(url=url, total=results_count, page=page,
                                      step=self._results_per_page, scope=self._results_per_page,
                                      url_args=url_args)

        # Get results and prepare info to render results page
        user = request.registry['res.users'].browse(request.cr, request.uid, request.uid, context=request.context)
        values = {'user': user,
                  'is_public_user': user.id == request.website.user_id.id,
                  'header': post.get('header', dict()),
                  'searches': post.get('searches', dict()),
                  'results_per_page': self._results_per_page,
                  'last_result_showing': min(results_count, page*self._results_per_page),
                  'results_count': results_count,
                  'results': [],
                  'pager': pager,
                  'search_on_pages': search_on_pages,
                  'search_on_blogposts': self._search_on_blogposts,
                  'search_on_comments': self._search_on_comments,
                  'search_on_customers': self._search_on_customers,
                  'search_on_jobs': self._search_on_jobs,
                  'search_on_products': self._search_on_products,
                  'case_sensitive': self._case_sensitive,
                  'sorting': sorting,
                  'search': search,
                  }

        if sql_query_ordered:
            cr.execute(sql_query_ordered)
            for result in cr.fetchall():
                result_id= result[0] + '-' + str(result[1])
                posts = posts + (result[1],)
                result_data={
                        'type': result[0],
                        'type_txt': _(result[0]),
                        'id': result[1],
                        'name': result[2],
                        'template_name':result[3] + '.' + result[2],
                        'template_source':result[4],
                        'website_meta_description':result[5],
                        'website_meta_title': result[6],
                        'website_meta_keywords':result[7],
                        'url': result[8] + result[2],
                        'image': result[9],     # seleccionar una imagen por tipo
                        'lang': result[10],
                        'lang_text': result[11],
                        'date': result[12][8:10]+"/"+result[12][5:7]+"/"+result[12][0:4],
                        'ocurrences': 0,
                        'object': None
                    }
                # Prepare result content near searched keyword
                if result_data['type']=='Page':
                    # Render page html
                    try:
                        html=request.registry['ir.ui.view'].render(cr, uid, result_data['template_name'], context=context, **post)
                    except Exception:
                        html='<main>'+_('Unable to get text page')+'</main>'
                    start=html.find("<main>")
                    end=html.find("</main>")+7

                elif result_data['type']=='Blog post':
                    # Render blog post html
                    try:
                        url_array=result_data['url'].split('/')
                        url_array[2]=slugify(url_array[2])
                        url_array[4]=slugify(url_array[4])
                        result_data['url']='/'.join(url_array)
                        result_data['url']=result_data['url']+"-"+str(result_data["id"])
                        blog_post=request.registry['blog.post'].browse(cr, uid, int(result_data['id']), context=context)
                        result_data['object']=blog_post
                        html=request.registry['ir.ui.view'].render(cr, uid, "website_search.blog_post_content", {'blog_post': blog_post}, context=context)
                    except Exception:
                        html='<main>'+_('Unable to get blog post text')+'</main>'

                    start=0
                    end=len(html)

                elif result_data['type']=='Blog post comment':
                    # Render blog post html
                    try:
                        url_array=result_data['url'].split('/')
                        url_array[2]=slugify(url_array[2])
                        url_array[4]=slugify(url_array[4])
                        result_data['url']='/'.join(url_array)
                        result_data['url']=result_data['url']+"-"+str(result_data["id"])
                        html=result_data['template_source']
                    except Exception:
                        html='<main>'+_('Unable to get blog post comment text')+'</main>'

                    start=0
                    end=len(html)

                elif result_data['type']=='Customer':
                    # Render customer info html
                    try:
                        url_array=result_data['url'].split('/')
                        url_array[2]=slugify(url_array[2])
                        result_data['url']='/'.join(url_array)
                        result_data['url']=result_data['url']+"-"+str(result_data["id"])
                        customer=request.registry['res.partner'].browse(cr, uid, int(result_data['id']), context=context)
                        result_data['object']=customer
                        html=request.registry['ir.ui.view'].render(cr, uid, "website_search.customer_detail", {'partner': customer}, context=context)
                    except Exception:
                        html='<main>'+_('Unable to get customer text')+'</main>'

                    start=0
                    end=len(html)

                elif result_data['type']=='Job':
                    # Render job info html
                    try:
                        url_array=result_data['url'].split('/')
                        url_array[3]=slugify(url_array[3])
                        result_data['url']='/'.join(url_array)
                        result_data['url']=result_data['url']+"-"+str(result_data["id"])
                        job=request.registry['hr.job'].browse(cr, uid, int(result_data['id']), context=context)
                        result_data['object']=job
                        html=request.registry['ir.ui.view'].render(cr, uid, "website_search.job_detail", {'job': job}, context=context)
                    except Exception:
                        html='<main>'+_('Unable to get job text')+'</main>'

                    start=0
                    end=len(html)


                elif result_data['type']=='Product':
                    # Render product info html
                    try:
                        url_array=result_data['url'].split('/')
                        url_array[3]=slugify(url_array[3])
                        result_data['url']='/'.join(url_array)
                        result_data['url']=result_data['url']+"-"+str(result_data["id"])
                        product=request.registry['product.template'].browse(cr, uid, int(result_data['id']), context=context)
                        result_data['object']=product
                        html=request.registry['ir.ui.view'].render(cr, uid, "website_search.product_detail", {'product': product}, context=context)
                    except Exception:
                        html='<main>'+_('Unable to get product text')+'</main>'

                    start=0
                    end=len(html)




                # Keep key part of html page
                html=html[start:end]

                # Convert to text, eliminate all tags and #, \n, [, ] symbols, and text between []
                if html2text:
                    html = html2text(html.decode('utf-8')).encode('utf-8')
                    html = self._removeSymbols(html.decode('utf-8'), '[', ']').encode('utf-8')
                    html = self._removeSymbols(html.decode('utf-8'), '\n').encode('utf-8')
                    html = self._removeSymbols(html.decode('utf-8'), '#').encode('utf-8')



                # If not case sensitive search, apply lower function to search term and html
                if case_sensitive:
                    search_term=search
                    search_html=html
                else:
                    search_term=search_lower
                    search_html=html.lower()

                # Trim content to a maximum total characters to show in description with nearest text
                if len(search_html)>self._max_text_content_len:
                    index=search_html.find(str(search_term), 0)
                    start=max(0, index-self._text_segment_back)
                    end=min(len(search_html), index+self._text_segment_forward)
                    html_trim=html[start:end]
                    search_html_trim=search_html[start:end]
                    if start>0:
                        html_trim="..."+html_trim
                        search_html_trim="..."+search_html_trim
                    if end<len(search_html):
                        html_trim=html_trim+"..."
                        search_html_trim=search_html_trim+"..."
                    search_html=search_html_trim
                    html=html_trim

                # Find keyword in description text to force style to background yellow and bold text
                index=search_html.find(str(search_term), 0)
                index_start=0
                str_styled_search="<span style='font-weight: bold; font-size: 100%%; background-color: yellow;'>%s</span>" % str(search)
                html_styled=''
                ocurrences=0
                while index>=0:
                    ocurrences+=1
                    html_styled+=html[index_start:index]
                    html_styled+=str_styled_search
                    index_start=index+len(str(search_term))
                    index=search_html.find(str(search_term), index_start)
                html_styled+=html[index_start:]


                result_data['content']="<p>"+html_styled+"</p>"
                result_data['ocurrences']=ocurrences
                values['results'].append(result_data)
        blog_post_ids = blog_post_env.search([('id', 'in', posts)])
        
        blog_tags_env = request.registry['blog.tag']
        blog_tag_ids = blog_tags_env.search(cr, uid, [], context=context)
        blog_tags = blog_tags_env.browse(cr, uid, blog_tag_ids, context=context)
        
        values2 = {'user': user,
                  'is_public_user': user.id == request.website.user_id.id,
                  'header': post.get('header', dict()),
                  'searches': post.get('searches', dict()),
                  'results_per_page': self._results_per_page,
                  'last_result_showing': min(results_count, page*self._results_per_page),
                  'results_count': results_count,
                  'pager': pager,
                  'search': search,
                  'all_blog_posts': blog_post_ids,
                  'popular_blogs' : popular_blogs[0:3],
                  'blog_tags': blog_tags,
                  }

        # Render results
        return request.website.render("theme_aditim.blog_aggregator_page", values2)
Beispiel #30
0
 def test_underscore(self):
     self.assertEqual("one-two", slugify(u"one_two"))
Beispiel #31
0
 def test_special_chars(self):
     self.assertEqual("o-d-o-o", slugify(u"o!#d{|\o/@~o&%^?"))
Beispiel #32
0
    def search_results(self, page=1, sorting='date', search='', **post):
        cr, uid, context = request.cr, request.uid, request.context

        if len(search) < self._min_search_len:
            return request.website.render("website_search.error_search_len",
                                          None)

        lang = request.context.get('lang')
        default_website_lang = request.website.default_lang_code[0:2]
        pages_use_translations = (default_website_lang != lang[0:2])
        db_use_translations = (lang[0:2] != 'en')

        # Check which modules are installed
        website_blog_installed = self._module_installed(cr, 'website_blog')
        website_partner_installed = self._module_installed(
            cr, 'website_partner')
        website_hr_recruitment_installed = self._module_installed(
            cr, 'website_hr_recruitment')
        website_sale_installed = self._module_installed(cr, 'website_sale')

        # Define search scope
        search_on_pages = self._search_on_pages or not (
            search_on_blogposts or search_on_comments or search_on_customers
            or search_on_jobs or search_on_products)
        search_on_blogposts = self._search_on_blogposts and website_blog_installed
        search_on_comments = self._search_on_comments and website_blog_installed
        search_on_customers = self._search_on_customers and website_partner_installed
        search_on_jobs = self._search_on_jobs and website_hr_recruitment_installed
        search_on_products = self._search_on_products and website_sale_installed
        case_sensitive = self._case_sensitive

        if not case_sensitive:
            search_lower = search.lower()

        url = "/search_results"
        sql_query = ""

        # Check for other order criteria, if new order criteria added, add here
        if sorting == 'date':
            sql_order_by = 'result_date desc'

        # Prepare Query to get search results on website pages

        if search_on_pages:
            if sql_query:
                sql_query += ' UNION ALL '
            if not pages_use_translations:
                sql_query += """
                  SELECT DISTINCT 'Page' as result_type, vw.id as result_id, dt.name as result_name,  'website' as template_module, vw.arch as template_source, vw.website_meta_description, vw.website_meta_title, vw.website_meta_keywords, '/page/' as result_path, '' as result_image, 'es' as result_lang, '' as result_lang_text, vw.write_date as result_date
                  FROM  ir_ui_view vw, ir_model_data dt
                  WHERE dt.module='website' and dt.model='ir.ui.view'
                  and dt.res_id=vw.id and vw.type='qweb' and vw.mode='primary' and vw.page=true """
                if case_sensitive:
                    sql_query += """and ( vw.arch ilike '%%%s%%' or vw.website_meta_description ilike '%%%s%%' or vw.website_meta_title ilike '%%%s%%' or vw.website_meta_keywords ilike '%%%s%%')
                """ % (search, search, search, search)
                else:
                    sql_query += """and ( lower(vw.arch) ilike '%%%s%%' or lower(vw.website_meta_description) ilike '%%%s%%' or lower(vw.website_meta_title) ilike '%%%s%%' or lower(vw.website_meta_keywords) ilike '%%%s%%')
                """ % (search_lower, search_lower, search_lower, search_lower)
            else:
                sql_query += """
                  SELECT DISTINCT 'Page' as result_type, vw.id as result_id, dt.name as result_name,  'website' as template_module, vw.arch as template_source, vw.website_meta_description, vw.website_meta_title, vw.website_meta_keywords, '/page/' as result_path, '' as result_image, tr.lang as result_lang, '' as result_lang_text, vw.write_date as result_date --tr.value as result_lang_text generated more rows and not used afterwards
                  FROM    ir_ui_view vw, ir_model_data dt, ir_translation tr
                  WHERE   tr.type='view' and tr.lang='%s' and tr.res_id =vw.id
                  and     dt.module='website' and dt.model='ir.ui.view'
                  and     dt.res_id=vw.id and vw.type='qweb' and vw.mode='primary' and vw.page=true """ % (
                    lang)
                if case_sensitive:
                    sql_query += """and     tr.value ilike '%%%s%%'""" % (
                        search)
                else:
                    sql_query += """and     lower(tr.value) ilike '%%%s%%'""" % (
                        search_lower)

        if search_on_blogposts:
            if sql_query:
                sql_query += ' UNION ALL '
            if db_use_translations:
                sql_query += """
                  SELECT DISTINCT 'Blog post' as result_type, blp.id as result_id, blp.name as result_name,  'website_blog' as template_module, tr.value as template_source, blp.website_meta_description, blp.website_meta_title, blp.website_meta_keywords,  '/blog/'||bl.name||'-'||bl.id|| '/post/' as result_path, '' as result_image, tr.lang as result_lang, '' as result_lang_text, blp.write_date as result_date --tr.value as result_lang_text generated more rows and not used afterwards
                  FROM ir_translation tr, blog_blog bl, blog_post blp
                  LEFT OUTER JOIN blog_post_blog_tag_rel tg_rel ON (tg_rel.blog_post_id=blp.id)
                  LEFT OUTER JOIN blog_tag tg ON (tg_rel.blog_tag_id=tg.id)
                  LEFT OUTER JOIN ir_translation tr2 ON (tr2.res_id=tg.id)
                  WHERE blp.blog_id=bl.id and tr.type='model' and tr.name='blog.post,content' and tr2.name='blog.tag,name'
                  and blp.website_published=true
                  and tr.res_id=blp.id and tr.lang='%s' """ % (lang)
                if case_sensitive:
                    sql_query += """and ( tr.value ilike '%%%s%%' or tr2.value ilike '%%%s%%')""" % (
                        search, search)
                else:
                    sql_query += """and ( lower(tr.value) ilike '%%%s%%' or lower(tr2.value) ilike '%%%s%%')""" % (
                        search_lower, search_lower)
            else:
                sql_query += """
                  SELECT DISTINCT 'Blog post' as result_type, blp.id as result_id, blp.name as result_name,  'website_blog' as template_module, blp.content as template_source, blp.website_meta_description, blp.website_meta_title, blp.website_meta_keywords, '/blog/'||bl.name||'-'||bl.id|| '/post/' as result_path, '' as result_image, '%s' as result_lang, '' as result_lang_text, blp.write_date as result_date
                  FROM blog_blog bl, blog_post blp
                  LEFT OUTER JOIN blog_post_blog_tag_rel tg_rel ON (tg_rel.blog_post_id=blp.id)
                  LEFT OUTER JOIN blog_tag tg ON (tg_rel.blog_tag_id=tg.id)
                  WHERE blp.website_published=true and blp.blog_id=bl.id """ % (
                    lang)
                if case_sensitive:
                    sql_query += """and ( blp.content ilike '%%%s%%' or blp.website_meta_title ilike '%%%s%%' or blp.website_meta_keywords ilike '%%%s%%' or tg.name ilike '%%%s%%')""" % (
                        search, search, search, search)
                else:
                    sql_query += """and ( lower(blp.content) ilike '%%%s%%' or lower(blp.website_meta_title) ilike '%%%s%%' or lower(blp.website_meta_keywords) ilike '%%%s%%' or lower(tg.name) ilike '%%%s%%')""" % (
                        search_lower, search_lower, search_lower, search_lower)

        if search_on_comments:
            if sql_query:
                sql_query += ' UNION ALL '

            sql_query += """
                  SELECT DISTINCT 'Blog post comment' as result_type, blp.id as result_id, blp.name as result_name,  'website_blog' as template_module, ml.body as template_source, '' as website_meta_description, '' as website_meta_title, '' as website_meta_keywords, '/blog/'||bl.name||'-'||bl.id|| '/post/' as result_path, '' as result_image, '' as result_lang, '' as result_lang_text, ml.write_date as result_date
                  FROM blog_blog bl, blog_post blp, mail_message ml
                  WHERE blp.website_published=true and ml.website_published=true and blp.blog_id=bl.id
                  and ml.res_id=blp.id and ml.model='blog.post' """
            if case_sensitive:
                sql_query += """and ml.body ilike '%%%s%%'""" % (search)
            else:
                sql_query += """and lower(ml.body) ilike '%%%s%%'""" % (
                    search_lower)

        if search_on_customers:
            if sql_query:
                sql_query += ' UNION ALL '
            if db_use_translations:
                sql_query += """
                  SELECT DISTINCT 'Customer' as result_type, rf.id as result_id, rf.name as result_name,  'website_customer' as template_module, tr.value as template_source, rf.website_meta_description, rf.website_meta_title, rf.website_meta_keywords, '/customers/' as result_path, '' as result_image, '%s' as result_lang, '' as result_lang_text, rf.write_date as result_date
                  FROM ir_translation tr, ir_translation tr2, res_partner rf
                  LEFT OUTER JOIN res_partner_res_partner_category_rel tg_rel ON (tg_rel.partner_id=rf.id)
                  LEFT OUTER JOIN res_partner_category tg ON (tg_rel.category_id=tg.id)
                  WHERE rf.website_published=true
                  and tr.type='model' and (tr.name='res.partner,website_description') --or tr.name='res.partner,website_short_description' )
                  and tr2.name='res.partner.category,name' and tr.res_id=rf.id and tr.lang='%s' """ % (
                    lang, lang)
                if case_sensitive:
                    sql_query += """and ( tr.value ilike '%%%s%%' or tr2.value ilike '%%%s%%')""" % (
                        search, search)
                else:
                    sql_query += """and ( lower(tr.value) ilike '%%%s%%' or lower(tr2.value) ilike '%%%s%%')""" % (
                        search_lower, search_lower)
            else:
                sql_query += """
                  SELECT DISTINCT 'Customer' as result_type, rf.id as result_id, rf.name as result_name,  'website_customer' as template_module, rf.website_description as template_source, rf.website_meta_description, rf.website_meta_title, rf.website_meta_keywords, '/customers/' as result_path, '' as result_image, '%s' as result_lang, '' as result_lang_text, rf.write_date as result_date
                  FROM res_partner rf
                  LEFT OUTER JOIN res_partner_res_partner_category_rel tg_rel ON (tg_rel.partner_id=rf.id)
                  LEFT OUTER JOIN res_partner_category tg ON (tg_rel.category_id=tg.id)
                  WHERE rf.website_published=true """ % (lang)
                if case_sensitive:
                    sql_query += """and ( rf.website_short_description ilike '%%%s%%' or rf.website_description ilike '%%%s%%' or rf.website_meta_keywords ilike '%%%s%%' or
                        rf.website_meta_title ilike '%%%s%%' or rf.website_meta_description  ilike '%%%s%%'  or tg.name ilike '%%%s%%')""" % (
                        search,
                        search,
                        search,
                        search,
                        search,
                        search,
                    )
                else:
                    sql_query += """and ( lower(rf.website_short_description) ilike '%%%s%%' or lower(rf.website_description) ilike '%%%s%%' or lower(rf.website_meta_keywords) ilike '%%%s%%' or
                        lower(rf.website_meta_title) ilike '%%%s%%' or lower(rf.website_meta_description)  ilike '%%%s%%'  or lower(tg.name) ilike '%%%s%%')""" % (
                        search_lower,
                        search_lower,
                        search_lower,
                        search_lower,
                        search_lower,
                        search_lower,
                    )

        if search_on_jobs:
            #Query for job opportunities
            if sql_query:
                sql_query += ' UNION ALL '
            sql_query += """
                  SELECT DISTINCT 'Job' as result_type, jb.id as result_id, jb.name as result_name,  'website_hr_recruitment' as template_module, jb.website_description as template_source, jb.website_meta_description, jb.website_meta_title, jb.website_meta_keywords, '/jobs/detail/' as result_path, '' as result_image, '' as result_lang, '' as result_lang_text, jb.write_date as result_date
                  FROM hr_job jb
                  WHERE jb.website_published=true """
            if case_sensitive:
                sql_query += """and ( jb.website_description ilike '%%%s%%' or jb.website_meta_keywords ilike '%%%s%%' or
                        jb.website_meta_title ilike '%%%s%%' or jb.website_meta_description  ilike '%%%s%%'  or jb.name ilike '%%%s%%')""" % (
                    search,
                    search,
                    search,
                    search,
                    search,
                )
            else:
                sql_query += """and ( lower(jb.website_description) ilike '%%%s%%' or lower(jb.website_meta_keywords) ilike '%%%s%%' or
                        lower(jb.website_meta_title) ilike '%%%s%%' or lower(jb.website_meta_description)  ilike '%%%s%%'  or lower(jb.name) ilike '%%%s%%')""" % (
                    search_lower,
                    search_lower,
                    search_lower,
                    search_lower,
                    search_lower,
                )

        if search_on_products:
            # Query for product info (shop)
            if sql_query:
                sql_query += ' UNION ALL '
            sql_query += """
                  SELECT DISTINCT 'Product' as result_type, pd.id as result_id, pd.name as result_name,  'website_sale' as template_module, pd.website_description as template_source, pd.website_meta_description, pd.website_meta_title, pd.website_meta_keywords, '/shop/product/' as result_path, '' as result_image, '' as result_lang, '' as result_lang_text, pd.write_date as result_date
                  FROM product_template pd
                  WHERE pd.website_published=true """
            if case_sensitive:
                sql_query += """and ( pd.website_description ilike '%%%s%%' or pd.website_meta_keywords ilike '%%%s%%' or
                        pd.website_meta_title ilike '%%%s%%' or pd.website_meta_description  ilike '%%%s%%'  or pd.name ilike '%%%s%%')""" % (
                    search,
                    search,
                    search,
                    search,
                    search,
                )
            else:
                sql_query += """and ( lower(pd.website_description) ilike '%%%s%%' or lower(pd.website_meta_keywords) ilike '%%%s%%' or
                        lower(pd.website_meta_title) ilike '%%%s%%' or lower(pd.website_meta_description)  ilike '%%%s%%'  or lower(pd.name) ilike '%%%s%%')""" % (
                    search_lower,
                    search_lower,
                    search_lower,
                    search_lower,
                    search_lower,
                )

        # Build query count
        if sql_query:
            sql_query_count = """SELECT count(distinct result_type||'-'||result_id  ) FROM ( %s ) as subquery""" % (
                sql_query)

        # Build query for results ordered
        if sql_query:
            limit = self._results_per_page
            offset = (page - 1) * self._results_per_page
            sql_query_ordered = """SELECT distinct result_type, result_id, result_name,  template_module, template_source, website_meta_description, website_meta_title, website_meta_keywords, result_path, result_image, result_lang, result_lang_text, result_date
                                 FROM ( %s ) as subquery
                                 ORDER BY %s
                                 LIMIT %s
                                 OFFSET %s

                                 """ % (sql_query, sql_order_by, limit, offset)

        # Get results count for pager
        if sql_query_count:
            cr.execute(sql_query_count)
            results_count = cr.fetchone()[0] or 0

        url_args = {}
        if search:
            url_args['search'] = search
        if sorting:
            url_args['sorting'] = sorting
        pager = request.website.pager(url=url,
                                      total=results_count,
                                      page=page,
                                      step=self._results_per_page,
                                      scope=self._results_per_page,
                                      url_args=url_args)

        # Get results and prepare info to render results page
        user = request.registry['res.users'].browse(request.cr,
                                                    request.uid,
                                                    request.uid,
                                                    context=request.context)
        values = {
            'user':
            user,
            'is_public_user':
            user.id == request.website.user_id.id,
            'header':
            post.get('header', dict()),
            'searches':
            post.get('searches', dict()),
            'results_per_page':
            self._results_per_page,
            'last_result_showing':
            min(results_count, page * self._results_per_page),
            'results_count':
            results_count,
            'results': [],
            'pager':
            pager,
            'search_on_pages':
            search_on_pages,
            'search_on_blogposts':
            self._search_on_blogposts,
            'search_on_comments':
            self._search_on_comments,
            'search_on_customers':
            self._search_on_customers,
            'search_on_jobs':
            self._search_on_jobs,
            'search_on_products':
            self._search_on_products,
            'case_sensitive':
            self._case_sensitive,
            'sorting':
            sorting,
            'search':
            search,
        }

        if sql_query_ordered:
            cr.execute(sql_query_ordered)
            for result in cr.fetchall():
                result_id = result[0] + '-' + str(result[1])
                result_data = {
                    'type':
                    result[0],
                    'type_txt':
                    _(result[0]),
                    'id':
                    result[1],
                    'name':
                    result[2],
                    'template_name':
                    result[3] + '.' + result[2],
                    'template_source':
                    result[4],
                    'website_meta_description':
                    result[5],
                    'website_meta_title':
                    result[6],
                    'website_meta_keywords':
                    result[7],
                    'url':
                    result[8] + result[2],
                    'image':
                    result[9],  # seleccionar una imagen por tipo
                    'lang':
                    result[10],
                    'lang_text':
                    result[11],
                    'date':
                    result[12][8:10] + "/" + result[12][5:7] + "/" +
                    result[12][0:4],
                    'ocurrences':
                    0,
                    'object':
                    None
                }
                # Prepare result content near searched keyword
                if result_data['type'] == 'Page':
                    # Render page html
                    try:
                        html = request.registry['ir.ui.view'].render(
                            cr,
                            uid,
                            result_data['template_name'],
                            context=context,
                            **post)
                    except Exception:
                        html = '<main>' + _(
                            'Unable to get text page') + '</main>'
                    start = html.find("<main>")
                    end = html.find("</main>") + 7

                elif result_data['type'] == 'Blog post':
                    # Render blog post html
                    try:
                        url_array = result_data['url'].split('/')
                        url_array[2] = slugify(url_array[2])
                        url_array[4] = slugify(url_array[4])
                        result_data['url'] = '/'.join(url_array)
                        result_data['url'] = result_data['url'] + "-" + str(
                            result_data["id"])
                        blog_post = request.registry['blog.post'].browse(
                            cr, uid, int(result_data['id']), context=context)
                        result_data['object'] = blog_post
                        html = request.registry['ir.ui.view'].render(
                            cr,
                            uid,
                            "website_search.blog_post_content",
                            {'blog_post': blog_post},
                            context=context)
                    except Exception:
                        html = '<main>' + _(
                            'Unable to get blog post text') + '</main>'

                    start = 0
                    end = len(html)

                elif result_data['type'] == 'Blog post comment':
                    # Render blog post html
                    try:
                        url_array = result_data['url'].split('/')
                        url_array[2] = slugify(url_array[2])
                        url_array[4] = slugify(url_array[4])
                        result_data['url'] = '/'.join(url_array)
                        result_data['url'] = result_data['url'] + "-" + str(
                            result_data["id"])
                        html = result_data['template_source']
                    except Exception:
                        html = '<main>' + _(
                            'Unable to get blog post comment text') + '</main>'

                    start = 0
                    end = len(html)

                elif result_data['type'] == 'Customer':
                    # Render customer info html
                    try:
                        url_array = result_data['url'].split('/')
                        url_array[2] = slugify(url_array[2])
                        result_data['url'] = '/'.join(url_array)
                        result_data['url'] = result_data['url'] + "-" + str(
                            result_data["id"])
                        customer = request.registry['res.partner'].browse(
                            cr, uid, int(result_data['id']), context=context)
                        result_data['object'] = customer
                        html = request.registry['ir.ui.view'].render(
                            cr,
                            uid,
                            "website_search.customer_detail",
                            {'partner': customer},
                            context=context)
                    except Exception:
                        html = '<main>' + _(
                            'Unable to get customer text') + '</main>'

                    start = 0
                    end = len(html)

                elif result_data['type'] == 'Job':
                    # Render job info html
                    try:
                        url_array = result_data['url'].split('/')
                        url_array[3] = slugify(url_array[3])
                        result_data['url'] = '/'.join(url_array)
                        result_data['url'] = result_data['url'] + "-" + str(
                            result_data["id"])
                        job = request.registry['hr.job'].browse(
                            cr, uid, int(result_data['id']), context=context)
                        result_data['object'] = job
                        html = request.registry['ir.ui.view'].render(
                            cr,
                            uid,
                            "website_search.job_detail", {'job': job},
                            context=context)
                    except Exception:
                        html = '<main>' + _(
                            'Unable to get job text') + '</main>'

                    start = 0
                    end = len(html)

                elif result_data['type'] == 'Product':
                    # Render product info html
                    try:
                        url_array = result_data['url'].split('/')
                        url_array[3] = slugify(url_array[3])
                        result_data['url'] = '/'.join(url_array)
                        result_data['url'] = result_data['url'] + "-" + str(
                            result_data["id"])
                        product = request.registry['product.template'].browse(
                            cr, uid, int(result_data['id']), context=context)
                        result_data['object'] = product
                        html = request.registry['ir.ui.view'].render(
                            cr,
                            uid,
                            "website_search.product_detail",
                            {'product': product},
                            context=context)
                    except Exception:
                        html = '<main>' + _(
                            'Unable to get product text') + '</main>'

                    start = 0
                    end = len(html)

                # Keep key part of html page
                html = html[start:end]

                # Convert to text, eliminate all tags and #, \n, [, ] symbols, and text between []
                if html2text:
                    html = html2text(html.decode('utf-8')).encode('utf-8')
                    html = self._removeSymbols(html.decode('utf-8'), '[',
                                               ']').encode('utf-8')
                    html = self._removeSymbols(html.decode('utf-8'),
                                               '\n').encode('utf-8')
                    html = self._removeSymbols(html.decode('utf-8'),
                                               '#').encode('utf-8')

                # If not case sensitive search, apply lower function to search term and html
                if case_sensitive:
                    search_term = search
                    search_html = html
                else:
                    search_term = search_lower
                    search_html = html.lower()

                # Trim content to a maximum total characters to show in description with nearest text
                if len(search_html) > self._max_text_content_len:
                    index = search_html.find(str(search_term), 0)
                    start = max(0, index - self._text_segment_back)
                    end = min(len(search_html),
                              index + self._text_segment_forward)
                    html_trim = html[start:end]
                    search_html_trim = search_html[start:end]
                    if start > 0:
                        html_trim = "..." + html_trim
                        search_html_trim = "..." + search_html_trim
                    if end < len(search_html):
                        html_trim = html_trim + "..."
                        search_html_trim = search_html_trim + "..."
                    search_html = search_html_trim
                    html = html_trim

                # Find keyword in description text to force style to background yellow and bold text
                index = search_html.find(str(search_term), 0)
                index_start = 0
                str_styled_search = "<span style='font-weight: bold; font-size: 100%%; background-color: yellow;'>%s</span>" % str(
                    search)
                html_styled = ''
                ocurrences = 0
                while index >= 0:
                    ocurrences += 1
                    html_styled += html[index_start:index]
                    html_styled += str_styled_search
                    index_start = index + len(str(search_term))
                    index = search_html.find(str(search_term), index_start)
                html_styled += html[index_start:]

                result_data['content'] = "<p>" + html_styled + "</p>"
                result_data['ocurrences'] = ocurrences
                values['results'].append(result_data)

        # Render results
        return request.website.render("website_search.search_results", values)
Beispiel #33
0
 def test_numbers(self):
     self.assertEqual("article-1", slugify(u"Article 1"))
Beispiel #34
0
 def test_str_to_unicode(self):
     self.assertEqual(
         "espana",
         slugify("España")
     )
Beispiel #35
0
 def test_numbers(self):
     self.assertEqual(
         "article-1",
         slugify(u"Article 1")
     )
Beispiel #36
0
 def _compute_name_slug(self):
     self.name_slug = slugify(self.name)
Beispiel #37
0
 def test_all(self):
     self.assertEqual(
         "do-you-know-martine-a-la-plage",
         slugify(u"Do YOU know 'Martine à la plage' ?")
     )
Beispiel #38
0
 def test_spaces(self):
     self.assertEqual(
         "spaces",
         slugify(u"   spaces   ")
     )
Beispiel #39
0
    def new_page(self, name, template='website.default_page', ispage=True):
        res = super(website, self).new_page(name, template, ispage)
        if ispage:
            template_module, dummy = template.split('.')
            website_id = self._context.get('website_id')

            # completely arbitrary max_length
            page_name = slugify(name, max_length=50)
            page_xmlid = "%s.%s" % (template_module, page_name)

            # find a free xmlid
            inc = 0
            domain_static = [('website_id', '=', False),
                             ('website_id', '=', website_id)]
            while self.env['ir.ui.view'].with_context(
                    active_test=False).sudo().search([('key', '=',
                                                       page_xmlid), '|'] +
                                                     domain_static):
                inc += 1
                page_xmlid = "%s.%s" % (template_module, page_name +
                                        ("-%s" % inc if inc else ""))
            page_name += (inc and "-%s" % inc or "")

            # new page
            template_record = self.env.ref(template)
            key = '%s.%s' % (template_module, page_name)
            page = template_record.copy({'website_id': website_id, 'key': key})
            page.with_context(lang=None).write({
                'arch':
                page.arch.replace(template, page_xmlid),
                'name':
                page_name,
                'page':
                ispage,
            })
            arch = "<?xml version='1.0'?><t t-name='website." + str(
                page_name) + "'><t t-call='website.layout'> \
                    <div id='wrap' class='oe_structure oe_empty'>"

            arch = arch + '<t t-if="not website.is_breadcum">'

            arch =arch+'<t t-if="not website.bread_cum_image">'\
                '<nav class="is-breadcrumb shop-breadcrumb" role="navigation" aria-label="breadcrumbs">'\
                      '<div class="container">'\
                        '<h1><span>'+str(page_name)+'</span></h1>'\
                        '<ul class="breadcrumb">'\
                            '<li><a href="/page/homepage">Home</a></li>'\
                            '<li class="active"><span>'+str(page_name)+'</span></li>'\
                        '</ul>'\
                      '</div>'\
                '</nav>'\
                '</t>'
            arch=arch+'<t t-if="website.bread_cum_image">'\
                '<t t-set="bread_cum" t-value="website.image_url(website,'+repr('bread_cum_image')+')"/>'\
                '<nav class="is-breadcrumb shop-breadcrumb" role="navigation" aria-label="breadcrumbs" t-attf-style="background-image:url(#{bread_cum}#)">'\
                    '<div class="container">'\
                        '<h1><span>'+str(page_name)+'</span></h1>'\
                        '<ul class="breadcrumb">'\
                            '<li><a href="/page/homepage">Home</a></li>'\
                            '<li class="active"><span>'+str(page_name)+'</span></li>'\
                        '</ul>'\
                      '</div>'\
                '</nav>'\
            '</t>'
            arch = arch + '</t>'
            arch = arch + '</div><div class="oe_structure"/></t></t>'
            page.with_context(lang=None).write({
                'arch': arch,
            })
            return page_xmlid
        return res
Beispiel #40
0
 def test_unicode(self):
     self.assertEqual("heterogeneite", slugify(u"hétérogénéité"))
Beispiel #41
0
 def test_unicode(self):
     self.assertEqual(
         "heterogeneite",
         slugify(u"hétérogénéité")
     )
Beispiel #42
0
 def test_caps(self):
     self.assertEqual("camelcase", slugify(u"CamelCase"))
Beispiel #43
0
 def test_underscore(self):
     self.assertEqual(
         "one-two",
         slugify(u"one_two")
     )
Beispiel #44
0
 def test_str_to_unicode(self):
     self.assertEqual("espana", slugify("España"))
Beispiel #45
0
 def test_caps(self):
     self.assertEqual(
         "camelcase",
         slugify(u"CamelCase")
     )
Beispiel #46
0
 def test_all(self):
     self.assertEqual("do-you-know-martine-a-la-plage",
                      slugify(u"Do YOU know 'Martine à la plage' ?"))
Beispiel #47
0
 def test_special_chars(self):
     self.assertEqual(
         "o-d-o-o",
         slugify(u"o!#d{|\o/@~o&%^?")
     )