示例#1
0
    def tabs(self):
        if self._tabs is None:

            found_current = False

            overview_css_class = ''

            if (ICommunity.providedBy(self.request.context) and
                    self.request.view_name in ['', 'view.html']):
                overview_css_class = 'curr'
                found_current = True

            tabs = [
                {'url': resource_url(self.context, self.request, 'view.html'),
                 'css_class': overview_css_class,
                 'name': 'OVERVIEW'}
                ]

            for toolinfo in get_listitems(IToolFactory):
                toolfactory = toolinfo['component']
                if toolfactory.is_present(self.context, self.request):
                    info = {}
                    info['url'] = toolfactory.tab_url(self.context,
                                                      self.request)
                    info['css_class'] = ''
                    if not found_current:
                        if toolfactory.is_current(self.context, self.request):
                            info['css_class'] = 'curr'
                            found_current = True
                    info['name'] = toolinfo['title'].upper()
                    tabs.append(info)

            self._tabs = tabs

        return self._tabs
示例#2
0
 def __call__(self):
     """ What tools can go in a community?
     """
     tools = get_listitems(IToolFactory)
     return [
         tool for tool in tools if tool['name'] not in self.exclude_tools
     ]
示例#3
0
文件: adapters.py 项目: claytron/karl
    def tabs(self):
        if self._tabs is None:

            found_current = False

            overview_css_class = ''

            if ( ICommunity.providedBy(self.request.context) and
                 self.request.view_name in ['','view.html','ux2_view.html'] ):
                overview_css_class = 'curr'
                found_current = True

            tabs = [
                {'url':resource_url(self.context, self.request, 'view.html'),
                 'css_class':overview_css_class,
                 'name':'OVERVIEW'}
                ]

            for toolinfo in get_listitems(IToolFactory):
                toolfactory = toolinfo['component']
                if toolfactory.is_present(self.context, self.request):
                    info = {}
                    info['url'] = toolfactory.tab_url(self.context,
                                                      self.request)
                    info['css_class'] = ''
                    if not found_current:
                        if toolfactory.is_current(self.context, self.request):
                            info['css_class'] = 'curr'
                            found_current = True
                    info['name'] = toolinfo['title'].upper()
                    tabs.append(info)

            self._tabs = tabs

        return self._tabs
示例#4
0
文件: adapters.py 项目: Falmarri/karl
    def tabs(self):
        if self._tabs is None:

            found_current = False

            overview_css_class = ""

            if ICommunity.providedBy(self.request.context) and self.request.view_name in ["", "view.html"]:
                overview_css_class = "curr"
                found_current = True

            tabs = [
                {
                    "url": resource_url(self.context, self.request, "view.html"),
                    "css_class": overview_css_class,
                    "name": "OVERVIEW",
                }
            ]

            for toolinfo in get_listitems(IToolFactory):
                toolfactory = toolinfo["component"]
                if toolfactory.is_present(self.context, self.request):
                    info = {}
                    info["url"] = toolfactory.tab_url(self.context, self.request)
                    info["css_class"] = ""
                    if not found_current:
                        if toolfactory.is_current(self.context, self.request):
                            info["css_class"] = "curr"
                            found_current = True
                    info["name"] = toolinfo["title"].upper()
                    tabs.append(info)

            self._tabs = tabs

        return self._tabs
示例#5
0
 def livesearch_options(self):
     if self._livesearch_options is None:
         self._livesearch_options = [
             item for item in get_listitems(IGroupSearchFactory)
             if item['component'].livesearch
         ]
     return self._livesearch_options
示例#6
0
文件: search.py 项目: boothead/karl
def jquery_livesearch_view(context, request):
    # Prefix search is with a wildcard at the end
    searchterm = request.params.get("val", None)

    if searchterm is None:
        # The request forgot to send the key we use to do a search, so
        # make a friendly error message.  Important for the unit test.
        msg = "Client failed to send a 'val' parameter as the searchterm"
        return HTTPBadRequest(msg)
    else:
        searchterm = searchterm + "*"

    records = LivesearchResults()
    principals = effective_principals(request)

    site_path = model_path(context)

    records.set_header("", pre='<div class="header"></div>')
    records.append_to(
        rowclass="showall",
        title="Show All",
        href=model_url(context, request, "searchresults.html", query={"body": searchterm}),
    )

    for listitem in get_listitems(IGroupSearchFactory):
        utility = listitem["component"]

        factory = utility(context, request, searchterm)

        if factory is None:
            continue

        try:
            num, docids, resolver = factory()
        except ParseError:
            continue

        groupname = listitem["title"]

        records.set_header(groupname, pre='<div class="header">%s</div>' % (groupname,))

        results = filter(None, map(resolver, docids))

        qs = {"body": searchterm, "kind": groupname}
        sr_href = model_url(context, request, "searchresults.html", query=qs)

        for result in results:
            records.append_to(
                rowclass="result", title=getattr(result, "title", "<No Title>"), href=model_url(result, request)
            )

        if results:
            records.append_to(rowclass="showall", title="Show All", href=sr_href)
        else:
            records.append_to(rowclass="noresult", title="No Result", href=sr_href)

    result = JSONEncoder().encode(list(records))
    return Response(result, content_type="application/x-json")
示例#7
0
 def test_functional_with_get_listitems(self):
     from zope.interface import Interface
     from zope.component import getGlobalSiteManager
     from repoze.lemonade.listitem import get_listitems
     class IFoo(Interface):
         pass
     def util():
         """"""
     self._callFUT(IFoo, util, 'foo1', 'title1', 'desc1', 20)
     self._callFUT(IFoo, util, 'foo2', 'title2', 'desc2', 10)
     gsm = getGlobalSiteManager()
     result = get_listitems(IFoo)
     self.assertEqual(len(result), 2)
     self.assertEqual(result[0]['name'], 'foo2')
     self.assertEqual(result[1]['name'], 'foo1')
示例#8
0
    def test_functional_with_get_listitems(self):
        from zope.interface import Interface
        from zope.component import getGlobalSiteManager
        from repoze.lemonade.listitem import get_listitems

        class IFoo(Interface):
            pass

        def util():
            """"""

        self._callFUT(IFoo, util, 'foo1', 'title1', 'desc1', 20)
        self._callFUT(IFoo, util, 'foo2', 'title2', 'desc2', 10)
        gsm = getGlobalSiteManager()
        result = get_listitems(IFoo)
        self.assertEqual(len(result), 2)
        self.assertEqual(result[0]['name'], 'foo2')
        self.assertEqual(result[1]['name'], 'foo1')
示例#9
0
文件: search.py 项目: cguardia/karl
def searchresults_view(context, request):
    request.unicode_errors = 'ignore'
    page_title = 'Search Results'
    api = TemplateAPI(context, request, page_title)
    if ICommunity.providedBy(context):
        layout = api.community_layout
        community = context.title
    else:
        layout = api.generic_layout
        community = None

    batch = None
    terms = ()
    error = None
    params = request.params.copy()
    if 'batch_start' in params:
        del params['batch_start']
    if 'batch_size' in params:
        del params['batch_size']

    kind_knob = []
    selected_kind = params.get('kind')
    for o in get_listitems(IGroupSearchFactory):
        component = o['component']
        if not component.advanced_search:
            continue
        kind = o['name']
        query = params.copy()
        query['kind'] = kind
        kind_knob.append({
            'name': kind,
            'title': o['title'],
            'icon': component.icon,
            'url': model_url(context, request, request.view_name,
                             query=query),
            'selected': kind == selected_kind,
        })
    query = params.copy()
    if 'kind' in query:
        del query['kind']
    kind_knob.insert(0, {
        'name': 'all_content',
        'title': 'All Content',
        'description': 'All Content',
        'icon': None,
        'url': model_url(context, request, request.view_name, query=query),
        'selected': not selected_kind,
    })

    since_knob = []
    selected_since = params.get('since')
    for id in since_order:
        option = since_options[id].copy()
        query = params.copy()
        if id is not None:
            query['since'] = id
        elif 'since' in query:
            del query['since']
        option['url'] = model_url(context, request, request.view_name,
                                  query=query)
        option['selected'] = id == selected_since
        since_knob.append(option)

    start_time = time.time()
    try:
        batch, terms = get_batch(context, request)
    except ParseError, e:
        error = 'Error: %s' % e
示例#10
0
文件: search.py 项目: iotest3/new
def jquery_livesearch_view(context, request):
    request.unicode_errors = 'ignore'
    try:
        searchterm = request.params.get('val', None)
    except UnicodeDecodeError:
        # Probably windows client didn't set request encoding. Try again.
        request.charset = 'ISO-8859-1'
        searchterm = request.params.get('val', None)

    if searchterm is None:
        # The request forgot to send the key we use to do a search, so
        # make a friendly error message.  Important for the unit test.
        msg = "Client failed to send a 'val' parameter as the searchterm"
        return HTTPBadRequest(msg)

    if '__profile__' in searchterm:
        enable_profile = True
        searchterm = searchterm.replace('__profile__', '')
    else:
        enable_profile = False

    weighted_term = WeightedQuery(searchterm)

    # maybe do some * checking to verify that we don't have a
    # prefix search < 3 chars

    records = []

    # we return back 5 results for each type of search
    results_per_type = 5

    kind = request.params.get('kind', '')
    if not kind:
        listitems = [
            item for item in get_listitems(IGroupSearchFactory) if
            item['component'].livesearch and item['component'].livesearch_all
        ]
    else:
        search_utility = queryUtility(IGroupSearchFactory, kind)
        if search_utility is None:
            msg = "The LiveSearch kind %s is not known" % kind
            return HTTPBadRequest(msg)
        else:
            # simulate a list item for the loop below
            listitems = (dict(component=search_utility), )
            # we'll just have on type of results, so we return back 20 results
            results_per_type = 20

    if enable_profile:
        import cProfile
        import pstats
        import StringIO
        pr = cProfile.Profile()
        pr.enable()

    start_time = time.time()
    for listitem in listitems:
        utility = listitem['component']
        factory = utility(context, request, weighted_term)
        if factory is None:
            continue
        factory.limit = results_per_type

        try:
            num, docids, resolver = factory()
        except ParseError:
            continue

        for result in (resolver(x) for x in docids):
            if result is None:
                continue
            record = queryMultiAdapter((result, request), ILiveSearchEntry)
            assert record is not None, ("Unexpected livesearch result: " +
                                        result.__class__.__name__)
            if kind == 'intranet':
                record['type'] = 'Intranet'
            records.append(record)
    end_time = time.time()
    log.debug('livesearch: %0.3fs for "%s", kind=%s', end_time - start_time,
              searchterm, kind)

    if enable_profile:
        pr.disable()
        s = StringIO.StringIO()
        ps = pstats.Stats(pr, stream=s).sort_stats('cumtime')
        ps.print_stats(100)  # Limit to 100 lines
        log.warning('livesearch profile: %0.3fs for "%s", kind=%s\n%s',
                    end_time - start_time, searchterm, kind, s.getvalue())

    return records
示例#11
0
文件: search.py 项目: iotest3/new
def _searchresults_view(context, request, page_title, calendar_search,
                        show_search_knobs):
    api = TemplateAPI(context, request, page_title)

    # The layout is decided independently of whether we are a
    # calendar search or not. What is taken in consideration: if we are
    # in a community. The /offices section is considered a non-community
    # and will use the wide layout.
    if ICommunity.providedBy(context):
        if calendar_search:
            # We are either in /communities, or in /offices. In the first case:
            # we use the community layout. For offices: we need the wide layout
            # with the generic layout.
            context_path = resource_path(context)
            wide = context_path.startswith('/offices')
            if wide:
                layout = api.generic_layout
            else:
                layout = api.community_layout
        else:
            layout = api.community_layout
        community = context.title
    else:
        layout = api.generic_layout
        community = None

    request.unicode_errors = 'ignore'
    batch = None
    terms = ()
    error = None
    params = request.params.copy()
    if 'batch_start' in params:
        del params['batch_start']
    if 'batch_size' in params:
        del params['batch_size']

    kind_knob = []
    selected_kind = params.get('kind')

    scope_path = request.params.get('scopePath', '')

    # We show the scope knob, but in a limited way.
    # We only have a path here, so we show that path
    # and a single option to go back to All KARL.
    # If we are on all karl already, this knob group
    # will not show at all, defaulting to KARL's legacy
    # behaviour.
    scope_label = request.params.get('scopeLabel', '')
    if scope_path:
        scope_knob = []
        scope_knob.append({
            'name': scope_label,
            'title': scope_label,
            'description': scope_label,
            'icon': None,
            'url': None,
            'selected': True,
        })
        query = params.copy()
        query.update(scopePath='', scopeLabel='All KARL')
        scope_knob.append({
            'name':
            'All KARL',
            'title':
            'All KARL',
            'description':
            'All KARL',
            'icon':
            None,
            'url':
            resource_url(find_root(context),
                         request,
                         request.view_name,
                         query=query),
            'selected':
            False,
        })
    else:
        # The knob will not show at all
        scope_knob = None

    # There is a mapping needed between the livesearch
    # and the advanced search "kind" identifiers. This artifact is
    # a bit of annoyance but it's the easiest to do this
    # transformation here. Previously this was done from js.
    # Currently, if you click on livesearch results to
    # get into the advanced search, the livesearch kinds
    # will be submitted: which is why we convert from here.
    selected_kind = {
        'pages': 'wiki',
        'posts': 'blog',
    }.get(selected_kind, selected_kind)

    # In case we have a calendar search:
    # we will use events only as the content type.
    if calendar_search and selected_kind is None:
        # This means: filter events only in the result.
        selected_kind = 'events'

    for o in get_listitems(IGroupSearchFactory):
        component = o['component']
        if not component.advanced_search:
            continue
        kind = o['name']
        query = params.copy()
        query['kind'] = kind
        kind_knob.append({
            'name':
            kind,
            'title':
            o['title'],
            'icon':
            component.icon,
            'url':
            resource_url(context, request, request.view_name, query=query),
            'selected':
            kind == selected_kind,
        })
    query = params.copy()
    if 'kind' in query:
        del query['kind']
    kind_knob.insert(
        0, {
            'name': 'all_content',
            'title': 'All Content',
            'description': 'All Content',
            'icon': None,
            'url': resource_url(
                context, request, request.view_name, query=query),
            'selected': not selected_kind,
        })

    since_knob = []
    selected_since = params.get('since')
    for id in since_order:
        option = since_options[id].copy()
        query = params.copy()
        if id is not None:
            query['since'] = id
        elif 'since' in query:
            del query['since']
        option['url'] = resource_url(context,
                                     request,
                                     request.view_name,
                                     query=query)
        option['selected'] = id == selected_since
        since_knob.append(option)

    sort_knob = []
    selected_sort = params.get('sort')
    for id in sort_order:
        option = sort_options[id].copy()
        query = params.copy()
        if id is not None:
            query['sort'] = id
        elif 'sort' in query:
            del query['sort']
        option['url'] = resource_url(context,
                                     request,
                                     request.view_name,
                                     query=query)
        option['selected'] = id == selected_sort
        sort_knob.append(option)

    start_time = time.time()
    try:
        batch, terms = get_batch(context, request)
    except ParseError, e:
        error = 'Error: %s' % e
示例#12
0
 def __call__(self):
     from karl.models.interfaces import IToolFactory
     from repoze.lemonade.listitem import get_listitems
     return get_listitems(IToolFactory)
示例#13
0
 def __call__(self):
     from karl.models.interfaces import IToolFactory
     from repoze.lemonade.listitem import get_listitems
     return get_listitems(IToolFactory)
示例#14
0
class AddIntranetFormController(object):
    def __init__(self, context, request):
        self.context = context
        self.request = request
        page_title = getattr(self, 'page_title', 'Add Intranet')
        self.api = TemplateAPI(context, request, page_title)

    def form_fields(self):
        fields = [('title', title_field),
                  ('name', name_field),
                  ('address', address_field),
                  ('city', city_field),
                  ('state', state_field),
                  ('country', country_field),
                  ('zipcode', zipcode_field),
                  ('telephone', telephone_field),
                  ('navigation', navigation_field),
                  ('middle_portlets', middle_portlets_field),
                  ('right_portlets', right_portlets_field),
                  ]
        return fields

    def form_widgets(self, fields):
        widgets = {'navigation': formish.TextArea(rows=10, cols=80),
                   'middle_portlets': formish.TextArea(rows=10, cols=80),
                   'right_portlets': formish.TextArea(rows=10, cols=80),
                   }
        return widgets

    def __call__(self):
        api = self.api
        layout_provider = get_layout_provider(self.context, self.request)
        layout = layout_provider('community')
        return {
            'api': api,
            'layout': layout,
            'actions': []}

    def handle_cancel(self):
        return HTTPFound(location=resource_url(self.context, self.request))

    def handle_submit(self, converted):
        request = self.request
        context = self.context

        intranets_parent = find_community(context)
        name = converted.get('name')
        if name:
            name_from = 'name'
        else:
            name = converted['title']
            name_from = 'title'
        try:
            name = make_name(intranets_parent, name)
        except ValueError, why:
            msg = why[0]
            raise ValidationError(**{name_from: msg})

        userid = authenticated_userid(request)
        community = create_content(ICommunity,
                                   converted['title'],
                                   u'',
                                   u'',
                                   userid,
                                   )
        if not converted['navigation']:
            converted['navigation'] = sample_navigation
        if converted['middle_portlets']:
            middle_portlets = split_lines(converted['middle_portlets'])
        else:
            middle_portlets = sample_middle_portlets
        if converted['right_portlets']:
            right_portlets = split_lines(converted['right_portlets'])
        else:
            right_portlets = sample_right_portlets

        # Jam on the other data
        community.address = converted['address']
        community.city = converted['city']
        community.state = converted['state']
        community.country = converted['country']
        community.zipcode = converted['zipcode']
        community.telephone = converted['telephone']
        community.navigation = clean_html(converted['navigation'])
        community.middle_portlets = middle_portlets
        community.right_portlets = right_portlets

        # required to use moderators_group_name and
        # members_group_name
        community.__name__ = name

        for toolinfo in get_listitems(IToolFactory):
            if toolinfo['name'] in ('forums', 'files'):
                toolinfo['component'].add(community, request)

        # Jam on the second interface IIntranet so we can attach
        # any other views to it.  Ditto for IIntranetRootFolder.
        alsoProvides(community, IIntranet)
        files = community.get('files', False)
        if files:
            alsoProvides(files, IIntranetRootFolder)

        users = find_users(context)
        moderators_group_name = community.moderators_group_name
        members_group_name = community.members_group_name

        for group_name in moderators_group_name, members_group_name:
            users.add_group(userid, group_name)

        # This subcommunity (intranet) gets added directly in the
        # parent, not in a tool subfolder.  E.g. store it in /osi.
        intranets_parent = find_community(context)
        intranets_parent[name] = community

        # Adding a community should take you to the Add Existing
        # User screen, so the moderator can include some users.
        location = resource_url(context, request)
        location = location + "?status_message=Intranet%20added"

        return HTTPFound(location=location)
示例#15
0
 def _callFUT(self, iface):
     from repoze.lemonade.listitem import get_listitems
     return get_listitems(iface)
示例#16
0
文件: adapters.py 项目: boothead/karl
 def __call__(self):
     """ What tools can go in a community?
     """
     tools = get_listitems(IToolFactory)
     return [tool for tool in tools if tool['name'] not in
             self.exclude_tools]
示例#17
0
文件: search.py 项目: claytron/karl
def jquery_livesearch_view(context, request):
    request.unicode_errors = 'ignore'
    try:
        searchterm = request.params.get('val', None)
    except UnicodeDecodeError:
        # Probably windows client didn't set request encoding. Try again.
        request.charset = 'ISO-8859-1'
        searchterm = request.params.get('val', None)

    if searchterm is None:
        # The request forgot to send the key we use to do a search, so
        # make a friendly error message.  Important for the unit test.
        msg = "Client failed to send a 'val' parameter as the searchterm"
        return HTTPBadRequest(msg)

    # maybe do some * checking to verify that we don't have a
    # prefix search < 3 chars

    records = []

    # we return back 5 results for each type of search
    results_per_type = 5

    kind = request.params.get('kind', None)
    if kind is None:
        listitems = [item for item in get_listitems(IGroupSearchFactory) if
                     item['component'].livesearch]
    else:
        search_utility = queryUtility(IGroupSearchFactory, kind)
        if search_utility is None:
            msg = "The LiveSearch kind %s is not known" % kind
            return HTTPBadRequest(msg)
        else:
            # simulate a list item for the loop below
            listitems = (dict(component=search_utility),)
            # we'll just have on type of results, so we return back 20 results
            results_per_type = 20
    start_time = time.time()
    for listitem in listitems:
        utility = listitem['component']
        factory = utility(context, request, searchterm)
        if factory is None:
            continue
        factory.limit = results_per_type

        try:
            num, docids, resolver = factory()
        except ParseError:
            continue

        for result in (resolver(x) for x in docids):
            if result is None:
                continue
            record = queryMultiAdapter((result, request), ILiveSearchEntry)
            assert record is not None, (
                "Unexpected livesearch result: " + result.__class__.__name__)
            records.append(record)
    end_time = time.time()
    log.debug('livesearch: %0.3fs for "%s", kind=%s',
        end_time - start_time, searchterm, kind)

    result = JSONEncoder().encode(records)
    return Response(result, content_type="application/json")
示例#18
0
def jquery_livesearch_view(context, request):
    # Prefix search is with a wildcard at the end
    try:
        searchterm = request.params.get('val', None)
    except UnicodeDecodeError:
        # Probably windows client didn't set request encoding. Try again.
        request.charset = 'ISO-8859-1'
        searchterm = request.params.get('val', None)

    if searchterm is None:
        # The request forgot to send the key we use to do a search, so
        # make a friendly error message.  Important for the unit test.
        msg = "Client failed to send a 'val' parameter as the searchterm"
        return HTTPBadRequest(msg)
    else:
        searchterm = searchterm + '*'

    records = LivesearchResults()

    records.set_header('',
        pre = '<div class="header"></div>',
        )
    records.append_to(
        rowclass = 'showall',
        title = 'Show All',
        href = model_url(context, request, 'searchresults.html',
                    query = {'body':searchterm},
                    ),
            )

    for listitem in get_listitems(IGroupSearchFactory):
        utility = listitem['component']

        factory = utility(context, request, searchterm)

        if factory is None:
            continue

        try:
            num, docids, resolver = factory()
        except ParseError:
            continue

        groupname = listitem['title']

        records.set_header(groupname,
            pre = '<div class="header">%s</div>' % (groupname, ),
            )

        results = filter(None, map(resolver, docids))

        qs = {'body':searchterm, 'kind':groupname}
        sr_href = model_url(context, request, 'searchresults.html', query=qs)

        for result in results:
            records.append_to(
                rowclass = 'result',
                title = getattr(result, 'title', '<No Title>'),
                href = model_url(result, request),
                )

        if results:
            records.append_to(
                rowclass = 'showall',
                title = 'Show All',
                href = sr_href,
                )
        else:
            records.append_to(
                rowclass = 'noresult',
                title = 'No Result',
                href = sr_href,
                )

    result = JSONEncoder().encode(list(records))
    return Response(result, content_type="application/x-json")
示例#19
0
文件: search.py 项目: araymund/karl
def _searchresults_view(context, request, page_title, calendar_search, show_search_knobs):
    api = TemplateAPI(context, request, page_title)

    # The layout is decided independently of whether we are a
    # calendar search or not. What is taken in consideration: if we are
    # in a community. The /offices section is considered a non-community
    # and will use the wide layout.
    if ICommunity.providedBy(context):
        if calendar_search:
            # We are either in /communities, or in /offices. In the first case:
            # we use the community layout. For offices: we need the wide layout
            # with the generic layout.
            context_path = resource_path(context)
            wide = context_path.startswith('/offices')
            if wide:
                layout = api.generic_layout
            else:
                layout = api.community_layout
        else:
            layout = api.community_layout
        community = context.title
    else:
        layout = api.generic_layout
        community = None

    request.unicode_errors = 'ignore'
    batch = None
    terms = ()
    error = None
    params = request.params.copy()
    if 'batch_start' in params:
        del params['batch_start']
    if 'batch_size' in params:
        del params['batch_size']

    kind_knob = []
    selected_kind = params.get('kind')

    scope_path = request.params.get('scopePath', '')

    # We show the scope knob, but in a limited way.
    # We only have a path here, so we show that path
    # and a single option to go back to All KARL.
    # If we are on all karl already, this knob group
    # will not show at all, defaulting to KARL's legacy
    # behaviour.
    scope_label = request.params.get('scopeLabel', '')
    if scope_path:
        scope_knob = []
        scope_knob.append({
            'name': scope_label,
            'title': scope_label,
            'description': scope_label,
            'icon': None,
            'url': None,
            'selected': True,
        })
        query = params.copy()
        query.update(scopePath='', scopeLabel='All KARL')
        scope_knob.append({
            'name': 'All KARL',
            'title': 'All KARL',
            'description': 'All KARL',
            'icon': None,
            'url': resource_url(find_root(context), request, request.view_name, query=query),
            'selected': False,
        })
    else:
        # The knob will not show at all
        scope_knob = None

    # There is a mapping needed between the livesearch
    # and the advanced search "kind" identifiers. This artifact is
    # a bit of annoyance but it's the easiest to do this
    # transformation here. Previously this was done from js.
    # Currently, if you click on livesearch results to
    # get into the advanced search, the livesearch kinds
    # will be submitted: which is why we convert from here.
    selected_kind = {
        'pages': 'wiki',
        'posts': 'blog',
        }.get(selected_kind, selected_kind)

    # In case we have a calendar search:
    # we will use events only as the content type.
    if calendar_search and selected_kind is None:
        # This means: filter events only in the result.
        selected_kind = 'events'

    for o in get_listitems(IGroupSearchFactory):
        component = o['component']
        if not component.advanced_search:
            continue
        kind = o['name']
        query = params.copy()
        query['kind'] = kind
        kind_knob.append({
            'name': kind,
            'title': o['title'],
            'icon': component.icon,
            'url': resource_url(context, request, request.view_name,
                             query=query),
            'selected': kind == selected_kind,
        })
    query = params.copy()
    if 'kind' in query:
        del query['kind']
    kind_knob.insert(0, {
        'name': 'all_content',
        'title': 'All Content',
        'description': 'All Content',
        'icon': None,
        'url': resource_url(context, request, request.view_name, query=query),
        'selected': not selected_kind,
    })

    since_knob = []
    selected_since = params.get('since')
    for id in since_order:
        option = since_options[id].copy()
        query = params.copy()
        if id is not None:
            query['since'] = id
        elif 'since' in query:
            del query['since']
        option['url'] = resource_url(context, request, request.view_name,
                                  query=query)
        option['selected'] = id == selected_since
        since_knob.append(option)

    sort_knob = []
    selected_sort = params.get('sort')
    for id in sort_order:
        option = sort_options[id].copy()
        query = params.copy()
        if id is not None:
            query['sort'] = id
        elif 'sort' in query:
            del query['sort']
        option['url'] = resource_url(context, request, request.view_name,
                                  query=query)
        option['selected'] = id == selected_sort
        sort_knob.append(option)

    start_time = time.time()
    try:
        batch, terms = get_batch(context, request)
    except ParseError, e:
        error = 'Error: %s' % e
示例#20
0
文件: tests.py 项目: Falmarri/karl
 def __call__(self):
     """ What tools can go in a community?
     """
     tools = get_listitems(IToolFactory)
     return [tool for tool in tools if tool["name"] not in EXCLUDE_TOOLS]
示例#21
0
文件: search.py 项目: zagy/karl
def jquery_livesearch_view(context, request):
    request.unicode_errors = 'ignore'
    try:
        searchterm = request.params.get('val', None)
    except UnicodeDecodeError:
        # Probably windows client didn't set request encoding. Try again.
        request.charset = 'ISO-8859-1'
        searchterm = request.params.get('val', None)

    if searchterm is None:
        # The request forgot to send the key we use to do a search, so
        # make a friendly error message.  Important for the unit test.
        msg = "Client failed to send a 'val' parameter as the searchterm"
        return HTTPBadRequest(msg)

    # maybe do some * checking to verify that we don't have a
    # prefix search < 3 chars

    records = []

    # we return back 5 results for each type of search
    results_per_type = 5

    kind = request.params.get('kind', '')
    if not kind:
        listitems = [
            item for item in get_listitems(IGroupSearchFactory)
            if item['component'].livesearch
        ]
    else:
        search_utility = queryUtility(IGroupSearchFactory, kind)
        if search_utility is None:
            msg = "The LiveSearch kind %s is not known" % kind
            return HTTPBadRequest(msg)
        else:
            # simulate a list item for the loop below
            listitems = (dict(component=search_utility), )
            # we'll just have on type of results, so we return back 20 results
            results_per_type = 20
    start_time = time.time()
    for listitem in listitems:
        utility = listitem['component']
        factory = utility(context, request, searchterm)
        if factory is None:
            continue
        factory.limit = results_per_type

        try:
            num, docids, resolver = factory()
        except ParseError:
            continue

        for result in (resolver(x) for x in docids):
            if result is None:
                continue
            record = queryMultiAdapter((result, request), ILiveSearchEntry)
            assert record is not None, ("Unexpected livesearch result: " +
                                        result.__class__.__name__)
            records.append(record)
    end_time = time.time()
    log.debug('livesearch: %0.3fs for "%s", kind=%s', end_time - start_time,
              searchterm, kind)

    result = JSONEncoder().encode(records)
    return Response(result, content_type="application/json")
示例#22
0
文件: api.py 项目: lslaz1/karl
 def livesearch_options(self):
     if self._livesearch_options is None:
         self._livesearch_options = [
             item for item in get_listitems(IGroupSearchFactory) if item["component"].livesearch
         ]
     return self._livesearch_options
示例#23
0
文件: search.py 项目: araymund/karl
def jquery_livesearch_view(context, request):
    request.unicode_errors = 'ignore'
    try:
        searchterm = request.params.get('val', None)
    except UnicodeDecodeError:
        # Probably windows client didn't set request encoding. Try again.
        request.charset = 'ISO-8859-1'
        searchterm = request.params.get('val', None)

    if searchterm is None:
        # The request forgot to send the key we use to do a search, so
        # make a friendly error message.  Important for the unit test.
        msg = "Client failed to send a 'val' parameter as the searchterm"
        return HTTPBadRequest(msg)

    if '__profile__' in searchterm:
        enable_profile = True
        searchterm = searchterm.replace('__profile__', '')
    else:
        enable_profile = False

    weighted_term = WeightedQuery(searchterm)

    # maybe do some * checking to verify that we don't have a
    # prefix search < 3 chars

    records = []

    # we return back 5 results for each type of search
    results_per_type = 5

    kind = request.params.get('kind', '')
    if not kind:
        listitems = [item for item in get_listitems(IGroupSearchFactory) if
                     item['component'].livesearch and
                     item['component'].livesearch_all]
    else:
        search_utility = queryUtility(IGroupSearchFactory, kind)
        if search_utility is None:
            msg = "The LiveSearch kind %s is not known" % kind
            return HTTPBadRequest(msg)
        else:
            # simulate a list item for the loop below
            listitems = (dict(component=search_utility),)
            # we'll just have on type of results, so we return back 20 results
            results_per_type = 20

    if enable_profile:
        import cProfile
        import pstats
        import StringIO
        pr = cProfile.Profile()
        pr.enable()

    start_time = time.time()
    for listitem in listitems:
        utility = listitem['component']
        factory = utility(context, request, weighted_term)
        if factory is None:
            continue
        factory.limit = results_per_type

        try:
            num, docids, resolver = factory()
        except ParseError:
            continue

        for result in (resolver(x) for x in docids):
            if result is None:
                continue
            record = queryMultiAdapter((result, request), ILiveSearchEntry)
            assert record is not None, (
                "Unexpected livesearch result: " + result.__class__.__name__)
            if kind == 'intranet':
                record['type'] = 'Intranet'
            records.append(record)
    end_time = time.time()
    log.debug('livesearch: %0.3fs for "%s", kind=%s',
        end_time - start_time, searchterm, kind)

    if enable_profile:
        pr.disable()
        s = StringIO.StringIO()
        ps = pstats.Stats(pr, stream=s).sort_stats('cumtime')
        ps.print_stats(100)  # Limit to 100 lines
        log.warning(
            'livesearch profile: %0.3fs for "%s", kind=%s\n%s',
            end_time - start_time, searchterm, kind, s.getvalue())

    return records
示例#24
0
文件: search.py 项目: claytron/karl
def _searchresults_view(context, request, page_title, calendar_search, show_search_knobs):
    api = TemplateAPI(context, request, page_title)

    # The layout is decided independently of whether we are a
    # calendar search or not. What is taken in consideration: if we are
    # in a community. The /offices section is considered a non-community
    # and will use the wide layout.
    if ICommunity.providedBy(context):
        if calendar_search:
            # We are either in /communities, or in /offices. In the first case:
            # we use the community layout. For offices: we need the wide layout
            # with the generic layout.
            context_path = resource_path(context)
            wide = context_path.startswith('/offices')
            if wide:
                layout = api.generic_layout
            else:
                layout = api.community_layout
        else:
            layout = api.community_layout
        community = context.title
    else:
        layout = api.generic_layout
        community = None

    request.unicode_errors = 'ignore'
    batch = None
    terms = ()
    error = None
    params = request.params.copy()
    if 'batch_start' in params:
        del params['batch_start']
    if 'batch_size' in params:
        del params['batch_size']

    kind_knob = []
    selected_kind = params.get('kind')

    # In case we have a calendar search:
    # we will use events only as the content type.
    if calendar_search and selected_kind is None:
        # This means: filter events only in the result.
        selected_kind = 'events'

    for o in get_listitems(IGroupSearchFactory):
        component = o['component']
        if not component.advanced_search:
            continue
        kind = o['name']
        query = params.copy()
        query['kind'] = kind
        kind_knob.append({
            'name': kind,
            'title': o['title'],
            'icon': component.icon,
            'url': resource_url(context, request, request.view_name,
                             query=query),
            'selected': kind == selected_kind,
        })
    query = params.copy()
    if 'kind' in query:
        del query['kind']
    kind_knob.insert(0, {
        'name': 'all_content',
        'title': 'All Content',
        'description': 'All Content',
        'icon': None,
        'url': resource_url(context, request, request.view_name, query=query),
        'selected': not selected_kind,
    })

    since_knob = []
    selected_since = params.get('since')
    for id in since_order:
        option = since_options[id].copy()
        query = params.copy()
        if id is not None:
            query['since'] = id
        elif 'since' in query:
            del query['since']
        option['url'] = resource_url(context, request, request.view_name,
                                  query=query)
        option['selected'] = id == selected_since
        since_knob.append(option)

    sort_knob = []
    selected_sort = params.get('sort')
    for id in sort_order:
        option = sort_options[id].copy()
        query = params.copy()
        if id is not None:
            query['sort'] = id
        elif 'sort' in query:
            del query['sort']
        option['url'] = resource_url(context, request, request.view_name,
                                  query=query)
        option['selected'] = id == selected_sort
        sort_knob.append(option)

    start_time = time.time()
    try:
        batch, terms = get_batch(context, request)
    except ParseError, e:
        error = 'Error: %s' % e