[Mapbender-commits] r8568 - in trunk/mapbender/http: classes php
svn_mapbender at osgeo.org
svn_mapbender at osgeo.org
Sat Feb 23 12:51:56 PST 2013
Author: armin11
Date: 2013-02-23 12:51:55 -0800 (Sat, 23 Feb 2013)
New Revision: 8568
Added:
trunk/mapbender/http/classes/class_ckan.php
trunk/mapbender/http/classes/class_ckanApi.php
trunk/mapbender/http/php/mod_exportMapbenderLayer2CkanObjects.php
trunk/mapbender/http/php/mod_syncCkan.php
Log:
Initial commit for push api to ckan instance. Tested with ckan 1.8.1b. Uses different api versions (also action api is supported). Not yet ready! It syncs mapbender layer objects to a ckan datamodel. A central group is defined for the mapbender instance. Well be further developed next week.
Added: trunk/mapbender/http/classes/class_ckan.php
===================================================================
--- trunk/mapbender/http/classes/class_ckan.php (rev 0)
+++ trunk/mapbender/http/classes/class_ckan.php 2013-02-23 20:51:55 UTC (rev 8568)
@@ -0,0 +1,77 @@
+<?php
+# http://www.mapbender.org/index.php/class_ckanPackage.php
+# Copyright (C) 2002 CCGIS
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2, or (at your option)
+# any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+require_once(dirname(__FILE__)."/../../core/globalSettings.php");
+
+class ckanPackage {
+ var $id;
+ var $name;
+ var $title;
+ var $resources;
+ var $author;
+ var $maintainer;
+ var $maintainer_email;
+ var $licence_id;
+ var $tags;
+ var $notes;
+ var $extras;
+
+ function __construct() {
+ //initialize empty ckanPackage object
+ //attributes which are handled by ckan itself
+ //$this->id = "";
+ //attributes which are handled by external datasources
+ $this->name = "";
+ $this->title = "";
+ $this->resources = array();
+ $this->author = "";
+ $this->author_email = "";
+ $this->maintainer = "";
+ $this->maintainer_email = "";
+ $this->licence_id = "";
+ $this->tags = "";//list
+ $this->notes = "";
+ $this->extras = "";//{ Name-String: String, ... } }
+ }
+
+ public function toSomething ($xml) {
+
+ return $xml;
+ }
+}
+class ckanGroup {
+ var $id;
+ var $name;
+ var $title;
+ var $packages;
+
+ function __construct() {
+ //initialize empty ckanGroup object
+ //attributes which are handled by ckan itself
+ //$this->id = "";
+ //attributes which are handled by external datasources
+ $this->name = "";
+ $this->title = "";
+ $this->packages = "";//list of datasets(packages)
+ }
+
+ public function toSomething ($xml) {
+ return $xml;
+ }
+}
+
+?>
Added: trunk/mapbender/http/classes/class_ckanApi.php
===================================================================
--- trunk/mapbender/http/classes/class_ckanApi.php (rev 0)
+++ trunk/mapbender/http/classes/class_ckanApi.php 2013-02-23 20:51:55 UTC (rev 8568)
@@ -0,0 +1,932 @@
+<?php
+/**
+ * Copyright (c) 2010 Jeffrey Barke <http://jeffreybarke.net/>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+ * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+ * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * Based on following software:
+ * A PHP client for the CKAN (Comprehensive Knowledge Archive Network) API.
+ *
+ * For details and documentation, please see http://github.com/jeffreybarke/Ckan_client-PHP
+ * @author Jeffrey Barke
+ * @copyright Copyright 2010 Jeffrey Barke
+ * @license http://github.com/jeffreybarke/Ckan_client-PHP/blob/master/LICENSE
+ * @link http://github.com/jeffreybarke/Ckan_client-PHP
+ *
+ */
+
+require_once(dirname(__FILE__) . "/../../core/globalSettings.php");
+
+class ckanApi
+{
+
+ // Properties ---------------------------------------------------------
+
+ /**
+ * Client's API key. Required for any PUT or POST methods.
+ *
+ * @link http://knowledgeforge.net/ckan/doc/ckan/api.html#ckan-api-keys
+ */
+ public $api_key = FALSE;
+
+ /**
+ * Servers Host IP. Required for any PUT or POST methods.
+ *
+ * @link http://knowledgeforge.net/ckan/doc/ckan/api.html#ckan-api-keys
+ */
+ public $host_name = FALSE;
+
+ /**
+ * Version of the CKAN API we're using.
+ *
+ * @var string
+ * @link http://knowledgeforge.net/ckan/doc/ckan/api.html#api-versions
+ */
+ private $api_version = '2';
+
+ /**
+ * URI to the CKAN web service.
+ *
+ * @var string
+ */
+ public $base_url = 'http://ckan.net/api/%d/';
+
+ /**
+ * Internal cURL object.
+ *
+ */
+ private $ch = FALSE;
+
+ /**
+ * cURL headers.
+ *
+ */
+ private $ch_headers;
+
+ /**
+ * Standard HTTP status codes.
+ *
+ * @var array
+ */
+ private $http_status_codes = array(
+ '200' => 'OK',
+ '201' => 'OK - package created successfully!',
+ '301' => 'Moved Permanently',
+ '400' => 'Bad Request',
+ '403' => 'Not Authorized',
+ '404' => 'Not Found',
+ '409' => 'Conflict (e.g. name already exists)',
+ '500' => 'Service Error'
+ );
+
+ /**
+ * Array of CKAN resources and their URI fragment.
+ *
+ * @var array
+ * @link http://knowledgeforge.net/ckan/doc/ckan/api.html#ckan-model-api
+ */
+ private $resources = array(
+ 'package_register' => 'rest/package',
+ 'package_entity' => 'rest/package',
+ 'group_register' => 'rest/group',
+ 'group_entity' => 'rest/group',
+ 'tag_register' => 'rest/tag',
+ 'tag_entity' => 'rest/tag',
+ 'rating_register' => 'rest/rating',
+ 'rating_entity' => 'rest/rating',
+ 'revision_register' => 'rest/revision',
+ 'revision_entity' => 'rest/revision',
+ 'license_list' => 'rest/licenses',
+ 'package_search' => 'search/package'
+ );
+
+ /**
+ * Array of CKAN resources and their URI fragment.
+ *
+ * @var array
+ * @link http://knowledgeforge.net/ckan/doc/ckan/api.html#ckan-model-api
+ */
+ private $actionList = array(
+ 'package_create' => 'action/package_create',
+ 'package_show' => 'action/package_show',
+ 'package_update' => 'action/package_update',
+ 'package_delete' => 'action/package_delete',
+ 'resource_create' => 'action/resource_create',
+ 'resource_show' => 'action/resource_show',
+ 'resource_update' => 'action/resource_update',
+ 'resource_delete' => 'action/resource_delete',
+ 'organization_create' => 'action/organization_create',
+ 'organization_show' => 'action/organization_show',
+ 'organization_update' => 'action/organization_update',
+ 'organization_delete' => 'action/organization_delete',
+ 'group_create' => 'action/group_create',
+ 'group_update' => 'action/group_update',
+ 'group_delete' => 'action/group_delete',
+ 'group_show' => 'action/group_show',
+ 'group_package_show' => 'action/group_package_show',
+ 'member_create' => 'action/member_create',
+ 'roles_show' => 'action/roles_show',
+ 'member_create' => 'action/member_create',
+ 'member_delete' => 'action/member_delete',
+ 'roles_show' => 'action/roles_show',
+ 'package_owner_org_update' => 'package_owner_org_update',
+ 'group_list_authz' => 'action/group_list_authz'
+ );
+
+ /**
+ * ckanApi user agent string.
+ *
+ * @var string
+
+ */
+ private $user_agent = CONNECTION_USERAGENT;
+
+ // Magic methods ------------------------------------------------------
+
+ /**
+ * Constructor
+ *
+ * Calls the API key, base URI and user agent setters.
+ * Initializes the internal cURL object.
+ *
+ * @param string CKAN API key.
+ */
+ public function __construct($api_key = FALSE,$host_name = FALSE)
+ {
+ // If provided, set the API key.
+ if ($api_key)
+ {
+ $this->set_api_key($api_key);
+ }
+ // If provided, set the Name of host to call - needed for decide if proxy should be used.
+ if ($host_name)
+ {
+ $e = new mb_exception($host_name);
+ $this->set_host_name($host_name);
+ }
+ // Set base URI and Ckan_client user agent string.
+ $this->set_base_url();
+ $this->set_user_agent();
+ // Create cURL object.
+ $this->ch = curl_init();
+ $e = new mb_exception($this->host_name);
+ $NOT_PROXY_HOSTS_array = explode(",", NOT_PROXY_HOSTS);
+
+ if(CONNECTION_PROXY != "" AND (in_array($this->host_name, $NOT_PROXY_HOSTS_array)!= true)){
+ curl_setopt($this->ch, CURLOPT_PROXY,CONNECTION_PROXY.":".CONNECTION_PORT);
+ $e = new mb_notice("class_ckanApi.php: Proxy will be used!");
+ if(CONNECTION_PASSWORD != ""){
+ curl_setopt ($this->ch, CURLOPT_PROXYUSERPWD, CONNECTION_USER.':'.CONNECTION_PASSWORD);
+ }
+ } else {
+ $e = new mb_notice("class_ckanApi.php: Proxy will not be used!");
+ }
+ // Follow any Location: headers that the server sends.
+ curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, TRUE);
+ // However, don't follow more than five Location: headers.
+ curl_setopt($this->ch, CURLOPT_MAXREDIRS, 5);
+ // Automatically set the Referer: field in requests
+ // following a Location: redirect.
+ curl_setopt($this->ch, CURLOPT_AUTOREFERER, TRUE);
+ // Return the transfer as a string instead of dumping to screen.
+ curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, TRUE);
+ // If it takes more than 45 seconds, fail
+ curl_setopt($this->ch, CURLOPT_TIMEOUT, 45);
+ // We don't want the header (use curl_getinfo())
+ curl_setopt($this->ch, CURLOPT_HEADER, FALSE);
+ // Set user agent to Ckan_client
+ curl_setopt($this->ch, CURLOPT_USERAGENT, $this->user_agent);
+ // Track the handle's request string
+ curl_setopt($this->ch, CURLINFO_HEADER_OUT, TRUE);
+ // Attempt to retrieve the modification date of the remote document.
+ curl_setopt($this->ch, CURLOPT_FILETIME, TRUE);
+ // Initialize cURL headers
+ $this->set_headers();
+ // Include PHP Markdown library
+ //require_once('lib/php_markdown/markdown.php');
+ }
+
+ /**
+ * Destructor
+ *
+ * Since it's possible to leave cURL open, this is the last chance to
+ * close it.
+ */
+ public function __destruct()
+ {
+ // Cleanup
+ if ($this->ch)
+ {
+ curl_close($this->ch);
+ unset($this->ch);
+ }
+ }
+
+ // Setters ------------------------------------------------------------
+
+ /**
+ * Sets the CKAN API key.
+ *
+ * @access public
+ * @param string CKAN API key.
+ * @return void
+ */
+ public function set_api_key($api_key)
+ {
+ $this->api_key = $api_key;
+ }
+
+ /**
+ * Sets the Host IP.
+ *
+ * @access public
+ * @param string HOST IP / Name.
+ * @return void
+ */
+ public function set_host_name($host_name)
+ {
+ $this->host_name = $host_name;
+ }
+
+ /**
+ * Sets the CKAN API base URI.
+ *
+ * @access private
+ * @return void
+ */
+ public function set_base_url()
+ {
+ // Append the CKAN API version to the base URI.
+ $this->base_url = sprintf($this->base_url, $this->api_version);
+ }
+
+ /**
+ * Sets the custom cURL headers.
+ *
+ * @access private
+ * @return void
+ */
+ private function set_headers()
+ {
+ $date = new DateTime(NULL, new DateTimeZone('UTC'));
+ $this->ch_headers = array(
+ 'Date: ' . $date->format('D, d M Y H:i:s') . ' GMT', // RFC 1123
+ 'Accept: application/json;q=1.0, application/xml;q=0.5, */*;q=0.0',
+ 'Accept-Charset: utf-8',
+ 'Accept-Encoding: gzip',
+ 'content-type: application/json'
+ );
+ }
+
+ /**
+ * Sets the Ckan_client user agent string.
+ *
+ * @access private
+ * @return void
+ */
+ private function set_user_agent()
+ {
+ if ('80' === @$_SERVER['SERVER_PORT'])
+ {
+ $server_name = 'http://' . $_SERVER['SERVER_NAME'];
+ }
+ else
+ {
+ $server_name = '';
+ }
+ $this->user_agent = sprintf($this->user_agent, $this->version) .
+ ' (' . $server_name . $_SERVER['PHP_SELF'] . ')';
+ }
+
+ // Public action API methods -----------------------------------------------
+
+ // package show
+
+ /**
+ * @access public
+ * @param string id or name of the dataset
+ * @return the dataset as dictionary
+ * @link http://docs.ckan.org/en/latest/apiv3.html#ckan.logic.action.get.package_show
+ */
+ public function action_package_show($id)
+ {
+ return $this->make_request('POST',
+ $this->actionList['package_show'],
+ $id);
+ }
+ // package create
+
+ /**
+ * @access public
+ * @param string package
+ * @return the newly created dataset as dictionary
+ * @link http://docs.ckan.org/en/latest/apiv3.html#ckan.logic.action.create.package_create
+ */
+ public function action_package_create($data)
+ {
+ return $this->make_request('POST',
+ $this->actionList['package_create'],
+ $data);
+ }
+
+
+ // package update
+
+ /**
+ * @access public
+ * @param string package
+ * @return the updated dataset as dictionary
+ * @link http://docs.ckan.org/en/latest/apiv3.html#ckan.logic.action.update.package_update
+ */
+ public function action_package_update($data)
+ {
+ return $this->make_request('POST',
+ $this->actionList['package_update'],
+ $data);
+ }
+
+
+ // package delete
+
+ /**
+ * @access public
+ * @param string id
+ * @return ?
+ * @link http://docs.ckan.org/en/latest/apiv3.html#ckan.logic.action.delete.package_delete
+ */
+ public function action_package_delete($id)
+ {
+ return $this->make_request('POST',
+ $this->actionList['package_delete'],
+ $id);
+ }
+
+ // group create
+
+ /**
+ * @access public
+ * @param string group
+ * @return the newly created group as dictionary
+ * @link http://docs.ckan.org/en/latest/apiv3.html#ckan.logic.action.create.group_create
+ */
+ public function action_group_create($data)
+ {
+ return $this->make_request('POST',
+ $this->actionList['group_create'],
+ $data);
+ }
+
+ // group show
+
+ /**
+ * @access public
+ * @param string group
+ * @return the newly created group as dictionary
+ * @link http://docs.ckan.org/en/latest/apiv3.html#ckan.logic.action.create.group_create
+ */
+ public function action_group_show($id)
+ {
+ return $this->make_request('POST',
+ $this->actionList['group_show'],
+ $id);
+ }
+
+ // group delete
+
+ /**
+ * @access public
+ * @param string id
+ * @return the newly created group as dictionary
+ * @link http://docs.ckan.org/en/latest/apiv3.html#ckan.logic.action.create.group_create
+ */
+ public function action_group_delete($id)
+ {
+ return $this->make_request('POST',
+ $this->actionList['group_delete'],
+ $id);
+ }
+
+ // group update
+
+ /**
+ * @access public
+ * @param string group
+ * @return the updated group as dictionary
+ * @link http://docs.ckan.org/en/latest/apiv3.html#ckan.logic.action.update.package_update
+ */
+ public function action_group_update($data)
+ {
+ return $this->make_request('POST',
+ $this->actionList['group_update'],
+ $data);
+ }
+
+ //group_package_show
+
+ /**
+ * @access public
+ * @param string group
+ * @return the packages of a group dictionaries
+ * @link http://docs.ckan.org/en/latest/apiv3.html#ckan.logic.action.
+ */
+ public function action_group_package_show($id)
+ {
+ return $this->make_request('POST',
+ $this->actionList['group_package_show'],
+ $id);
+ }
+
+ // Public (API) methods -----------------------------------------------
+
+ // package register resource
+
+ /**
+ * @access public
+ * @return array An array of all package IDs.
+ */
+ public function get_package_register()
+ {
+ return $this->make_request('GET', $this->resources['package_register']);
+ }
+
+ /**
+ * @access public
+ * @param string package
+ * @return bool
+ * @link http://knowledgeforge.net/ckan/doc/ckan/api.html#model-api-data-formats
+ */
+ public function post_package_register($id, $data)
+ {
+ return $this->make_request('POST',
+ $this->resources['package_register']. "/" . $id ,
+ $data);
+ }
+
+ /**
+ * @access public
+ * @param string package
+ * @return bool
+ * @link http://knowledgeforge.net/ckan/doc/ckan/api.html#model-api-data-formats
+ * @since Version 0.1.0
+ * doc: https://github.com/luizsoliveira/Ckan_client-PHP/commit/patch-1
+ */
+ public function post_package_update($data)
+ {
+ $json = json_decode($data, TRUE);
+ return $this->make_request('POST',
+ $this->resources['package_register'] . "/" . $json['name'],
+ $data);
+ }
+
+ // package entity resouce
+
+ /**
+ * @access public
+ * @param string package ID
+ * @return object package
+ * @link http://knowledgeforge.net/ckan/doc/ckan/api.html#model-api-data-formats
+ */
+ public function get_package_entity($package)
+ {
+ $e = new mb_exception($this->resources['package_entity'] . '/' . urlencode($package));
+ return $this->make_request('GET',
+ $this->resources['package_entity'] . '/' . urlencode($package));
+ }
+
+ /**
+ * @access public
+ * @param string package ID
+ * @param string Packing
+ * @return bool
+ * @link http://knowledgeforge.net/ckan/doc/ckan/api.html#model-api-data-formats
+ */
+ public function put_package_entity($packageName, $data)
+ {
+ return $this->make_request('PUT',
+ $this->resources['package_entity'] . '/' . urlencode($packageName),
+ $data);
+ }
+
+ //Following function is not allowed - it seems to be only possible to delete one package if version 3 of the api is used (action api)
+ /*public function delete_package_entity($package)
+ {
+ return $this->make_request('DELETE',
+ $this->resources['package_entity'] . '/' . urlencode($package));
+ }*/
+
+ public function delete_package_entity($data)
+ {
+ $e = new mb_exception("post: ".$data);
+ return $this->make_request('POST',
+ '../action/package_delete',
+ $data);
+ }
+
+ // package utility alias
+
+ /**
+ * CKAN package GET utility alias.
+ *
+ * @see get_package_register(), get_package_entity()
+ * @access public
+ */
+ public function get_package($package = FALSE)
+ {
+ if ($package)
+ {
+ return $this->get_package_entity($package);
+ }
+ else
+ {
+ return $this->get_package_register();
+ }
+ }
+
+ // Group register resource
+
+ /**
+ * @access public
+ * @return array An array of all group IDs.
+ */
+ public function get_group_register()
+ {
+ return $this->make_request('GET', $this->resources['group_register']);
+ }
+
+ // Group entity resource
+
+ /**
+ * @access public
+ * @param string Group ID
+ * @return object Group
+ * @link http://knowledgeforge.net/ckan/doc/ckan/api.html#model-api-data-formats
+ */
+ public function get_group_entity($group)
+ {
+ return $this->make_request('GET',
+ $this->resources['group_entity'] . '/' . urlencode($group));
+ }
+
+ // Group utility alias
+
+ /**
+ * CKAN group GET utility alias.
+ *
+ * @see get_group_register(), get_group_entity()
+ * @access public
+ */
+ public function get_group($group = FALSE)
+ {
+ if ($group)
+ {
+ return $this->get_group_entity($group);
+ }
+ else
+ {
+ return $this->get_group_register();
+ }
+ }
+
+ // Tag register resource
+
+ /**
+ * @access public
+ */
+ public function get_tag_register()
+ {
+ return $this->make_request('GET', $this->resources['tag_register']);
+ }
+
+ // Tag entity resource
+
+ /**
+ * @access public
+ */
+ public function get_tag_entity($tag)
+ {
+ return $this->make_request('GET', $this->resources['tag_entity'] .
+ '/' . urlencode($tag));
+ }
+
+ // Tag utility alias
+
+ /**
+ * @access public
+ */
+ public function get_tag($tag = FALSE)
+ {
+ if ($tag)
+ {
+ return $this->get_tag_entity($tag);
+ }
+ else
+ {
+ return $this->get_tag_register();
+ }
+ }
+
+ // Revision register resource
+
+ /**
+ * @access public
+ */
+ public function get_revision_register()
+ {
+ return $this->make_request('GET',
+ $this->resources['revision_register']);
+ }
+
+ // Revision entity resource
+
+ /**
+ * @access public
+ */
+ public function get_revision_entity($revision)
+ {
+ return $this->make_request('GET',
+ $this->resources['revision_entity'] . '/' . urlencode($revision));
+ }
+
+ // Revision utility alias
+
+ /**
+ * @access public
+ */
+ public function get_revision($revision = FALSE)
+ {
+ if ($revision)
+ {
+ return $this->get_revision_entity($revision);
+ }
+ else
+ {
+ return $this->get_revision_register();
+ }
+ }
+
+ // License list resource
+
+ /**
+ * @access public
+ */
+ public function get_license_list()
+ {
+ return $this->make_request('GET', $this->resources['license_list']);
+ }
+
+ // License utility alias
+
+ public function get_license()
+ {
+ return $this->get_license_list();
+ }
+
+ // Search API
+
+ /**
+ * Searches CKAN packages.
+ *
+ * @access public
+ * @param string Keywords to search for
+ * @param array Optional. Search options.
+ * @return mixed If success, search object. On fail, false.
+ */
+ public function search_package($keywords, $opts = array())
+ {
+ // Gots to have keywords or there's nothing to search for.
+ // Also, $opts better be an array
+ if (0 === strlen(trim($keywords)) || FALSE === is_array($opts))
+ {
+ throw new Exception('We need keywords, yo!');
+ }
+ $q = '';
+ // Set querystring based on $opts param.
+ $q .= '&order_by=' . ((isset($opts['order_by']))
+ ? urlencode($opts['order_by']) : 'rank');
+ $q .= '&offset=' . ((isset($opts['offset']))
+ ? urlencode($opts['offset']) : '0');
+ $q .= '&limit=' . ((isset($opts['limit']))
+ ? urlencode($opts['limit']) : '20');
+ $q .= '&filter_by_openness=' . ((isset($opts['openness']))
+ ? urlencode($opts['openness']) : '0');
+ $q .= '&filter_by_downloadable=' . ((isset($opts['downloadable']))
+ ? urlencode($opts['downloadable']) : '0');
+ return $data = $this->make_request('GET',
+ $this->resources['package_search'] . '?q=' .
+ urlencode($keywords) . $q);
+ }
+
+ /**
+ * CKAN package search utility alias, since it's most likely ppl just
+ * want to search the packages.
+ *
+ * @see search_package()
+ * @access public
+ */
+ public function search($keywords, $opts = array())
+ {
+ return $this->search_package($keywords, $opts);
+ }
+
+ // Public methods -----------------------------------------------------
+
+ /**
+ * Helper function to ease the display of search results.
+ * Outputs directly to screen.
+ *
+ * @access public
+ * @param object Result from search() or search_package()
+ * @param array Optional. An array of formatting options.
+ * @return void
+ */
+ public function search_display($data, $opts = array())
+ {
+ if ($data)
+ {
+ // Set vars based on $opts param.
+ $search_term = (isset($opts['search_term'])) ?
+ $opts['search_term'] : '';
+ $title_tag = '<' .
+ ((isset($opts['title_tag'])) ? $opts['title_tag'] : 'h2') . '>';
+ $title_close_tag = str_replace('<', '</', $title_tag);
+ $result_list_tag = (isset($opts['result_list_tag']))
+ ? $opts['result_list_tag'] : 'ul';
+ if (strlen(trim($result_list_tag)))
+ {
+ $result_list_close_tag = '</' . $result_list_tag . '>';
+ $result_list_tag = '<' . $result_list_tag . '>';
+ }
+ else
+ {
+ $result_list_close_tag = '';
+ }
+ $show_notes = (isset($opts['show_notes']))
+ ? $opts['show_notes'] : FALSE;
+ $format_notes = (isset($opts['format_notes']))
+ ? $opts['format_notes'] : FALSE;
+ // Set search title string
+ // is|are, count, ''|s, ''|search_term, .|:
+ printf($title_tag . 'There %s %d result%s%s%s' . $title_close_tag,
+ (($data->count === 1) ? 'is' : 'are'),
+ $data->count,
+ (($data->count === 1) ? '' : 's'),
+ (strlen(trim($search_term))
+ ? ' for “' . $search_term . '”' : ''),
+ (($data->count === 0) ? '.' : ':'));
+ if ($data->count > 0)
+ {
+ print $result_list_tag;
+ foreach ($data->results as $val)
+ {
+ $package = $this->get_package_entity($val);
+ printf('<li><a href="%s">%s</a>',
+ $package->ckan_url,
+ $package->title);
+ if (isset($package->notes) && $package->notes &&
+ $show_notes)
+ {
+ print ': ';
+ if (TRUE === $format_notes)
+ {
+ print $package->notes;
+ }
+ elseif (FALSE === $format_notes)
+ {
+ print $package->notes;
+ }
+ else
+ {
+ print strip_tags($package->notes,
+ $format_notes);
+ }
+ }
+ print '</li>';
+ }
+ print $result_list_close_tag;
+ }
+ }
+ }
+
+ // Private methods ----------------------------------------------------
+
+ /**
+ * Make a request to the CKAN API.
+ *
+ * @access private
+ * @param string HTTP method (GET, PUT, POST).
+ * @param string URI fragment to CKAN resource.
+ * @param string Optional. String in JSON-format that will be in request body.
+ * @return mixed If success, either an array or object. Otherwise FALSE.
+
+ */
+ private function make_request($method, $url, $data = FALSE)
+ {
+ // Set cURL method.
+ curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, strtoupper($method));
+ // Set cURL URI.
+ $e = new mb_exception($this->base_url . $url);
+ $curlUrl = $this->base_url . $url;
+ curl_setopt($this->ch, CURLOPT_URL, $curlUrl);
+ // If POST or PUT, add Authorization: header and request body
+ if ($method === 'POST' || $method === 'PUT')
+ {
+ // We needs a key and some data, yo!
+ $e = new mb_exception("method: ".$method." new url: ".$this->base_url . $url." data: ".$data);
+ if ( ! ($this->api_key && $data))
+ {
+ // throw exception
+ throw new Exception('Missing either an API key or POST data.');
+ }
+ else
+ {
+ // Add Authorization: header.
+ $this->ch_headers[] = 'Authorization: ' . $this->api_key;
+ $e = new mb_exception("added following to headers: ".'Authorization: ' . $this->api_key);
+ // Add data to request body.
+ curl_setopt($this->ch, CURLOPT_POSTFIELDS, $data);
+ }
+ }
+ else
+ {
+ // Since we can't use HTTPS,
+ // if it's in there, remove Authorization: header
+ $key = array_search('Authorization: ' . $this->api_key,
+ $this->ch_headers);
+ if ($key !== FALSE)
+ {
+ unset($this->ch_headers[$key]);
+ }
+ curl_setopt($this->ch, CURLOPT_POSTFIELDS, NULL);
+ }
+ // Set headers.
+ curl_setopt($this->ch, CURLOPT_HTTPHEADER, $this->ch_headers);
+ // Execute request and get response headers.
+ $response = curl_exec($this->ch);
+ $info = curl_getinfo($this->ch);
+ // Check HTTP response code
+ if ($info['http_code'] !== 200)
+ {
+ throw new Exception($info['http_code'] . ': ' .
+ $this->http_status_codes[$info['http_code']]);
+ } else {
+ $e = new mb_exception("Returned 200 - OK");
+ $e = new mb_exception($response);
+ }
+ // Determine how to parse
+ if (isset($info['content_type']) && $info['content_type'])
+ {
+ $content_type = str_replace('application/', '',
+ substr($info['content_type'], 0,
+ strpos($info['content_type'], ';')));
+ //return $response;
+ return $this->parse_response($response, $content_type);
+ }
+ else
+ {
+ throw new Exception('Unknown content type.');
+ }
+ }
+
+ /**
+ * Parse the response from the CKAN API.
+ *
+ * @access private
+ * @param string Data returned from the CKAN API.
+ * @param string Format of data returned from the CKAN API.
+ * @return mixed If success, either an array or object. Otherwise FALSE.
+
+ */
+ private function parse_response($data = FALSE, $format = FALSE)
+ {
+ if ($data)
+ {
+ if ('json' === $format)
+ {
+ return json_decode($data);
+ }
+ else
+ {
+ throw new Exception('Unable to parse this data format.');
+ }
+ }
+ return FALSE;
+ }
+
+}
Added: trunk/mapbender/http/php/mod_exportMapbenderLayer2CkanObjects.php
===================================================================
--- trunk/mapbender/http/php/mod_exportMapbenderLayer2CkanObjects.php (rev 0)
+++ trunk/mapbender/http/php/mod_exportMapbenderLayer2CkanObjects.php 2013-02-23 20:51:55 UTC (rev 8568)
@@ -0,0 +1,279 @@
+<?php
+//mod_exportMapbenderLayer2CkanObjects.php
+require_once(dirname(__FILE__)."/../../core/globalSettings.php");
+require_once(dirname(__FILE__).'/../../conf/ckan.conf');
+
+//metadata columns of wms table
+/*contactorganization
+contactperson
+address
+city
+postcode
+contactvoicetelephone
+contactelectronicmailaddress*/
+
+//select open data information from mapbenders database
+$sql = <<<SQL
+
+select wms_id, layer_id, layer.uuid as uuid, wms_title || ':' || layer_title as title, wms_abstract || ':' || layer_abstract as notes, tou_licence_title, tou_licence_url, tou_licence_id, isopen, to_timestamp(wms_timestamp) as wms_timestamp, to_timestamp(wms_timestamp_create) as wms_timestamp_create, wms_owner as service_owner, fkey_mb_group_id as service_group, contactperson, address, city, postcode, contactvoicetelephone, contactelectronicmailaddress from (select termsofuse_id, description as tou_licence_title, descriptionlink as tou_licence_url, wms_tou.name as tou_licence_id, wms_tou.isopen as isopen, wms_id, wms_title, wms_timestamp, wms_timestamp_create, wms.wms_abstract, wms.wms_owner, wms.fkey_mb_group_id, contactperson, address, city, postcode, contactvoicetelephone, contactelectronicmailaddress from (select * from termsofuse inner join wms_termsofuse on termsofuse.termsofuse_id = wms_termsofuse.fkey_termsofuse_id and termsofuse.termsofuse_id in (2,3,4,5)) as wms_tou
inner join wms on wms_tou.fkey_wms_id = wms.wms_id) as wms_tou2 inner join layer on wms_tou2.wms_id = layer.fkey_wms_id and layer_searchable=1;
+
+SQL;
+$result = db_query($sql);
+
+//initialize result array
+$sqlTable = array();
+while ($row = db_fetch_array($result)) {
+ $sqlTable['name'][] = $row['uuid'];
+ $sqlTable['title'][] = $row['title'];
+ $sqlTable['service_id'][] = $row['wms_id'];
+ $sqlTable['resource_type'][] = "Kartenebene";
+ $sqlTable['resource_id'][] = $row['layer_id'];
+ $sqlTable['service_group'][] = $row['service_group'];
+ $sqlTable['service_owner'][] = $row['service_owner'];
+ $sqlTable['service_person'][] = $row['contactperson'];
+ $sqlTable['service_address'][] = $row['address'];
+ $sqlTable['service_city'][] = $row['city'];
+ $sqlTable['service_postcode'][] = $row['postcode'];
+ $sqlTable['service_phone'][] = $row['contactvoicetelephone'];
+ $sqlTable['service_email'][] = $row['contactelectronicmailaddress'];
+ $sqlTable['notes'][] = $row['notes'];
+ $sqlTable['tou_licence_title'][] = $row['tou_licence_title'];
+ $sqlTable['tou_licence_id'][] = $row['tou_licence_id'];
+ $sqlTable['tou_licence_url'][] = $row['tou_licence_url'];
+ $sqlTable['isopen'][] = $row['isopen'];
+ $sqlTable['temporal_coverage_to'][] = $row['wms_timestamp'];
+ $sqlTable['temporal_coverage_from'][] = $row['wms_timestamp_create'];
+}
+$groupOwnerArray = array();
+$groupOwnerArray[0] = $sqlTable['service_group'];
+$groupOwnerArray[1] = $sqlTable['service_owner'];
+
+//get orga information
+$groupOwnerArray = getOrganizationInfoForServices($groupOwnerArray);
+
+//push information from groupOwnerArray to sqlTable
+$sqlTable['organization'] = $groupOwnerArray[3];
+$sqlTable['userId'] = $groupOwnerArray[2];
+$sqlTable['orgaId'] = $groupOwnerArray[11];
+$sqlTable['group_title'] = $groupOwnerArray[4];
+$sqlTable['group_address'] = $groupOwnerArray[5];
+$sqlTable['group_email'] = $groupOwnerArray[6];
+$sqlTable['group_telephone'] = $groupOwnerArray[7];
+$sqlTable['group_postcode'] = $groupOwnerArray[8];
+$sqlTable['group_city'] = $groupOwnerArray[9];
+$sqlTable['group_logo'] = $groupOwnerArray[10];
+$sqlTable['group_homepage'] = $groupOwnerArray[12];
+//echo "test";
+//test output
+/*for ($i=0; $i < count($sqlTable['name']); $i++){
+ echo $sqlTable['name'][$i]." - ".$sqlTable['title'][$i]." - ".$sqlTable['service_id'][$i]." - ".$sqlTable['resource_id'][$i]." - ".$sqlTable['organization'][$i]." - ".$sqlTable['orgaId'][$i]."<br>";
+ }*/
+$transpSqlTable = array_transpose($sqlTable);
+/*echo "<br>".$test[0]['name']."<br>";
+$test2 = $test[0];
+echo "<br>".$test2['name']." - ".$test2['title']."<br>";
+echo "<br>".$sqlTable['name'][0]."<br>";*/
+
+$ckanPackages = new stdClass();
+$ckanPackages->result = array();
+for ($i=0; $i < count($sqlTable['name']); $i++){
+ $ckanPackages->result[] = buildCkanPackage($transpSqlTable[$i]);
+}
+header('Content-Type: application/json; charset='.CHARSET);
+echo json_encode($ckanPackages);
+//build json objects!
+
+function buildCkanPackage ($mbArray) {
+ //example package and mapping
+ $package->maintainer = $mbArray['group_title']; //mb_group.mb_group_name
+ $package->point_of_contact = $mbArray['group_title'];//"Andreas Becker"; //mb_user.mb_user_name - owner
+ $package->point_of_contact_free_address = $mbArray['group_address']."- test - ". $mbArray['group_postcode']." ".$mbArray['group_city']."\n".$mbArray['group_telephone'];//"Ferdinand-Sauerbruch-Straße 15"; //mb_group.mb_group_address
+ $package->point_of_contact_email = $mbArray['group_email'];//"poststelle at lvermgeo.rlp"; //mb_group.mb_group_email
+ $package->license = $mbArray['tou_licence_title'];//"Datenlizenz Deutschland – Namensnennung – nicht kommerziell"; // termsofuse.description
+ $package->author = $mbArray['mb_user_id'];//""; //mb_group.mb_group_name
+ $package->download_url = "http://www.geoportal.rlp.de/mapbender/php/wms.php?layer_id=".$mbArray['resource_id']."&REQUEST=GetCapabilities&VERSION=1.1.1&SERVICE=WMS";//$mbArray['mb_user_id'];//"http://www.geoportal.rlp.de/portal/karten.html?LAYER[zoom]=1&LAYER[id]=36699"; //
+ $package->version = "";//$mbArray['mb_user_id'];//""; //
+ $package->groups = array();
+ //for v1/v2 - only $package->groups[0] = "gdi-rp"; //constant
+ //$package->groups[0] = CKAN_GROUP_NAME;
+ //for v3:
+ $package->groups[0]->name = CKAN_GROUP_NAME; //constant
+ $package->name = $mbArray['name'];// $datasetName; //layer.uuid
+ $package->notes = $mbArray['notes'];//"Die (Digitale) Topographische Karte 1:100 000 ermöglicht aufgrund der abgebildeten Fläche die Darstellung großräumige Gebiete."; //wms.wms_abstract || layer.layer_abstract
+ $package->title = $mbArray['title'];//"Topographische Karte Rheinland-Pfalz 1:100.000"; //wms.wms_title || layer.layer_title - OK
+ $package->other_terms_of_use = "other terms of use";//$mbArray['mb_user_id'];// "test tou"; //null or ""
+ //TODO: problem date format
+ //$package->temporal_coverage_to = $mbArray['temporal_coverage_to'];// "2012-01-01"; // last update ? wms.wms_timestamp - OK
+ //$package->temporal_coverage_from = $mbArray['temporal_coverage_from'];// "2011-01-01"; // last update ? wms.wms_timestamp_create - OK
+ $package->temporal_coverage_to = "2012-01-01"; // last update ? wms.wms_timestamp - OK
+ $package->temporal_coverage_from = "2011-01-01"; // last update ? wms.wms_timestamp_create - OK
+
+ $package->content_type = $mbArray['resource_type'];// "testcontenttype"; //constant: Service
+ if ($mbArray['isopen'] == 1) {
+ $package->isopen = true;//true; //termsofuse.isopen - OK
+ } else {
+ $package->isopen = false;
+ }
+ $package->resources = array();
+
+ $package->resources[0]->description = "Anzeige im GeoPortal.rlp";//$mbArray['mb_user_id'];// "Link zur WMS-Darstellung im GeoPortal.rlp, die Darstellung erfolgt ab einem Maßstab 1:500.000"; //fix: "".id.id?
+ $package->resources[0]->format = "Kartenviewer"; //constant
+ $package->resources[0]->url = "http://www.geoportal.rlp.de/mapbender/php/wms.php?layer_id=".$mbArray['resource_id']."&REQUEST=GetCapabilities&VERSION=1.1.1&SERVICE=WMS";// "http://www.geoportal.rlp.de/portal/karten.html?LAYER[zoom]=1&LAYER[id]=36699"; //constant .. ids
+ $package->resources[0]->resource_type = "visualization"; //constant
+
+ $package->resources[1]->description = "WMS Capabilities Link zur Integration in GIS oder Webapplikationen";//$mbArray['mb_user_id'];// "Link zur WMS-Darstellung im GeoPortal.rlp, die Darstellung erfolgt ab einem Maßstab 1:500.000"; //fix: "".id.id?
+ $package->resources[1]->format = "WMS"; //constant
+ $package->resources[1]->url = "http://www.geoportal.rlp.de/mapbender/php/wms.php?layer_id=".$mbArray['resource_id']."&REQUEST=GetCapabilities&VERSION=1.1.1&SERVICE=WMS";// "http://www.geoportal.rlp.de/portal/karten.html?LAYER[zoom]=1&LAYER[id]=36699"; //constant .. ids
+ $package->resources[1]->resource_type = "visualization"; //constant
+
+ $package->resources[2]->description = "Metadaten zur WMS Kartenebene";//$mbArray['mb_user_id'];// "Link zur WMS-Darstellung im GeoPortal.rlp, die Darstellung erfolgt ab einem Maßstab 1:500.000"; //fix: "".id.id?
+ $package->resources[2]->format = "html"; //constant
+ $package->resources[2]->url = "http://www.geoportal.rlp.de/mapbender/php/mod_showMetadata.php?languageCode=de&resource=layer&layout=tabs&id=".$mbArray['resource_id'];// "http://www.geoportal.rlp.de/portal/karten.html?LAYER[zoom]=1&LAYER[id]=36699"; //constant .. ids
+ $package->resources[2]->resource_type = "metadata"; //constant
+
+ $package->author_address->url = $mbArray['mb_user_id'];// null; //null
+ $package->author_address->email = $mbArray['mb_user_id'];// ""; // ""
+ $package->maintainer_address->url = $mbArray['group_homepage'];//$mbArray['service_address'];// null; //mb_group.mb_group_homepage
+ $package->maintainer_address->email = $mbArray['service_email'];// ""; //mb_group.mb_group_email
+ $package->maintainer_address->free_address = $mbArray['service_address'].'\n'.$mbArray['service_postcode'];// null; //mb_group.mb_group_address - more things with \r\n mb_group_voicetelephone, ...
+ $package->terms_of_use->license_id = $mbArray['tou_licence_id'];// "ger-name-nc"; //termsofuse.name - OK
+ $package->terms_of_use->license_title = $mbArray['tou_licence_title'];// "Datenlizenz Deutschland – Namensnennung – nicht kommerziell"; //termsofuse.description OK
+ $package->terms_of_use->license_url = $mbArray['tou_licence_url'];// null; //termsofuse.descriptionlink OK
+ $package->terms_of_use->other = "test licence";//$mbArray['mb_user_id'];// null; // null?
+ /*
+ $package->extras->sector = "Öffentlicher Sektor";
+ $package->extras->is_free_of_charge = false;
+ $package->extras->tag_thesauri = array();
+ $package->extras->tag_sources = array();
+ $package->extras->geographical_coverage = "Rheinland-Pfalz";
+ $package->extras->geographical_granularity = "Land";
+ $package->extras->content_type = "Datensatz";
+ $package->extras->used_datasets = array();*/
+ return $package;
+}
+
+//other functions
+function getOrganizationInfoForServices($groupOwnerArray) {
+ //split array into two lists which are requested in two separate sqls
+ $listGroupIds = array();
+ $listOwnerIds = array();
+ //echo "<br>count groupOwnerArray: ".count($groupOwnerArray[0]);
+ for ($i=0; $i < count($groupOwnerArray[0]); $i++){
+ $key = $i;
+ if (!isset($groupOwnerArray[0][$i]) || is_null($groupOwnerArray[0][$i]) || $groupOwnerArray[0][$i] == 0){
+ $listOwnerIds[$key] = $groupOwnerArray[1][$i];
+ } else {
+ $listGroupIds[$key] = $groupOwnerArray[0][$i];
+ }
+ }
+ //for ownerList
+ $metadataContactArray = array();
+ $metadataContact = array();
+ $listGroupIdsKeys = array_keys($listGroupIds);
+ $listOwnerIdsKeys = array_keys($listOwnerIds);
+ $listOwnerIdsString = implode(",",$listOwnerIds);
+ $listGroupIdsString = implode(",",$listGroupIds);
+ //do the database requests
+ if ($listOwnerIdsString != "") {
+ $sql = "SELECT mb_group_name as metadatapointofcontactorgname, mb_group_title as metadatapointofcontactorgtitle, mb_group_id, mb_group_logo_path as metadatapointofcontactorglogo, mb_group_address as metadatapointofcontactorgaddress, mb_group_email as metadatapointofcontactorgemail, mb_group_postcode as metadatapointofcontactorgpostcode, mb_group_city as metadatapointofcontactorgcity, mb_group_voicetelephone as metadatapointofcontactorgtelephone, mb_group_facsimiletelephone as metadatapointofcontactorgfax , mb_group_homepage, b.mb_user_id as mb_user_id FROM mb_group AS a, mb_user AS b, mb_user_mb_group AS c WHERE b.mb_user_id IN (".$listOwnerIdsString.") AND b.mb_user_id = c.fkey_mb_user_id AND c.fkey_mb_group_id = a.mb_group_id AND c.mb_user_mb_group_type=2";
+ $resultOrgaOwner = db_query($sql);
+ $index = 0;
+ while ($row = db_fetch_array($resultOrgaOwner)) {
+ //push information into metadataContactArray
+ $metadataContactOwnerArray[$index]['metadatapointofcontactorgname'] = $row['metadatapointofcontactorgname'];
+ $metadataContactOwnerArray[$index]['metadatapointofcontactorgtitle'] = $row['metadatapointofcontactorgtitle'];
+ $metadataContactOwnerArray[$index]['metadatapointofcontactorgaddress'] = $row['metadatapointofcontactorgaddress'];
+ $metadataContactOwnerArray[$index]['metadatapointofcontactorgemail'] = $row['metadatapointofcontactorgemail'];
+ $metadataContactOwnerArray[$index]['metadatapointofcontactorgtelephone'] = $row['metadatapointofcontactorgtelephone'];
+ $metadataContactOwnerArray[$index]['metadatapointofcontactorgpostcode'] = $row['metadatapointofcontactorgpostcode'];
+ $metadataContactOwnerArray[$index]['metadatapointofcontactorgcity'] = $row['metadatapointofcontactorgcity'];
+ $metadataContactOwnerArray[$index]['metadatapointofcontactorglogo'] = $row['metadatapointofcontactorglogo'];
+ $metadataContactOwnerArray[$index]['mb_group_homepage'] = $row['mb_group_homepage'];
+ $metadataContactOwnerArray[$index]['mb_user_id'] = $row['mb_user_id'];
+ $metadataContactOwnerArray[$index]['orga_id'] = $row['mb_group_id'];
+ $index++;
+ }
+ $index = 0;
+ //push information directly into $groupOwnerArray at indizes from
+ for ($i=0; $i < count($listOwnerIds); $i++){
+ //find index of user with special id in array $metadataContactOwnerArray['user_id']
+ $index = findIndexInMultiDimArray($metadataContactOwnerArray, $listOwnerIds[$i], 'mb_user_id');
+ $groupOwnerArray[2][$listOwnerIdsKeys[$i]] = $metadataContactOwnerArray[$index]['user_id']; //user_id - 2
+ $groupOwnerArray[3][$listOwnerIdsKeys[$i]] = $metadataContactOwnerArray[$index]['metadatapointofcontactorgname']; //orga_name - 3
+ $groupOwnerArray[4][$listOwnerIdsKeys[$i]] = $metadataContactOwnerArray[$index]['metadatapointofcontactorgtitle']; //title - 4
+ $groupOwnerArray[5][$listOwnerIdsKeys[$i]] = $metadataContactOwnerArray[$index]['metadatapointofcontactorgaddress']; //address - 5
+ $groupOwnerArray[6][$listOwnerIdsKeys[$i]] = $metadataContactOwnerArray[$index]['metadatapointofcontactorgemail']; //email - 6
+ $groupOwnerArray[7][$listOwnerIdsKeys[$i]] = $metadataContactOwnerArray[$index]['metadatapointofcontactorgtelephone']; //telephone - 7
+ $groupOwnerArray[8][$listOwnerIdsKeys[$i]] = $metadataContactOwnerArray[$index]['metadatapointofcontactorgpostcode']; //postcode - 8
+ $groupOwnerArray[9][$listOwnerIdsKeys[$i]] = $metadataContactOwnerArray[$index]['metadatapointofcontactorgcity']; //city - 9
+ $groupOwnerArray[10][$listOwnerIdsKeys[$i]] = $metadataContactOwnerArray[$index]['metadatapointofcontactorglogo']; //logo - 10
+ $groupOwnerArray[11][$listOwnerIdsKeys[$i]] = $metadataContactOwnerArray[$index]['orga_id'];
+ $groupOwnerArray[12][$listOwnerIdsKeys[$i]] = $metadataContactOwnerArray[$index]['mb_group_homepage'];
+ }
+ }
+ //for groupList
+ if ($listGroupIdsString != "") {
+ $sql = "SELECT mb_group_name as metadatapointofcontactorgname, mb_group_title as metadatapointofcontactorgtitle, mb_group_id, mb_group_logo_path as metadatapointofcontactorglogo, mb_group_address as metadatapointofcontactorgaddress, mb_group_email as metadatapointofcontactorgemail, mb_group_postcode as metadatapointofcontactorgpostcode, mb_group_city as metadatapointofcontactorgcity, mb_group_voicetelephone as metadatapointofcontactorgtelephone, mb_group_facsimiletelephone as metadatapointofcontactorgfax, mb_group_homepage, mb_group_id FROM mb_group WHERE mb_group_id IN (".$listGroupIdsString.")";
+ $resultOrgaGroup = db_query($sql);
+ $index = 0;
+ while ($row = db_fetch_array($resultOrgaGroup)) {
+ //push information into metadataContactArray
+ $metadataContactGroupArray[$index]['metadatapointofcontactorgname'] = $row['metadatapointofcontactorgname'];
+ $metadataContactGroupArray[$index]['metadatapointofcontactorgtitle'] = $row['metadatapointofcontactorgtitle'];
+ $metadataContactGroupArray[$index]['metadatapointofcontactorgaddress'] = $row['metadatapointofcontactorgaddress'];
+ $metadataContactGroupArray[$index]['metadatapointofcontactorgemail'] = $row['metadatapointofcontactorgemail'];
+ $metadataContactGroupArray[$index]['metadatapointofcontactorgtelephone'] = $row['metadatapointofcontactorgtelephone'];
+ $metadataContactGroupArray[$index]['metadatapointofcontactorgpostcode'] = $row['metadatapointofcontactorgpostcode'];
+ $metadataContactGroupArray[$index]['metadatapointofcontactorgcity'] = $row['metadatapointofcontactorgcity'];
+ $metadataContactGroupArray[$index]['metadatapointofcontactorglogo'] = $row['metadatapointofcontactorglogo'];
+ $metadataContactGroupArray[$index]['mb_group_homepage'] = $row['mb_group_homepage'];
+ $metadataContactGroupArray[$index]['mb_user_id'] = $row['mb_user_id'];
+ $metadataContactGroupArray[$index]['orga_id'] = $row['mb_group_id'];
+ $index++;
+ }
+ $index = 0;
+ //push information directly into $groupOwnerArray at indizes from
+ for ($i=0; $i < count($listGroupIds); $i++){
+ //find index of user with special id in array $metadataContactGroupArray['user_id']
+ $index = findIndexInMultiDimArray($metadataContactGroupArray, $listGroupIds[$i], 'mb_user_id');
+ $groupOwnerArray[2][$listGroupIdsKeys[$i]] = $metadataContactGroupArray[$index]['mb_user_id']; //user_id - 2
+ $groupOwnerArray[3][$listGroupIdsKeys[$i]] = $metadataContactGroupArray[$index]['metadatapointofcontactorgname']; //orga_name - 3
+ $groupOwnerArray[4][$listGroupIdsKeys[$i]] = $metadataContactGroupArray[$index]['metadatapointofcontactorgtitle']; //title - 4
+ $groupOwnerArray[5][$listGroupIdsKeys[$i]] = $metadataContactGroupArray[$index]['metadatapointofcontactorgaddress']; //address - 5
+ $groupOwnerArray[6][$listGroupIdsKeys[$i]] = $metadataContactGroupArray[$index]['metadatapointofcontactorgemail']; //email - 6
+ $groupOwnerArray[7][$listGroupIdsKeys[$i]] = $metadataContactGroupArray[$index]['metadatapointofcontactorgtelephone']; //telephone - 7
+ $groupOwnerArray[8][$listGroupIdsKeys[$i]] = $metadataContactGroupArray[$index]['metadatapointofcontactorgpostcode']; //postcode - 8
+ $groupOwnerArray[9][$listGroupIdsKeys[$i]] = $metadataContactGroupArray[$index]['metadatapointofcontactorgcity']; //city - 9
+ $groupOwnerArray[10][$listGroupIdsKeys[$i]] = $metadataContactGroupArray[$index]['metadatapointofcontactorglogo']; //logo - 10
+
+ $groupOwnerArray[11][$listGroupIdsKeys[$i]] = $metadataContactGroupArray[$index]['orga_id'];
+ $groupOwnerArray[12][$listGroupIdsKeys[$i]] = $metadataContactGroupArray[$index]['mb_group_homepage'];
+ }
+ }
+ return $groupOwnerArray;
+}
+
+function array_transpose($array, $selectKey = false) {
+ if (!is_array($array)) return false;
+ $return = array();
+ foreach($array as $key => $value) {
+ if (!is_array($value)) return $array;
+ if ($selectKey) {
+ if (isset($value[$selectKey])) $return[] = $value[$selectKey];
+ } else {
+ foreach ($value as $key2 => $value2) {
+ $return[$key2][$key] = $value2;
+ }
+ }
+ }
+ return $return;
+}
+function findIndexInMultiDimArray($multiDimArray, $needle, $columnName) {
+ foreach($multiDimArray as $index => $object) {
+ if($object[$columnName] == $needle) return $index;
+ }
+ return FALSE;
+}
+
+
+?>
Added: trunk/mapbender/http/php/mod_syncCkan.php
===================================================================
--- trunk/mapbender/http/php/mod_syncCkan.php (rev 0)
+++ trunk/mapbender/http/php/mod_syncCkan.php 2013-02-23 20:51:55 UTC (rev 8568)
@@ -0,0 +1,470 @@
+<?php
+// Display errors for demo
+//@ini_set('error_reporting', E_ALL);
+//@ini_set('display_errors', 'stdout');
+// Include class_ckanApi.php
+require_once(dirname(__FILE__).'/../classes/class_ckanApi.php');
+require_once(dirname(__FILE__).'/../classes/class_ckan.php');
+require_once(dirname(__FILE__).'/../classes/class_connector.php');
+require_once(dirname(__FILE__).'/../../conf/ckan.conf');
+
+// Create CKAN object
+// Takes optional API key parameter. Required for POST and PUT methods.
+$apiKey = API_KEY;
+$serverIp = CKAN_SERVER_IP;
+//initial instantiation of api class
+$ckan = new ckanApi($apiKey, $serverIp);
+$ckan->base_url='http://'.$serverIp.':5000/api/';
+
+//echo "API-key: ".$ckan->api_key."<br>";
+//echo "API-baseUrl: ".$ckan->base_url;
+
+//parse request parameters
+if (isset($_REQUEST["action"]) & $_REQUEST["action"] != "") {
+ $testMatch = $_REQUEST["action"];
+ if (!($testMatch == 'package_delete' or $testMatch == 'package_create' or $testMatch == 'package_show' or $testMatch == 'group_create' or $testMatch == 'group_delete' or $testMatch == 'group_package_show' or $testMatch == 'delete_all_packages_by_group' or $testMatch == 'group_show')){
+ echo 'action: <b>'.$testMatch.'</b> is not valid.<br/>';
+ die();
+ }
+ $action = $testMatch;
+ $testMatch = NULL;
+}
+
+
+//get json objects from mapbender json interface
+/*$mapbenderCkanUrl = "http://localhost/mapbender_trunk/php/mod_exportMapbenderLayer2CkanObjects.php";
+$ckanObjectConnector = new connector($mapbenderCkanUrl);
+$ckanObjects = json_decode($ckanObjectConnector->file);
+header('Content-Type: application/json; charset='.CHARSET);
+echo json_encode($ckanObjects);
+*/
+
+//get current dataset names from mapbenders ckan object interface
+$mapbenderCkanUrl = "http://localhost/mapbender_trunk/php/mod_exportMapbenderLayer2CkanObjects.php";
+$ckanObjectConnector = new connector($mapbenderCkanUrl);
+$ckanObjects = json_decode($ckanObjectConnector->file);
+
+foreach ($ckanObjects->result as $dataset) {
+ $mbDatasetArray[] = $dataset->name;
+}
+print "<b>Mapbender datasets:</b><br>";
+if (count($mbDatasetArray) == 0) {
+ $mbDatasetArray = false;
+}
+
+if ($mbDatasetArray) {
+ foreach ($mbDatasetArray as $dataset) {
+ print $dataset."<br>";
+ }
+}
+print "<b>ckan datasets:</b><br>";
+//get old package names for defined group in ckan.conf file
+//thru action api
+$ckanDatasetArray = get_packages_by_group(CKAN_GROUP_NAME);
+if ($ckanDatasetArray) {
+ //debug output
+ foreach ($ckanDatasetArray as $dataset) {
+ print $dataset."<br>";
+ }
+}
+
+//compare the arrays
+//first those which can be deleted
+if ($ckanDatasetArray && $mbDatasetArray) {
+ $datasetToDelete = array_diff($ckanDatasetArray, $mbDatasetArray);
+} else {
+ if (!$ckanDatasetArray) {
+ $datasetToDelete = false;
+ }
+ if (!$mbDatasetArray) {
+ $datasetToDelete = $ckanDatasetArray;
+ }
+}
+
+//show datasets to be deleted:
+if ($datasetToDelete) {
+ print "<b>ckan datasets to be deleted:</b><br>";
+ //debug output
+ foreach ($datasetToDelete as $dataset) {
+ print $dataset."<br>";
+ }
+}
+
+//check datasets to be updated:
+if (!$ckanDatasetArray) {
+ $datasetToUpdate = false;
+} else {
+ //get identical datasets
+ $datasetToUpdate = array_intersect($mbDatasetArray,$ckanDatasetArray);
+}
+
+if ($datasetToUpdate) {
+ print "<b>ckan datasets to update:</b><br>";
+ foreach ($datasetToUpdate as $dataset) {
+ print $dataset."<br>";
+ }
+} else {
+ print "<b>No datasets to update!</b><br>";
+}
+
+//get datasets to be created
+if ($ckanDatasetArray && $mbDatasetArray) {
+ $datasetToCreate = array_diff($mbDatasetArray, $ckanDatasetArray);
+} else {
+ if (!$ckanDatasetArray) {
+ $datasetToCreate = $mbDatasetArray;
+ }
+ if (!$mbDatasetArray) {
+ $datasetToCreate = false;
+ }
+}
+
+if ($datasetToCreate) {
+ print "<b>Mapbender datasets to be created for the first time:</b><br>";
+ foreach ($datasetToCreate as $dataset) {
+ print $dataset."<br>";
+ }
+ print "<br>";
+} else {
+ print "<b>No datasets to create!</b><br>";
+}
+
+//identify which are identical and which are new and which are lost
+
+//first delete the orphaned
+foreach ($datasetToDelete as $datasetName) {
+ $result = package_delete($datasetName,CKAN_API_UPDATE);
+ if ($result) {
+ print "Package ".$datasetName." deleted successfully!<br>";
+ } else {
+ print "Package ".$datasetName." could not be deleted!<br>";
+ }
+}
+
+if ($datasetToUpdate) {
+ print "<b>Update of datasets</b><br>";
+}
+//second update the identical ones
+foreach ($datasetToUpdate as $datasetName) {
+ //get dataset from object
+ $index = array_search($datasetName,$mbDatasetArray);
+ if (is_int($index)) {
+ $newPackage = $ckanObjects->result[$index];
+ //change group field if not the action api is requested!
+ if (CKAN_API_UPDATE == 2 || CKAN_API_UPDATE == 1) {
+ for ($i=0;$i < count($newPackage->groups);$i++) {
+ $newPackage->groups[$i] = $newPackage->groups[$i]->name;
+ }
+ }
+ //update it with action api
+ $result = package_update ($newPackage,CKAN_API_UPDATE);
+ if ($result) {
+ print "Dataset ".$datasetName." successfully updated!<br>";
+ //print json_encode($result);
+ } else {
+ print "Could not update dataset ".$datasetName."!<br>";
+ }
+ }
+}
+
+//second create the new ones
+foreach ($datasetToCreate as $datasetName) {
+ //get dataset from object
+ $index = array_search($datasetName,$mbDatasetArray);
+ if (is_int($index)) {
+ $newPackage = $ckanObjects->result[$index];
+ //create it with action api
+ $result = package_create ($newPackage,CKAN_API_CREATE);
+ if ($result) {
+ print "Dataset ".$datasetName." successfully created!<br>";
+ //print json_encode($result);
+ } else {
+ print "Could not create dataset ".$datasetName."!<br>";
+ }
+ }
+}
+
+$datasetName = $_REQUEST["name"];
+
+print time()."<br>";
+
+die();
+
+switch ($action) {
+ case 'package_show':
+ $result = package_get ($_REQUEST["name"]);
+ if ($result) {
+ print json_encode($result);
+ } else {
+ print "Dataset with name ".$_REQUEST["name"]." not found!";
+ }
+ break;
+ case 'package_create':
+ $result = package_create ($newDataset,3);
+ if ($result) {
+ print json_encode($result);
+ } else {
+ print "Dataset could not be created!";
+ }
+ break;
+}
+
+//functions for interacting with ckan apis
+function package_get ($packageName) {
+ try {
+ $ckan = new ckanApi(API_KEY,CKAN_SERVER_IP);
+ $ckan->base_url='http://'.CKAN_SERVER_IP.':5000/api/';
+ $idArray = array ('id'=>$packageName);
+ $resultDataset = $ckan->action_package_show(json_encode($idArray));
+ if ($resultDataset->success) {
+ return $resultDataset->result;
+ } else {
+ return false;
+ }
+ }
+ catch (Exception $e)
+ {
+ $error = new mb_exception('mod_syncCkan.php: Caught exception: '.$e->getMessage());
+ return false;
+ }
+}
+
+function package_update ($package, $apiVersion) {
+ //check if package already exists
+ $existingPackage = package_get ($package->name);
+ if ($existingPackage) {
+ switch ($apiVersion) {
+ case 3:
+ //update it ;-)
+ $ckan = new ckanApi(API_KEY,CKAN_SERVER_IP);
+ $ckan->base_url='http://'.CKAN_SERVER_IP.':5000/api/';
+ try {
+ $result = $ckan->action_package_update(json_encode($package));
+ }
+ catch (Exception $e) {
+ $error = new mb_exception('mod_syncCkan.php: update dataset http_code:'.$e->getMessage());
+ }
+ if ($result->success) {
+ $result = $result->result;
+ } else {
+ $error = new mb_exception('mod_syncCkan.php: error when trying to update dataset!');
+ $result = false;
+ }
+ return $result;
+ break;
+ case 1:
+ //update it with api v1 ;-)
+ $ckan = new ckanApi(API_KEY,CKAN_SERVER_IP);
+ $ckan->base_url='http://'.CKAN_SERVER_IP.':5000/api/1/';
+ try {
+ $result = $ckan->put_package_entity($package->name,json_encode($package));
+ }
+ catch (Exception $e) {
+ $error = new mb_exception('mod_syncCkan.php: update dataset http_code:'.$e->getMessage());
+ return false;
+ }
+ return $result;
+ break;
+ case 2:
+ //update it with api v2 ;-)
+ $ckan = new ckanApi(API_KEY,CKAN_SERVER_IP);
+ $ckan->base_url='http://'.CKAN_SERVER_IP.':5000/api/2/';
+ $error = new mb_exception('mod_syncCkan.php: '.$package->groups[0]);
+ try {
+ $result = $ckan->post_package_register($existingPackage->id,json_encode($package));
+ }
+ catch (Exception $e) {
+ $error = new mb_exception('mod_syncCkan.php: update dataset http_code:'.$e->getMessage());
+ return false;
+ }
+ return $result;
+ break;
+ }
+ } else {
+ $error = new mb_exception('mod_syncCkan.php: No package found to update!');
+ return false;
+ }
+}
+
+function package_create ($package,$apiVersion) {
+ //check if package already exists
+ $existingPackage = package_get ($package->name);
+ if ($existingPackage) {
+ //check if existing was deleted
+ $error = new mb_exception('mod_syncCkan.php: There is already an existing package with name: '.$package->name);
+ if ($existingPackage->status == 'deleted') {
+ $error = new mb_exception('mod_syncCkan.php: with status \'deleted\'');
+ } else {
+ $error = new mb_exception('mod_syncCkan.php: with status \'active\'');
+ }
+ return false;
+ } else {
+ //package insertion
+ $ckan = new ckanApi(API_KEY,CKAN_SERVER_IP);
+ switch ($apiVersion) {
+ case 1:
+ $ckan->base_url='http://'.CKAN_SERVER_IP.':5000/api/1/';
+ try {
+ $resultDataset = $ckan->post_package_register(json_encode($package));
+ if ($resultDataset->success) {
+ $result = $resultDataset->result;
+ } else {
+ $error = new mb_exception('mod_syncCkan.php: error when trying to create dataset!');
+ $result = false;
+ }
+ }
+ catch (Exception $e) {
+ $error = new mb_exception('mod_syncCkan.php: http_code:'.$e->getMessage());
+ $result = $e->getMessage();
+ }
+ break;
+ case 3:
+ $ckan->base_url='http://'.CKAN_SERVER_IP.':5000/api/';
+ try {
+ $resultDataset = $ckan->action_package_create(json_encode($package));
+ if ($resultDataset->success) {
+ $result = $resultDataset->result;
+ } else {
+ $error = new mb_exception('mod_syncCkan.php: error when trying to create dataset!');
+ $result = false;
+ }
+ }
+ catch (Exception $e) {
+ $error = new mb_exception('mod_syncCkan.php: http_code:'.$e->getMessage());
+ }
+ break;
+ }
+ if ($result) {
+ return $result;
+ } else {
+ return false;
+ }
+ }
+
+}
+
+function get_packages_by_group($groupname) {
+ $ckan = new ckanApi(API_KEY,CKAN_SERVER_IP);
+ $ckan->base_url='http://'.CKAN_SERVER_IP.':5000/api/';
+ $datasetNames = array();
+ try {
+ $groupArray = array ('id'=>$groupname);
+ $result = $ckan->action_group_package_show(json_encode($groupArray));
+ if ($result->success) {
+ foreach ($result->result as $dataset) {
+ $datasetNames[] = $dataset->name;
+ }
+ } else {
+ return false;
+ }
+ }
+ catch (Exception $e) {
+ $error = new mb_exception('mod_syncCkan.php: get_packages_by_group: http_code:'.$e->getMessage());
+ }
+ return $datasetNames;
+}
+
+function package_delete($packageName,$apiVersion) {
+ //check if package already exists
+ $existingPackage = package_get ($packageName);
+ if ($existingPackage) {
+ //check if existing was deleted
+ $error = new mb_exception('mod_syncCkan.php: Following package will be deleted: '.$package->name);
+ if ($existingPackage->state == 'deleted') {
+ $error = new mb_exception('mod_syncCkan.php: package was deleted already nothing to be done!');
+ return true;
+ } else {
+ $error = new mb_exception('mod_syncCkan.php: Start deleting it!');
+ switch ($apiVersion) {
+ case 3:
+ //update the name and status of package to delete:
+ $existingPackage->state = "deleted";
+ $existingPackage->name = $existingPackage->name."_".time();
+ //some special elements for rhineland palatinate dataset validation:
+ /*Validation error: "{'__type': 'Validation Error', 'point_of_contact': [u'Missing value'], 'content_type': [u'Missing value'], 'point_of_contact_free_address': [u'At least one value must be specified'], 'point_of_contact_email': [u'At least one value must be specified'], 'other_terms_of_use': [u'Missing value'], 'point_of_contact_url': [u'At least one value must be specified']}"*/
+ //- don't help delete it with api 2
+ //
+ //$existingPackage->point_of_contact = "dummy";
+ //$existingPackage->content_type = "dummy";
+ //$existingPackage->point_of_contact_free_address = "dummy";
+ //$existingPackage->point_of_contact_email = "dummy";
+ //$existingPackage->other_terms_of_use = "dummy";
+ //$existingPackage->point_of_contact_url = "http://www.geoportal.rlp.de";
+ try {
+ $ckan = new ckanApi(API_KEY,CKAN_SERVER_IP);
+ $ckan->base_url='http://'.CKAN_SERVER_IP.':5000/api/';
+ $result = $ckan->action_package_update(json_encode($existingPackage));
+ }
+ catch (Exception $e) {
+ $error = new mb_exception('mod_syncCkan.php: get_packages_by_group: http_code:'.$e->getMessage());
+ }
+ if ($result->success) {
+ return true;
+ } else {
+ return false;
+ }
+ break;
+ case 2:
+ //the existing package was called by action api therefor group will be defined as dict and be flattened before update
+ //TODO: check if api 2 uses dict for group or not!
+ for ($i=0;$i < count($existingPackage->groups);$i++) {
+ $error = new mb_exception('mod_syncCkan.php: groups['.$i.']->name old:'.$existingPackage->groups[$i]->name);
+
+ $existingPackage->groups[$i] = $existingPackage->groups[$i]->name;
+ $error = new mb_exception('mod_syncCkan.php: groups['.$i.'] new:'.$existingPackage->groups[$i]);
+ }
+ //update the name and status of package to delete:
+ $existingPackage->state = "deleted";
+ $existingPackage->name = $existingPackage->name."_".time();
+ //update it with api v2 ;-)
+ $ckan = new ckanApi(API_KEY,CKAN_SERVER_IP);
+ $ckan->base_url='http://'.CKAN_SERVER_IP.':5000/api/2/';
+ try {
+ $result = $ckan->post_package_register($existingPackage->id,json_encode($existingPackage));
+ }
+ catch (Exception $e) {
+ $error = new mb_exception('mod_syncCkan.php: update dataset http_code:'.$e->getMessage());
+ return false;
+ }
+ return $result;
+ break;
+ case 1:
+ //update it with api v1 ;-)
+ for ($i=0;$i < count($existingPackage->groups);$i++) {
+ $error = new mb_exception('mod_syncCkan.php: groups['.$i.']->name old:'.$existingPackage->groups[$i]->name);
+
+ $existingPackage->groups[$i] = $existingPackage->groups[$i]->name;
+ $error = new mb_exception('mod_syncCkan.php: groups['.$i.'] new:'.$existingPackage->groups[$i]);
+ }
+ //some rp specials for deleting non conformant datasets - which maybe generated by hand!
+ /*2013-02-23 21:37:57,704 ERROR [ckan.controllers.api] Validation error: "{'point_of_contact': [u'Missing value'], 'content_type': [u'Missing value'], 'point_of_contact_free_address': [u'At least one value must be specified'], 'point_of_contact_email': [u'At least one value must be specified'], 'point_of_contact_url': [u'At least one value must be specified']}"*/
+
+ $existingPackage->point_of_contact = "dummy";
+ $existingPackage->content_type = "dummy";
+ $existingPackage->point_of_contact_free_address = "dummy";
+ $existingPackage->point_of_contact_email = "dummy at dummy.de";
+ $existingPackage->point_of_contact_url = "http://test.de";
+
+ //update the name and status of package to delete:
+ $existingPackage->state = "deleted";
+ $existingPackage->name = $existingPackage->name."_".time();
+ $ckan = new ckanApi(API_KEY,CKAN_SERVER_IP);
+ $ckan->base_url='http://'.CKAN_SERVER_IP.':5000/api/1/';
+ try {
+ $result = $ckan->put_package_entity($packageName,json_encode($existingPackage));
+ }
+ catch (Exception $e) {
+ $error = new mb_exception('mod_syncCkan.php: update dataset http_code:'.$e->getMessage());
+ return false;
+ }
+ return $result;
+ break;
+ }
+ }
+ } else {
+ $error = new mb_exception('mod_syncCkan.php: No existing package found, deleting not needed!');
+ return true;
+ }
+}
+
+?>
More information about the Mapbender_commits
mailing list