static function smwfProcessSPARQLQueryParserFunctionGTP( &$parser ) { global $smwgWebserviceEndpoint; if ( !isset( $smwgWebserviceEndpoint ) ) return ''; global $smwgIQRunningNumber; $smwgIQRunningNumber++; $params = func_get_args(); array_shift( $params ); // we already know the $parser ... SMWSPARQLQueryProcessor::processFunctionParams( $params, $querystring, $params, $printouts ); $query = SMWSPARQLQueryProcessor::createQuery( $querystring, $params, SMWQueryProcessor::INLINE_QUERY, '', $printouts ); if ( !( ( $query->querymode == SMWQuery::MODE_INSTANCES ) || ( $query->querymode == SMWQuery::MODE_NONE ) ) ) { return ''; } self::prequery( $params, $printouts, $label, $wom_id ); // source from SMWHalo, SMW_SPARQLQueryProcessor.php // Query routing allows extensions to provide alternative stores as data sources // The while feature is experimental and is not properly integrated with most of SMW's architecture. For instance, some query printers just fetch their own store. // / TODO: case-insensitive global $smwgQuerySources; $query->params = $params; // this is a hack if ( array_key_exists( "source", $params ) && array_key_exists( $params["source"], $smwgQuerySources ) ) { $store = new $smwgQuerySources[$params["source"]](); } else { $store = smwfGetStore(); // default store } $res = $store->getQueryResult( $query ); if ( !is_array( $res ) ) { $qResults['tsc'] = $res; } else { $qResults = $res; } foreach ( $qResults as $source => $res ) { while ( $row = $res->getNext() ) { $firstcol = true; foreach ( $row as $field ) { $object = $field->getNextObject(); $text = $object->getWikiValue(); self::$queryProps[$wom_id][$label][] = $text; // get the first column only break; } } } return ''; }
/** * Get derived properties. * @param SMWSemanticData $semData * Annotated facts of an article * @return SMWSemanticData * Derived facts of the article */ public static function getDerivedProperties(SMWSemanticData $semData) { global $smwgIP, $smwgHaloIP, $smwgTripleStoreGraph; require_once $smwgIP . '/includes/SMW_QueryProcessor.php'; require_once $smwgHaloIP . '/includes/storage/SMW_TripleStore.php'; $derivedProperties = new SMWSemanticData($semData->getSubject()); $subject = $semData->getSubject()->getDBkey(); global $wgContLang; $subject = $semData->getSubject(); $ns = strtolower($wgContLang->getNSText($subject->getNamespace())); if (empty($ns)) { $ns = 'a'; } $localName = $subject->getDBkey(); $inst = $smwgTripleStoreGraph . TSNamespaces::$INST_NS_SUFFIX; // $queryText = "PREFIX a:<$inst> SELECT ?pred ?obj WHERE { a:$subject ?pred ?obj . }"; // $queryText = "SELECT ?pred ?obj WHERE { a:$subject ?pred ?obj . }"; $queryText = "SELECT ?pred ?obj WHERE { <" . $smwgTripleStoreGraph . "/{$ns}#{$localName}> ?pred ?obj . }"; // echo $queryText; wfRunHooks('BeforeDerivedPropertyQuery', array(&$queryText)); // Ask for all properties of the subject (derived and ground facts) $q = SMWSPARQLQueryProcessor::createQuery($queryText, array()); $res = smwfGetStore()->getQueryResult($q); // SMWQueryResult wfRunHooks('AfterDerivedPropertyQuery', array()); wfRunHooks('FilterQueryResults', array(&$res, array('pred'))); $propVal = array(); while ($row = $res->getNext()) { //$row: SMWResultArray[] $i = 0; $valuesForProperty = array(); $key = false; if (count($row) == 2) { $properties = array(); $values = array(); // There may be several properties with the same values $p = $row[0]; while (($object = $p->getNextObject()) !== false) { if ($object instanceof SMWURIValue) { $keys = $object->getDBkeys(); $properties[] = $keys[0]; } else { $properties[] = $object->getDBkey(); } } // Retrieve the values of the properties $v = $row[1]; while (($object = $v->getNextObject()) !== false) { $values[] = $object; } } foreach ($properties as $p) { if (array_key_exists($p, $propVal)) { // The same property may appear several times $propVal[$p] = array_merge($values, $propVal[$p]); } else { $propVal[$p] = $values; } } } // Check is a property is derived or directly annotated foreach ($propVal as $propName => $derivedValues) { // does the property already exist? $prop = SMWPropertyValue::makeUserProperty($propName); $values = $semData->getPropertyValues($prop); foreach ($derivedValues as $dv) { $isDerived = true; $val = null; foreach ($values as $v) { if ($dv->getTypeID() == '_wpg' && $v->getTypeID() == '_wpg') { $vt1 = $dv->getTitle(); $vt2 = $v->getTitle(); if (isset($vt1) && isset($vt2) && $vt1->getText() == $vt2->getText()) { $isDerived = false; break; } } else { if ($dv->getTypeID() == '_wpg' && $v->getTypeID() != '_wpg') { // how can this happen? $isDerived = false; break; } else { if ($dv->isNumeric()) { if ($dv->getWikiValue() == $v->getWikiValue()) { $isDerived = false; break; } } else { if (array_shift($dv->getDBkeys()) == array_shift($v->getDBkeys())) { $isDerived = false; break; } } } } } if ($isDerived) { $property = SMWPropertyValue::makeUserProperty($propName); $derivedProperties->addPropertyObjectValue($property, $dv); } } } return $derivedProperties; }
public function updateQueryResult($queryId) { $queryString = SMWQRCQueryManagementHandler::getInstance()->getSearchMetadataQueryString($queryId); // SMWQueryProcessor::processFunctionParams(array($queryString), $queryString, $params, $printouts); $query = SMWQueryProcessor::createQuery($queryString, $params); $queryResults = $this->getQueryResult($query, true, false)->getResults(); //echo('<pre>'.print_r($queryResults, true).'</pre>'); if (count($queryResults) > 0) { //this query is still in use global $smwgDefaultStore; $defaultStore = new $smwgDefaultStore(); $title = $queryResults[0]->getTitle(); $semanticData = $defaultStore->getsemanticData($title); $metadata = SMWQRCQueryManagementHandler::getInstance()->getQueryCallMetadata($semanticData, $queryId); $queryParams = array($metadata['queryString']); //if($metadata['limit']) $queryParams[] = 'limit='.$metadata['limit']; if ($metadata['offset']) { $queryParams[] = 'offset=' . $metadata['offset']; } if (array_key_exists('extraPropertyPrintouts', $metadata)) { foreach (explode(';', $metadata['extraPropertyPrintouts']) as $pP) { $queryParams[] = '?' . $pP; } } if (array_key_exists('extraCategoryPrintouts', $metadata)) { $queryParams[] = '?Category'; } //echo('<pre>'.print_r($queryParams, true).'</pre>'); if (array_key_exists('isSPARQLQuery', $metadata)) { SMWSPARQLQueryProcessor::processFunctionParams($queryParams, $querystring, $params, $printouts); $query = SMWSPARQLQueryProcessor::createQuery($querystring, $params, SMWQueryProcessor::INLINE_QUERY, 'table', $printouts); } else { SMWQueryProcessor::processFunctionParams($queryParams, $querystring, $params, $printouts); $query = SMWQueryProcessor::createQuery($querystring, $params); } //echo('<pre>'.print_r($query, true).'</pre>'); $this->getQueryResult($query, true); //invalidate parser caches global $invalidateParserCache; if ($invalidateParserCache) { foreach ($queryResults as $qR) { $title = $qR->getTitle(); $title->invalidateCache(); // wfGetParserCacheStorage()->delete( // ParserCache::singleton()->getKey(Article::newFromID($title->getArticleID()), new ParserOptions())); } } } else { $qrcStore = SMWQRCStore::getInstance()->getDB(); $qrcStore->deleteQueryData($queryId); } return true; }
public static function getResultFromQueryString($querystring, $params, $extraprintouts, $outputmode, $context = SMWQueryProcessor::INLINE_QUERY) { $format = SMWQueryProcessor::getResultFormat($params); $query = SMWSPARQLQueryProcessor::createQuery($querystring, $params, $context, $format, $extraprintouts); $result = SMWQueryProcessor::getResultFromQuery($query, $params, $extraprintouts, $outputmode, $context, $format); return $result; }
protected function extractQueryParameters($p) { // This code rather hacky since there are many ways to call that special page, the most involved of // which is the way that this page calls itself when data is submitted via the form (since the shape // of the parameters then is governed by the UI structure, as opposed to being governed by reason). global $wgRequest, $smwgQMaxInlineLimit; // First make all inputs into a simple parameter list that can again be parsed into components later. if ($wgRequest->getCheck('q')) { // called by own Special, ignore full param string in that case $rawparams = SMWInfolink::decodeParameters($wgRequest->getVal('p'), false); // p is used for any additional parameters in certain links } else { // called from wiki, get all parameters $rawparams = SMWInfolink::decodeParameters($p, true); } // Check for q= query string, used whenever this special page calls itself (via submit or plain link): $this->m_querystring = $wgRequest->getText('q'); if ($this->m_querystring != '') { $rawparams[] = $this->m_querystring; } // Check for param strings in po (printouts), appears in some links and in submits: $paramstring = $wgRequest->getText('po'); if ($paramstring != '') { // parameters from HTML input fields $ps = explode("\n", $paramstring); // params separated by newlines here (compatible with text-input for printouts) foreach ($ps as $param) { // add initial ? if omitted (all params considered as printouts) $param = trim($param); if ($param != '' && $param[0] != '?') { $param = '?' . $param; } $rawparams[] = $param; } } // Now parse parameters and rebuilt the param strings for URLs SMWSPARQLQueryProcessor::processFunctionParams($rawparams, $this->m_querystring, $this->m_params, $this->m_printouts); // Try to complete undefined parameter values from dedicated URL params if (!array_key_exists('format', $this->m_params)) { if (array_key_exists('rss', $this->m_params)) { // backwards compatibility (SMW<=1.1 used this) $this->m_params['format'] = 'rss'; } else { // default $this->m_params['format'] = 'broadtable'; } } $sortcount = $wgRequest->getVal('sc'); if (!is_numeric($sortcount)) { $sortcount = 0; } // commented out because TSC does not accept empty sort/order parameters /*if ( !array_key_exists('order',$this->m_params) ) { $this->m_params['order'] = $wgRequest->getVal( 'order' ); // basic ordering parameter (, separated) for ($i=0; $i<$sortcount; $i++) { if ($this->m_params['order'] != '') { $this->m_params['order'] .= ','; } $value = $wgRequest->getVal( 'order' . $i ); $value = ($value == '')?'ASC':$value; $this->m_params['order'] .= $value; } } if ( !array_key_exists('sort',$this->m_params) ) { $this->m_params['sort'] = $wgRequest->getText( 'sort' ); // basic sorting parameter (, separated) for ($i=0; $i<$sortcount; $i++) { if ( ($this->m_params['sort'] != '') || ($i>0) ) { // admit empty sort strings here $this->m_params['sort'] .= ','; } $this->m_params['sort'] .= $wgRequest->getText( 'sort' . $i ); } }*/ // Find implicit ordering for RSS -- needed for downwards compatibility with SMW <=1.1 if ($this->m_params['format'] == 'rss' && $this->m_params['sort'] == '' && $sortcount == 0) { foreach ($this->m_printouts as $printout) { if (strtolower($printout->getLabel()) == "date" && $printout->getTypeID() == "_dat") { $this->m_params['sort'] = $printout->getTitle()->getText(); $this->m_params['order'] = 'DESC'; } } } if (!array_key_exists('offset', $this->m_params)) { $this->m_params['offset'] = $wgRequest->getVal('offset'); if ($this->m_params['offset'] == '') { $this->m_params['offset'] = 0; } } if (!array_key_exists('limit', $this->m_params)) { $this->m_params['limit'] = $wgRequest->getVal('limit'); if ($this->m_params['limit'] == '') { $this->m_params['limit'] = $this->m_params['format'] == 'rss' ? 10 : 20; // standard limit for RSS } } $this->m_params['limit'] = min($this->m_params['limit'], $smwgQMaxInlineLimit); if (!array_key_exists('merge', $this->m_params)) { $this->m_params['merge'] = $wgRequest->getVal('merge'); if ($this->m_params['merge'] == '') { $this->m_params['merge'] = true; // merge per default } } $this->m_editquery = $wgRequest->getVal('eq') != '' || '' == $this->m_querystring; }
function smwf_qi_QIAccess($method, $params) { $p_array = explode(",", $params); global $smwgQEnabled; if ($method == "getPropertyInformation") { return qiGetPropertyInformation($p_array[0]); } else { if ($method == "getPropertyTypes") { $p_array = func_get_args(); $types = "<propertyTypes>"; for ($i = 1; $i < count($p_array); $i++) { $types .= qiGetPropertyInformation($p_array[$i]); } $types .= "</propertyTypes>"; return $types; } else { if ($method == "getNumericTypes") { $numtypes = array(); $types = SMWDataValueFactory::getKnownTypeLabels(); foreach ($types as $v) { $id = SMWDataValueFactory::findTypeID($v); if (SMWDataValueFactory::newTypeIDValue($id)->isNumeric()) { array_push($numtypes, strtolower($v)); } } return implode(",", $numtypes); } else { if ($method == "getQueryResult") { $result = "null"; if ($smwgQEnabled) { // read fix parameters from QI GUI $params = count($p_array) > 1 ? explode("|", $p_array[1]) : array(); $fixparams = array(); foreach ($params as $p) { if (strlen($p) > 0 && strpos($p, "=") !== false) { list($key, $value) = explode("=", $p); $fixparams[trim($key)] = str_replace('%2C', ',', $value); } } // indicate that it comes from an ajax call $fixparams['ajaxCall'] = true; // fix bug 10812: if query string contains a , $p_array[0] = str_replace('%2C', ',', $p_array[0]); // read query with printouts and (possibly) other parameters like sort, order, limit, etc... $pos = strpos($p_array[0], "|?"); if ($pos > 0) { $rawparams[] = trim(substr($p_array[0], 0, $pos)); $ps = explode("|?", trim(substr($p_array[0], $pos + 2))); foreach ($ps as $param) { $rawparams[] = "?" . trim($param); } } else { $ps = preg_split('/[^\\|]{1}\\|{1}(?!\\|)/s', $p_array[0]); if (count($ps) > 1) { // last char of query condition is missing (matched with [^\|]{1}) therefore copy from original $rawparams[] = trim(substr($p_array[0], 0, strlen($ps[0]) + 1)); array_shift($ps); // remove the query condition // add other params for formating etc. foreach ($ps as $param) { $rawparams[] = trim($param); } } else { $rawparams[] = trim($p_array[0]); } } $rawparams = array_merge($rawparams, $fixparams); // set some default values, if params are not set if (!in_array('reasoner', array_keys($fixparams))) { $fixparams['reasoner'] = 'ask'; } if (!in_array('format', array_keys($fixparams))) { $fixparams['format'] = 'table'; } // use SMW classes or TSC classes and parse params and answer query if ($fixparams['reasoner'] == 'ask') { SMWQueryProcessor::processFunctionParams($rawparams, $querystring, $params, $printouts); } else { if ($fixparams['reasoner'] == 'sparql') { SMWSPARQLQueryProcessor::processFunctionParams($rawparams, $querystring, $params, $printouts); } } // check if there is any result and if it corresponds to the selected format $mainlabel = isset($rawparams['mainlabel']) && $rawparams['mainlabel'] == '-'; $invalidRes = smwf_qi_CheckValidResult($printouts, $fixparams['format'], $mainlabel); if ($invalidRes != 0) { return wfMsg('smw_qi_printout_err' . $invalidRes); } // quickfix: unset conflicting params for maps if (in_array($fixparams['format'], array("map", "googlemaps2", "openlayers", "yahoomaps"))) { if (isset($params['reasoner'])) { unset($params['reasoner']); } if (isset($params['ajaxcall'])) { unset($params['ajaxcall']); } if (isset($params['merge'])) { unset($params['merge']); } } // answer query using the SMW classes or TSC classes if ($fixparams['reasoner'] == 'ask') { $result = SMWQueryProcessor::getResultFromQueryString($querystring, $params, $printouts, SMW_OUTPUT_WIKI); } else { if ($fixparams['reasoner'] == 'sparql') { $result = SMWSPARQLQueryProcessor::getResultFromQueryString($querystring, $params, $printouts, SMW_OUTPUT_WIKI); } } // check for empty result if (is_array($result) && trim($result[0]) == '' || trim($result == '')) { return wfMsg('smw_qi_printout_err4'); } switch ($fixparams['format']) { case 'timeline': case 'exhibit': case 'eventline': return $result; break; case 'gallery': case 'googlepie': case 'googlebar': case 'ofc-pie': case 'ofc-bar': case 'ofc-bar_3d': case 'ofc-line': case 'ofc-scatterline': return is_array($result) ? $result[0] : $result; break; case 'map': case 'googlemaps2': case 'openlayers': case 'yahoomaps': return wfMsg('smw_qi_printout_notavailable'); default: } $result = parseWikiText($result); // add target="_new" for all links $pattern = "|<a|i"; $result = preg_replace($pattern, '<a target="_new"', $result); return $result; } } else { if ($method == "getQueryResultForDownload") { $result = "null"; if ($smwgQEnabled) { $params = array('format' => $p_array[1], 'link' => $p_array[2], 'intro' => $p_array[3], 'sort' => $p_array[4], 'limit' => $p_array[5], 'mainlabel' => $p_array[6], 'order' => $p_array[7], 'default' => $p_array[8], 'headers' => $p_array[9]); $result = applyQueryHighlighting($p_array[0], $params); // add target="_new" for all links $pattern = "|<a|i"; $result = preg_replace($pattern, '<a target="_new"', $result); } if ($result != "null" && $result != "") { global $request_query; $request_query = true; } return $result; } else { if ($method == "getSupportedParameters") { global $smwgResultFormats; wfLoadExtensionMessages('SemanticMediaWiki'); $format = $p_array[0]; if (array_key_exists($format, $smwgResultFormats)) { $formatclass = $smwgResultFormats[$format]; } else { $formatclass = "SMWListResultPrinter"; } // fix for missing parameter order $order_missing = true; $intro_missing = true; $outro_missing = true; $qp = new $formatclass($format, false); $params = $qp->getParameters(); // repair some misplaced parameters for ($i = 0; $i < count($params); $i++) { switch ($params[$i]['name']) { case "order": $order_missing = false; break; case "template": if ($format != "template") { array_splice($params, $i, 1); } break; case "intro": if (substr($format, 0, 4) != "ofc-") { $intro_missing = false; } break; case "outro": if (substr($format, 0, 4) != "ofc-") { $outro_missing = false; } break; case "headers": if ($format != "table" && $format != "broadtable") { array_splice($params, $i, 1); } break; } } if ($order_missing) { $params[] = array('name' => 'order', 'type' => 'enumeration', 'description' => wfMsg('smw_qi_tt_order'), 'values' => array('ascending', 'descending')); } if ($intro_missing) { $params[] = array('name' => 'intro', 'type' => 'string', 'description' => wfMsg('smw_qi_tt_intro')); } if ($outro_missing) { $params[] = array('name' => 'outro', 'type' => 'string', 'description' => wfMsg('smw_qi_tt_outro')); } $jsonEnc = new Services_JSON(); return $jsonEnc->encode($params); } else { return "false"; } } } } } } }
/** * The {{#sparql }} parser function processing part. */ function smwfProcessSPARQLInlineQueryParserFunction(&$parser) { global $smwgWebserviceEndpoint; if (isset($smwgWebserviceEndpoint)) { global $smwgIQRunningNumber; $smwgIQRunningNumber++; $params = func_get_args(); array_shift($params); // we already know the $parser ... return SMWSPARQLQueryProcessor::getResultFromFunctionParams($params, SMW_OUTPUT_WIKI); } else { return smwfEncodeMessages(array(wfMsgForContent('smw_sparql_disabled'))); } }