Beispiel #1
0
 public function getResourcesCollection()
 {
     $collection = new Endpoint(new Customer());
     $collection->string('name', 'first_name');
     $collection->boolean('published', true);
     $collection->dateTime('updated', 'Last update');
     return $collection;
 }
 protected function setUp()
 {
     global $EndPoint4store, $modeDebug, $prefixSparql, $prefixTurtle, $graph1, $graph2;
     $s = new Endpoint($EndPoint4store, false, $modeDebug);
     $r = $s->delete($graph1);
     $r = $s->delete($graph2);
     $r = $s->delete("default:");
 }
 public function testInsertWhenOffline()
 {
     global $EndPoint4store, $modeDebug, $prefixSparql, $prefixTurtle, $graph1, $graph2;
     $sp = new Endpoint($EndPoint4store, false, $modeDebug);
     $q = $prefixSparql . " \n\n\t\t\tINSERT DATA {  \n\t\t\t\tGRAPH <" . $graph1 . "> {    \n\t\t\t\ta:A b:Name \"Test2\" .   \n\t\t\t\ta:A b:Name \"Test3\" .   \n\t\t\t\ta:A b:Name \"Test4\" .  \n    \t\t}}";
     $res = $sp->query($q, 'raw');
     $err = $sp->getErrors();
     if ($err) {
         //print_r($err);
     }
     $this->assertTrue(count($err) > 0);
     $this->assertFalse($res);
 }
 public static function handleEndpointRequest(Endpoint $Endpoint)
 {
     $Subscription = $Endpoint->getSubscription($GLOBALS['Session']->Person);
     if (!$Subscription && ($_SERVER['REQUEST_METHOD'] == 'POST' || $_SERVER['REQUEST_METHOD'] == 'PUT')) {
         $Subscription = Subscription::create(['EndpointID' => $Endpoint->ID, 'PersonID' => $GLOBALS['Session']->PersonID], true);
         return static::respond('subscriptionCreated', ['data' => $Subscription, 'success' => true]);
     } elseif ($Subscription && $_SERVER['REQUEST_METHOD'] == 'DELETE') {
         $Subscription->destroy();
         $Subscription = null;
         return static::respond('subscriptionDeleted', ['data' => $Subscription, 'success' => true]);
     }
     return static::respond('subscription', ['data' => $Subscription]);
 }
Beispiel #5
0
 function __construct($parameters)
 {
     $endpoint = new \Endpoint($this->endpoint);
     /* Add namespace prefixes to query */
     $query = $this->_joinAndAffix($this->prefixes, "\n", "PREFIX ");
     /* Add select statement to query */
     $query .= "\nSELECT DISTINCT * ";
     /* Add where clauses to query */
     $wheres = array('?laur rdf:type nobel:Laureate', '?laur rdfs:label ?label', 'optional { ?laur dbpedia-owl:birthPlace ?birthPlace }', 'optional { ?laur owl:sameAs ?sameAs }', '?laur nobel:laureateAward ?award', '?laur nobel:nobelPrize ?prize', '?laur foaf:gender ?gender');
     /* Select by award */
     if (isset($parameters['award'])) {
         $award = $parameters['award'];
         if (in_array($award, $this->awards)) {
             $wheres[] = "?award nobel:category <http://data.nobelprize.org/resource/category/{$award}>";
         }
     }
     /* Select by gender */
     if (isset($parameters['gender'])) {
         $gender = $parameters['gender'];
         if (in_array($gender, array('male', 'female'))) {
             $wheres[] = "?laur foaf:gender '{$gender}'";
         }
     }
     $whereString = $this->_joinAndAffix($wheres, "\n", "\t", ' .');
     /* Select by region */
     if (isset($parameters['region'])) {
         global $baseUrl;
         $url = "{$baseUrl}/regions-api.php";
         $regions_json = file_get_contents($url);
         $regionMapping = json_decode($regions_json, true);
         // assure that region is in list
         if (in_array($parameters['region'], array_keys($regionMapping))) {
             $filters = array();
             $data = $regionMapping[$parameters['region']];
             foreach ($data as $str) {
                 $str = urlencode(str_replace(" ", "_", $str));
                 $filters[] = "?birthPlace = <http://data.nobelprize.org/resource/country/{$str}>";
             }
             $filter = implode(' || ', $filters);
             $whereString .= "\n\tFILTER( {$filter} )";
         }
     }
     $query .= "WHERE {\n{$whereString}\n}\n";
     $this->_query = $query;
     global $gCacheLocal;
     if ($gCacheLocal) {
         global $gCache;
         $cacheKey = 'LD-' . md5($query);
         $result = $gCache->get($cacheKey);
         if ($result === null) {
             $result = $endpoint->query($query);
             global $gExternalLaureateDataCacheTime;
             $gCache->set($cacheKey, $result, $gExternalLaureateDataCacheTime * 3600);
         }
     } else {
         $result = $endpoint->query($query);
     }
     $this->_result = $result["result"]["rows"];
 }
Beispiel #6
0
 static function insert($turtle, $graph, $endpoint)
 {
     $sp_write = new Endpoint($endpoint, false);
     $q = "INSERT DATA {  \n\t\t\t\t\t\tGRAPH <" . $graph . "> {    \n\t\t\t\t\t\t{$turtle}\n\t\t    \t\t}}";
     $res = $sp_write->query($q, 'raw');
     $err = $sp_write->getErrors();
     if ($err) {
         throw new Exception(self::buildMessage($err));
     }
     if (!$res) {
         $msg = "Query insert new triples return: False without errors";
         throw new Exception($msg);
     }
 }
 /**
  * Test if Endpoints can be created for all databases
  */
 public function testDeleteNonExistentEndpoint()
 {
     $endpoint = 'tcp://127.0.0.1:8532';
     // Try to get a non-existent document out of a nonexistent collection
     // This should cause an exception with a code of 404
     try {
         $e = null;
         $response = Endpoint::delete($this->connection, $endpoint);
     } catch (\Exception $e) {
         // don't bother us... just give us the $e
     }
     $this->assertInstanceOf('triagens\\ArangoDb\\ServerException', $e);
     $this->assertTrue($e->getCode() == 404, 'Should be 404, instead got: ' . $e->getCode());
 }
Beispiel #8
0
 public function __construct($routeName, $tableName)
 {
     global $db;
     $this->_routeName = $routeName;
     $this->_tableName = $tableName;
     $query = "DESCRIBE {$tableName}";
     $result = $this->runQuery($query, "no fetch");
     $tableColumns = array();
     foreach ($result as $row) {
         if ($row['Key'] != "") {
             $this->_tableIndex = $row['Field'];
         }
         $tableColumns[] = array($row['Type'] => $row['Field']);
     }
     $this->_tableColumns = $tableColumns;
     $query = preg_replace("/request={$routeName}\\/{0,1}&{0,1}/", "", $_SERVER["QUERY_STRING"]);
     if (strpos($_SERVER["QUERY_STRING"], "&") === false) {
         $request = "{$routeName}/" . $query;
     } else {
         $request = "{$routeName}/?" . $query;
     }
     parent::__construct($request);
     $this->Request = urldecode($request);
 }
 private function findEndpoint()
 {
     if (!$this->getClient()->getCatalog()) {
         $this->getClient()->authenticate();
     }
     $catalog = $this->getClient()->getCatalog();
     echo "Catalog:<br/>";
     print_r($catalog);
     //echo "<br/>Catalog->getItems():<br/>";
     //print_r($catalog->getItems());
     // Search each service to find The One
     foreach ($catalog->getItems() as $service) {
         if ($service->hasType($this->type) && $service->hasName($this->name)) {
             $endpoint = $service->getEndpointFromRegion($this->region, $this->regionless);
             return Endpoint::factory($endpoint, $this->getClient());
         }
     }
     echo "<br/>CatalogService findEndpoint : no endpoint.<br/>";
     return null;
 }
<?php

/** 
 * @version 0.4.1
 * @package Bourdercloud/PHP4store
 * @copyright (c) 2011 Bourdercloud.com
 * @author Karima Rafes <*****@*****.**>
 * @license http://www.opensource.org/licenses/mit-license.php
 */
/** 
 * @ignore
 */
//require_once('php4store/Endpoint.php');
require '../lib/php4store/Endpoint.php';
$endpoint = "http://dbpedia.org/";
// READ ONLY  ******************************************
$sp_readonly = new Endpoint($endpoint);
$q = "select *  where {?x ?y ?z.} LIMIT 5";
$rows = $sp_readonly->query($q, 'rows');
$err = $sp_readonly->getErrors();
if ($err) {
    print_r($err);
    throw new Exception(print_r($err, true));
}
var_dump($rows);
Beispiel #11
0
 /**
  * Constructor. Creates a new endpoint.
  * @param string  $endpoint Endpoint name
  * @param array   $params   Endpoint params
  * @param boolean $signed   OAuth signed endpoint. Default set to false.
  */
 public function __construct($endpoint, $params = array(), $signed = FALSE)
 {
     $ep = array("method" => "GET", "endpoint" => $endpoint, "params" => $params, "signed" => $signed);
     // Constructs a new endpoint
     parent::__construct($ep);
 }
Beispiel #12
0
<?php

/** 
 * @version 0.4.1
 * @package Bourdercloud/PHP4store
 * @copyright (c) 2011 Bourdercloud.com
 * @author Karima Rafes <*****@*****.**>
 * @license http://www.opensource.org/licenses/mit-license.php
 */
/** 
 * @ignore
 */
require 'init4Store.php';
//require_once('php4store/Endpoint.php');
require '../lib/php4store/Endpoint.php';
//remove this line in your code
start4store();
$readonly = false;
$s = new Endpoint('http://*****:*****@prefix foaf: <http://xmlns.com/foaf/0.1/> .\n\t<http://github.com/bordercloud/4store-php> foaf:maker <http://www.bordercloud.com/wiki/user:Karima_Rafes> .\n");
var_dump($r);
echo "test " . $s->count();
//remove this line in your code
stop4store();
 /**
  * Validate the options
  *
  * @throws ClientException
  * @return void - will throw if an invalid option value is found
  */
 private function validate()
 {
     if (isset($this->_values[self::OPTION_HOST]) && !is_string($this->_values[self::OPTION_HOST])) {
         throw new ClientException('host should be a string');
     }
     if (isset($this->_values[self::OPTION_PORT]) && !is_int($this->_values[self::OPTION_PORT])) {
         throw new ClientException('port should be an integer');
     }
     // can use either endpoint or host/port
     if (isset($this->_values[self::OPTION_HOST]) && isset($this->_values[self::OPTION_ENDPOINT])) {
         throw new ClientException('must not specify both host and endpoint');
     } else {
         if (isset($this->_values[self::OPTION_HOST]) && !isset($this->_values[self::OPTION_ENDPOINT])) {
             // upgrade host/port to an endpoint
             $this->_values[self::OPTION_ENDPOINT] = 'tcp://' . $this->_values[self::OPTION_HOST] . ':' . $this->_values[self::OPTION_PORT];
         }
     }
     assert(isset($this->_values[self::OPTION_ENDPOINT]));
     // set up a new endpoint, this will also validate it
     $this->getEndpoint();
     if (Endpoint::getType($this->_values[self::OPTION_ENDPOINT]) === Endpoint::TYPE_UNIX) {
         // must set port to 0 for UNIX sockets
         $this->_values[self::OPTION_PORT] = 0;
     }
     if (isset($this->_values[self::OPTION_AUTH_TYPE]) && !in_array($this->_values[self::OPTION_AUTH_TYPE], self::getSupportedAuthTypes())) {
         throw new ClientException('unsupported authorization method');
     }
     if (isset($this->_values[self::OPTION_CONNECTION]) && !in_array($this->_values[self::OPTION_CONNECTION], self::getSupportedConnectionTypes())) {
         throw new ClientException(sprintf("unsupported connection value '%s'", $this->_values[self::OPTION_CONNECTION]));
     }
     UpdatePolicy::validate($this->_values[self::OPTION_UPDATE_POLICY]);
     UpdatePolicy::validate($this->_values[self::OPTION_REPLACE_POLICY]);
     UpdatePolicy::validate($this->_values[self::OPTION_DELETE_POLICY]);
 }
 /**
  * Create a request string (header and body)
  *
  * @param ConnectionOptions $options - connection options
  * @param string            $method  - HTTP method
  * @param string            $url     - HTTP URL
  * @param string            $body    - optional body to post
  * @param array             $customHeader - any arry containing header elements
  *
  * @return string - assembled HTTP request string
  */
 public static function buildRequest(ConnectionOptions $options, $method, $url, $body, $customHeader = array())
 {
     $host = $contentType = $authorization = $connection = '';
     $length = strlen($body);
     $endpoint = $options[ConnectionOptions::OPTION_ENDPOINT];
     if (Endpoint::getType($endpoint) !== Endpoint::TYPE_UNIX) {
         $host = sprintf('Host: %s%s', Endpoint::getHost($endpoint), self::EOL);
     }
     if ($options[ConnectionOptions::OPTION_BATCH] === true) {
         $contentType = 'Content-Type: multipart/form-data; boundary=' . self::MIME_BOUNDARY . self::EOL;
     } else {
         if ($length > 0 && $options[ConnectionOptions::OPTION_BATCHPART] === false) {
             // if body is set, we should set a content-type header
             $contentType = 'Content-Type: application/json' . self::EOL;
         }
     }
     if (isset($options[ConnectionOptions::OPTION_AUTH_TYPE]) && isset($options[ConnectionOptions::OPTION_AUTH_USER])) {
         // add authorization header
         $authorizationValue = base64_encode($options[ConnectionOptions::OPTION_AUTH_USER] . ':' . $options[ConnectionOptions::OPTION_AUTH_PASSWD]);
         $authorization = sprintf('Authorization: %s %s%s', $options[ConnectionOptions::OPTION_AUTH_TYPE], $authorizationValue, self::EOL);
     }
     if (isset($options[ConnectionOptions::OPTION_CONNECTION])) {
         // add connection header
         $connection = sprintf("Connection: %s%s", $options[ConnectionOptions::OPTION_CONNECTION], self::EOL);
     }
     $apiVersion = 'X-Arango-Version: ' . Connection::$_apiVersion . self::EOL;
     $customHeaders = "";
     foreach ($customHeader as $headerKey => $headerValue) {
         $customHeaders .= $headerKey . ": " . $headerValue . self::EOL;
     }
     // finally assemble the request
     $request = sprintf('%s %s %s%s', $method, $url, self::PROTOCOL, self::EOL) . $host . $apiVersion . $customHeaders . $contentType . $authorization . $connection . sprintf('Content-Length: %s%s%s', $length, self::EOL, self::EOL) . $body;
     return $request;
 }
Beispiel #15
0
 /**
  * This function parse a SPARQL query, send the query and parse the SPARQL result in a array. 
  * You can custom the result with the parameter $result_format : 
  * <ul>
  * <li>rows to return array of results
  * <li>row to return array of first result
  * <li>raw to return boolean for request ask, insert and delete
  * </ul>
  * @param string $q : Query SPARQL 
  * @param string $result_format : Optional,  rows, row or raw
  * @return array|boolean in function of parameter $result_format
  * @access public
  */
 public function query($q, $result_format = '')
 {
     $t1 = Endpoint::mtime();
     $response = $this->queryRead($q);
     xml_parse($this->_parserSparqlResult->getParser(), $response, true);
     $result = $this->_parserSparqlResult->getResult();
     $result['query_time'] = Endpoint::mtime() - $t1;
     return $result;
 }
Beispiel #16
0
 /**
  * This function parse a SPARQL query, send the query and parse the SPARQL result in a array. 
  * You can custom the result with the parameter $result_format : 
  * <ul>
  * <li>rows to return array of results
  * <li>row to return array of first result
  * <li>raw to return boolean for request ask, insert and delete
  * </ul>
  * @param string $q : Query SPARQL 
  * @param string $result_format : Optional,  rows, row or raw
  * @return array|boolean in function of parameter $result_format
  * @access public
  */
 public function query($q, $result_format = 'rows')
 {
     $t1 = Endpoint::mtime();
     $result = null;
     switch ($result_format) {
         case "json":
             $response = $this->queryRead($q, "application/sparql-results+json");
             $result = json_decode($response);
             break;
         case "row":
         case "raw":
         default:
             //rows
             $response = "";
             if (preg_match("/(INSERT|DELETE|CLEAR|LOAD)/i", $q)) {
                 $response = $this->queryUpdate($q);
             } else {
                 $response = $this->queryRead($q);
             }
             $parser = $this->_parserSparqlResult->getParser();
             $success = xml_parse($parser, $response, true);
             $result = $this->_parserSparqlResult->getResult();
             if (!$success) {
                 //if(! array_key_exists("result",$result)){
                 $message = "Error parsing XML result:" . xml_error_string(xml_get_error_code($parser)) . ' Response : ' . $response . "\n";
                 $error = $this->errorLog($q, null, $this->_endpoint, 200, $message);
                 $this->addError($error);
                 return false;
             }
     }
     $result['query_time'] = Endpoint::mtime() - $t1;
     switch ($result_format) {
         case "row":
             return $result["result"]["rows"][0];
         case "raw":
             return $result["result"]["rows"][0][$result["result"]["variables"][0]];
         case "json":
         default:
             //rows
             return $result;
     }
 }
 public function execute($par = null)
 {
     global $wgOut, $wgScriptPath;
     $queryWithoutPrefix = isset($_REQUEST["queryWithoutPrefix"]) ? stripslashes($_REQUEST["queryWithoutPrefix"]) : "";
     $query = isset($_REQUEST["query"]) ? stripslashes($_REQUEST["query"]) : "";
     $endpoint = isset($_REQUEST["endpoint"]) ? stripslashes(trim($_REQUEST["endpoint"])) : "http://dbpedia.org/sparql";
     $output = isset($_REQUEST["output"]) ? stripslashes($_REQUEST["output"]) : "";
     $titleRequest = isset($_REQUEST["titleRequest"]) ? stripslashes($_REQUEST["titleRequest"]) : "";
     $description = isset($_REQUEST["description"]) ? stripslashes($_REQUEST["description"]) : "";
     // $wgOut->addHTML( isset($_REQUEST["query"])?stripslashes($_REQUEST["query"]):"Vide");
     // $wgOut->addHTML(print_r($_REQUEST,true));
     // $wgOut->addHTML(print_r($queryWithoutPrefix,true));
     // $wgOut->addHTML(print_r($query,true));
     // $wgOut->addHTML(print_r($output,true));
     if ($query != "" && $output == "save" && $titleRequest != "") {
         if ($this->pageExists($titleRequest)) {
             $wgOut->addHTML("<h2>" . wfMsg('specialsparqlquery_error_title_exists_yet') . "</h2> \n");
             $wgOut->addHTML();
         } else {
             $this->savePage($titleRequest, $this->template($query, $description));
             $wgOut->addWikiText(wfMsg('specialsparqlquery_your_query_saved_here') . "[[{$titleRequest}]]");
         }
     }
     if ($query == "" || $output == "save" || $output == "wiki") {
         $wgOut->addWikiText(wfMsg('specialsparqlquery_mainpage'));
         $wgOut->addHTML("<pre>" . htmlentities($this->prefix(), ENT_QUOTES, 'UTF-8') . "</pre>");
         $wgOut->addHTML("<form method='post' name='formQuery'>");
         $wgOut->addHTML("<input type='hidden' name='output' value='wiki'>");
         $wgOut->addHTML("<input type='hidden' name='prefix' value='" . htmlentities($this->prefix(), ENT_QUOTES, 'UTF-8') . " '>");
         $wgOut->addHTML("<input type='hidden' name='query' >");
         $wgOut->addHTML(wfMsg('specialsparqlquery_endpointsparql') . " : <input type='text' name='endpoint' size='50' value='" . $endpoint . " '>");
         $wgOut->addHTML("<textarea name='queryWithoutPrefix' cols='25' rows='15'>");
         $strQuery = $queryWithoutPrefix != "" ? $queryWithoutPrefix : $this->exampleSparql(0);
         $wgOut->addHTML($strQuery);
         $wgOut->addHTML("</textarea>");
         $wgOut->addHTML("<br/>");
         $wgOut->addHTML("<script language='javascript' type='text/javascript' src='" . $wgScriptPath . "/extensions/LinkedWiki/js/bordercloud.js'></script>");
         $wgOut->addHTML("<SCRIPT>\r\n<!-- \r\nfunction validAndSendQuery(){\r\n\tvar query = document.formQuery.prefix.value + ' ' + document.formQuery.queryWithoutPrefix.value;\r\n\tif(! document.formQuery.toXML.checked){\r\n\t\tdocument.formQuery.query.value= query;\r\n\t\tdocument.formQuery.submit();\r\n\t}else{\t\t\r\n\t\twindow.open('" . $endpoint . "?query=' + escape(query.replace('\\n','')));\r\n\t}\r\n}\r\nfunction validWithJS(){\r\n\tvar query = document.formQuery.prefix.value + ' ' + document.formQuery.queryWithoutPrefix.value;\r\n\r\n\tbcValidateSPARQL('" . $endpoint . "',query);\r\n}\r\n//-->\r\n</SCRIPT>");
         $wgOut->addHTML("<input type='button' value='" . wfMsg('specialsparqlquery_sendquery') . "'  onClick='validAndSendQuery();' />");
         $wgOut->addHTML("<input type='button' value='(R&D) Validation (js)'  onClick='validWithJS();' />");
         $wgOut->addHTML("   Xml : <input type='checkbox'  name='toXML' />");
         $wgOut->addHTML(" </form>");
         $wgOut->addHTML("<div  id='bc_div'></div>");
         $wgOut->addHTML("<div style='display: none;'>");
         $wgOut->addHTML("<img id='canvas-image-wait' src='" . $wgScriptPath . "/extensions/LinkedWiki/js/wait.png'></img>");
         $wgOut->addHTML("</div>");
         if ($queryWithoutPrefix != "") {
             $sp = new Endpoint($endpoint);
             $rs = $sp->query($query);
             $errs = $sp->getErrors();
             if ($errs) {
                 $wgOut->addHTML("<h1>ERROR(s)</h1>\n");
                 foreach ($errs as $err) {
                     if (is_array($err)) {
                         foreach ($err as $suberr) {
                             $wgOut->addHTML("<pre>{$suberr}.</pre> \n");
                         }
                     } else {
                         if (preg_match("/bcjeton/i", $err) && (preg_match("/insert/i", $strQuery) || preg_match("/delete/i", $strQuery))) {
                             $wgOut->addHTML("<pre>You have not the right to write in the dataset.</pre> \n");
                         } else {
                             $wgOut->addHTML("<pre>{$err}.</pre> \n");
                         }
                     }
                 }
             } else {
                 //						//efSparqlParserFunction_simple( $querySparqlWiki,$endpoint ,$classHeaders = '',$headers = '', $debug = null)
                 $arr = efSparqlParserFunction_simple($query, $endpoint, '', '', null);
                 $wgOut->addWikiText($arr[0]);
                 $wgOut->addWikiText("==" . wfMsg('specialsparqlquery_usethisquery') . "==");
                 $wgOut->addWikiText(wfMsg('specialsparqlquery_usethisquery_tutorial'));
                 $wgOut->addHTML("<pre>{{#sparql:" . htmlentities($query, ENT_QUOTES, 'UTF-8') . "\n|endpoint=" . htmlentities($endpoint, ENT_QUOTES, 'UTF-8') . "}}</pre>");
             }
             //$wgOut->addWikiText("==".wfMsg('specialsparqlquery_linkxml')."==");
             //$queryurl= $endpoint."?query=".urlencode( str_replace('\n','',$query));
             //$wgOut->addHTML("<a href='$queryurl'>".htmlentities( $queryurl, ENT_QUOTES, 'UTF-8')."</a>");
         }
     }
     $this->setHeaders();
 }
Beispiel #18
0
<?php

/** 
 * @version 0.4.1
 * @package Bourdercloud/PHP4store
 * @copyright (c) 2011 Bourdercloud.com
 * @author Karima Rafes <*****@*****.**>
 * @license http://www.opensource.org/licenses/mit-license.php
 */
/** 
 * @ignore
 */
require 'init4Store.php';
//require_once('php4store/Endpoint.php');
require '../lib/php4store/Endpoint.php';
//remove this line in your code
start4store();
$readonly = false;
$s = new Endpoint('http://*****:*****@prefix foaf: <http://xmlns.com/foaf/0.1/> .\n\t<http://www.bordercloud.com/wiki/user:Karima_Rafes>  foaf:workplaceHomepage <http://www.bordercloud.com>.\n");
var_dump($r);
//remove this line in your code
stop4store();
Beispiel #19
0
 /**
  * Update specific parameters on the logged-in user
  *
  * @param  array $parameters Array containing the parameters to update
  * @return void
  */
 public function update(array $parameters)
 {
     $user = json_decode(self::put("me", ['json' => $parameters])->getBody(), true);
     parent::update($user);
 }
Beispiel #20
0
 /**
  * @param $args (array)
  *    required args are
  *      - realm ( i.e. user,site,organization )
  *      - path ( specific method to call )
  */
 static function get($args)
 {
     $endpoint = new Endpoint($args);
     return $endpoint->lookup($args);
 }
Beispiel #21
0
 /**
  * Sets the passed options on the endpoint.
  *
  * Only sets endpoints matching setters in the Endpoint class.
  *
  * @param Endpoint $endpoint
  * @param array    $options
  *
  * @return Endpoint
  * @throws MalformedRouteException
  */
 protected function setOptions(Endpoint $endpoint, array $options)
 {
     if (isset($options['guard'])) {
         $endpoint->setGuard($options['guard']);
     }
     if (isset($options['filter'])) {
         $endpoint->setFilter($options['filter']);
     }
     if (isset($options['prefix'])) {
         $endpoint->setPrefix($options['prefix']);
     }
     return $endpoint;
 }
Beispiel #22
0
class Endpoint
{
    public $start_time;
    function __construct()
    {
        $this->start_time = time();
        ini_set('error_log', '/home/sean/errors');
        ini_set('error_append_string', '\\n---------');
        error_log("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
        require_once '/home/sean/projects/common/orm.php';
        require_once '/home/sean/projects/common/helper.php';
        $here = scandir('.');
        foreach ($here as $v) {
            if (strpos($v, '.php') === FALSE) {
                continue;
            }
            require_once __DIR__ . '/' . $v;
        }
    }
    function exec()
    {
        try {
            $lvb = new LongPollQuery();
            $lvb->poll();
        } catch (Exception $e) {
            echo json_encode(array('Exception' => $e->getMessage()));
        }
    }
}
$endpoint = new Endpoint();
$endpoint->exec();
Beispiel #23
0
 /**
  * Retrieves an endpoint
  * @param [array] $args Elements as follow:
  *        [string] realm user, site, organization
  *        [string] path specific method to call
  * @return [string] $endpoint_string
  */
 static function get($args)
 {
     $endpoint = new Endpoint($args);
     $endpoint_string = $endpoint->lookup($args);
     return $endpoint_string;
 }
 /**
  * Add endpoint.
  *
  * @param string $publicUrl
  * @param string $adminUrl
  *
  * @return $this
  */
 public function addEndpoint($publicUrl, $adminUrl)
 {
     $endpoint = new Endpoint();
     $endpoint->setPublicUrl($publicUrl);
     $endpoint->setAdminUrl($adminUrl);
     $endpoint->setService($this);
     $this->endpoints[] = $endpoint;
     return $this;
 }
Beispiel #25
0
<?php

// git clone https://github.com/BorderCloud/SPARQL
// ./query -r -e https://example.com/sparql-auth  -f ./example/queryRead1.rq -l login -p password -v
require_once '../Endpoint.php';
$endpoint = "https://example.com/sparql-auth";
$sp_ReadAndWrite = new Endpoint($endpoint, false);
$sp_ReadAndWrite->setLogin("login");
$sp_ReadAndWrite->setPassword("password");
$q = "select *  where {?x ?y ?z.} LIMIT 5";
$rows = $sp_ReadAndWrite->query($q, 'rows');
$err = $sp_ReadAndWrite->getErrors();
if ($err) {
    print_r($err);
    throw new Exception(print_r($err, true));
}
foreach ($rows["result"]["variables"] as $variable) {
    printf("%-20.20s", $variable);
    echo '|';
}
echo "\n";
foreach ($rows["result"]["rows"] as $row) {
    foreach ($rows["result"]["variables"] as $variable) {
        printf("%-20.20s", $row[$variable]);
        echo '|';
    }
    echo "\n";
}
?>

 /**
  * Create a new public Ajax endpoint with preconfigured headers for JSON values.
  * @param string $action The action name associated to your endpoint.
  * @param callable $handler The callback executed each time the endpoint is requested.
  */
 public function __construct($action, callable $handler)
 {
     parent::__construct($action, $handler, true);
 }
Beispiel #27
0
<?php

// git clone https://github.com/BorderCloud/SPARQL
// ./query -r -e https://example.com/sparql-auth  -f ./example/queryRead1.rq -l login -p password -v
require_once '../Endpoint.php';
$endpoint = "http://example.com/sparql-auth/";
$sp_ReadAndWrite = new Endpoint($endpoint, false, true);
$sp_ReadAndWrite->setEndpointQuery($endpoint);
$sp_ReadAndWrite->setEndpointUpdate($endpoint);
$sp_ReadAndWrite->setLogin("test");
$sp_ReadAndWrite->setPassword("test!");
/*
    PREFIX dct: <http://purl.org/dc/terms/>
PREFIX dctype: <http://purl.org/dc/dcmitype/>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX vcard: <http://www.w3.org/2006/vcard/ns#>
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
     * 
PREFIX dcat: <http://www.w3.org/ns/dcat#>
PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>            
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
     * */
$q = <<<EOT
            
PREFIX theme: <http://data.sparql.pro/w/Q> 
PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>   
            
INSERT 
  { GRAPH <http://sparql.pro/lodTest> { 
 /**
  * @depends testCheck
  */
 public function testCount()
 {
     global $EndPoint4store, $modeDebug, $prefixSparql, $prefixTurtle, $graph1, $graph2;
     $s = new Endpoint($EndPoint4store, true, $modeDebug);
     $this->assertEquals(0, $s->count($graph1));
 }
Beispiel #29
0
<?php

require_once '../Endpoint.php';
$endpoint = "http://data.bnf.fr/sparql";
$sp_readonly = new Endpoint($endpoint);
$sp_readonly->setMethodHTTPRead("GET");
$q = "select *  where {?x ?y ?z.} LIMIT 5";
$rows = $sp_readonly->query($q, 'rows');
$err = $sp_readonly->getErrors();
if ($err) {
    print_r($err);
    throw new Exception(print_r($err, true));
}
foreach ($rows["result"]["variables"] as $variable) {
    printf("%-20.20s", $variable);
    echo '|';
}
echo "\n";
foreach ($rows["result"]["rows"] as $row) {
    foreach ($rows["result"]["variables"] as $variable) {
        printf("%-20.20s", $row[$variable]);
        echo '|';
    }
    echo "\n";
}
?>

Beispiel #30
0
function efSparqlParserFunction_tableCell($querySparqlWiki, $endpoint, $debug = null)
{
    $specialC = array("&#39;");
    $replaceC = array("'");
    $querySparql = str_replace($specialC, $replaceC, $querySparqlWiki);
    $str = "";
    $sp = new Endpoint($endpoint);
    $rs = $sp->query($querySparqlWiki);
    $errs = $sp->getErrors();
    if ($errs) {
        $strerr = "";
        foreach ($errs as $err) {
            $strerr .= "'''Error #sparql :" . $err . "'''<br/>";
        }
        return $strerr;
    }
    $lignegrise = false;
    $variables = $rs['result']['variables'];
    $str = "";
    foreach ($rs['result']['rows'] as $row) {
        $str .= "\n";
        $separateur = "| ";
        foreach ($variables as $variable) {
            if ($row[$variable . " type"] == "uri") {
                $str .= $separateur . efSparqlParserFunction_uri2Link($row[$variable]);
            } else {
                $str .= $separateur . $row[$variable];
            }
            $separateur = " || ";
        }
        $str .= "\n|- \n";
    }
    if ($debug != null && $debug == "YES") {
        $str .= "INPUT WIKI : " . $querySparqlWiki . "\n";
        $str .= "Query : " . $querySparql . "\n";
        $str .= print_r($rs, true);
        $str .= print_r($rs, true);
        return array("<pre>" . $str . "</pre>", 'noparse' => true, 'isHTML' => false);
    }
    return array($str, 'noparse' => false, 'isHTML' => false);
}