/
helpers.py
2607 lines (2055 loc) · 82 KB
/
helpers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# encoding: utf-8
'''Helper functions
Consists of functions to typically be used within templates, but also
available to Controllers. This module is available to templates as 'h'.
'''
import email.utils
import datetime
import logging
import re
import os
import pytz
import tzlocal
import urllib
import pprint
import copy
import urlparse
from urllib import urlencode
import uuid
from paste.deploy import converters
from webhelpers.html import HTML, literal, tags, tools
from webhelpers import paginate
import webhelpers.text as whtext
import webhelpers.date as date
from markdown import markdown
from bleach import clean as bleach_clean, ALLOWED_TAGS, ALLOWED_ATTRIBUTES
from pylons import url as _pylons_default_url
from ckan.common import config, is_flask_request
from flask import redirect as _flask_redirect
from flask import _request_ctx_stack, current_app
from routes import redirect_to as _routes_redirect_to
from routes import url_for as _routes_default_url_for
from flask import url_for as _flask_default_url_for
from werkzeug.routing import BuildError as FlaskRouteBuildError
import i18n
from six import string_types
import ckan.exceptions
import ckan.model as model
import ckan.lib.formatters as formatters
import ckan.lib.maintain as maintain
import ckan.lib.datapreview as datapreview
import ckan.logic as logic
import ckan.lib.uploader as uploader
import ckan.authz as authz
import ckan.plugins as p
import ckan
from ckan.common import _, ungettext, c, request, session, json
from markupsafe import Markup, escape
log = logging.getLogger(__name__)
DEFAULT_FACET_NAMES = u'organization groups tags res_format license_id'
MARKDOWN_TAGS = set([
'del', 'dd', 'dl', 'dt', 'h1', 'h2',
'h3', 'img', 'kbd', 'p', 'pre', 's',
'sup', 'sub', 'strike', 'br', 'hr'
]).union(ALLOWED_TAGS)
MARKDOWN_ATTRIBUTES = copy.deepcopy(ALLOWED_ATTRIBUTES)
MARKDOWN_ATTRIBUTES.setdefault('img', []).extend(['src', 'alt', 'title'])
class HelperAttributeDict(dict):
def __init__(self, *args, **kwargs):
super(HelperAttributeDict, self).__init__(*args, **kwargs)
self.__dict__ = self
def __getitem__(self, key):
try:
value = super(HelperAttributeDict, self).__getitem__(key)
except KeyError:
raise ckan.exceptions.HelperError(
'Helper \'{key}\' has not been defined.'.format(
key=key
)
)
return value
# Builtin helper functions.
_builtin_functions = {}
helper_functions = HelperAttributeDict()
def core_helper(f, name=None):
"""
Register a function as a builtin helper method.
"""
def _get_name(func_or_class):
# Handles both methods and class instances.
try:
return func_or_class.__name__
except AttributeError:
return func_or_class.__class__.__name__
_builtin_functions[name or _get_name(f)] = f
return f
def _datestamp_to_datetime(datetime_):
''' Converts a datestamp to a datetime. If a datetime is provided it
just gets returned.
:param datetime_: the timestamp
:type datetime_: string or datetime
:rtype: datetime
'''
if isinstance(datetime_, string_types):
try:
datetime_ = date_str_to_datetime(datetime_)
except TypeError:
return None
except ValueError:
return None
# check we are now a datetime
if not isinstance(datetime_, datetime.datetime):
return None
if datetime_.tzinfo is not None:
return datetime_
# all dates are considered UTC internally,
# change output if `ckan.display_timezone` is available
datetime_ = datetime_.replace(tzinfo=pytz.utc)
datetime_ = datetime_.astimezone(get_display_timezone())
return datetime_
@core_helper
def redirect_to(*args, **kw):
'''Issue a redirect: return an HTTP response with a ``302 Moved`` header.
This is a wrapper for :py:func:`routes.redirect_to` that maintains the
user's selected language when redirecting.
The arguments to this function identify the route to redirect to, they're
the same arguments as :py:func:`ckan.plugins.toolkit.url_for` accepts,
for example::
import ckan.plugins.toolkit as toolkit
# Redirect to /dataset/my_dataset.
toolkit.redirect_to(controller='package', action='read',
id='my_dataset')
Or, using a named route::
toolkit.redirect_to('dataset_read', id='changed')
If given a single string as argument, this redirects without url parsing
toolkit.redirect_to('http://example.com')
toolkit.redirect_to('/dataset')
toolkit.redirect_to('/some/other/path')
'''
if are_there_flash_messages():
kw['__no_cache__'] = True
# Routes router doesn't like unicode args
uargs = map(lambda arg: str(arg) if isinstance(arg, unicode) else arg,
args)
_url = ''
skip_url_parsing = False
parse_url = kw.pop('parse_url', False)
if uargs and len(uargs) is 1 and isinstance(uargs[0], string_types) \
and (uargs[0].startswith('/') or is_url(uargs[0])) \
and parse_url is False:
skip_url_parsing = True
_url = uargs[0]
if skip_url_parsing is False:
_url = url_for(*uargs, **kw)
if _url.startswith('/'):
_url = str(config['ckan.site_url'].rstrip('/') + _url)
if is_flask_request():
return _flask_redirect(_url)
else:
return _routes_redirect_to(_url)
@maintain.deprecated('h.url is deprecated please use h.url_for')
@core_helper
def url(*args, **kw):
'''
Deprecated: please use `url_for` instead
'''
return url_for(*args, **kw)
@core_helper
def get_site_protocol_and_host():
'''Return the protocol and host of the configured `ckan.site_url`.
This is needed to generate valid, full-qualified URLs.
If `ckan.site_url` is set like this::
ckan.site_url = http://example.com
Then this function would return a tuple `('http', 'example.com')`
If the setting is missing, `(None, None)` is returned instead.
'''
site_url = config.get('ckan.site_url', None)
if site_url is not None:
parsed_url = urlparse.urlparse(site_url)
return (
parsed_url.scheme.encode('utf-8'),
parsed_url.netloc.encode('utf-8')
)
return (None, None)
def _get_auto_flask_context():
'''
Provides a Flask test request context if we are outside the context
of a web request (tests or CLI)
'''
from ckan.config.middleware import _internal_test_request_context
from ckan.lib.cli import _cli_test_request_context
# This is a normal web request, there is a request context present
if _request_ctx_stack.top:
return None
# We are outside a web request. A test web application was created
# (and with it a test request context with the relevant configuration)
if _internal_test_request_context:
return _internal_test_request_context
# We are outside a web request. This is a CLI command. A test request
# context was created when setting it up
if _cli_test_request_context:
return _cli_test_request_context
@core_helper
def url_for(*args, **kw):
'''Return the URL for an endpoint given some parameters.
This is a wrapper for :py:func:`flask.url_for`
and :py:func:`routes.url_for` that adds some extra features that CKAN
needs.
To build a URL for a Flask view, pass the name of the blueprint and the
view function separated by a period ``.``, plus any URL parameters::
url_for('api.action', ver=3, logic_function='status_show')
# Returns /api/3/action/status_show
For a fully qualified URL pass the ``_external=True`` parameter. This
takes the ``ckan.site_url`` and ``ckan.root_path`` settings into account::
url_for('api.action', ver=3, logic_function='status_show',
_external=True)
# Returns http://example.com/api/3/action/status_show
URLs built by Pylons use the Routes syntax::
url_for(controller='package', action='read', id='my_dataset')
# Returns '/dataset/my_dataset'
Or, using a named route::
url_for('dataset_read', id='changed')
# Returns '/dataset/changed'
Use ``qualified=True`` for a fully qualified URL when targeting a Pylons
endpoint.
For backwards compatibility, an effort is made to support the Pylons syntax
when building a Flask URL, but this support might be dropped in the future,
so calls should be updated.
'''
# Get the actual string code for the locale
locale = kw.pop('locale', None)
if locale and isinstance(locale, i18n.Locale):
locale = i18n.get_identifier_from_locale_class(locale)
# remove __ckan_no_root and add after to not pollute url
no_root = kw.pop('__ckan_no_root', False)
# All API URLs generated should provide the version number
if kw.get('controller') == 'api' or args and args[0].startswith('api.'):
ver = kw.get('ver')
if not ver:
raise Exception('API URLs must specify the version (eg ver=3)')
_auto_flask_context = _get_auto_flask_context()
try:
if _auto_flask_context:
_auto_flask_context.push()
# First try to build the URL with the Flask router
my_url = _url_for_flask(*args, **kw)
except FlaskRouteBuildError:
# If it doesn't succeed, fallback to the Pylons router
my_url = _url_for_pylons(*args, **kw)
finally:
if _auto_flask_context:
_auto_flask_context.pop()
# Add back internal params
kw['__ckan_no_root'] = no_root
# Rewrite the URL to take the locale and root_path into account
return _local_url(my_url, locale=locale, **kw)
def _url_for_flask(*args, **kw):
'''Build a URL using the Flask router
This function should not be called directly, use ``url_for`` instead
This function tries to support the Pylons syntax for ``url_for`` and adapt
it to the Flask one, eg::
# Pylons
url_for(controller='api', action='action', ver=3, qualified=True)
# Flask
url_for('api.action', ver=3, _external=True)
Raises :py:exception:`werkzeug.routing.BuildError` if it couldn't
generate a URL.
'''
if (len(args) and '_' in args[0]
and '.' not in args[0]
and not args[0].startswith('/')):
# Try to translate Python named routes to Flask endpoints
# eg `dataset_new` -> `dataset.new`
args = (args[0].replace('_', '.', 1), )
elif kw.get('controller') and kw.get('action'):
# If `controller` and `action` are passed, build a Flask endpoint
# from them
# eg controller='user', action='login' -> 'user.login'
args = ('{0}.{1}'.format(kw.pop('controller'), kw.pop('action')),)
# Support Pylons' way of asking for full URLs
external = kw.pop('_external', False) or kw.pop('qualified', False)
# The API routes used to require a slash on the version number, make sure
# we remove it
if (args and args[0].startswith('api.') and
isinstance(kw.get('ver'), string_types) and
kw['ver'].startswith('/')):
kw['ver'] = kw['ver'].replace('/', '')
# Try to build the URL with flask.url_for
my_url = _flask_default_url_for(*args, **kw)
if external:
# Don't rely on the host generated by Flask, as SERVER_NAME might not
# be set or might be not be up to date (as in tests changing
# `ckan.site_url`). Contrary to the Routes mapper, there is no way in
# Flask to pass the host explicitly, so we rebuild the URL manually
# based on `ckan.site_url`, which is essentially what we did on Pylons
protocol, host = get_site_protocol_and_host()
parts = urlparse.urlparse(my_url)
my_url = urlparse.urlunparse((protocol, host, parts.path, parts.params,
parts.query, parts.fragment))
return my_url
def _url_for_pylons(*args, **kw):
'''Build a URL using the Pylons (Routes) router
This function should not be called directly, use ``url_for`` instead
'''
# We need to provide protocol and host to get full URLs, get them from
# ckan.site_url
if kw.get('qualified', False) or kw.get('_external', False):
kw['protocol'], kw['host'] = get_site_protocol_and_host()
# The Pylons API routes require a slask on the version number for some
# reason
if kw.get('controller') == 'api' and kw.get('ver'):
if (isinstance(kw['ver'], int) or
not kw['ver'].startswith('/')):
kw['ver'] = '/%s' % kw['ver']
# Try to build the URL with routes.url_for
return _routes_default_url_for(*args, **kw)
@core_helper
def url_for_static(*args, **kw):
'''Returns the URL for static content that doesn't get translated (eg CSS)
It'll raise CkanUrlException if called with an external URL
This is a wrapper for :py:func:`routes.url_for`
'''
if args:
url = urlparse.urlparse(args[0])
url_is_external = (url.scheme != '' or url.netloc != '')
if url_is_external:
CkanUrlException = ckan.exceptions.CkanUrlException
raise CkanUrlException('External URL passed to url_for_static()')
return url_for_static_or_external(*args, **kw)
@core_helper
def url_for_static_or_external(*args, **kw):
'''Returns the URL for static content that doesn't get translated (eg CSS),
or external URLs
This is a wrapper for :py:func:`routes.url_for`
'''
def fix_arg(arg):
url = urlparse.urlparse(str(arg))
url_is_relative = (url.scheme == '' and url.netloc == '' and
not url.path.startswith('/'))
if url_is_relative:
return '/' + url.geturl()
return url.geturl()
if args:
args = (fix_arg(args[0]), ) + args[1:]
if kw.get('qualified', False):
kw['protocol'], kw['host'] = get_site_protocol_and_host()
my_url = _routes_default_url_for(*args, **kw)
return _local_url(my_url, locale='default', **kw)
@core_helper
def is_url(*args, **kw):
'''
Returns True if argument parses as a http, https or ftp URL
'''
if not args:
return False
try:
url = urlparse.urlparse(args[0])
except ValueError:
return False
default_valid_schemes = ('http', 'https', 'ftp')
valid_schemes = config.get('ckan.valid_url_schemes', '').lower().split()
return url.scheme in (valid_schemes or default_valid_schemes)
def _local_url(url_to_amend, **kw):
# If the locale keyword param is provided then the url is rewritten
# using that locale .If return_to is provided this is used as the url
# (as part of the language changing feature).
# A locale of default will not add locale info to the url.
default_locale = False
locale = kw.pop('locale', None)
no_root = kw.pop('__ckan_no_root', False)
allowed_locales = ['default'] + i18n.get_locales()
if locale and locale not in allowed_locales:
locale = None
if locale:
if locale == 'default':
default_locale = True
else:
try:
locale = request.environ.get('CKAN_LANG')
default_locale = request.environ.get('CKAN_LANG_IS_DEFAULT', True)
except TypeError:
default_locale = True
root = ''
if kw.get('qualified', False):
# if qualified is given we want the full url ie http://...
protocol, host = get_site_protocol_and_host()
root = _routes_default_url_for('/',
qualified=True,
host=host,
protocol=protocol)[:-1]
# ckan.root_path is defined when we have none standard language
# position in the url
root_path = config.get('ckan.root_path', None)
if root_path:
# FIXME this can be written better once the merge
# into the ecportal core is done - Toby
# we have a special root specified so use that
if default_locale:
root_path = re.sub('/{{LANG}}', '', root_path)
else:
root_path = re.sub('{{LANG}}', str(locale), root_path)
# make sure we don't have a trailing / on the root
if root_path[-1] == '/':
root_path = root_path[:-1]
else:
if default_locale:
root_path = ''
else:
root_path = '/' + str(locale)
url_path = url_to_amend[len(root):]
url = '%s%s%s' % (root, root_path, url_path)
# stop the root being added twice in redirects
if no_root and url_to_amend.startswith(root):
url = url_to_amend[len(root):]
if not default_locale:
url = '/%s%s' % (locale, url)
if url == '/packages':
error = 'There is a broken url being created %s' % kw
raise ckan.exceptions.CkanUrlException(error)
return url
@core_helper
def url_is_local(url):
'''Returns True if url is local'''
if not url or url.startswith('//'):
return False
parsed = urlparse.urlparse(url)
if parsed.scheme:
domain = urlparse.urlparse(url_for('/', qualified=True)).netloc
if domain != parsed.netloc:
return False
return True
@core_helper
def full_current_url():
''' Returns the fully qualified current url (eg http://...) useful
for sharing etc '''
return (url_for(request.environ['CKAN_CURRENT_URL'], qualified=True))
@core_helper
def current_url():
''' Returns current url unquoted'''
return urllib.unquote(request.environ['CKAN_CURRENT_URL'])
@core_helper
def lang():
''' Return the language code for the current locale eg `en` '''
return request.environ.get('CKAN_LANG')
@core_helper
def ckan_version():
'''Return CKAN version'''
return ckan.__version__
@core_helper
def lang_native_name(lang=None):
''' Return the langage name currently used in it's localised form
either from parameter or current environ setting'''
lang = lang or lang()
locale = i18n.get_locales_dict().get(lang)
if locale:
return locale.display_name or locale.english_name
return lang
class Message(object):
'''A message returned by ``Flash.pop_messages()``.
Converting the message to a string returns the message text. Instances
also have the following attributes:
* ``message``: the message text.
* ``category``: the category specified when the message was created.
'''
def __init__(self, category, message, allow_html):
self.category = category
self.message = message
self.allow_html = allow_html
def __str__(self):
return self.message
__unicode__ = __str__
def __html__(self):
if self.allow_html:
return self.message
else:
return escape(self.message)
class _Flash(object):
# List of allowed categories. If None, allow any category.
categories = ["", "alert-info", "alert-error", "alert-success"]
# Default category if none is specified.
default_category = ""
def __init__(self, session_key="flash", categories=None,
default_category=None):
self.session_key = session_key
if categories is not None:
self.categories = categories
if default_category is not None:
self.default_category = default_category
if self.categories and self.default_category not in self.categories:
raise ValueError("unrecognized default category %r"
% (self.default_category, ))
def __call__(self, message, category=None, ignore_duplicate=False,
allow_html=False):
if not category:
category = self.default_category
elif self.categories and category not in self.categories:
raise ValueError("unrecognized category %r" % (category, ))
# Don't store Message objects in the session, to avoid unpickling
# errors in edge cases.
new_message_tuple = (category, message, allow_html)
messages = session.setdefault(self.session_key, [])
# ``messages`` is a mutable list, so changes to the local variable are
# reflected in the session.
if ignore_duplicate:
for i, m in enumerate(messages):
if m[1] == message:
if m[0] != category:
messages[i] = new_message_tuple
session.save()
return # Original message found, so exit early.
messages.append(new_message_tuple)
session.save()
def pop_messages(self):
messages = session.pop(self.session_key, [])
# only save session if it has changed
if messages:
session.save()
return [Message(*m) for m in messages]
def are_there_messages(self):
return bool(session.get(self.session_key))
flash = _Flash()
# this is here for backwards compatability
_flash = flash
@core_helper
def flash_notice(message, allow_html=False):
''' Show a flash message of type notice '''
flash(message, category='alert-info', allow_html=allow_html)
@core_helper
def flash_error(message, allow_html=False):
''' Show a flash message of type error '''
flash(message, category='alert-error', allow_html=allow_html)
@core_helper
def flash_success(message, allow_html=False):
''' Show a flash message of type success '''
flash(message, category='alert-success', allow_html=allow_html)
@core_helper
def are_there_flash_messages():
''' Returns True if there are flash messages for the current user '''
return flash.are_there_messages()
def _link_active(kwargs):
''' creates classes for the link_to calls '''
if is_flask_request():
return _link_active_flask(kwargs)
else:
return _link_active_pylons(kwargs)
def _link_active_pylons(kwargs):
highlight_actions = kwargs.get('highlight_actions',
kwargs.get('action', '')).split()
return (c.controller == kwargs.get('controller')
and c.action in highlight_actions)
def _link_active_flask(kwargs):
blueprint, endpoint = request.url_rule.endpoint.split('.')
return(kwargs.get('controller') == blueprint and
kwargs.get('action') == endpoint)
def _link_to(text, *args, **kwargs):
'''Common link making code for several helper functions'''
assert len(args) < 2, 'Too many unnamed arguments'
def _link_class(kwargs):
''' creates classes for the link_to calls '''
suppress_active_class = kwargs.pop('suppress_active_class', False)
if not suppress_active_class and _link_active(kwargs):
active = ' active'
else:
active = ''
kwargs.pop('highlight_actions', '')
return kwargs.pop('class_', '') + active or None
def _create_link_text(text, **kwargs):
''' Update link text to add a icon or span if specified in the
kwargs '''
if kwargs.pop('inner_span', None):
text = literal('<span>') + text + literal('</span>')
if icon:
text = literal('<i class="fa fa-%s"></i> ' % icon) + text
return text
icon = kwargs.pop('icon', None)
class_ = _link_class(kwargs)
return tags.link_to(
_create_link_text(text, **kwargs),
url_for(*args, **kwargs),
class_=class_
)
@core_helper
def nav_link(text, *args, **kwargs):
'''
:param class_: pass extra class(es) to add to the ``<a>`` tag
:param icon: name of ckan icon to use within the link
:param condition: if ``False`` then no link is returned
'''
if is_flask_request():
return nav_link_flask(text, *args, **kwargs)
else:
return nav_link_pylons(text, *args, **kwargs)
def nav_link_flask(text, *args, **kwargs):
if len(args) > 1:
raise Exception('Too many unnamed parameters supplied')
blueprint, endpoint = request.url_rule.endpoint.split('.')
if args:
kwargs['controller'] = blueprint or None
named_route = kwargs.pop('named_route', '')
if kwargs.pop('condition', True):
if named_route:
link = _link_to(text, named_route, **kwargs)
else:
link = _link_to(text, **kwargs)
else:
link = ''
return link
def nav_link_pylons(text, *args, **kwargs):
if len(args) > 1:
raise Exception('Too many unnamed parameters supplied')
if args:
kwargs['controller'] = kwargs.get('controller')
log.warning('h.nav_link() please supply controller as a named '
'parameter not a positional one')
named_route = kwargs.pop('named_route', '')
if kwargs.pop('condition', True):
if named_route:
link = _link_to(text, named_route, **kwargs)
else:
link = _link_to(text, **kwargs)
else:
link = ''
return link
@core_helper
@maintain.deprecated('h.nav_named_link is deprecated please '
'use h.nav_link\nNOTE: you will need to pass the '
'route_name as a named parameter')
def nav_named_link(text, named_route, **kwargs):
'''Create a link for a named route.
Deprecated in ckan 2.0 '''
return nav_link(text, named_route=named_route, **kwargs)
@core_helper
@maintain.deprecated('h.subnav_link is deprecated please '
'use h.nav_link\nNOTE: if action is passed as the second '
'parameter make sure it is passed as a named parameter '
'eg. `action=\'my_action\'')
def subnav_link(text, action, **kwargs):
'''Create a link for a named route.
Deprecated in ckan 2.0 '''
kwargs['action'] = action
return nav_link(text, **kwargs)
@core_helper
@maintain.deprecated('h.subnav_named_route is deprecated please '
'use h.nav_link\nNOTE: you will need to pass the '
'route_name as a named parameter')
def subnav_named_route(text, named_route, **kwargs):
'''Generate a subnav element based on a named route
Deprecated in ckan 2.0 '''
return nav_link(text, named_route=named_route, **kwargs)
@core_helper
def build_nav_main(*args):
''' build a set of menu items.
args: tuples of (menu type, title) eg ('login', _('Login'))
outputs <li><a href="...">title</a></li>
'''
output = ''
for item in args:
menu_item, title = item[:2]
if len(item) == 3 and not check_access(item[2]):
continue
output += _make_menu_item(menu_item, title)
return output
@core_helper
def build_nav_icon(menu_item, title, **kw):
'''Build a navigation item used for example in ``user/read_base.html``.
Outputs ``<li><a href="..."><i class="icon.."></i> title</a></li>``.
:param menu_item: the name of the defined menu item defined in
config/routing as the named route of the same name
:type menu_item: string
:param title: text used for the link
:type title: string
:param kw: additional keywords needed for creating url eg ``id=...``
:rtype: HTML literal
'''
return _make_menu_item(menu_item, title, **kw)
@core_helper
def build_nav(menu_item, title, **kw):
'''Build a navigation item used for example breadcrumbs.
Outputs ``<li><a href="...">title</a></li>``.
:param menu_item: the name of the defined menu item defined in
config/routing as the named route of the same name
:type menu_item: string
:param title: text used for the link
:type title: string
:param kw: additional keywords needed for creating url eg ``id=...``
:rtype: HTML literal
'''
return _make_menu_item(menu_item, title, icon=None, **kw)
@core_helper
def build_extra_admin_nav():
'''Build extra navigation items used in ``admin/base.html`` for values
defined in the config option ``ckan.admin_tabs``. Typically this is
populated by extensions.
:rtype: HTML literal
'''
admin_tabs_dict = config.get('ckan.admin_tabs')
output = ''
if admin_tabs_dict:
for key in admin_tabs_dict:
output += build_nav_icon(key, admin_tabs_dict[key])
return output
def _make_menu_item(menu_item, title, **kw):
''' build a navigation item used for example breadcrumbs
outputs <li><a href="..."></i> title</a></li>
:param menu_item: the name of the defined menu item defined in
config/routing as the named route of the same name
:type menu_item: string
:param title: text used for the link
:type title: string
:param **kw: additional keywords needed for creating url eg id=...
:rtype: HTML literal
This function is called by wrapper functions.
'''
_menu_items = config['routes.named_routes']
if menu_item not in _menu_items:
raise Exception('menu item `%s` cannot be found' % menu_item)
item = copy.copy(_menu_items[menu_item])
item.update(kw)
active = _link_active(item)
needed = item.pop('needed')
for need in needed:
if need not in kw:
raise Exception('menu item `%s` need parameter `%s`'
% (menu_item, need))
link = _link_to(title, menu_item, suppress_active_class=True, **item)
if active:
return literal('<li class="active">') + link + literal('</li>')
return literal('<li>') + link + literal('</li>')
@core_helper
def default_group_type():
return str(config.get('ckan.default.group_type', 'group'))
@core_helper
def get_facet_items_dict(facet, limit=None, exclude_active=False):
'''Return the list of unselected facet items for the given facet, sorted
by count.
Returns the list of unselected facet contraints or facet items (e.g. tag
names like "russian" or "tolstoy") for the given search facet (e.g.
"tags"), sorted by facet item count (i.e. the number of search results that
match each facet item).
Reads the complete list of facet items for the given facet from
c.search_facets, and filters out the facet items that the user has already
selected.
Arguments:
facet -- the name of the facet to filter.
limit -- the max. number of facet items to return.
exclude_active -- only return unselected facets.
'''
if not c.search_facets or \
not c.search_facets.get(facet) or \
not c.search_facets.get(facet).get('items'):
return []
facets = []
for facet_item in c.search_facets.get(facet)['items']:
if not len(facet_item['name'].strip()):
continue
if not (facet, facet_item['name']) in request.params.items():
facets.append(dict(active=False, **facet_item))
elif not exclude_active:
facets.append(dict(active=True, **facet_item))
# Sort descendingly by count and ascendingly by case-sensitive display name
facets.sort(key=lambda it: (-it['count'], it['display_name'].lower()))
if hasattr(c, 'search_facets_limits'):
if c.search_facets_limits and limit is None:
limit = c.search_facets_limits.get(facet)
# zero treated as infinite for hysterical raisins
if limit is not None and limit > 0:
return facets[:limit]
return facets
@core_helper
def has_more_facets(facet, limit=None, exclude_active=False):
'''
Returns True if there are more facet items for the given facet than the
limit.
Reads the complete list of facet items for the given facet from
c.search_facets, and filters out the facet items that the user has already
selected.
Arguments:
facet -- the name of the facet to filter.
limit -- the max. number of facet items.
exclude_active -- only return unselected facets.
'''
facets = []
for facet_item in c.search_facets.get(facet)['items']:
if not len(facet_item['name'].strip()):
continue
if not (facet, facet_item['name']) in request.params.items():
facets.append(dict(active=False, **facet_item))
elif not exclude_active:
facets.append(dict(active=True, **facet_item))
if c.search_facets_limits and limit is None:
limit = c.search_facets_limits.get(facet)
if limit is not None and len(facets) > limit:
return True