package.py 47.2 KB
Newer Older
Marko Kuder's avatar
Marko Kuder committed
1
# -*- encoding: utf-8 -*-
Kristijan Čagran's avatar
Kristijan Čagran committed
2
import exceptions
luka_androjna's avatar
luka_androjna committed
3
import re
4
import urllib2
Marko Kuder's avatar
Marko Kuder committed
5
from urllib import urlencode
6
import logging
7
8
import mimetypes
import paste.fileapp
Marko Kuder's avatar
Marko Kuder committed
9
from lxml import html
10
11
from urllib import quote
from urllib2 import HTTPError, URLError
Marko Kuder's avatar
Marko Kuder committed
12
from urlparse import urljoin
Marko Kuder's avatar
Marko Kuder committed
13
14
from paste.deploy.converters import asbool
from pylons import config
15
16

from ckan import logic
Marko Kuder's avatar
Marko Kuder committed
17
from ckan.common import OrderedDict, request
18
from ckan.lib.base import model, abort, response, g, h, BaseController
19
from ckanext.dgu.model.package_likes import PackageLikes
Marko Kuder's avatar
Marko Kuder committed
20
import ckanext.dgu.lib.captcha as captcha
21
from ckanext.dgu.plugins_toolkit import render, c, request, _, ObjectNotFound, NotAuthorized, ValidationError, get_action, check_access
22
from ckan.lib.field_types import DateType, DateConvertError
Marko Kuder's avatar
Marko Kuder committed
23
import ckan.lib.navl.dictization_functions as dict_fns
24
from ckan.lib.navl.dictization_functions import Invalid, DataError, unflatten
25
from ckanext.dgu.schema import GeoCoverageType
26
from ckan.lib.navl.dictization_functions import missing
David Read's avatar
David Read committed
27
import ckan.controllers.package
Marko Kuder's avatar
Marko Kuder committed
28
from ckan.controllers.package import _encode_params
29
from ckanext.dgu.lib.helpers import get_executive_editors, get_from_flat_dict, get_user_email, get_user_name, free_tags, send_post, refresh_drupal_themes_async
30
from ckanext.dgu.lib.mailer_opsi import mail_recipient
31
from ckanext.dgu.lib.reports import refresh_opsi_reports_async
32
from ckan.lib.package_saver import PackageSaver
33
from ckan.lib.search import SearchIndexError
34
import ckan.lib.uploader as uploader
Marko Kuder's avatar
Marko Kuder committed
35
import ckan.plugins as p
36
37
from ckanext.dgu.forms.validators import tag_string_to_list as opsi_tag_string_to_list

38
39

log = logging.getLogger(__name__)
Marko Kuder's avatar
Marko Kuder committed
40
PISRS_URL = 'http://www.pisrs.si/Pis.web/pregledPredpisa?sop='
41

42
redirect = ckan.lib.base.redirect
Marko Kuder's avatar
Marko Kuder committed
43
44
45
46
47
48
49
50
NotFound = logic.NotFound
NotAuthorized = logic.NotAuthorized
ValidationError = logic.ValidationError
tuplize_dict = logic.tuplize_dict
clean_dict = logic.clean_dict
parse_params = logic.parse_params
flatten_to_string_key = logic.flatten_to_string_key

Marko Kuder's avatar
Marko Kuder committed
51
52
53
54
55
56
57
58
def _encode_params(params):
    return [(k, v.encode('utf-8') if isinstance(v, basestring) else str(v))
            for k, v in params]

def url_with_params(url, params):
    params = _encode_params(params)
    return url + u'?' + urlencode(params)

Marko Kuder's avatar
Marko Kuder committed
59
60
def recent_url(params, package_type=None):
    if not package_type or package_type == 'dataset':
Marko Kuder's avatar
Marko Kuder committed
61
        url = h.url_for(controller='ckanext.dgu.controllers.package:PackageController', action='recent')
Marko Kuder's avatar
Marko Kuder committed
62
63
64
65
    else:
        url = h.url_for('{0}_recent'.format(package_type))
    return url_with_params(url, params)

Marko Kuder's avatar
Marko Kuder committed
66
67
68
69
70
71
72
def search_url(params, package_type=None):
    if not package_type or package_type == 'dataset':
        url = h.url_for(controller='package', action='search')
    else:
        url = h.url_for('{0}_search'.format(package_type))
    return url_with_params(url, params)

David Read's avatar
David Read committed
73
class PackageController(ckan.controllers.package.PackageController):
74

75
76
77
78
    def __before__(self, action, **params):
        super(PackageController, self).__before__(action, **params)
        c.all_resources = 'all' in request.params.keys()

79
    def history(self, id):
80
        if not c.user:
81
            abort(401, 'Log-in to see this page')
David Read's avatar
David Read committed
82
        return super(PackageController, self).history(id)
83

84
    def increase_package_likes(self, id):
85
        try:
86
            PackageLikes.increase_package_likes(package_id=id)
87
88
89
        except p.toolkit.ValidationError:
            log.debug('ValidationError while increasing package likes.')

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
    def recent(self, podrocje=None):
        from ckan.lib.search import SearchError, SearchQueryError

        package_type = self._guess_package_type()
        try:
            context = {'model': model, 'user': c.user or c.author,
                       'auth_user_obj': c.userobj}
            check_access('site_read', context)
        except NotAuthorized:
            abort(401, _('Not authorized to see this page'))

        # unicode format (decoded from utf8)
        q = c.q = request.params.get('q', u'')
        c.query_error = False
        try:
            page = int(request.params.get('page', 1))
        except ValueError, e:
            abort(400, ('"page" parameter must be an integer'))
        limit = g.datasets_per_page

        # most search operations should reset the page counter:
        params_nopage = [(k, v) for k, v in request.params.items()
                         if k != 'page']

        def drill_down_url(alternative_url=None, **by):
            return h.add_url_param(alternative_url=alternative_url,
                                   controller='package', action='search',
                                   new_params=by)

        c.drill_down_url = drill_down_url

        def remove_field(key, value=None, replace=None, alternative_url=None):
            return h.remove_url_param(key, value=value, replace=replace,
                                  alternative_url=alternative_url,
                                  controller='package', action='search')

        c.remove_field = remove_field

        sort_by = 'metadata_modified desc'
        c.sort_by_fields = [('metadata_modified', 'desc')]

        def pager_url(q=None, page=None):
            params = list(params_nopage)
            params.append(('page', page))
Marko Kuder's avatar
Marko Kuder committed
134
            return recent_url(params, package_type)
135
136
137

        c.search_url_params = urlencode(_encode_params(params_nopage))

138
        recent_vars = {}
139
140
141
142
143
144
145
146
        try:
            c.fields = []
            # c.fields_grouped will contain a dict of params containing
            # a list of values eg {'tags':['tag1', 'tag2']}
            c.fields_grouped = {}
            search_extras = {}
            fq = ''
            for (param, value) in request.params.items():
147
148
                if param == 'all_podrocje':
                    recent_vars['podrocje'] = value
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
                if param not in ['q', 'page', 'sort'] \
                        and len(value) and not param.startswith('_'):
                    if not param.startswith('ext_'):
                        # DGU has no fields with non-ascii, but not sure how to cope
                        # with SOLR params with non-ascii - not sure what encoding would
                        # be, so ignore.
                        param = param.decode('ascii', 'ignore')
                        c.fields.append((param, value))
                        fq += ' %s:"%s"' % (param, value)
                        if param not in c.fields_grouped:
                            c.fields_grouped[param] = [value]
                        else:
                            c.fields_grouped[param].append(value)
                    else:
                        search_extras[param] = value

            context = {'model': model, 'session': model.Session,
                       'user': c.user or c.author, 'for_view': True,
                       'auth_user_obj': c.userobj}

            if package_type and package_type != 'dataset':
                # Only show datasets of this particular type
                fq += ' +dataset_type:{type}'.format(type=package_type)
            else:
                # Unless changed via config options, don't show non standard
                # dataset types on the default search page
                if not asbool(config.get('ckan.search.show_all_types', 'False')):
                    fq += ' +dataset_type:dataset'

            facets = OrderedDict()

            default_facet_titles = {
                    'organization': _('Organizations'),
                    'groups': _('Groups'),
                    'tags': _('Tags'),
                    'res_format': _('Formats'),
                    'license_id': _('Licenses'),
                    }

            for facet in g.facets:
                if facet in default_facet_titles:
                    facets[facet] = default_facet_titles[facet]
                else:
                    facets[facet] = facet

            # Facet titles
            for plugin in p.PluginImplementations(p.IFacets):
                facets = plugin.dataset_facets(facets, package_type)

            c.facet_titles = facets

            data_dict = {
                'q': q,
                'fq': fq.strip(),
                'facet.field': facets.keys(),
                'rows': limit,
                'start': (page - 1) * limit,
                'sort': sort_by,
                'extras': search_extras
            }

            query = get_action('package_search')(context, data_dict)
            c.sort_by_selected = query['sort']

            c.page = h.Page(
                collection=query['results'],
                page=page,
                url=pager_url,
                item_count=query['count'],
                items_per_page=limit
            )
            c.facets = query['facets']
            c.search_facets = query['search_facets']
            c.page.items = query['results']
        except SearchQueryError, se:
            # User's search parameters are invalid, in such a way that is not
            # achievable with the web interface, so return a proper error to
            # discourage spiders which are the main cause of this.
            log.info('Dataset search query rejected: %r', se.args)
            abort(400, _('Invalid search query: {error_message}')
                  .format(error_message=str(se)))
        except SearchError, se:
            # May be bad input from the user, but may also be more serious like
            # bad code causing a SOLR syntax error, or a problem connecting to
            # SOLR
            log.error('Dataset search error %s (%s): %r', request.url, request.environ.get('HTTP_USER_AGENT'), se.args)
            c.query_error = True
            c.facets = {}
            c.search_facets = {}
            c.page = h.Page(collection=[])
        # DGU fix for negative page number - fixed in a different way on master
        except ValidationError, e:
            # e.g. ?page=0
            abort(400, 'Parameter error: %s' % e)
        c.search_facets_limits = {}
        for facet in c.search_facets.keys():
            try:
                limit = int(request.params.get('_%s_limit' % facet,
                                               g.facets_default_number))
            except ValueError:
                abort(400, _('Parameter "{parameter_name}" is not '
                             'an integer').format(
                                 parameter_name='_%s_limit' % facet
                             ))
            c.search_facets_limits[facet] = limit
254
255
            
        
256
257
258
259

        self._setup_template_variables(context, {},
                                       package_type=package_type)

260
        return render("package/recent.html", extra_vars=recent_vars)
261
    
Marko Kuder's avatar
Marko Kuder committed
262
263
264
    def get_sop_name(self, id):
        try:
            page = html.fromstring(urllib2.urlopen(PISRS_URL+id).read())
Marko Kuder's avatar
Marko Kuder committed
265
            for title in page.xpath("//h1/text()"):
266
267
268
269
                title = title.strip()
                if title.find('\n') > 0:
                    title = title[0:title.find('\n')].strip()
                return '{"name": "'+ title + '" , "url": "' + (PISRS_URL + id)+'"}'
Kristijan Čagran's avatar
Kristijan Čagran committed
270
271
        except exceptions.UnicodeError:
            return '{"name": "Vnos ni v pravilnem formatu." , "url":""}'
Marko Kuder's avatar
Marko Kuder committed
272
        except URLError:
273
274
            return '{"name": "Napaka pri poizvedbi SOP" , "url":' + (PISRS_URL + id) + '"}'
        return '{"name": "Predpis s tem SOP ni bil najden" , "url": "' + (PISRS_URL + id) + '"}'
275

276
277
278
279
280
281
282
283
284
285
286
287
    def all_packages(self):

        ctx = {'model': model, 'session': model.Session}
        package_list = get_action("package_list")(ctx, {})

        def linkify_packages(pkgs):
            x = 0
            for pkg in pkgs:
                yield '<a href="/dataset/{p}">{p}</a><br/>'.format(p=pkg)

        c.datasets = linkify_packages(package_list)
        return render("package/all_datasets.html")
288

289
290
    def _send_message_to_owner(self, pkg_dict, data_dict):
        from genshi.template.text import NewTextTemplate
291

292
293
        errors = {}
        error_summary = {}
luka_androjna's avatar
luka_androjna committed
294
        owner_id = pkg_dict['creator_user_id']
295
296
297
        owner = model.User.get(owner_id)
        owner_email = get_user_email(owner)
        owner_name = get_user_name(owner)
298
        recipient = 'objavitelj'
299
300
301
        if 'notification_recipient' in pkg_dict:
            recipient = pkg_dict['notification_recipient']

luka_androjna's avatar
luka_androjna committed
302
        elif not owner_id:
303
304
            errors['message'] = [u'Ta zbirka nima avtorja']
            error_summary['message'] = u'Ta zbirka nima avtorja, zato ni bilo mogoče poslati sporočila'
305
        if 'message' not in errors:
luka_androjna's avatar
luka_androjna committed
306
307
308
309
            recipients = []
            if recipient == 'oba':
                recipients = [
                    {
310
311
                        'name': owner_name,
                        'email': owner_email
luka_androjna's avatar
luka_androjna committed
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
                    },
                    {
                        'name': pkg_dict['foi-name'],
                        'email': pkg_dict['foi-email']
                    }
                ]
            elif recipient == 'skrbnik':
                recipients = [
                    {
                        'name': pkg_dict['foi-name'],
                        'email': pkg_dict['foi-email']
                    }
                ]
            elif recipient == 'objavitelj':
                recipients = [
                    {
328
329
                        'name': owner_name,
                        'email': owner_email
luka_androjna's avatar
luka_androjna committed
330
331
332
333
                    }
                ]
            for recip in recipients:
                if not recip['email']:
334
                    errors['message'] = [u'Prejemnik obvestil zbirke nima elektronskega naslova']
luka_androjna's avatar
luka_androjna committed
335
336
337
338
339
340
                    error_summary['message'] = u'Prejemnik obvestil zbirke nima elektronskega naslova, zato ni bilo mogoče poslati sporočila'

            url = urljoin(g.site_url,
                          h.url_for(controller='ckanext.dgu.controllers.package:PackageController',
                          action='edit', id=pkg_dict['id']))

luka_androjna's avatar
luka_androjna committed
341
            if 'message' not in errors:
342
343
                extra_vars = {
                    'user': get_user_name(),
344
                    'dataset': pkg_dict['title'],
345
                    'editor_message': data_dict["message"],
346
                    'edit_url': url
347
348
349
                }
                email_msg = render("email/draft_comment.txt", extra_vars=extra_vars,
                                   loader_class=NewTextTemplate)
luka_androjna's avatar
luka_androjna committed
350
351
352
353
354
355

                for recip in recipients:
                    mail_recipient(recip['name'],
                                   recip['email'],
                                   subject=u'Obvestilo o vašem osnutku '+pkg_dict['title'],
                                   body=email_msg)
356
357
        return errors, error_summary
    
358
359
    def _report_opsi_issue_to_owner(self, pkg_dict, data_dict):
        from genshi.template.text import NewTextTemplate
360

361
362
        errors = {}
        error_summary = {}
363
364
365
366
367
368
        creator_id = pkg_dict['creator_user_id']
        creator = model.User.get(creator_id)
        creator_email = get_user_email(creator) or ''
        creator_name = get_user_name(creator)

        recipients = []
369
        # if set, the maintainer_email overrides all other settings
370
        maintainer_email = pkg_dict.get('maintainer_email')
371
372
373
374
375
376
377
378
        if maintainer_email:
            recipients = [{'name': creator_name or maintainer_email, 'email': maintainer_email}]
        else:
            recipient = 'objavitelj'
            if 'notification_recipient' in pkg_dict:
                recipient = pkg_dict['notification_recipient']
            if recipient == 'objavitelj' or recipient == 'oba':
                if creator_email:
Marko Kuder's avatar
Marko Kuder committed
379
                    recipients.append( { 'name': creator_name or creator_email, 'email': creator_email } )
Marko Kuder's avatar
Marko Kuder committed
380
                elif recipient != 'oba' and pkg_dict.get('foi-email'): #fallback
381
382
383
384
                    recipients.append( { 'name': pkg_dict.get('foi-name', pkg_dict['foi-email']), 'email': pkg_dict['foi-email'] } )
            if recipient == 'skrbnik' or recipient == 'oba':
                if pkg_dict.get('foi-email'):
                    recipients.append( { 'name': pkg_dict.get('foi-name', pkg_dict['foi-email']), 'email': pkg_dict['foi-email'] } )
Marko Kuder's avatar
Marko Kuder committed
385
                elif recipient != 'oba' and creator_email: #fallback
Marko Kuder's avatar
Marko Kuder committed
386
                    recipients.append( { 'name': creator_name or creator_email, 'email': creator_email } )
387
388
389
390
391
392
393
394
395
396

        url = urljoin(g.site_url,
                      h.url_for(controller='ckanext.dgu.controllers.package:PackageController',
                                action='edit', id=pkg_dict['id']))
        view_url = urljoin(g.site_url,
                           h.url_for(controller='ckanext.dgu.controllers.package:PackageController',
                                     action='read', id=pkg_dict['id']))

        recipient_text = ''
        if recipients:
luka_androjna's avatar
test3    
luka_androjna committed
397
            for recip in recipients:
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
                recipient_text += recip['name'] + ' ('+recip['email']+'), '
            recipient_text = recipient_text[0:-2]

        extra_vars = {
            'user': data_dict.get('name', ''),
            'user_email': data_dict.get('email', ''),
            'dataset': pkg_dict['title'],
            'editor_message': data_dict["message"],
            'edit_url': url,
            'view_url': view_url,
            'owner': recipient_text
        }

        sent_emails = []
        if recipients:
            email_msg = render("email/opsi_issue.txt", extra_vars=extra_vars,
                               loader_class=NewTextTemplate)
luka_androjna's avatar
test 1    
luka_androjna committed
415

416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
            for recip in recipients:
                if recip['email'] and recip['email'] not in sent_emails:
                    mail_recipient(recip['name'],
                                   recip['email'],
                                   subject=u'Predlog popravka v vaši zbirki '+pkg_dict['title'],
                                   body=email_msg)
                    sent_emails.append(recip['email'])

            email_msg_exec = render("email/opsi_issue_exec.txt", extra_vars=extra_vars, loader_class=NewTextTemplate)
        else:
            email_msg_exec = render("email/opsi_issue_exec_error.txt", extra_vars=extra_vars, loader_class=NewTextTemplate)
            log.warning("Package " + pkg_dict['id'] + " recipients have no email, notification will be sent to executive editors only.")

        exec_editors = get_executive_editors()
        for (name,recipient,id) in exec_editors:
            if recipient and recipient not in sent_emails:
                mail_recipient(name,
                       recipient,
                       subject=u'Predlog popravka v zbirki '+pkg_dict['title'],
                       body=email_msg_exec)
                sent_emails.append(recipient)
        log.debug('User sent OPSI issue for package %s, notification was sent to %s', pkg_dict['id'], sent_emails)
438
439
440
441
442
443
444
445
446
447
448
        return errors, error_summary
    
    def report_opsi_issue(self, id, data=None, errors=None, error_summary=None):
        """
        Display form for sending message to author
        :return: html
        """
        
        package_type = self._get_package_type(id)
        context = {'model': model, 'session': model.Session,
                   'user': c.user or c.author, 'auth_user_obj': c.userobj,
Marko Kuder's avatar
Marko Kuder committed
449
                   'report': 'report' in request.params}
450
451
452
453
454
455
456
457
458
459
        
        try:
            pkg_dict = get_action('package_show')(context, {'id':id}) # has side-effect of populating context.get('package')
        except NotAuthorized:
            abort(401, 'Nimate pravic za ogled zbirke')

        data_dict = {}
        errors = {}
        error_summary = {}
        c.pkg = context.get('package')
Marko Kuder's avatar
Marko Kuder committed
460
        if 'report' in request.params:
461
462
463
464
465
            # Send message to author
            try:
                data_dict = logic.clean_dict(unflatten(logic.tuplize_dict(logic.parse_params(request.params))))
            except logic.NotAuthorized:
                base.abort(401, _('Not authorized to see this page'))
luka_androjna's avatar
luka_androjna committed
466
467
468
469

            try:
                captcha.check_recaptcha(request)
            except captcha.CaptchaError:
470
471
                errors['captcha'] = [u'Napačna captcha']
                error_summary['captcha'] = u'Nepravilno izpolnjeno preverjanje ReCAPTCHA.'
472
473
            except HTTPError:
                errors['captcha'] = [u'Napaka pri preverjanju captcha']
Marko Kuder's avatar
Marko Kuder committed
474
                error_summary['captcha'] = u'Prišlo je do napake pri preverjanju ReCAPTCHA. Prosimo, poskusite ponovno.'
475
476
477
            if data_dict["message"].strip() == '':
                errors['message'] = [u'Manjkajoča vrednost']
                error_summary['message'] = u'Komentar je obvezen.'
478
            elif data_dict.get('email', '') == '':
luka_androjna's avatar
luka_androjna committed
479
480
                errors['email'] = [u'Manjkajoča vrednost']
                error_summary['email'] = u'Email je obvezen.'
luka_androjna's avatar
luka_androjna committed
481
482
483
            elif not re.compile(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)").match(data_dict.get('email', '')):
                errors['email'] = [u'Nepravilno izpolnjena vrednost']
                error_summary['email'] = u'Pravilno izpolnjen email je obvezen.'
luka_androjna's avatar
luka_androjna committed
484
            elif not errors:
Marko Kuder's avatar
Marko Kuder committed
485
                er, er_sum = self._report_opsi_issue_to_owner(pkg_dict, data_dict)
486
487
                errors.update(er)
                error_summary.update(er_sum)
Marko Kuder's avatar
Marko Kuder committed
488
489
490
            if not errors:
                h.flash_success(u'Vaše sporočilo je bilo poslano avtorju zbirke \'%s\'.' % pkg_dict['title'], allow_html=True)
                p.toolkit.redirect_to(controller='package', action='read', id=id)
Marko Kuder's avatar
Marko Kuder committed
491
        vars = {'data_dict': data_dict, 'errors': errors, 'error_summary': error_summary}
492
493
        return render('issues/opsi_issue.html', extra_vars=vars)
    
494
495
496
497
498
499
500
501
502
503
    def change_status(self, id, data=None, errors=None, error_summary=None):
        """
        Display form for publishing or sending message to author
        :return: html
        """
        
        package_type = self._get_package_type(id)
        context = {'model': model, 'session': model.Session,
                   'user': c.user or c.author, 'auth_user_obj': c.userobj,
                   'publish': 'publish' in request.params,
504
                   'reject': 'reject' in request.params}
505
506
507
508
509
510

        try:
            check_access('package_change_state',context)
        except NotAuthorized:
            abort(401, _('Not authorized to see this page'))

511
512
513
514
515
516
517
518
        try:
            pkg_dict = get_action('package_show')(context, {'id':id}) # has side-effect of populating context.get('package')
        except NotAuthorized:
            abort(401, 'Nimate pravic za urejanje zbirke')

        data = {}
        errors = {}
        error_summary = {}
Marko Kuder's avatar
Marko Kuder committed
519
        old_state = pkg_dict['state']
520
        if pkg_dict['state'] == 'draft' and ('unpublished' not in pkg_dict or not p.toolkit.asbool(pkg_dict['unpublished'])):
521
522
523
524
            h.flash_success(u'Osnutkom ni mogoče spreminjati stanja, dokler niso v potrjevanju.', allow_html=True)
            self._form_save_redirect(pkg_dict['name'], 'edit', package_type=package_type)
            return render('package/change_status.html')
        
Marko Kuder's avatar
Marko Kuder committed
525
        c.pkg = context.get('package')
526
        if 'reject' in request.params or 'publish' in request.params:
Marko Kuder's avatar
Marko Kuder committed
527
            # Send message to author
528
529
530
531
            try:
                data_dict = logic.clean_dict(unflatten(logic.tuplize_dict(logic.parse_params(request.params))))
            except logic.NotAuthorized:
                base.abort(401, _('Not authorized to see this page'))
532

533
            if data_dict["message"].strip() == '' and (not 'publish' in request.params):
534
535
                errors['message'] = [u'Če zbirka ne bo objavljena, je komentar obvezen.']
                error_summary['message'] = u'Manjkajoča vrednost'
536
537
                vars = {'data': data, 'errors': errors, 'error_summary': error_summary}
                return p.toolkit.render('package/change_status.html', extra_vars=vars)
538
            if data_dict["message"].strip() != '':
539
                er, er_sum = self._send_message_to_owner(pkg_dict, data_dict)
540
                errors.update(er)
541
                error_summary.update(er_sum)
Marko Kuder's avatar
Marko Kuder committed
542
543
        try: # TODO: have special action package_publish
            if not errors and 'publish' in request.params:
544
            #return self._save_edit(id, context, package_type=package_type)
545
                pkg_dict['state'] = 'active'
546
                pkg_dict['unpublished'] = 'False'
547
                pkg_dict['tag_string'] = ', '.join(free_tags(pkg_dict))
548
                get_action('package_update')(context, pkg_dict)
549
                self._on_publish(context, id)
Marko Kuder's avatar
Marko Kuder committed
550
            elif not errors and 'reject' in request.params:
Marko Kuder's avatar
Marko Kuder committed
551
                pkg_dict['state'] = 'draft'
Marko Kuder's avatar
Marko Kuder committed
552
553
554
                pkg_dict['unpublished'] = 'False'
                pkg_dict['tag_string'] = ', '.join(free_tags(pkg_dict))
                get_action('package_update')(context, pkg_dict)
Marko Kuder's avatar
Marko Kuder committed
555
                if old_state == 'active':
556
                    refresh_drupal_themes_async(context)
Marko Kuder's avatar
Marko Kuder committed
557
558
559
560
561
562
563
564
565
566
        except NotAuthorized:
            abort(401, 'Nimate dovoljenja za spremembo statusa zbirke %s' % id)
        except ObjectNotFound, e:
            abort(404, 'Ta zbirka ne obstaja')
        except DataError:
            abort(400, _(u'Integrity Error'))
        except SearchIndexError, e:
            abort(500, _(u'Unable to update search index.') + repr(e.args))
        except ValidationError, e:
            abort(400, u'Stanja zbirke ni bilo mogoče spremeniti: ' + repr(e.error_dict))
567
568

        vars = {'data': data, 'errors': errors, 'error_summary': error_summary}
569
570
        if errors:
            return render('package/change_status.html', extra_vars=vars)
571
        elif 'reject' in request.params:
572
            h.flash_success(u'Vaše sporočilo je bilo poslano avtorju zbirke \'%s\'.' % pkg_dict['title'], allow_html=True)
573
            refresh_opsi_reports_async()
574
575
            self._form_save_redirect(pkg_dict['name'], 'edit', package_type=package_type)
            #h.redirect_to(controller='package', action='read', id=id)
576
        elif 'publish' in request.params:
577
            h.flash_success(u'Zbirka \'%s\' je objavljena.' % pkg_dict['title'], allow_html=True)
578
            refresh_opsi_reports_async()
579
580
            self._form_save_redirect(pkg_dict['name'], 'edit', package_type=package_type)
            #h.redirect_to(controller='package', action='read', id=id)
581
        self._setup_template_variables(context, {'id': id}, package_type=package_type)
582
        
583
        return render('package/change_status.html', extra_vars=vars)
584

585
    def delete(self, id):
586
        """Provide a delete ('withdraw') action, but only for UKLP datasets"""
587
588
589
590
591
592
        context = {
            'model': model,
            'session': model.Session,
            'user': c.user,
        }

593
594
595
        try:
            pkg_dict = get_action('package_show')(context, {'id':id}) # has side-effect of populating context.get('package')
        except NotAuthorized:
596
            abort(401, 'Nimate pravic za ogled zbirke')
597
598

        if request.params: # POST
599
600
601
602
603
604
            if 'cancel' in request.params:
                h.redirect_to(controller='package', action='read', id=id)
            elif 'delete' in request.params:
                try:
                    package_name = pkg_dict['name']
                    get_action('package_delete')(context, {'id':id})
605
                    is_uklp = get_from_flat_dict(pkg_dict['extras'], 'UKLP') == 'True'
606
                    if is_uklp:
607
                        action = 'umaknjena'
608
609
                        resource_type = get_from_flat_dict(pkg_dict['extras'], 'resource-type') + ' record'
                    else:
610
611
612
613
                        action = 'izbrisana'
                        resource_type = 'zbirka'
                    h.flash_success(u'%s uspešno %s.' \
                                    % (resource_type, action))
614
615
616
617
618
619
620
621
622
623
624
625
626
                    self._form_save_redirect(package_name, 'edit')
                except NotAuthorized:
                    abort(401, _('Unauthorized to delete package %s') % id)
                except ObjectNotFound, e:
                    abort(404, _('Package not found'))
                except DataError:
                    abort(400, _(u'Integrity Error'))
                except SearchIndexError, e:
                    abort(500, _(u'Unable to update search index.') + repr(e.args))
                except ValidationError, e:
                    abort(400, _('Unable to delete package.') + repr(e.error_dict))
            else:
                abort(400, 'Parameter error')
627

628
629
630
631
632
633
634
635
636
        # GET
        c.pkg = context.get('package')
        try:
            check_access('package_delete', context)
        except NotAuthorized, e:
            abort(401, _('Unauthorized to delete package.'))
        package_type = self._get_package_type(id)
        self._setup_template_variables(context, {'id': id}, package_type=package_type)
        return render('package/delete.html')
637
    
638
639
640
641
642
643
644
645
646
647
    def new(self, data=None, errors=None, error_summary=None):
        context = {'model': model, 'session': model.Session,
                   'user': c.user or c.author, 'auth_user_obj': c.userobj,
                   'save': 'save' in request.params}

        # Package needs to have a organization group in the call to
        # check_access and also to save it
        try:
            check_access('package_create', context)
        except NotAuthorized, e:
648
            if 'Ne pripadate nobeni organizaciji' in str(e):
Marko Kuder's avatar
Marko Kuder committed
649
                abort(401, _(u'Ne pripadate nobeni organizaciji. Če želite objavljati, vas prosimo, da izpolnete obrazec za članstvo: %s') % urljoin(g.site_url,h.url_for(controller='ckanext.dgu.controllers.publisher:PublisherController', action='apply')))
650
651
652
            else:
                abort(401, _('Unauthorized to create a package'))
        return super(PackageController, self).new(data, errors, error_summary)
653
654
655
656
657
658
659
660
661
662

    def _tag_string_to_list(self, tag_string):
        ''' This is used to change tags from a sting to a list of dicts '''
        out = []
        for tag in opsi_tag_string_to_list(tag_string):
            if tag:
                out.append({'name': tag,
                            'state': 'active'})
        return out

663
664
665
666
667
668
669
670
671
672
    def _save_new(self, context, package_type=None):
        # The staged add dataset used the new functionality when the dataset is
        # partially created so we need to know if we actually are updating or
        # this is a real new.
        is_an_update = False
        ckan_phase = request.params.get('_ckan_phase')
        from ckan.lib.search import SearchIndexError
        try:
            data_dict = clean_dict(dict_fns.unflatten(
                tuplize_dict(parse_params(request.POST))))
673
            if request.params['save'] == u'Objavi':
674
                data_dict['state']='active'
675
                data_dict['unpublished']='False'
676
            elif request.params['save'] == u'Shrani osnutek':
677
                data_dict['state']='draft'
678
                data_dict['unpublished']='False'
679
            elif request.params['save'] == u'Pošlji v objavo':
680
                data_dict['state']='draft'
681
                data_dict['unpublished']='True'
Marko Kuder's avatar
Marko Kuder committed
682
683
684
685

            if 'tag_string' in data_dict:
                data_dict['tags'] = self._tag_string_to_list(
                    data_dict['tag_string'])
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
            if ckan_phase:
                # prevent clearing of groups etc
                context['allow_partial_update'] = True
                if data_dict.get('pkg_name'):
                    is_an_update = True
                    # This is actually an update not a save
                    data_dict['id'] = data_dict['pkg_name']
                    del data_dict['pkg_name']
                    # this is actually an edit not a save
                    pkg_dict = get_action('package_update')(context, data_dict)

                    if request.params['save'] == 'go-metadata':
                        # redirect to add metadata
                        url = h.url_for(controller='package',
                                        action='new_metadata',
                                        id=pkg_dict['name'])
                    else:
                        # redirect to add dataset resources
                        url = h.url_for(controller='package',
                                        action='new_resource',
                                        id=pkg_dict['name'])
                    redirect(url)
                # Make sure we don't index this dataset
                if request.params['save'] not in ['go-resource', 'go-metadata']:
                    data_dict['state'] = 'draft'
                # allow the state to be changed
                context['allow_state_change'] = True

            data_dict['type'] = package_type
            context['message'] = data_dict.get('log_message', '')
            pkg_dict = get_action('package_create')(context, data_dict)
            if ckan_phase:
                # redirect to add dataset resources
                url = h.url_for(controller='package',
                                action='new_resource',
                                id=pkg_dict['name'])
                redirect(url)

            self._form_save_redirect(pkg_dict['name'], 'new', package_type=package_type)
        except NotAuthorized:
            raise
            abort(401, _('Unauthorized to read package %s') % '')
        except NotFound, e:
            abort(404, _('Dataset not found'))
        except dict_fns.DataError:
            abort(400, _(u'Integrity Error'))
        except SearchIndexError, e:
            try:
                exc_str = unicode(repr(e.args))
            except Exception:  # We don't like bare excepts
                exc_str = unicode(str(e))
            abort(500, _(u'Unable to add package to search index.') + exc_str)
        except ValidationError, e:
            errors = e.error_dict
            error_summary = e.error_summary
            if is_an_update:
                # we need to get the state of the dataset to show the stage we
                # are on.
                pkg_dict = get_action('package_show')(context, data_dict)
                data_dict['state'] = pkg_dict['state']
                return self.edit(data_dict['id'], data_dict,
                                 errors, error_summary)
            data_dict['state'] = 'none'
            return self.new(data_dict, errors, error_summary)

    def _save_edit(self, name_or_id, context, package_type=None):
        from ckan.lib.search import SearchIndexError
        log.debug('Package save request name: %s POST: %r',
                  name_or_id, request.POST)
        try:
            data_dict = clean_dict(dict_fns.unflatten(
                tuplize_dict(parse_params(request.POST))))
758
            old_state = data_dict.get('state', 'active')
759
            if request.params['save'] == u'Objavi':
760
                data_dict['state']='active'
761
                data_dict['unpublished']='False'
762
            elif request.params['save'] == u'Shrani osnutek':
763
                data_dict['state']='draft'
764
                data_dict['unpublished']='False'
765
            elif request.params['save'] == u'Pošlji v objavo':
766
                data_dict['state']=old_state #leave state as is
767
                data_dict['unpublished']='True'
768
769
770
771
772
            if '_ckan_phase' in data_dict:
                # we allow partial updates to not destroy existing resources
                context['allow_partial_update'] = True
                del data_dict['_ckan_phase']
                del data_dict['save']
Marko Kuder's avatar
Marko Kuder committed
773
            if 'tag_string' in data_dict:
luka_androjna's avatar
luka_androjna committed
774
775
                data_dict['tags'] = self._tag_string_to_list(
                    data_dict['tag_string'])
776
777
778
779
780
781
782
783
784
785
            context['message'] = data_dict.get('log_message', '')
            if not context['moderated']:
                context['pending'] = False
            data_dict['id'] = name_or_id
            pkg = get_action('package_update')(context, data_dict)
            if request.params.get('save', '') == 'Approve':
                get_action('make_latest_pending_package_active')(
                    context, data_dict)
            c.pkg = context['package']
            c.pkg_dict = pkg
786
787
788
789
790
791
792
793
794
            new_creator_user = data_dict.get('creator_user_id','')
            if new_creator_user:
                role_show_dict = {'domain_object': data_dict['id'], 'roles': ['admin']}
                existing_roles = get_action('roles_show')(context, role_show_dict)
                role_update_dict_list = [{'user': new_creator_user, 'roles': ['admin']}]
                for role in existing_roles.get('roles',[]):
                    if role.get('role', '') == 'admin' and role.get('user_id','') != new_creator_user:
                        role_update_dict_list.append({'user': role.get('user_id'), 'roles': []})
                updated_roles = get_action('user_role_bulk_update')(context, {'domain_object': data_dict['id'], 'user_roles': role_update_dict_list})
Marko Kuder's avatar
Marko Kuder committed
795
            if old_state == 'active' and data_dict['state'] != 'active':
796
                refresh_drupal_themes_async(context)
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
            self._form_save_redirect(pkg['name'], 'edit', package_type=package_type)
        except NotAuthorized:
            abort(401, _('Unauthorized to read package %s') % id)
        except NotFound, e:
            abort(404, _('Dataset not found'))
        except dict_fns.DataError:
            abort(400, _(u'Integrity Error'))
        except SearchIndexError, e:
            try:
                exc_str = unicode(repr(e.args))
            except Exception:  # We don't like bare excepts
                exc_str = unicode(str(e))
            abort(500, _(u'Unable to update search index.') + exc_str)
        except ValidationError, e:
            errors = e.error_dict
            error_summary = e.error_summary
            return self.edit(name_or_id, data_dict, errors, error_summary)
814
 
815
    def _generate_admin_recipient(self, user):
816
817
        from pylons import config
        if not config.get('email_to'):
818
819
820
821
822
823
            log.error('Obvestilo o osnutku uporabnika "%s" ni bilo poslano, ker v '
                      'nastavitvah CKAN-a ni nastavljen naslov dgu.admin.email.',
                      str(c.user))
            h.flash_error(_("Napaka v sistemski konfiguraciji"))
            return None
        
824
825
        return [(config.get('error_email_from', 'OPSI Administrator'),
                           config['email_to'], 0)]
luka_androjna's avatar
luka_androjna committed
826

827
    def _send_publication_notification(self, context, pkgname):
828
829
830
        from ckan.logic.action import error_summary
        from genshi.template.text import NewTextTemplate

luka_androjna's avatar
luka_androjna committed
831
        pkg_dict = get_action('package_show')(context, {'id': pkgname})
832
        owner_id = pkg_dict['creator_user_id']
833
834
835
        owner = model.User.get(owner_id)
        owner_email = get_user_email(owner)
        owner_name = get_user_name(owner)
836
        recipient = 'objavitelj'
837
838
        if 'notification_recipient' in pkg_dict:
            recipient = pkg_dict['notification_recipient']
luka_androjna's avatar
luka_androjna committed
839
840
841
842
843

        recipients = []
        if recipient == 'oba':
            recipients = [
                {
844
845
                    'name': owner_name,
                    'email': owner_email
luka_androjna's avatar
luka_androjna committed
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
                },
                {
                    'name': pkg_dict['foi-name'],
                    'email': pkg_dict['foi-email']
                }
            ]
        elif recipient == 'skrbnik':
            recipients = [
                {
                    'name': pkg_dict['foi-name'],
                    'email': pkg_dict['foi-email']
                }
            ]
        elif recipient == 'objavitelj':
            recipients = [
                {
862
863
                    'name': owner_name,
                    'email': owner_email
luka_androjna's avatar
luka_androjna committed
864
865
866
867
868
869
                }
            ]
        for recip in recipients:
            if not recip['email']:
                log.warning("Package " + pkgname + " owner with id " + recip['name'] + " has no email, notification " +
                            "will be sent to executive editors only.")
870
871
872
873
                
        exec_editors = get_executive_editors()
        if not exec_editors:
            exec_editors =  self._generate_admin_recipient(c.user)
874
875
        for (ee_name, ee_email, ee_id) in  exec_editors:
            recipients.append({'name': ee_name, 'email': ee_email})
luka_androjna's avatar
luka_androjna committed
876

877
        view_url = urljoin(g.site_url,
luka_androjna's avatar
luka_androjna committed
878
879
                           h.url_for(controller='ckanext.dgu.controllers.package:PackageController',
                                     action='read', id=pkgname))
880
881
882
883
884

        extra_vars = {
            'executive_editor': get_user_name(c.user),
            'dataset': pkgname,
            'view_url': view_url,
luka_androjna's avatar
luka_androjna committed
885
            'editor': get_user_name(pkg_dict['creator_user_id'])
886
887
888
        }
        email_msg = render("email/publication_notification.txt", extra_vars=extra_vars,
                           loader_class=NewTextTemplate)
889

890
        try:
891
            sent_emails = [] #prevent duplicate sending if owner is also executive editor
892
            missing_emails = []
luka_androjna's avatar
luka_androjna committed
893
            for recip in recipients:
894
895
896
                if not recip['email']:
                    missing_emails = recip
                elif recip['email'] not in sent_emails:
897
                    mail_recipient(recip['name'],
luka_androjna's avatar
luka_androjna committed
898
                               recip['email'],
899
900
                               subject='Obvestilo o objavi',
                               body=email_msg)
901
                    sent_emails.append(recip['email'])
902
            log.debug('User "%s" published %s, notification was sent to %s',
luka_androjna's avatar
luka_androjna committed
903
                      c.user, pkgname, recipients)
904
905
            if missing_emails:
                log.error('Notification to recipients %s rejected, because of missing email addresses.', missing_emails)
906
        except Exception, e:
luka_androjna's avatar
luka_androjna committed
907
908
909
910
911
912
913
            contact_url = config.get('ckan.site_url', 'https://podatki.gov.si') + '/kontakt'
            h.flash_error(
                u'Pri pošiljanju vašega zahtevka je prišlo do napake. Prosimo, da nas o tem obvestite s <a href="' + contact_url + u'">kontaktnim obrazcem</a> na naši strani.',
                allow_html=True)
            log.error(
                'User "%s" prevented from sending publication notification to recipients %s because of mail configuration error: %s',
                c.user, str(recipients), e)
914
915
916

    def _on_publish(self, context, pkgname):
        self._send_publication_notification(context, pkgname)
917
        refresh_drupal_themes_async(context)
918
919
920
921
922
 
    def _send_draft_notification(self, pkgname):
        from ckan.logic.action import error_summary
        from genshi.template.text import NewTextTemplate

923
924
925
926
927
928
        recipients = get_executive_editors()
        if not recipients:
            recipients =  self._generate_admin_recipient(c.user)
            if not recipients:
                return
            
929
        view_url = urljoin(g.site_url,
930
931
932
            h.url_for(controller='ckanext.dgu.controllers.package:PackageController',
                      action='read', id=pkgname))
        
933
        edit_url = urljoin(g.site_url,
934
935
            h.url_for(controller='ckanext.dgu.controllers.package:PackageController',
                      action='edit', id=pkgname))
936
937
938
939

        log.debug('User "%s" requested publication of draft %s, notification was sent to admin %s',
                  c.user, pkgname, recipients)
        extra_vars = {
940
            'user': get_user_name(c.user),
941
            'dataset': pkgname,
942
943
            'view_url': view_url,
            'edit_url': edit_url
944
945
946
947
948
        }
        email_msg = render("email/draft_publication_request.txt", extra_vars=extra_vars,
                           loader_class=NewTextTemplate)

        try:
Marko Kuder's avatar
Marko Kuder committed
949
            sent_emails = []
950
            for (name,email,id) in recipients:
951
                if email and email not in sent_emails:
952
953
954
955
956
                    mail_recipient(name,
                                   email,
                                   subject='Obvestilo o novem osnutku',
                                   body=email_msg)
                    sent_emails.append(email)
957
        except Exception, e:
958
959
960
            contact_url = config.get('ckan.site_url', 'https://podatki.gov.si')+'/kontakt'
            h.flash_error(u'Pri pošiljanju vašega zahtevka glavnim urednikom je prišlo do napake. Prosimo, da nas o tem obvestite s <a href="' + contact_url + u'">kontaktnim obrazcem</a> na naši strani.', allow_html=True)
            log.error('User "%s" prevented from sending draft confirmation because of mail configuration error: %s', c.user, e)
luka_androjna's avatar
luka_androjna committed
961

962
        h.flash_success(u'Vaš zahtevek za objavo zbirke \'%s\' je bil poslan glavnim urednikom v potrditev. Ob spremembi stanja boste dobili obvestilo.' % pkgname, allow_html=True)
963

964
    def _form_save_redirect(self, pkgname, action, package_type=None):
965
966
967
        context = {'model': model, 'session': model.Session,
                   'user': c.user or c.author, 'auth_user_obj': c.userobj,
                   'publish': True}
Marko Kuder's avatar
Marko Kuder committed
968
        if 'save' in request.params:
969
            if request.params['save'] == u'Objavi':
970
                log.debug('Save request from form')
971
                self._on_publish(context, pkgname)
972
            elif request.params['save'] == u'Shrani osnutek':
973
                log.debug('Draft request from form')
974
            elif request.params['save'] == u'Pošlji v objavo':
975
                log.debug('Send request from form')
976
                self._send_draft_notification(pkgname)
977
            refresh_opsi_reports_async()
Marko Kuder's avatar
Marko Kuder committed
978
        elif 'delete' in request.params:
979
            refresh_drupal_themes_async(context)
Marko Kuder's avatar
Marko Kuder committed
980
            log.debug('Deleted package '+str(pkgname))
981
        else:
Marko Kuder's avatar
Marko Kuder committed
982
            log.debug('Package '+str(pkgname)+' redirecting.')
983
        return super(PackageController, self)._form_save_redirect(pkgname, action, package_type=None)
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
    
    def opsi_resource_download(self, id, resource_id, filename=None):
        """
        Provides a direct download by either redirecting the user to the url stored
         or downloading an uploaded file directly.
        """
        context = {'model': model, 'session': model.Session,
                   'user': c.user or c.author, 'auth_user_obj': c.userobj}

        try:
            rsc = get_action('resource_show')(context, {'id': resource_id})
            pkg = get_action('package_show')(context, {'id': id})
        except NotFound:
            abort(404, _('Resource not found'))
        except NotAuthorized:
            abort(401, _('Unauthorized to read resource %s') % id)

        if rsc.get('url_type') == 'upload':
            upload = uploader.ResourceUpload(rsc)
            filepath = upload.get_path(rsc['id'])
            log.debug('File path to retrieve: '+filepath)
            fileapp = paste.fileapp.FileApp(filepath)
            try:
               status, headers, app_iter = request.call_application(fileapp)
            except OSError:
               abort(404, _('Resource data not found'))
            response.headers.update(dict(headers))
            content_type, content_enc = mimetypes.guess_type(rsc.get('url',''))
            if content_type:
                response.headers['Content-Type'] = content_type
            response.status = status
            return app_iter
        elif not 'url' in rsc:
            abort(404, _('No download is available'))
        redirect(rsc['url'])
1019
1020
1021
1022
1023
1024

class CommentProxy(BaseController):
    '''A proxy to Drupal on another server to provide comment HTML. Useful only
    for test purposes, when Drupal is not present locally.
    '''
    def get_comments(self, id):
1025
        url = 'https://podatki.gov.si/comment/get/5b3267d8-4307-4eef-a9af-3a4c28224694?comments_per_page=999999'
David Read's avatar
David Read committed
1026
1027
        #url = 'http://co-dev1.dh.bytemark.co.uk/comment/get/%s' % quote(id)
        return self._read_url(url)
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043

    def _read_url(self, url, post_data=None, content_type=None):
        headers = {'Content-Type': content_type} if content_type else {}
        request = urllib2.Request(url, post_data, headers)
        try:
            f = urllib2.urlopen(request)
        except HTTPError, e:
            response.status_int = 400
            return 'Proxied server returned %s: %s' % (e.code, e.msg)
        except URLError, e:
            err = str(e)
            if 'Connection timed out' in err:
                response.status_int = 504
                return 'Proxied server timed-out: %s' % err
            raise e # Send an exception email to handle it better
        return f.read()