recherche: première ébauche
[auf_framonde.git] / project / aldryn_search / helpers.py
CommitLineData
5f23ec55
PH
1# -*- coding: utf-8 -*-
2from django.contrib.auth.models import AnonymousUser
3from django.template import RequestContext
4from django.test import RequestFactory
5from django.utils.text import smart_split
6try:
7 from django.utils.encoding import force_unicode
8except ImportError:
9 from django.utils.encoding import force_text as force_unicode
10
11from .conf import settings
12from .utils import get_field_value, strip_tags
13
14
15def get_cleaned_bits(data):
16 decoded = force_unicode(data)
17 stripped = strip_tags(decoded)
18 return smart_split(stripped)
19
20
21def get_plugin_index_data(base_plugin, request):
22 text_bits = []
23
24 instance, plugin_type = base_plugin.get_plugin_instance()
25
26 if instance is None:
27 # this is an empty plugin
28 return text_bits
29
30 search_fields = getattr(instance, 'search_fields', [])
31
32 if hasattr(instance, 'search_fulltext'):
33 # check if the plugin instance has search enabled
34 search_contents = instance.search_fulltext
35 elif hasattr(base_plugin, 'search_fulltext'):
36 # now check in the base plugin instance (CMSPlugin)
37 search_contents = base_plugin.search_fulltext
38 elif hasattr(plugin_type, 'search_fulltext'):
39 # last check in the plugin class (CMSPluginBase)
40 search_contents = plugin_type.search_fulltext
41 else:
42 # disabled if there's search fields defined,
43 # otherwise it's enabled.
44 search_contents = not bool(search_fields)
45
46 if search_contents:
47 plugin_contents = instance.render_plugin(
48 context=RequestContext(request))
49
50 if plugin_contents:
51 text_bits = get_cleaned_bits(plugin_contents)
52 else:
53 values = (get_field_value(instance, field) for field in search_fields)
54
55 for value in values:
56 cleaned_bits = get_cleaned_bits(value or '')
57 text_bits.extend(cleaned_bits)
58 return text_bits
59
60
61def get_request(language=None):
62 """
63 Returns a Request instance populated with cms specific attributes.
64 """
65 request_factory = RequestFactory(HTTP_HOST=settings.ALLOWED_HOSTS[0])
66 request = request_factory.get("/")
67 request.session = {}
68 request.LANGUAGE_CODE = language or settings.LANGUAGE_CODE
69 # Needed for plugin rendering.
70 request.current_page = None
71 request.user = AnonymousUser()
72 return request