def read_one_history(request): # Handle the parameters (locale, profile) bv = BaseView(request) bv._handle_parameters() try: output_format = request.matchdict['output'] except KeyError: output_format = 'html' uid = request.matchdict.get('uid', None) if check_valid_uuid(uid) is not True: raise HTTPNotFound() isLoggedIn, isModerator = checkUserPrivileges(request) stakeholders, count = stakeholder_protocol3.read_one_history( request, uid=uid) activeVersion = None for sh in stakeholders: if 'statusName' in sh: sh['statusName'] = get_translated_status(request, sh['statusName']) if sh.get('statusId') == 2: activeVersion = sh.get('version') templateValues = { 'versions': stakeholders, 'count': count, 'activeVersion': activeVersion, 'isModerator': isModerator } templateValues.update({ 'profile': get_current_profile(request), 'locale': get_current_locale(request) }) if output_format == 'html': template = 'stakeholders/history.mak' # RSS feed output elif output_format == 'rss': template = 'stakeholders/history_rss.mak' else: raise HTTPNotFound("Requested output format is not supported.") return render_to_response(getTemplatePath(request, template), templateValues, request)
def read_one(request): """ Read one Stakeholder based on ID and return all versions of this Stakeholder. Also return pending versions by currently logged in user and all pending versions of this Stakeholder if logged in as moderator. Default output format: JSON """ # Handle the parameters (locale, profile) bv = BaseView(request) bv._handle_parameters() try: output_format = request.matchdict['output'] except KeyError: output_format = 'json' uid = request.matchdict.get('uid', None) if check_valid_uuid(uid) is not True: raise HTTPNotFound() if output_format == 'json': stakeholders = stakeholder_protocol3.read_one(request, uid=uid, public=False) return render_to_response('json', stakeholders, request) elif output_format == 'html': # Show the details of a Stakeholder by rendering the form in readonly # mode. stakeholders = stakeholder_protocol3.read_one(request, uid=uid, public=False, translate=False) version = request.params.get('v', None) if (stakeholders and 'data' in stakeholders and len(stakeholders['data']) != 0): for sh in stakeholders['data']: if 'version' in sh: if version is None: # If there is no version provided, show the first # version visible to the user version = str(sh['version']) if str(sh['version']) == version: templateValues = renderReadonlyForm(request, 'stakeholders', sh) templateValues['profile'] = get_current_profile(request) templateValues['locale'] = get_current_locale(request) # Append the short uid and the uid to the templates values templateValues['uid'] = uid templateValues['shortuid'] = uid.split("-")[0] # Append also the site key from the commenting system templateValues['site_key'] = comments_sitekey(request)['site_key'] # and the url of the commenting system templateValues['comments_url'] = request.registry.settings['lmkp.comments_url'] return render_to_response( getTemplatePath(request, 'stakeholders/details.mak'), templateValues, request ) return HTTPNotFound() elif output_format == 'form': if request.user is None: # Make sure the user is logged in raise HTTPForbidden() # Query the Stakeholders with the given identifier stakeholders = stakeholder_protocol3.read_one(request, uid=uid, public=False, translate=False) version = request.params.get('v', None) if (stakeholders and 'data' in stakeholders and len(stakeholders['data']) != 0): for sh in stakeholders['data']: if 'version' in sh: if version is None: # If there is no version provided, show the first # version visible to the user version = str(sh['version']) if str(sh['version']) == version: templateValues = renderForm(request, 'stakeholders', itemJson=sh) if isinstance(templateValues, Response): return templateValues templateValues['profile'] = get_current_profile(request) templateValues['locale'] = get_current_locale(request) return render_to_response( getTemplatePath(request, 'stakeholders/form.mak'), templateValues, request ) return HTTPNotFound() elif output_format in ['review', 'compare']: if output_format == 'review': # Only moderators can see the review page. isLoggedIn, isModerator = checkUserPrivileges(request) if isLoggedIn is False or isModerator is False: raise HTTPForbidden() camefrom = request.params.get('camefrom', '') review = StakeholderReview(request) availableVersions = None recalculated = False defaultRefVersion, defaultNewVersion = review._get_valid_versions( Stakeholder, uid) refVersion = request.params.get('ref', None) if refVersion is not None: try: refVersion = int(refVersion) except: refVersion = None if refVersion is None or output_format == 'review': # No reference version indicated, use the default one # Also use the default one for review because it cannot be changed. refVersion = defaultRefVersion else: availableVersions = review._get_available_versions(Stakeholder, uid, review=output_format=='review') # Check if the indicated reference version is valid if refVersion not in [v.get('version') for v in availableVersions]: refVersion = defaultRefVersion newVersion = request.params.get('new', None) if newVersion is not None: try: newVersion = int(newVersion) except: newVersion = None if newVersion is None: # No new version indicated, use the default one newVersion = defaultNewVersion else: if availableVersions is None: availableVersions = review._get_available_versions(Stakeholder, uid, review=output_format=='review') # Check if the indicated new version is valid if newVersion not in [v.get('version') for v in availableVersions]: newVersion = defaultNewVersion if output_format == 'review': # If the Stakeholders are to be reviewed, only the changes which # were applied to the newVersion are of interest stakeholders, recalculated = review.get_comparison(Stakeholder, uid, refVersion, newVersion) else: # If the Stakeholders are compared, the versions as they are stored # in the database are of interest, without any recalculation stakeholders = [ stakeholder_protocol3.read_one_by_version(request, uid, refVersion, translate=False ), stakeholder_protocol3.read_one_by_version(request, uid, newVersion, translate=False ) ] templateValues = renderReadonlyCompareForm(request, 'stakeholders', stakeholders[0], stakeholders[1], review=output_format=='review') # Collect metadata for the reference version refMetadata = {} if stakeholders[0] is not None: refMetadata = stakeholders[0].get_metadata(request) # Collect metadata and missing keys for the new version newMetadata = {} missingKeys = [] reviewable = False if stakeholders[1] is not None: stakeholders[1].mark_complete(get_mandatory_keys(request, 'sh', False)) missingKeys = stakeholders[1]._missing_keys localizer = get_localizer(request) if localizer.locale_name != 'en': db_lang = Session.query(Language).filter(Language.locale == localizer.locale_name).first() missingKeys = get_translated_db_keys(SH_Key, missingKeys, db_lang) missingKeys = [m[1] for m in missingKeys] newMetadata = stakeholders[1].get_metadata(request) reviewable = (len(missingKeys) == 0 and 'reviewableMessage' in templateValues and templateValues['reviewableMessage'] is None) if output_format == 'review': pendingVersions = [] if availableVersions is None: availableVersions = review._get_available_versions(Stakeholder, uid, review=output_format=='review') for v in sorted(availableVersions, key=lambda v:v.get('version')): if v.get('status') == 1: pendingVersions.append(v.get('version')) templateValues['pendingVersions'] = pendingVersions templateValues.update({ 'identifier': uid, 'refVersion': refVersion, 'refMetadata': refMetadata, 'newVersion': newVersion, 'newMetadata': newMetadata, 'missingKeys': missingKeys, 'reviewable': reviewable, 'recalculated': recalculated, 'camefrom': camefrom, 'profile': get_current_profile(request), 'locale': get_current_locale(request) }) if output_format == 'review': return render_to_response( getTemplatePath(request, 'stakeholders/review.mak'), templateValues, request ) else: return render_to_response( getTemplatePath(request, 'stakeholders/compare.mak'), templateValues, request ) elif output_format == 'formtest': # Test if a Stakeholder is valid according to the form configuration stakeholders = stakeholder_protocol3.read_one(request, uid=uid, public=False, translate=False) version = request.params.get('v', None) if (stakeholders and 'data' in stakeholders and len(stakeholders['data']) != 0): for sh in stakeholders['data']: if 'version' in sh: if version is None: version = str(sh['version']) if str(sh['version']) == version: categorylist = getCategoryList(request, 'stakeholders') return render_to_response('json', checkValidItemjson(categorylist, sh), request) return HTTPNotFound() else: # If the output format was not found, raise 404 error raise HTTPNotFound()
def read_many(request): """ Read many, returns also pending Activities by currently logged in user and all pending Activities if logged in as moderator. Default output format: JSON """ # Handle the parameters (locale, profile) bv = BaseView(request) bv._handle_parameters() try: output_format = request.matchdict['output'] except KeyError: output_format = 'json' if output_format == 'json': activities = activity_protocol3.read_many(request, public=False) return render_to_response('json', activities, request) elif output_format == 'html': """ Show a HTML representation of the Activities in a grid. """ # Get page parameter from request and make sure it is valid page = request.params.get('page', 1) try: page = int(page) except: page = 1 page = max(page, 1) # Page should be >= 1 # Get pagesize parameter from request and make sure it is valid pageSize = request.params.get('pagesize', 10) try: pageSize = int(pageSize) except: pageSize = 10 pageSize = max(pageSize, 1) # Page size should be >= 1 pageSize = min(pageSize, 50) # Page size should be <= 50 # Spatial filter spatialfilter = _handle_spatial_parameters(request) # Query the items with the protocol items = activity_protocol3.read_many(request, public=False, limit=pageSize, offset=pageSize*page-pageSize) statusFilter = request.params.get('status', None) isLoggedIn, isModerator = checkUserPrivileges(request) return render_to_response(getTemplatePath(request, 'activities/grid.mak'), { 'data': items['data'] if 'data' in items else [], 'total': items['total'] if 'total' in items else 0, 'profile': get_current_profile(request), 'locale': get_current_locale(request), 'spatialfilter': spatialfilter, 'invfilter': None, 'statusfilter': statusFilter, 'currentpage': page, 'pagesize': pageSize, 'isModerator': isModerator }, request) elif output_format == 'form': # This is used to display a new and empty form for an Activity if request.user is None: # Make sure the user is logged in raise HTTPForbidden() newInvolvement = request.params.get('inv', None) templateValues = renderForm(request, 'activities', inv=newInvolvement) if isinstance(templateValues, Response): return templateValues templateValues.update({ 'uid': '-', 'version': 0, 'profile': get_current_profile(request), 'locale': get_current_locale(request) }) return render_to_response( getTemplatePath(request, 'activities/form.mak'), templateValues, request ) elif output_format == 'geojson': activities = activity_protocol3.read_many_geojson(request, public=False) return render_to_response('json', activities, request) else: # If the output format was not found, raise 404 error raise HTTPNotFound()
def downloadAll(request): """ """ # Handle the parameters (locale, profile) bv = BaseView(request) bv._handle_parameters() # get all keys for heading line a_keys = activity_protocol3.read_all_keys(request)["data"] sh_keys = stakeholder_protocol3.read_all_keys(request)["data"] sh_values_empty = [None]*len(sh_keys) # spatial filter _handle_spatial_parameters(request) activities = activity_protocol3.read_many(request, public=False, offset=0, limit=9999) rows = [] value, year = None, None # detect the maximum count of Secondary investors max_involvements = max([len(filter(lambda i: i.get("role", "") == "Secondary Investor", a.get("involvements", []))) for a in activities.get("data", [])]) for a in activities.get("data", []): activity = [] for key in ACTIVITY_HEADER: if key == "geometry": activity.append(",".join(map(str, a.get(key, {}).get("coordinates", [])))) else: activity.append(a.get(key, None)) # look for all activity values for a_key in a_keys: for tg in a.get("taggroups", []): value, year = None, None for t in tg.get("tags", []): if t.get("key") == "Year": year = t.get("value") elif t.get("key") == a_key: value = t.get("value", None) if value and year: activity.append(unicode("%s (%s)" % (value, year)).encode("utf-8")) break elif value: activity.append(unicode("%s" % value).encode("utf-8")) break if not value: activity.append(None) # look for Investor values investor_value = None # limit Investors to maximum of one for i in filter(lambda i: i.get("role", "") == "Investor", a.get("involvements", []))[:1]: for s_key in sh_keys: for tg in i.get("data").get("taggroups", []): investor_value = None for t in tg.get("tags", []): if t.get("key") == s_key: investor_value = t.get("value", None) if investor_value: activity.append(unicode("%s" % investor_value).encode("utf-8")) break if not investor_value: activity.append(None) # look for all Secondary Investor values investor_value = None secondary_investors = filter(lambda i: i.get("role", "") == "Secondary Investor", a.get("involvements", [])) for i in range(1, max_involvements + 1): if i <= len(secondary_investors): si = secondary_investors[i-1] for s_key in sh_keys: for tg in si.get("data").get("taggroups", []): investor_value = None for t in tg.get("tags", []): if t.get("key") == s_key: investor_value = t.get("value", None) if investor_value: activity.append(unicode("%s" % investor_value).encode("utf-8")) break if not investor_value: activity.append(None) else: activity.extend(sh_values_empty) rows.append(activity) HEADER = ACTIVITY_HEADER + a_keys HEADER = HEADER + ["Investor: %s" % sv for sv in sh_keys] for i in range(1, max_involvements + 1): HEADER = HEADER + ["%i. Secondary Investor: %s" % (i, sv) for sv in sh_keys] HEADER = [unicode(h).encode("utf-8") for h in HEADER] result = { "header": HEADER, "rows": rows, } return result
def read_one(request): """ Read one Activity based on ID and return all versions of this Activity. Also return pending versions by currently logged in user and all pending versions of this Activity if logged in as moderator. Default output format: JSON """ # Handle the parameters (locale, profile) bv = BaseView(request) bv._handle_parameters() try: output_format = request.matchdict['output'] except KeyError: output_format = 'json' uid = request.matchdict.get('uid', None) if check_valid_uuid(uid) is not True: raise HTTPNotFound() if output_format == 'json': activities = activity_protocol3.read_one(request, uid=uid, public=False) return render_to_response('json', activities, request) elif output_format == 'html': # Show the details of an Activity by rendering the form in readonly # mode. activities = activity_protocol3.read_one(request, uid=uid, public=False, translate=False) version = request.params.get('v', None) if activities and 'data' in activities and len(activities['data']) != 0: for a in activities['data']: if 'version' in a: if version is None: # If there was no version provided, show the first # version visible to the user version = str(a['version']) if str(a['version']) == version: templateValues = renderReadonlyForm(request, 'activities', a) templateValues['profile'] = get_current_profile(request) templateValues['locale'] = get_current_locale(request) # Append the short uid and the uid to the templates values templateValues['uid'] = uid templateValues['version'] = version templateValues['shortuid'] = uid.split("-")[0] # Append also the site key from the commenting system templateValues['site_key'] = comments_sitekey(request)['site_key'] # and the url of the commenting system templateValues['comments_url'] = request.registry.settings['lmkp.comments_url'] return render_to_response( getTemplatePath(request, 'activities/details.mak'), templateValues, request ) return HTTPNotFound() elif output_format == 'form': if request.user is None: # Make sure the user is logged in raise HTTPForbidden() # Query the Activities wih the given identifier activities = activity_protocol3.read_one(request, uid=uid, public=False, translate=False) version = request.params.get('v', None) if activities and 'data' in activities and len(activities['data']) != 0: for a in activities['data']: if 'version' in a: if version is None: # If there was no version provided, show the first # version visible to the user version = str(a['version']) if str(a['version']) == version: templateValues = renderForm(request, 'activities', itemJson=a) if isinstance(templateValues, Response): return templateValues templateValues['profile'] = get_current_profile(request) templateValues['locale'] = get_current_locale(request) templateValues['uid'] = uid templateValues['version'] = version return render_to_response( getTemplatePath(request, 'activities/form.mak'), templateValues, request ) return HTTPNotFound() elif output_format in ['review', 'compare']: if output_format == 'review': # Only moderators can see the review page. isLoggedIn, isModerator = checkUserPrivileges(request) if isLoggedIn is False or isModerator is False: raise HTTPForbidden() review = ActivityReview(request) availableVersions = None recalculated = False defaultRefVersion, defaultNewVersion = review._get_valid_versions( Activity, uid) refVersion = request.params.get('ref', None) if refVersion is not None: try: refVersion = int(refVersion) except: refVersion = None if refVersion is None or output_format == 'review': # No reference version indicated, use the default one # Also use the default one for review because it cannot be changed. refVersion = defaultRefVersion else: availableVersions = review._get_available_versions(Activity, uid, review=output_format == 'review') # Check if the indicated reference version is valid if refVersion not in [v.get('version') for v in availableVersions]: refVersion = defaultRefVersion newVersion = request.params.get('new', None) if newVersion is not None: try: newVersion = int(newVersion) except: newVersion = None if newVersion is None: # No new version indicated, use the default one newVersion = defaultNewVersion else: if availableVersions is None: availableVersions = review._get_available_versions(Activity, uid, review=output_format == 'review') # Check if the indicated new version is valid if newVersion not in [v.get('version') for v in availableVersions]: newVersion = defaultNewVersion if output_format == 'review': # If the Activities are to be reviewed, only the changes which were # applied to the newVersion are of interest activities, recalculated = review.get_comparison(Activity, uid, refVersion, newVersion) else: # If the Activities are compared, the versions as they are stored # in the database are of interest, without any recalculation activities = [ activity_protocol3.read_one_by_version(request, uid, refVersion, geometry='full', translate=False ), activity_protocol3.read_one_by_version(request, uid, newVersion, geometry='full', translate=False ) ] templateValues = renderReadonlyCompareForm(request, 'activities', activities[0], activities[1], review=output_format == 'review') # Collect metadata for the reference version refMetadata = {} if activities[0] is not None: refMetadata = activities[0].get_metadata(request) # Collect metadata and missing keys for the new version newMetadata = {} missingKeys = [] reviewable = False if activities[1] is not None: activities[1].mark_complete(get_mandatory_keys(request, 'a', False)) missingKeys = activities[1]._missing_keys localizer = get_localizer(request) if localizer.locale_name != 'en': db_lang = Session.query(Language).filter(Language.locale == localizer.locale_name).first() missingKeys = get_translated_db_keys(A_Key, missingKeys, db_lang) missingKeys = [m[1] for m in missingKeys] newMetadata = activities[1].get_metadata(request) reviewable = (len(missingKeys) == 0 and 'reviewableMessage' in templateValues and templateValues['reviewableMessage'] is None) if output_format == 'review': pendingVersions = [] if availableVersions is None: availableVersions = review._get_available_versions(Activity, uid, review=output_format == 'review') for v in sorted(availableVersions, key=lambda v:v.get('version')): if v.get('status') == 1: pendingVersions.append(v.get('version')) templateValues['pendingVersions'] = pendingVersions templateValues.update({ 'identifier': uid, 'refVersion': refVersion, 'refMetadata': refMetadata, 'newVersion': newVersion, 'newMetadata': newMetadata, 'missingKeys': missingKeys, 'reviewable': reviewable, 'recalculated': recalculated, 'profile': get_current_profile(request), 'locale': get_current_locale(request) }) if output_format == 'review': return render_to_response( getTemplatePath(request, 'activities/review.mak'), templateValues, request ) else: return render_to_response( getTemplatePath(request, 'activities/compare.mak'), templateValues, request ) elif output_format == 'geojson': # A version is required version = request.params.get('v', None) if version is None: raise HTTPBadRequest('You must specify a version as parameter ?v=X') translate = request.params.get('translate', 'true').lower() == 'true' activities = activity_protocol3.read_one_geojson_by_version(request, uid, version, translate=translate) return render_to_response('json', activities, request) elif output_format == 'formtest': # Test if an Activity is valid according to the form configuration activities = activity_protocol3.read_one(request, uid=uid, public=False, translate=False) version = request.params.get('v', None) if activities and 'data' in activities and len(activities['data']) != 0: for a in activities['data']: if 'version' in a: if version is None: version = str(a['version']) if str(a['version']) == version: categorylist = getCategoryList(request, 'activities') return render_to_response('json', checkValidItemjson(categorylist, a), request) return HTTPNotFound() # Output the areal statistics for the requested activity based on the # Web Processing Service elif output_format == 'statistics': # Try to get the base URL to the web processing service which provides # the areal statistics. # If no web processing service is configured, it is assumed that the # platform does not provide the areal statistics try: wps_host = request.registry.settings['lmkp.base_wps'] except KeyError: raise HTTPNotFound() spatial_accuracy_map = get_spatial_accuracy_map(request) # Check if the spatial accuracy map is configured in the application.yml # file if spatial_accuracy_map is None: raise HTTPNotFound() # Show the details of an Activity by rendering the form in readonly # mode. activities = activity_protocol3.read_one(request, uid=uid, public=False, translate=False) activity = activities['data'][0] coords = activity['geometry']['coordinates'] for taggroup in activity['taggroups']: if taggroup['main_tag']['key'] == _(u"Spatial Accuracy"): spatial_accuracy = taggroup['main_tag']['value'] buffer = spatial_accuracy_map[spatial_accuracy] wps_parameters = { "ServiceProvider": "", "metapath": "", "Service": "WPS", "Request": "Execute", "Version": "1.0.0", "Identifier": "BufferStatistics", "DataInputs": "lon=%s;lat=%s;epsg=4326;buffer=%s" % (coords[0], coords[1], buffer), "RawDataOutput": 'bufferstatistics@mimeType=application/json' } if not wps_host.endswith("?"): wps_host = "%s?" % wps_host for k, v in wps_parameters.items(): wps_host = "%s%s=%s&" % (wps_host, k, v) log.debug("Accessing: %s" % wps_host) try: handle = urllib.urlopen(wps_host) except IOError: return HTTPInternalServerError("Remote server not accessible.") templateValues = json.loads(handle.read()) templateValues['uid'] = uid templateValues['shortuid'] = uid.split("-")[0] return render_to_response( getTemplatePath(request, 'activities/statistics.mak'), templateValues, request ) else: # If the output format was not found, raise 404 error raise HTTPNotFound()