public function viewAction() { $this->view->placeholder('main.window.title')->set('Historyproxy'); $this->addModuleContext('main.window.historyproxy.search'); OntoWiki::getInstance()->getNavigation()->disableNavigation(); $model = $this->_owApp->selectedModel; $event = new Erfurt_Event('onQueryHistory'); // $model->getModelIri() /** * Get last imports */ $event->function = 'getLastImports'; $event->parameters = array(); $event->trigger(); $this->view->importsFunction = $event->function; $this->view->importsParameters = $event->parameters; $this->view->importsCallback = $event->callback; /** * Get last changes */ $event->function = 'getChangesFromRange'; $event->parameters = array($model->getModelIri(), '01-01-2014', '30-01-2014'); $event->trigger(); $this->view->changeFunction = $event->function; $this->view->changeParameters = $event->parameters; $this->view->changeCallback = $event->callback; }
/** * RouteStartup is triggered before any routing happens. */ public function routeStartup(Zend_Controller_Request_Abstract $request) { /** * @trigger onRouteStartup */ $event = new Erfurt_Event('onRouteStartup'); $event->trigger(); }
public function displayLiteralPropertyValue($value = null, $property = '', $datatype = 'http://www.w3.org/2001/XMLSchema#string') { if ($value === null) { $newValue = ''; } else { $event = new Erfurt_Event('onDisplayLiteralPropertyValue'); $event->value = $value; $event->datatype = $datatype; $event->property = $property; $newValue = $event->trigger(); // TODO: check why newValue sometimes is null if ($newValue == null) { $newValue = $value; } } return $newValue; }
/** * Returns the property values for all resources at once. * This method generate one SPARQL query to receive all values . * Original Name was getValues() * @return array */ public function getValuesBySingleQuery() { if ($this->_valuesUptodate) { return $this->_values; } else { $this->updateValueQuery(); } if (empty($this->_resources)) { return array(); } $this->getResults(); $result = array(); if (isset($this->_results['results']['bindings'])) { $result = $this->_results['results']['bindings']; } //fill titlehelper foreach ($result as $row) { foreach ($this->_shownProperties as $property) { if (isset($row[$property['varName']]) && $row[$property['varName']]['type'] == 'uri' && substr($row[$property['varName']]['value'], 0, 2) != '_:') { $this->_titleHelper->addResource($row[$property['varName']]['value']); } } if (isset($row['__TYPE']) && $row['__TYPE']['type'] == 'uri') { $this->_titleHelper->addResource($row['__TYPE']['value']); } $this->_titleHelper->addResource($row[$this->_resourceVar->getName()]['value']); } $valueResults = array(); foreach ($result as $row) { $resourceUri = $row[$this->_resourceVar->getName()]['value']; if (!array_key_exists($resourceUri, $valueResults)) { $valueResults[$resourceUri] = array(); } $url = new OntoWiki_Url(array('route' => 'properties'), array('r')); $value = null; $link = null; foreach ($row as $varName => $data) { if (!isset($valueResults[$resourceUri][$varName])) { $valueResults[$resourceUri][$varName] = array(); } if ($data['type'] == 'uri') { if (substr($data['value'], 0, 2) == '_:') { continue; // skip blanknode values here due to backend problems with filters } // object type is uri --> handle object property $objectUri = $data['value']; $url->setParam('r', $objectUri, true); $link = (string) $url; // set up event $event = new Erfurt_Event('onDisplayObjectPropertyValue'); //find uri foreach ($this->_shownProperties as $property) { if ($varName == $property['varName']) { $event->property = $property['uri']; } } $event->value = $objectUri; // trigger $value = $event->trigger(); // set default if event has not been handled if (!$event->handled()) { $value = $this->_titleHelper->getTitle($objectUri); } } else { // object is a literal $object = $data['value']; $propertyUri = null; foreach ($this->_shownProperties as $property) { if ($varName == $property['varName']) { $propertyUri = $property['uri']; } } if ($object !== null) { // set up event $event = new Erfurt_Event('onDisplayLiteralPropertyValue'); $event->property = $propertyUri; $event->value = $object; $event->setDefault($object); // trigger $value = $event->trigger(); } } //check for dulplicate values if (isset($valueResults[$resourceUri][$varName])) { foreach ($valueResults[$resourceUri][$varName] as $old) { if ($old['origvalue'] == $data['value'] && $old['type'] == $data['type']) { $link = null; continue 2; // dont add this value } } } //add value $valueResults[$resourceUri][$varName][] = array('value' => $value, 'origvalue' => $data['value'], 'type' => $data['type'], 'url' => $link, 'uri' => $data['value']); $value = null; $link = null; } } foreach ($this->getShownResources() as $resource) { if (!isset($valueResults[$resource['value']])) { //there are no statements about this resource $valueResults[$resource['value']] = array(); } } $this->_values = $valueResults; $this->_valuesUptodate = true; return $valueResults; }
private function endOutput($config) { $event = new Erfurt_Event('onNavigationEndOutput'); $event->config = $config; $event->trigger(); }
/** * Searches for relevant URIs for given term(s). This service has two * modes. One that returns all matching URIs and one that returns only * resource URIs that are defined as properties or at least used once as * property. * * q - The mandatory parameter q contains a whitespace seperated list of * serach terms. * * mode - This optional parameter sets the search mode. The default value * is 0. In this mode all matching URIs will be returned. If the * mode is set to 1, only matching URIs are returned, that are * defined as properties or that are used as propertie at least * once. * * limit - Optional sets the maximum number of URIs the result may contain. * The default value is SEARCH_DEFAULT_LIMIT. The maximum value * is SEARCH_MAX_LIMIT. * * classes - an optional paramter which is a json_encoded array of class URIs * * This service will output a json encoded string, which represents the * result list. Each entry is returned with an title, the URI itself and * the source of that result. The entry components are sepearted by a | and * the entries are seperated by a newline. If nothing is found an empty * json encodes string will be returned. */ public function searchAction() { // Use the selected graph if present. If not, search all available graphs. if (null === $this->_graphUri) { throw new OntoWiki_Exception("model must be selected or specified with the m parameter"); } $modelUri = $this->_graphUri; // Check for the mandatory q parameter. $q = $this->_request->q; if (null === $q) { $this->_response->setRawHeader('HTTP/1.0 400 Bad Request'); echo '400 Bad Request - The q parameter is missing.'; return; } $termsArray = explode(' ', $q); // check for the classes json array $classes = array(); if (null !== $this->_request->classes) { $classes = json_decode($this->_request->classes); if (!is_array($classes)) { $classes = array(); } } // Set the search mode. if (null !== $this->_request->mode) { if ((int) $this->_request->mode === self::SEARCH_MODE_PROPERTIES) { $mode = self::SEARCH_MODE_PROPERTIES; } else { // Default to search mode all. $mode = self::SEARCH_MODE_ALL; } } else { $mode = self::SEARCH_MODE_ALL; } // Check for optional limit parameter. if (null !== $this->_request->limit) { $limit = $this->_request->limit; if ((int) $limit > 0 && $limit <= self::SEARCH_MAX_LIMIT) { $limit = (int) $limit; } else { // Default to search mode all. $limit = self::SEARCH_DEFAULT_LIMIT; } } else { $limit = self::SEARCH_DEFAULT_LIMIT; } // Check whether given term is a URI! If a URI is given we return an empty result, for some users // may want to enter URIs themself. if (count($termsArray) === 1) { foreach ($termsArray as $t) { $regExp = '/^(' . implode(':|', $this->_listIanaSchemes()) . ':).$/'; if (preg_match($regExp, $t)) { echo json_encode(''); return; } if (strlen($t) > 20) { echo json_encode(''); return; } } } $result = array(); // Step 1a: Search the local database for URIs (class restricted) $localWithRestriction = $this->_searchLocal($termsArray, $modelUri, $mode, $limit, $classes); if (count($localWithRestriction) > 0) { $result = $localWithRestriction; } // Step 1b: Search the local database for URIs (NOT class restricted) $local = $this->_searchLocal($termsArray, $modelUri, $mode, $limit); if (count($local) > 0) { // put new result values at the end of the result array foreach ($local as $resultKey => $resultValue) { if (!isset($result[$resultKey])) { $result[$resultKey] = $resultValue; } } } if ($mode === self::SEARCH_MODE_ALL && count($result) < $limit) { // Step 2: Extend the result with the results from plugins... $currentCount = count($result); require_once 'Erfurt/Event.php'; $event = new Erfurt_Event('onDatagatheringComponentSearch'); $event->translate = $this->_owApp->translate; $event->termsArray = $termsArray; $event->modelUri = $modelUri; $event->classes = $classes; $pluginResult = $event->trigger(); if (is_array($pluginResult)) { foreach ($pluginResult as $uri => $value) { if (!isset($result[$uri])) { $result[$uri] = $value; $currentCount++; } if ($currentCount === $limit) { break; } } } // 3. Step: Expand qnames if (count($result) < $limit) { $currentCount = count($result); $expanded = $this->_expandNamespaces($termsArray, $modelUri); if (count($expanded) > 0) { foreach ($expanded as $uri => $value) { if (!isset($result[$uri])) { $result[$uri] = $value; $currentCount++; } if ($currentCount === $limit) { break; } } } } // 4. If there is place for one more result, we add auto generated URI. if (count($result) < $limit) { $store = Erfurt_App::getInstance()->getStore(); $model = $store->getModel($modelUri); if ($model) { $suffix = ''; foreach ($termsArray as $t) { $suffix .= ucfirst($t); } $prefix = $model->getBaseUri(); $lastChar = substr($prefix, -1); if ($lastChar !== '/' && $lastChar !== '#') { $prefix .= '/'; } $uri = $prefix . urlencode($suffix); if (!isset($result[$uri])) { $translate = $this->_owApp->translate; $result[$uri] = implode(' ', $termsArray) . '|' . $uri . '|' . $translate->_('Generated URI'); } } } } // 5. if the user input was an URI, give this URI as result back too if (Zend_Uri::check($termsArray[0]) == true) { $translate = $this->_owApp->translate; $result = array($termsArray[0] => $termsArray[0] . '|' . $termsArray[0] . '|' . $translate->_('your manual input')) + $result; } $body = json_encode(implode(PHP_EOL, $result)); if (isset($this->_request->callback)) { $callback = $this->_request->callback; // build jsonp $body = $callback . ' (' . $body . ')'; } // send $response = $this->getResponse(); // comment from seebi: why this issnt set to application/json? with //$response->setHeader('Content-Type', 'application/json'); $response->setBody($body); }
/** * Builds the query part of the URL */ protected function _buildQuery() { $event = new Erfurt_Event('onBuildUrl'); $event->base = $this->_base; $event->route = $this->_route; $event->controller = $this->_controller; $event->action = $this->_action; $event->params = $this->_params; $urlCreated = $event->trigger(); if ($event->handled()) { if ($urlCreated && isset($event->url)) { return $event->url; } else { $this->_params = $event->params; $this->_controller = $event->controller; $this->_action = $event->action; $this->_route = $event->route; } } // check params foreach ($this->_params as $name => $value) { if (is_string($value) && preg_match('/\\//', $value)) { $this->_useSefUrls = false; } } $url = ''; if ($this->_route) { // checking if reset of route-defaults necessary // fixes pager usage fails on versioning pages if (count($this->_route->getDefaults()) == 0) { $resetRoute = false; } else { $resetRoute = true; } if ($this->_useSefUrls) { // let the route assemble the whole URL $url = $this->_route->assemble($this->_params, $resetRoute, true); } else { // we will assign parameters ourselves $url = $this->_route->assemble(array(), $resetRoute); $url = sprintf('%s/%s', $url, '?' . http_build_query($this->_params, '&')); } } else { if ($this->_useSefUrls) { $query = ''; $lastKey = ''; foreach ($this->_params as $key => $value) { if (is_scalar($value)) { $value = urlencode($value); $query .= "{$key}/{$value}/"; $lastKey = $key; } } // remove trailing slash $query = rtrim($query, '/'); } else { $query = '?' . http_build_query($this->_params, '&'); } $parts = array_filter(array($this->_controller, $this->_action, $query)); $url = implode('/', $parts); } // HACK: $this->_useSefUrls = true; return $this->_base . ltrim($url, '/'); }
/** * This method is called, when the onIsDispatchable event was triggered. * * The onIsDispatchable event is fired in an early stage of the OntoWiki * request lifecycle. Hence it is not decided in that moment, which controller * an action will be used. * * The given Erfurt_Event object has an uri property, which contains the * requested URI. The method then checks if a resource identified by that * URI exists in the local store. Iff this is the case it sends a redirect * to another URL depending on the requested MIME type. * * $event->uri contains the request URI. * * @param Erfurt_Event $event The event containing the required parameters. * * @return boolean false if the request was not handled, i.e. no resource was found. */ public function onIsDispatchable($event) { $store = null; try { $store = OntoWiki::getInstance()->erfurt->getStore(); } catch (Exception $e) { // if we can't get the store, we do nothing return; } $request = Zend_Controller_Front::getInstance()->getRequest(); $response = Zend_Controller_Front::getInstance()->getResponse(); $aliascheck = new Erfurt_Event('onResolveDomainAliasInput'); $aliascheck->uri = $event->uri; $aliascheck->trigger(); $uri = $aliascheck->uri; try { // Check for a supported type by investigating the suffix of the URI or by // checking the Accept header (content negotiation). The $matchingSuffixFlag // parameter contains true if the suffix was used instead of the Accept header. $matchingSuffixFlag = false; $type = $this->_getTypeForRequest($request, $uri, $matchingSuffixFlag); // We need a readable graph to query. We use the first graph that was found. // If no readable graph is available for the current user, we cancel here. list($graph, $matchedUri) = $this->_matchGraphAndUri($uri); if (!$graph || !$matchedUri) { // URI not found return false; } if ($uri !== $matchedUri) { // Re-append faux file extension if ($matchingSuffixFlag) { $matchedUri .= '.' . $type; } // Redirect to new (correct URI) $response->setRedirect((string) $matchedUri, 301); return; } // Prepare for redirect according to the given type. $url = null; // This will contain the URL to redirect to. switch ($type) { case 'rdf': case 'n3': case 'ttl': // Check the config, whether provenance information should be included. $prov = false; if (isset($this->_privateConfig->provenance) && isset($this->_privateConfig->provenance->enabled)) { $prov = (bool) $this->_privateConfig->provenance->enabled; } // Special case: If the graph URI is identical to the requested URI, we export // the whole graph instead of only data regarding the resource. if ($graph === $uri) { $controllerName = 'model'; $actionName = 'export'; } else { $controllerName = 'resource'; $actionName = 'export'; } // Create a URL with the export action on the resource or model controller. // Set the required parameters for this action. $url = new OntoWiki_Url(array('controller' => $controllerName, 'action' => $actionName), array()); $url->setParam('r', $uri, true)->setParam('f', $type)->setParam('m', $graph)->setParam('provenance', $prov); break; case 'html': default: // Defaults to the standard property view. // Set the required parameters for this action. $url = new OntoWiki_Url(array('route' => 'properties'), array()); $url->setParam('r', $uri, true)->setParam('m', $graph); break; } // Make $graph the active graph (session required) and make the resource // in $uri the active resource. $activeModel = $store->getModel($graph); OntoWiki::getInstance()->selectedModel = $activeModel; OntoWiki::getInstance()->selectedResource = new OntoWiki_Resource($uri, $activeModel); // Mark the request as dispatched, since we have all required information now. $request->setDispatched(true); // Give plugins a chance to do something before redirecting. $event = new Erfurt_Event('onBeforeLinkedDataRedirect'); $event->response = $response; $event->trigger(); // Give plugins a chance to handle the redirection instead of doing it here. $event = new Erfurt_Event('onShouldLinkedDataRedirect'); $event->request = $request; $event->response = $response; $event->type = $type; $event->uri = $uri; $event->flag = $matchingSuffixFlag; $event->setDefault(true); $shouldRedirect = $event->trigger(); if ($shouldRedirect) { // set redirect and send immediately $response->setRedirect((string) $url, 303); return; } return !$shouldRedirect; // will default to false } catch (Erfurt_Exception $e) { // don't handle errors since other plug-ins // could chain this event return false; } }
/** * trigger events, based on nowstring and load * * @return void */ private function _triggerEvents() { $now = new DateTime($this->nowString); $lastMinutly = new DateTime($this->load->lastMinutly); $lastMinutlyDiff = $this->_toSeconds($now->diff($lastMinutly)); if ($lastMinutlyDiff >= 60) { $this->load->lastMinutly = $this->nowString; /** * @trigger onEveryMinute */ $event = new Erfurt_Event('onEveryMinute'); $event->trigger(); if ($event->handled) { $this->logSuccess('triggered onEveryMinute (handled)'); } else { $this->logSuccess('triggered onEveryMinute (but not handled)'); } } $lastHourly = new DateTime($this->load->lastHourly); $lastHourlyDiff = $this->_toSeconds($now->diff($lastHourly)); if ($lastHourlyDiff >= 60 * 60) { $this->load->lastHourly = $this->nowString; /** * @trigger onEveryHour */ $event = new Erfurt_Event('onEveryHour'); $event->trigger(); if ($event->handled) { $this->logSuccess('triggered onEveryHour (handled)'); } else { $this->logSuccess('triggered onEveryHour (but not handled)'); } } $lastDaily = new DateTime($this->load->lastDaily); $lastDailyDiff = $this->_toSeconds($now->diff($lastDaily)); if ($lastDailyDiff >= 60 * 60 * 24) { $this->load->lastDaily = $this->nowString; /** * @trigger onEveryDay */ $event = new Erfurt_Event('onEveryDay'); $event->trigger(); if ($event->handled) { $this->logSuccess('triggered onEveryDay (handled)'); } else { $this->logSuccess('triggered onEveryDay (but not handled)'); } } }
protected function _checkTargetExists($targetUri) { if ($this->_targetGraph == null) { $event = new Erfurt_Event('onNeedsGraphForLinkedDataUri'); $event->uri = $targetUri; $graph = $event->trigger(); if ($graph) { $this->_targetGraph = $graph; /* * If we get a target graph from linked data plugin, we know that the target uri * exists, since getGraphsUsingResource ist used by store. */ return true; } else { /* * If there is no answer to 'onNeedsGraphForLinkedDataUri' we have to ask the store */ $store = Erfurt_App::getInstance()->getStore(); $graphs = $store->getReadableGraphsUsingResource($targetUri); if ($graphs === null) { return false; } else { $this->_targetGraph = $graphs[0]; return true; } } } }
private function _isLinkedDataUri($uri) { $event = new Erfurt_Event('onNeedsLinkedDataUri'); $event->uri = $uri; $result = (bool) $event->trigger(); return $result; }
private function _getImportActions() { /** * @trigger onProvideImportActions event to provide additional import actions * * Parameter: importActions * * Example: * <code> * <?php * $importActions = array('empty' => array( * 'controller' => 'model', * 'action' => 'info', * 'label' => 'Create an (nearly) empty knowledge base', * 'description' => 'Just add the label to the new model.' * )); * ?> * </code> */ $event = new Erfurt_Event('onProvideImportActions'); $event->importActions = array(); $result = $event->trigger(); return $event->importActions; }
/** * Constructor */ public function init() { /** * @trigger onBeforeInitController * Triggered before a controller of class OntoWiki_Controller_Base (or derived) * is initialized. */ $event = new Erfurt_Event('onBeforeInitController'); $eventResult = $event->trigger(); // init controller variables $this->_owApp = OntoWiki::getInstance(); $this->_config = $this->_owApp->config; $this->_session = $this->_owApp->session; $this->_erfurt = $this->_owApp->erfurt; $this->_eventDispatcher = Erfurt_Event_Dispatcher::getInstance(); // set important script variables $this->view->themeUrlBase = $this->_config->themeUrlBase; $this->view->urlBase = $this->_config->urlBase; $this->view->staticUrlBase = $this->_config->staticUrlBase; $this->view->libraryUrlBase = $this->_config->staticUrlBase . 'libraries/'; $graph = $this->_owApp->selectedModel; if ($graph instanceof Erfurt_Rdf_Model) { if ($graph->isEditable()) { $this->view->placeholder('update')->set(array('defaultGraph' => $graph->getModelIri(), 'queryEndpoint' => $this->_config->urlBase . 'sparql/', 'updateEndpoint' => $this->_config->urlBase . 'update/')); } } // check config for additional styles if ($stylesExtra = $this->_config->themes->styles) { $this->view->themeExtraStyles = $stylesExtra->toArray(); } else { $this->view->themeExtraStyles = array(); } // disable layout for Ajax requests if ($this->_request->isXmlHttpRequest()) { $this->_helper->layout()->disableLayout(); } // initialize view helpers $this->view->headTitle($this->_config->title->prefix, 'SET'); $this->view->headTitle()->setSeparator($this->_config->title->separator); $this->view->headMeta()->setHttpEquiv('Content-Type', 'text/html; charset=' . $this->_config->encoding); $this->view->headMeta()->setName('generator', 'OntoWiki — Collaborative Knowledge Engineering'); // RDFauthor view configuration $viewMode = isset($this->_config->rdfauthor->viewmode) ? $this->_config->rdfauthor->viewmode : 'inline'; // inject JSON variables into view $this->view->jsonVars = ' var urlBase = "' . $this->_config->urlBase . '"; var themeUrlBase = "' . $this->_config->themeUrlBase . '"; var _OWSESSION = "' . _OWSESSION . '"; var RDFAUTHOR_BASE = "' . $this->_config->staticUrlBase . 'libraries/RDFauthor/"; var RDFAUTHOR_VIEW_MODE = "' . $viewMode . '";' . PHP_EOL; if (defined('_OWDEBUG')) { $this->view->jsonVars .= ' var RDFAUTHOR_DEBUG = 1;'; } if ($this->_owApp->selectedModel) { $this->view->jsonVars .= ' var selectedGraph = { URI: "' . (string) $this->_owApp->selectedModel . '", title: ' . json_encode((string) $this->_owApp->selectedModel->getTitle()) . ', editable: ' . ($this->_owApp->selectedModel->isEditable() ? 'true' : 'false') . ' }; var RDFAUTHOR_DEFAULT_GRAPH = "' . (string) $this->_owApp->selectedModel . '";' . PHP_EOL; } if ($this->_owApp->selectedResource) { $this->view->jsonVars .= ' var selectedResource = { URI: "' . (string) $this->_owApp->selectedResource . '", title: ' . json_encode((string) $this->_owApp->selectedResource->getTitle()) . ', graphURI: "' . (string) $this->_owApp->selectedModel . '" }; var RDFAUTHOR_DEFAULT_SUBJECT = "' . (string) $this->_owApp->selectedResource . '";' . PHP_EOL; } // set ratio between left bar and main window if (isset($this->_session->sectionRation)) { $this->view->headScript()->appendScript('var sectionRatio = ' . $this->_session->sectionRation . ';'); } if (isset($this->_config->meta)) { if (isset($this->_config->meta->Keywords)) { $this->view->metaKeywords = $this->_config->meta->Keywords; } if (isset($this->_config->meta->Description)) { $this->view->metaDescription = $this->_config->meta->Description; } } /** * @trigger onAfterInitController * Triggered after a controller from class OntoWiki_Controller_Base (or derived) * has been initialized. */ $event = new Erfurt_Event('onAfterInitController'); $event->response = $this->_response; $eventResult = $event->trigger(); }
/** * RouteShutdown is the earliest event in the dispatch cycle, where a * fully routed request object is available */ public function routeShutdown(Zend_Controller_Request_Abstract $request) { // only once if (!$this->_isSetup) { $frontController = Zend_Controller_Front::getInstance(); $ontoWiki = OntoWiki::getInstance(); // instantiate model if parameter passed if (isset($request->m)) { $store = $ontoWiki->erfurt->getStore(); try { $model = $store->getModel($request->getParam('m', null, false)); $ontoWiki->selectedModel = $model; } catch (Erfurt_Store_Exception $e) { // When no user is given (Anoymous) give the requesting party a chance to authenticate. if (Erfurt_App::getInstance()->getAuth()->getIdentity()->isAnonymousUser()) { // In this case we allow the requesting party to authorize... $response = $frontController->getResponse(); $response->setException(new OntoWiki_Http_Exception(401)); return; } // post error message $ontoWiki->prependMessage(new OntoWiki_Message('<p>Could not instantiate model: ' . $e->getMessage() . '</p>' . '<a href="' . $ontoWiki->config->urlBase . '">Return to index page</a>', OntoWiki_Message::ERROR, array('escape' => false))); // hard redirect since finishing the dispatch cycle will lead to errors header('Location:' . $ontoWiki->config->urlBase . 'error/error'); return; } } // instantiate resource if parameter passed if (isset($request->r)) { $store = $ontoWiki->erfurt->getStore(); $rParam = $request->getParam('r', null, true); $graph = $ontoWiki->selectedModel; if (null === $graph) { // try to use first readable graph $possibleGraphs = $store->getGraphsUsingResource((string) $rParam, true); if (count($possibleGraphs) > 0) { try { $graph = $store->getModel($possibleGraphs[0]); $ontoWiki->selectedModel = $graph; } catch (Erfurt_Store_Exception $e) { $graph = null; // fail as before (see below) } } } if ($graph instanceof Erfurt_Rdf_Model) { $resource = new OntoWiki_Resource($rParam, $graph); $ontoWiki->selectedResource = $resource; } else { // post error message $ontoWiki->prependMessage(new OntoWiki_Message('<p>Could not instantiate resource. No model selected.</p>' . '<a href="' . $ontoWiki->config->urlBase . '">Return to index page</a>', OntoWiki_Message::ERROR, array('escape' => false))); // hard redirect since finishing the dispatch cycle will lead to errors header('Location:' . $ontoWiki->config->urlBase . 'error/error'); return; } } /** * @trigger onRouteShutdown */ $event = new Erfurt_Event('onRouteShutdown'); $event->request = $request; $event->trigger(); // avoid setting up twice $this->_isSetup = true; } }
public function exportAction() { $this->_addLastModifiedHeader(); $this->_helper->viewRenderer->setNoRender(); $this->_helper->layout->disableLayout(); if (isset($this->_request->m)) { $modelUri = $this->_request->m; } else { if (isset($this->_owApp->selectedModel)) { $modelUri = $this->_owApp->selectedModel->getModelUri(); } else { $response = $this->getResponse(); $response->setRawHeader('HTTP/1.0 400 Bad Request'); throw new OntoWiki_Controller_Exception("No model given."); } } $resource = $this->getParam('r', true); // Check whether the f parameter is given. If not: default to rdf/xml if (!isset($this->_request->f)) { $format = 'rdfxml'; } else { $format = $this->_request->f; } $format = Erfurt_Syntax_RdfSerializer::normalizeFormat($format); $store = $this->_erfurt->getStore(); // Check whether given format is supported. If not: 400 Bad Request. if (!in_array($format, array_keys(Erfurt_Syntax_RdfSerializer::getSupportedFormats()))) { $response = $this->getResponse(); $response->setRawHeader('HTTP/1.0 400 Bad Request'); throw new OntoWiki_Controller_Exception("Format '{$format}' not supported."); } // Check whether model exists. If not: 404 Not Found. if (!$store->isModelAvailable($modelUri, false)) { $response = $this->getResponse(); $response->setRawHeader('HTTP/1.0 404 Not Found'); throw new OntoWiki_Controller_Exception("Model '{$modelUri}' not found."); } // Check whether model is available (with acl). If not: 403 Forbidden. if (!$store->isModelAvailable($modelUri)) { $response = $this->getResponse(); $response->setRawHeader('HTTP/1.0 403 Forbidden'); throw new OntoWiki_Controller_Exception("Model '{$modelUri}' not available."); } $filename = 'export' . date('Y-m-d_Hi'); switch ($format) { case 'rdfxml': $contentType = 'application/rdf+xml'; $filename .= '.rdf'; break; case 'rdfn3': $contentType = 'text/rdf+n3'; $filename .= '.n3'; break; case 'rdfjson': $contentType = 'application/json'; $filename .= '.json'; break; case 'turtle': $contentType = 'application/x-turtle'; $filename .= '.ttl'; break; } /* * Event: allow for adding / deleting statements to the export * event uses a memory model and gets an empty memory model as * default value, all plugins should add statements to the existing * value and should not create a new model as return value */ $event = new Erfurt_Event('beforeExportResource'); $event->resource = $resource; $event->modelUri = $modelUri; $event->setDefault = new Erfurt_Rdf_MemoryModel(); $addedModel = $event->trigger(); if (is_object($addedModel) && get_class($addedModel) == 'Erfurt_Rdf_MemoryModel') { $addedStatements = $addedModel->getStatements(); } else { $addedStatements = array(); } $response = $this->getResponse(); $response->setHeader('Content-Type', $contentType, true); $response->setHeader('Content-Disposition', 'filename="' . $filename . '"'); $serializer = Erfurt_Syntax_RdfSerializer::rdfSerializerWithFormat($format); echo $serializer->serializeResourceToString($resource, $modelUri, false, true, $addedStatements); }
/** * Deletes statements in an array from the graph specified by $graphIri. * * @param string $graphUri URI the the model * @param array $statementsArray RDF/PHP statements array * @param bool $useAc use Access Control or not * * @throws Erfurt_Exception * * @return void */ public function deleteMultipleStatements($graphUri, array $statementsArray, $useAc = true) { // check whether model is available if (!$this->isModelAvailable($graphUri)) { throw new Erfurt_Store_Exception('Model "' . $graphUri . '" is not available.'); } // check whether model is editable if ($useAc && !$this->_checkAc($graphUri, 'edit')) { throw new Erfurt_Store_Exception('No permissions to edit model.'); } $this->_backendAdapter->deleteMultipleStatements($graphUri, $statementsArray); $queryCache = Erfurt_App::getInstance()->getQueryCache(); $queryCache->invalidateWithStatements($graphUri, $statementsArray); $event = new Erfurt_Event('onDeleteMultipleStatements'); $event->graphUri = $graphUri; $event->statements = $statementsArray; $event->trigger(); }
// use include, so we can catch it with the error handler require_once 'OntoWiki.php'; } catch (Exception $e) { header('HTTP/1.1 500 Internal Server Error'); echo 'Fatal Error: Could not load the OntoWiki Application Framework classes.<br />' . PHP_EOL . 'Your installation directory seems to be screwed.'; return; } /* check/include Erfurt_App */ try { // use include, so we can catch it with the error handler require_once 'Erfurt/App.php'; } catch (Exception $e) { header('HTTP/1.1 500 Internal Server Error'); echo 'Fatal Error: Could not load the Erfurt Framework classes.<br />' . PHP_EOL . 'Maybe you should install it with apt-get or with "make deploy"?'; return; } // restore old error handler restore_error_handler(); // bootstrap try { $application->bootstrap(); } catch (Exception $e) { header('HTTP/1.1 500 Internal Server Error'); echo 'Error on bootstrapping application: '; echo $e->getMessage(); return; } $event = new Erfurt_Event('onPostBootstrap'); $event->bootstrap = $application->getBootstrap(); $event->trigger(); $application->run();
/** * Returns TRUE if the Zend_Controller_Request_Abstract object can be * dispatched to a controller. * * Use this method wisely. By default, the dispatcher will fall back to the * default controller (either in the module specified or the global default) * if a given controller does not exist. This method returning false does * not necessarily indicate the dispatcher will not still dispatch the call. * * @param Zend_Controller_Request_Abstract $action * * @return boolean */ public function isDispatchable(Zend_Controller_Request_Abstract $request) { // Zend 1.10+ changes $className = $this->getControllerClass($request); $actionMethod = strtolower($request->getActionName()) . 'Action'; if (class_exists($className, false)) { if (method_exists($className, $actionMethod)) { return true; } } $fileSpec = $this->classToFilename($className); $dispatchDir = $this->getDispatchDirectory(); $test = $dispatchDir . DIRECTORY_SEPARATOR . $fileSpec; if (Zend_Loader::isReadable($test)) { require_once $test; if (method_exists($className, $actionMethod)) { return true; } } /** * @trigger onIsDispatchable * Triggered if no suitable controller has been found. Plug-ins can * attach to this event in order to modify request URLs or provide * mechanisms that do not allow a controller/action mapping from URL * parts. */ $pathInfo = ltrim($request->getPathInfo(), '/'); // URI may not contain a whitespace character! $pathInfo = str_replace(' ', '+', $pathInfo); $pathInfo = urldecode($pathInfo); if (class_exists($className, false)) { // give a chance to let class handle (e.g. index controller news action default) return true; } $event = new Erfurt_Event('onIsDispatchable'); $event->uri = $this->urlBase . $pathInfo; $event->request = $request; $eventResult = (bool) $event->trigger(); return $eventResult; }
/** * OntoWiki Update Endpoint * * Only data inserts and deletes are implemented at the moment (e.g. no graph patterns). * * @todo LOAD <> INTO <>, CLEAR GRAPH <>, CREATE[SILENT] GRAPH <>, DROP[ SILENT] GRAPH <> */ public function updateAction() { // service controller needs no view renderer $this->_helper->viewRenderer->setNoRender(); // disable layout for Ajax requests $this->_helper->layout()->disableLayout(); $store = OntoWiki::getInstance()->erfurt->getStore(); $response = $this->getResponse(); $defaultGraph = $this->_request->getParam('default-graph-uri', null); $namedGraph = $this->_request->getParam('named-graph-uri', null); $insertGraph = null; $deleteGraph = null; $insertModel = null; $deleteModel = null; if (isset($this->_request->query)) { // we have a query, enter SPARQL/Update mode $query = $this->_request->getParam('query', ''); OntoWiki::getInstance()->logger->info('SPARQL/Update query: ' . $query); $matches = array(); // insert preg_match('/INSERT\\s+DATA(\\s+INTO\\s*<(.+)>)?\\s*{\\s*([^}]*)/i', $query, $matches); $insertGraph = isset($matches[2]) && $matches[2] !== '' ? $matches[2] : null; $insertTriples = isset($matches[3]) ? $matches[3] : ''; if (null === $insertGraph && $insertTriples !== '') { if (null !== $defaultGraph) { $insertGraph = $defaultGraph; } if (null !== $namedGraph) { $insertGraph = $namedGraph; } } OntoWiki::getInstance()->logger->info('SPARQL/Update insertGraph: ' . $insertGraph); OntoWiki::getInstance()->logger->info('SPARQL/Update insertTriples: ' . $insertTriples); // delete preg_match('/DELETE\\s+DATA(\\s+FROM\\s*<(.+)>)?\\s*{\\s*([^}]*)/i', $query, $matches); $deleteGraph = isset($matches[2]) && $matches[2] !== '' ? $matches[2] : null; $deleteTriples = isset($matches[3]) ? $matches[3] : ''; if (null === $deleteGraph && $deleteTriples !== '') { if (null !== $defaultGraph) { $deleteGraph = $defaultGraph; } if (null !== $namedGraph) { $deleteGraph = $namedGraph; } } // TODO: normalize literals $parser = Erfurt_Syntax_RdfParser::rdfParserWithFormat('nt'); $insert = $parser->parse($insertTriples, Erfurt_Syntax_RdfParser::LOCATOR_DATASTRING); $parser->reset(); $delete = $parser->parse($deleteTriples, Erfurt_Syntax_RdfParser::LOCATOR_DATASTRING); if (null !== $insertGraph) { try { $insertModel = $insertGraph ? $store->getModel($insertGraph) : $store->getModel($namedGraph); } catch (Erfurt_Store_Exception $e) { // TODO: error if (defined('_OWDEBUG')) { OntoWiki::getInstance()->logger->info('Could not instantiate models.'); } return; } } if (null !== $deleteGraph) { try { $deleteModel = $deleteGraph ? $store->getModel($deleteGraph) : $store->getModel($namedGraph); } catch (Erfurt_Store_Exception $e) { // TODO: error if (defined('_OWDEBUG')) { OntoWiki::getInstance()->logger->info('Could not instantiate models.'); } return; } } } else { // no query, inserts and delete triples by JSON via param $insert = json_decode($this->_request->getParam('insert', '{}'), true); $delete = json_decode($this->_request->getParam('delete', '{}'), true); if ($this->_request->has('delete_hashed')) { $hashedObjectStatements = $this->_findStatementsForObjectsWithHashes($namedGraph, json_decode($this->_request->getParam('delete_hashed'), true)); $delete = array_merge_recursive($delete, $hashedObjectStatements); } try { $namedModel = $store->getModel($namedGraph); $insertModel = $namedModel; $deleteModel = $namedModel; } catch (Erfurt_Store_Exception $e) { // TODO: error if (defined('_OWDEBUG')) { OntoWiki::getInstance()->logger->info('Could not instantiate models.'); } return; } } $flag = false; /** * @trigger onUpdateServiceAction is triggered when Service-Controller Update Action is executed. * Event contains following attributes: * deleteModel : model to delete statments from * deleteData : statements payload being deleted * insertModel : model to add statements to * insertDara : statements payload being added */ $event = new Erfurt_Event('onUpdateServiceAction'); $event->deleteModel = $deleteModel; $event->insertModel = $insertModel; $event->deleteData = $delete; $event->insertData = $insert; $event->trigger(); // writeback $delete = $event->deleteData; $insert = $event->insertData; $changes = isset($event->changes) ? $event->changes : null; // delete if ($deleteModel && $deleteModel->isEditable()) { try { $deleteModel->deleteMultipleStatements((array) $delete); $flag = true; if (defined('_OWDEBUG')) { OntoWiki::getInstance()->logger->info(sprintf('Deleted statements from graph <%s>', $deleteModel->getModelUri())); } } catch (Erfurt_Store_Exception $e) { if (defined('_OWDEBUG')) { OntoWiki::getInstance()->logger->info('Could not delete statements from graph: ' . $e->getMessage() . PHP_EOL . 'Statements: ' . print_r($delete, true)); } } } // insert if ($insertModel && $insertModel->isEditable()) { OntoWiki::getInstance()->logger->info('add Statements: ' . print_r($delete, true)); $count = $insertModel->addMultipleStatements((array) $insert); $flag = true; if (defined('_OWDEBUG')) { OntoWiki::getInstance()->logger->info(sprintf('Inserted %i statements into graph <%s>', $count, $insertModel->getModelUri())); } } // nothing done? if (!$flag) { // When no user is given (Anoymous) give the requesting party a chance to authenticate. if (Erfurt_App::getInstance()->getAuth()->getIdentity()->isAnonymousUser()) { // In this case we allow the requesting party to authorize $response->setRawHeader('HTTP/1.1 401 Unauthorized'); $response->setHeader('WWW-Authenticate', 'Basic realm="OntoWiki"'); return; } } if ($changes) { /** * @see {http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.2} */ $response->setHttpResponseCode(201); $response->setHeader('Location', $changes['changed']); $response->setHeader('Content-Type', 'application/json'); $response->setBody(json_encode($changes)); } }
/** * Returns an array of predicate values for the current resource. * The array is indexed with the predicate's URIs. * * @return array */ public function getValues() { if (null === $this->_valueResults) { $this->_valueResults = array(); // get results $results = $this->getQueryResults(); // load predicates first $this->getPredicates(); // URL object to build URLs $url = new OntoWiki_Url(array('route' => 'properties'), array('r')); // keep track of URI objects already used $objects = array(); foreach ($results as $graph => $resultsForGraph) { $this->_valueResults[$graph] = array(); foreach ($resultsForGraph as $row) { $predicateUri = $row['predicate']['value']; if (!array_key_exists($predicateUri, $objects)) { $objects[$predicateUri] = array(); } // create space for value information if not exists if (!array_key_exists($predicateUri, $this->_valueResults[$graph])) { $this->_valueResults[$graph][$predicateUri] = array(); } // default values $value = array('content' => null, 'object' => null, 'object_hash' => null, 'datatype' => null, 'lang' => null, 'url' => null, 'uri' => null, 'curi' => null); switch ($row['object']['type']) { case 'uri': // every URI objects is only used once for each statement if (in_array($row['object']['value'], $objects[$predicateUri])) { continue; } // URL $url->setParam('r', $row['object']['value'], true); $value['url'] = (string) $url; // URI $value['uri'] = $row['object']['value']; // title $title = $this->_titleHelper->getTitle($row['object']['value']); /** * @trigger onDisplayObjectPropertyValue Triggered if an object value of some * property is returned. Plugins can attach to this trigger in order to modify * the value that gets displayed. * Event payload: value, property, title and link */ // set up event $event = new Erfurt_Event('onDisplayObjectPropertyValue'); $event->value = $row['object']['value']; $event->property = $predicateUri; $event->title = $title; $event->link = (string) $url; // trigger $value['object'] = $event->trigger(); if (!$event->handled()) { // object (modified by plug-ins) $value['object'] = $title; } array_push($objects[$predicateUri], $row['object']['value']); break; case 'typed-literal': $event = new Erfurt_Event('onDisplayLiteralPropertyValue'); $value['datatype'] = OntoWiki_Utils::compactUri($row['object']['datatype']); $literalString = Erfurt_Utils::buildLiteralString($row['object']['value'], $row['object']['datatype']); $value['object_hash'] = md5($literalString); $event->value = $row['object']['value']; $event->datatype = $row['object']['datatype']; $event->property = $predicateUri; $value['object'] = $event->trigger(); // keep unmodified value in content $value['content'] = $row['object']['value']; if (!$event->handled()) { // object (modified by plug-ins) $value['object'] = $row['object']['value']; } break; case 'literal': // original (unmodified) for RDFa $value['content'] = $row['object']['value']; $literalString = Erfurt_Utils::buildLiteralString($row['object']['value'], null, isset($row['object']['xml:lang']) ? $row['object']['xml:lang'] : null); $value['object_hash'] = md5($literalString); /** * @trigger onDisplayLiteralPropertyValue Triggered if a literal value of some * property is returned. Plugins can attach to this trigger in order to modify * the value that gets displayed. */ $event = new Erfurt_Event('onDisplayLiteralPropertyValue'); $event->value = $row['object']['value']; $event->property = $predicateUri; // set literal language if (isset($row['object']['xml:lang'])) { $value['lang'] = $row['object']['xml:lang']; $event->language = $row['object']['xml:lang']; } // trigger $value['object'] = $event->trigger(); // keep unmodified value in content $value['content'] = $row['object']['value']; // set default if event has not been handled if (!$event->handled()) { $value['object'] = $row['object']['value']; } break; } // push it only if it doesn't exceed number of items to display if (count($this->_valueResults[$graph][$predicateUri]) < $this->_limit) { array_push($this->_valueResults[$graph][$predicateUri], $value); } else { $this->_predicateResults[$graph][$predicateUri]['has_more'] = true; } if (count($this->_valueResults[$graph][$predicateUri]) > 1) { // create the "has more link" (used for area context menu as well) // do it only once per predicate if (!isset($this->_predicateResults[$graph][$predicateUri]['has_more_link'])) { //when all values are literal, we dont use a link to the list,but to the query editor $allValuesAreLiterals = true; foreach ($this->_valueResults[$graph][$predicateUri] as $value) { if (isset($value['uri'])) { $allValuesAreLiterals = false; } } if (!$allValuesAreLiterals) { $hasMoreUrl = new OntoWiki_Url(array('route' => 'instances', 'action' => 'list'), array()); $filterExp = json_encode(array('filter' => array(array('action' => 'add', 'mode' => 'box', 'id' => 'allvalues', 'property' => $predicateUri, 'isInverse' => true, 'propertyLabel' => "value", 'filter' => 'equals', 'value1' => $this->_uri, 'value2' => null, 'valuetype' => 'uri', 'literaltype' => null, 'hidden' => false)))); $hasMoreUrl->setParam('instancesconfig', $filterExp)->setParam('init', true); } else { $hasMoreUrl = new OntoWiki_Url(array('controller' => 'queries', 'action' => 'editor'), array()); $hasMoreUrl->setParam('query', 'SELECT ?value WHERE {<' . $this->_uri . '> <' . $predicateUri . '> ?value}')->setParam('immediate', true); } $this->_predicateResults[$graph][$predicateUri]['has_more_link'] = (string) $hasMoreUrl; } } } } return $this->_valueResults; } }
/** * Registers a new user */ public function registerAction() { OntoWiki::getInstance()->getNavigation()->disableNavigation(); $this->_helper->viewRenderer->setScriptAction('register'); $this->view->placeholder('main.window.title')->set('Register User'); $this->view->formActionUrl = $this->_config->urlBase . 'application/register'; $this->view->formMethod = 'post'; $this->view->formClass = 'simple-input input-justify-left'; $this->view->formName = 'registeruser'; $this->view->username = ''; $this->view->readonly = ''; $this->view->email = ''; $toolbar = $this->_owApp->toolbar; $toolbar->appendButton(OntoWiki_Toolbar::SUBMIT, array('name' => 'Register User'))->appendButton(OntoWiki_Toolbar::RESET, array('name' => 'Reset Form')); $this->view->placeholder('main.window.toolbar')->set($toolbar); $post = $this->_request->getPost(); $this->_owApp->appendMessage(new OntoWiki_Message('Already own an <span class="openid">OpenID?</span> <a href="' . $this->_config->urlBase . 'application/openidreg">Register here</a>', OntoWiki_Message::INFO, array('escape' => false, 'translate' => false))); $contentType = $this->_request->getHeader('Content-Type'); if (strstr($contentType, 'application/json')) { $rawBody = $this->_request->getRawBody(); echo $rawBody; $post = Zend_Json::decode($rawBody); } if ($post) { /* status var in order to fire corresponding events */ $registrationError = true; $registeredUsernames = array(); $registeredEmailAddresses = array(); foreach ($this->_erfurt->getUsers() as $userUri => $userArray) { if (array_key_exists('userName', $userArray)) { $registeredUsernames[] = $userArray['userName']; } if (array_key_exists('userEmail', $userArray)) { $registeredEmailAddresses[] = str_replace('mailto:', '', $userArray['userEmail']); } } $email = $post['email']; $this->view->email = $email; $username = $post['username']; $this->view->username = $username; $password = $post['password']; $passwordTwo = $post['password2']; $emailValidator = new Zend_Validate_EmailAddress(); if (!$this->_erfurt->isActionAllowed('RegisterNewUser') || !($actionConfig = $this->_erfurt->getActionConfig('RegisterNewUser'))) { $message = 'Action not permitted for the current user.'; $this->_owApp->appendMessage(new OntoWiki_Message($message, OntoWiki_Message::ERROR)); } else { if (trim($email) == '') { $message = 'Email address must not be empty.'; $this->_owApp->appendMessage(new OntoWiki_Message($message, OntoWiki_Message::ERROR)); } else { if (in_array($email, $registeredEmailAddresses)) { $message = 'Email address is already registered.'; $this->_owApp->appendMessage(new OntoWiki_Message($message, OntoWiki_Message::ERROR)); } else { if (isset($actionConfig['mailvalidation']) && $actionConfig['mailvalidation'] == 'yes' && !$emailValidator->isValid($email)) { $message = 'Email address validation failed.'; $this->_owApp->appendMessage(new OntoWiki_Message($message, OntoWiki_Message::ERROR)); } else { if (in_array($username, $registeredUsernames) || $username == $this->_owApp->erfurt->getStore()->getDbUser()) { $message = 'Username already registered.'; $this->_owApp->appendMessage(new OntoWiki_Message($message, OntoWiki_Message::ERROR)); } else { if (isset($actionConfig['uidregexp']) && !preg_match($actionConfig['uidregexp'], $username)) { $message = 'Username contains illegal characters.'; $this->_owApp->appendMessage(new OntoWiki_Message($message, OntoWiki_Message::ERROR)); } else { if ($password !== $passwordTwo) { $message = 'Passwords do not match.'; $this->_owApp->appendMessage(new OntoWiki_Message($message, OntoWiki_Message::ERROR)); } else { if (strlen($password) < 5) { $message = 'Password needs at least 5 characters.'; $this->_owApp->appendMessage(new OntoWiki_Message($message, OntoWiki_Message::ERROR)); } else { if (isset($actionConfig['passregexp']) && $actionConfig['passregexp'] != '' && !@preg_match($actionConfig['passregexp'], $password)) { $message = 'Password does not match regular expression set in system configuration'; $this->_owApp->appendMessage(new OntoWiki_Message($message, OntoWiki_Message::ERROR)); } else { // give default group? if (isset($actionConfig['defaultGroup'])) { $group = $actionConfig['defaultGroup']; } // add new user if ($this->_erfurt->addUser($username, $password, $email, $group)) { $message = 'The user "' . $username . '" has been successfully registered.'; $this->_owApp->appendMessage(new OntoWiki_Message($message, OntoWiki_Message::SUCCESS)); $registrationError = false; } else { $message = 'A registration error occured. Please refer to the log entries.'; $this->_owApp->appendMessage(new OntoWiki_Message($message, OntoWiki_Message::ERROR)); } } } } } } } } } } /* * fire events for success and error */ if ($registrationError === false) { $event = new Erfurt_Event('onRegisterUser'); $event->username = $username; $event->response = $this->_response; $event->trigger(); } else { $event = new Erfurt_Event('onRegisterUserFailed'); $event->username = $username; $event->message = $message; $event->response = $this->_response; $event->trigger(); } } }