/**
	 * 
	 * @return SMWQuery
	 */
	protected function getQuery( $queryString, array $printouts ) {
		SMWQueryProcessor::addThisPrintout( $printouts, $this->parameters );
		
		return SMWQueryProcessor::createQuery(
			$queryString,
			SMWQueryProcessor::getProcessedParams( $this->parameters, $printouts ),
			SMWQueryProcessor::SPECIAL_PAGE,
			'',
			$printouts
		);
	}
示例#2
0
 function testExcelQueryPrinter()
 {
     $params = array();
     $context = SMWQueryProcessor::INLINE_QUERY;
     $format = "exceltable";
     $extraprintouts = array();
     $querystring = "[[Category:Car]]";
     $query = SMWQueryProcessor::createQuery($querystring, $params, $context, $format, $extraprintouts);
     $res = smwfGetStore()->getQueryResult($query);
     $result = SMWQueryProcessor::getResultFromQuery($query, $params, $extraprintouts, SMW_OUTPUT_FILE, $context, $format);
     $this->assertFileContentsIgnoringWhitespaces("testcases/resources/excel_qp_result.dat", $result);
 }
示例#3
0
 /**
  * Method for handling the ask concept function.
  * 
  * @todo The possible use of this in an HTML or Specal page context needs to be revisited. The code mentions it, but can this actually happen?
  * @todo The escaping of symbols in concept queries needs to be revisited.
  * 
  * @since 1.5.3
  * 
  * @param Parser $parser
  */
 public static function render(Parser &$parser)
 {
     global $wgContLang, $wgTitle;
     $title = $parser->getTitle();
     $pconc = new SMWDIProperty('_CONC');
     if ($title->getNamespace() != SMW_NS_CONCEPT) {
         $result = smwfEncodeMessages(array(wfMsgForContent('smw_no_concept_namespace')));
         SMWOutputs::commitToParser($parser);
         return $result;
     } elseif (count(SMWParseData::getSMWdata($parser)->getPropertyValues($pconc)) > 0) {
         $result = smwfEncodeMessages(array(wfMsgForContent('smw_multiple_concepts')));
         SMWOutputs::commitToParser($parser);
         return $result;
     }
     // process input:
     $params = func_get_args();
     array_shift($params);
     // We already know the $parser ...
     // Use first parameter as concept (query) string.
     $concept_input = str_replace(array('&gt;', '&lt;'), array('>', '<'), array_shift($params));
     // second parameter, if any, might be a description
     $concept_docu = array_shift($params);
     // NOTE: the str_replace above is required in MediaWiki 1.11, but not in MediaWiki 1.14
     $query = SMWQueryProcessor::createQuery($concept_input, SMWQueryProcessor::getProcessedParams(array('limit' => 20, 'format' => 'list')), SMWQueryProcessor::CONCEPT_DESC);
     $concept_text = $query->getDescription()->getQueryString();
     if (!is_null(SMWParseData::getSMWData($parser))) {
         $diConcept = new SMWDIConcept($concept_text, $concept_docu, $query->getDescription()->getQueryFeatures(), $query->getDescription()->getSize(), $query->getDescription()->getDepth());
         SMWParseData::getSMWData($parser)->addPropertyObjectValue($pconc, $diConcept);
     }
     // display concept box:
     $rdflink = SMWInfolink::newInternalLink(wfMsgForContent('smw_viewasrdf'), $wgContLang->getNsText(NS_SPECIAL) . ':ExportRDF/' . $title->getPrefixedText(), 'rdflink');
     SMWOutputs::requireResource('ext.smw.style');
     // TODO: escape output, preferably via Html or Xml class.
     $result = '<div class="smwfact"><span class="smwfactboxhead">' . wfMsgForContent('smw_concept_description', $title->getText()) . (count($query->getErrors()) > 0 ? ' ' . smwfEncodeMessages($query->getErrors()) : '') . '</span>' . '<span class="smwrdflink">' . $rdflink->getWikiText() . '</span>' . '<br />' . ($concept_docu ? "<p>{$concept_docu}</p>" : '') . '<pre>' . str_replace('[', '&#x005B;', $concept_text) . "</pre>\n</div>";
     if (!is_null($wgTitle) && $wgTitle->isSpecialPage()) {
         global $wgOut;
         SMWOutputs::commitToOutputPage($wgOut);
     } else {
         SMWOutputs::commitToParser($parser);
     }
     return $result;
 }
示例#4
0
/**
 * Returns query results in the SPARQL XML format.
 *  
 * Serves as entry point for the wiki SOAP server as well as for answering 
 * queries via ajax interface.
 * 
 * @param string $queryString in ASK or SPARQL syntax
 * @return XML string
 */
function query($rawQuery, $format = "xml")
{
    $mediaWikiLocation = dirname(__FILE__) . '/../../..';
    global $smwgHaloIP;
    require_once $smwgHaloIP . '/includes/storage/SMW_RESTWebserviceConnector.php';
    require_once "{$mediaWikiLocation}/SemanticMediaWiki/includes/SMW_QueryProcessor.php";
    require_once "{$mediaWikiLocation}/SMWHalo/includes/queryprinters/SMW_QP_XML.php";
    global $smwgWebserviceEndpoint;
    $eqi = new ExternalQueryInterface();
    // source == null means default (SMW reasoner)
    $params = $eqi->parseParameters($rawQuery);
    $source = array_key_exists("source", $params) ? $params['source'] : NULL;
    $query = $params['query'];
    // check if source other than default or smw
    if (!is_null($source) && $source != 'smw') {
        // TSC
        // if webservice endpoint is set, sent to TSC
        if (isset($smwgWebserviceEndpoint)) {
            return $eqi->answerSPARQL($query, $eqi->serializeParams($params));
        } else {
            // fallback, redirect to SMW
            return $eqi->answerASK($rawQuery, $format);
        }
    } else {
        // SMW
        // truncate any parameters or printouts, before parsing
        $paramPos = strpos($rawQuery, "|");
        if ($paramPos === false) {
            $queryString = $rawQuery;
        } else {
            $queryString = substr($rawQuery, 0, $paramPos);
        }
        // answer query
        $query = SMWQueryProcessor::createQuery($queryString, array(), false);
        if (count($query->getErrors()) > 0) {
            throw new Exception($query->getErrors());
        } else {
            return $eqi->answerASK($rawQuery, $format);
        }
    }
}
示例#5
0
 /**
  * Format and output report results using the given information plus
  * OutputPage
  *
  * @param OutputPage $out OutputPage to print to
  * @param Skin $skin User skin to use
  * @param Database $dbr Database (read) connection to use
  * @param int $res Result pointer
  * @param int $num Number of available result rows
  * @param int $offset Paging offset
  */
 protected function outputResults($out, $skin, $dbr, $res, $num, $offset)
 {
     global $wgContLang;
     $all_display_params = SDUtils::getDisplayParamsForCategory($this->category);
     $querystring = null;
     $printouts = $params = array();
     // only one set of params is handled for now
     if (count($all_display_params) > 0) {
         $display_params = array_map('trim', $all_display_params[0]);
         SMWQueryProcessor::processFunctionParams($display_params, $querystring, $params, $printouts);
     }
     if (!empty($querystring)) {
         $query = SMWQueryProcessor::createQuery($querystring, $params);
     } else {
         $query = new SMWQuery();
     }
     if (!array_key_exists('format', $params)) {
         $params['format'] = 'category';
     }
     if (array_key_exists('mainlabel', $params)) {
         $mainlabel = $params['mainlabel'];
     } else {
         $mainlabel = '';
     }
     $r = $this->addSemanticResultWrapper($dbr, $res, $num, $query, $mainlabel, $printouts);
     $printer = SMWQueryProcessor::getResultPrinter($params['format'], SMWQueryProcessor::SPECIAL_PAGE, $r);
     if (version_compare(SMW_VERSION, '1.6.1', '>')) {
         SMWQueryProcessor::addThisPrintout($printouts, $params);
         $params = SMWQueryProcessor::getProcessedParams($params, $printouts);
     }
     $prresult = $printer->getResult($r, $params, SMW_OUTPUT_HTML);
     $prtext = is_array($prresult) ? $prresult[0] : $prresult;
     SMWOutputs::commitToOutputPage($out);
     // Crappy hack to get the contents of SMWOutputs::$mHeadItems,
     // which may have been set in the result printer, and dump into
     // headItems of $out.
     // How else can we do this?
     global $wgParser;
     SMWOutputs::commitToParser($wgParser);
     if (!is_null($wgParser->mOutput)) {
         // getHeadItems() was added in MW 1.16
         if (method_exists($wgParser->getOutput(), 'getHeadItems')) {
             $headItems = $wgParser->getOutput()->getHeadItems();
         } else {
             $headItems = $wgParser->getOutput()->mHeadItems;
         }
         foreach ($headItems as $key => $item) {
             $out->addHeadItem($key, $item);
         }
         // Force one more parser function, so links appear.
         $wgParser->replaceLinkHolders($prtext);
     }
     $html = array();
     $html[] = $prtext;
     if (!$this->listoutput) {
         $html[] = $this->closeList();
     }
     $html = $this->listoutput ? $wgContLang->listToText($html) : implode('', $html);
     $out->addHTML($html);
 }
 private function getExtraDownloadLinks()
 {
     $downloadLinks = '';
     if ($this->m_querystring === '') {
         return $downloadLinks;
     }
     $params = $this->m_params;
     $params = SMWQueryProcessor::getProcessedParams($params, $this->m_printouts);
     $query = SMWQueryProcessor::createQuery($this->m_querystring, $params, SMWQueryProcessor::SPECIAL_PAGE, '', $this->m_printouts);
     $link = QueryLinker::get($query);
     $link->setParameter('true', 'prettyprint');
     $link->setParameter('true', 'unescape');
     $link->setParameter('json', 'format');
     $link->setCaption('JSON');
     $downloadLinks .= $link->getHtml();
     $link = QueryLinker::get($query);
     $link->setCaption('CSV');
     $link->setParameter('csv', 'format');
     $downloadLinks .= ' | ' . $link->getHtml();
     $link = QueryLinker::get($query);
     $link->setCaption('RSS');
     $link->setParameter('rss', 'format');
     $downloadLinks .= ' | ' . $link->getHtml();
     $link = QueryLinker::get($query);
     $link->setCaption('RDF');
     $link->setParameter('rdf', 'format');
     $downloadLinks .= ' | ' . $link->getHtml();
     return '(' . $downloadLinks . ')';
 }
 public function updateData(SMWSemanticData $data, $store)
 {
     //get list of properties which are set by this article
     //todo: think about only querying for modified properties
     $properties = $data->getProperties();
     foreach ($properties as $name => $property) {
         //ignore internal properties
         if (!$property->isUserDefined() || $name == QRC_HQID_LABEL) {
             unset($properties[$name]);
         }
     }
     //determine differences between the new and the original semantic data
     global $wgTitle;
     if ($wgTitle) {
         $originalData = $store->getSemanticData($wgTitle);
         foreach ($originalData->getProperties() as $oName => $oProperty) {
             if (array_key_exists($oName, $properties)) {
                 $oValues = $originalData->getPropertyValues($oProperty);
                 $values = $data->getPropertyValues($properties[$oName]);
                 if (count($oValues) == count($values)) {
                     $oWikiValues = array();
                     foreach ($oValues as $key => $value) {
                         $oWikiValues[$value->getWikiValue()] = true;
                     }
                     $wikiValues = array();
                     foreach ($values as $key => $value) {
                         $wikiValues[$value->getWikiValue()] = true;
                     }
                     $unset = true;
                     foreach (array_keys($values) as $value) {
                         if (!array_key_exists($value, $oWikiValues)) {
                             $unset = false;
                             break;
                         }
                     }
                     if ($unset) {
                         unset($properties[$oName]);
                     }
                 }
                 //echo('<pre>'.print_r($oProperty, true).'</pre>');
                 //echo('<pre>'.print_r(, true).'</pre>');
             } else {
                 if ($oProperty->isUserDefined() && $name != QRC_HQID_LABEL) {
                     $properties[$oName] = $oProperty;
                 }
             }
         }
     }
     //deal with categories and determine which queries to update
     $categories = array();
     global $wgParser;
     if ($wgParser && $wgParser->getOutput() && $wgTitle) {
         $categories = $wgParser->getOutput()->getCategories();
         $originalCategories = $wgTitle->getParentCategories();
         //echo('<pre>'.print_r($originalCategories, true).'</pre>');
         foreach (array_keys($originalCategories) as $category) {
             $category = substr($category, strpos($category, ':') + 1);
             if (array_key_exists($category, $categories)) {
                 unset($categories[$category]);
             } else {
                 $categories[$category] = true;
             }
         }
     }
     //echo('<pre>'.print_r(array_keys($categories), true).'</pre>');
     //echo('<pre>'.print_r(array_keys($properties), true).'</pre>');
     if (count($properties) > 0 || count($categories) > 0) {
         //query for all articles that use a query which depends on one of the properties
         $queryString = SMWQRCQueryManagementHandler::getInstance()->getSearchQueriesAffectedByDataModification(array_keys($properties), array_keys($categories));
         SMWQueryProcessor::processFunctionParams(array($queryString), $queryString, $params, $printouts);
         $query = SMWQueryProcessor::createQuery($queryString, $params);
         $queryResults = $this->getQueryResult($query, true, false)->getResults();
         //get query ids which have to be invalidated
         $queryIds = array();
         foreach ($queryResults as $queryResult) {
             $semanticData = $store->getSemanticData($queryResult);
             $invalidatePC = false;
             $tQueryIds = SMWQRCQueryManagementHandler::getInstance()->getIdsOfQueriesUsingProperty($semanticData, $properties);
             if (count($tQueryIds) > 0) {
                 $invalidatePC = true;
             }
             $queryIds = array_merge($queryIds, $tQueryIds);
             $tQueryIds = SMWQRCQueryManagementHandler::getInstance()->getIdsOfQueriesUsingCategory($semanticData, $categories);
             if (count($tQueryIds) > 0) {
                 $invalidatePC = true;
             }
             $queryIds = array_merge($queryIds, $tQueryIds);
             global $invalidateParserCache, $showInvalidatedCacheEntries;
             if ($invalidatePC && $invalidateParserCache && !$showInvalidatedCacheEntries) {
                 $title = $queryResult->getTitle();
                 $title->invalidateCache();
             }
         }
         $qrcStore = SMWQRCStore::getInstance()->getDB();
         $qrcStore->invalidateQueryData($queryIds);
     }
     return $store->doUpdateData($data);
 }
示例#8
0
 /**
  * Gets all pages for a specific SF. The pages returned have an instance of the requested SF defined.
  *
  * @param string $sfName The name of the SF.
  * @param string $substring Subtsting to search upon in the names of the SFs.
  * @return array A list of page names.
  */
 public function getPageList($sfName, $substring)
 {
     $__pageList = array();
     $__serverUtility = new PCPServer();
     $__store = smwfGetStore();
     if (strstr($sfName, ':') !== false) {
         list($__sfNamespace, $__sfTitle) = split(':', $sfName);
     } else {
         $__sfTitle = $sfName;
     }
     if ($__sfTitle == '') {
         // search for all SFs
         $__tmpList = SFUtils::getAllForms();
         // categories or properties which use a spcific SF
         // the structure is $__referencingAnnotations['root']['FORMNAME'][NS-NUMBER]['PAGETITLE']
         // 				    $__referencingAnnotations['root']['FORMNAME']['sfobj']
         $__referencingAnnotations = array();
         // first: get all categories / properties that have the SF as default form
         foreach ($__tmpList as $__tmpSF) {
             // workaround: trigger an ASK query
             $__queryobj = SMWQueryProcessor::createQuery("[[Has default form::{$__tmpSF}]]", array());
             $__queryobj->querymode = SMWQuery::MODE_INSTANCES;
             $__res = smwfGetStore()->getQueryResult($__queryobj);
             $__resCount = $__res->getCount();
             for ($__i = 0; $__i < $__resCount; $__i++) {
                 $__resArray = $__res->getNext();
                 // SMWResultArray[]
                 foreach ($__resArray as $__resElement) {
                     // object from class SMWResultArray
                     $__tmpArr = $__resElement->getContent();
                     // SMWWikiPageValue[]
                     $__resPage = $__tmpArr[0];
                     // object from class SMWWikiPageValue - only 1 element is expected
                     $__referencingAnnotations[$__tmpSF][$__resPage->getNamespace()][$__resPage->getText()] = $__resPage->getTitle();
                 }
             }
         }
         // second: get all categories / properties that have the SF as an alternate form
         $__queryobj = array();
         $__res = array();
         foreach ($__tmpList as $__tmpSF) {
             // workaround: trigger an ASK query
             $__queryobj = SMWQueryProcessor::createQuery("[[Has alternate form::{$__tmpSF}]]", array());
             $__queryobj->querymode = SMWQuery::MODE_INSTANCES;
             $__res = smwfGetStore()->getQueryResult($__queryobj);
             $__resCount = $__res->getCount();
             for ($__i = 0; $__i < $__resCount; $__i++) {
                 $__resArray = $__res->getNext();
                 // SMWResultArray[]
                 foreach ($__resArray as $__resElement) {
                     // object from class SMWResultArray
                     $__tmpArr = $__resElement->getContent();
                     // SMWWikiPageValue[]
                     $__resPage = $__tmpArr[0];
                     // object from class SMWWikiPageValue - only 1 element is expected
                     $__referencingAnnotations[$__tmpSF][$__resPage->getNamespace()][$__resPage->getText()] = $__resPage->getTitle();
                 }
             }
             // now add the SF structure
             // we need at first the template title, but in future even comparision based on fields is possible
             if (isset($__referencingAnnotations[$__tmpSF][$__resPage->getNamespace()])) {
                 $__referencingAnnotations[$__tmpSF]['sfobj'] = $this->serializedForm($__tmpSF);
             }
         }
         // now determine the pages using the found categories / properties
         foreach (array_keys($__referencingAnnotations) as $__sformName) {
             $__sfCategories = $__referencingAnnotations[$__sformName][NS_CATEGORY];
             $__sfProperties = $__referencingAnnotations[$__sformName][SMW_NS_PROPERTY];
             // build a complex ASK query for all categories and properties
             $__complexQuery = '';
             if (isset($__sfCategories)) {
                 if ($__sfCategories !== NULL) {
                     foreach (array_keys($__sfCategories) as $__sfCategory) {
                         if ($__complexQuery !== '') {
                             $__complexQuery .= " OR [[Category:{$__sfCategory}]]";
                         } else {
                             $__complexQuery .= "[[Category:{$__sfCategory}]]";
                         }
                     }
                 }
             }
             if (isset($__sfProperties)) {
                 if ($__sfProperties !== NULL) {
                     foreach (array_keys($__sfProperties) as $__sfProperty) {
                         if ($__complexQuery !== '') {
                             $__complexQuery .= " OR [[{$__sfProperty}::+]]";
                         } else {
                             $__complexQuery .= "[[{$__sfProperty}::+]]";
                         }
                     }
                 }
             }
             $__queryobj = SMWQueryProcessor::createQuery($__complexQuery, array());
             $__queryobj->querymode = SMWQuery::MODE_INSTANCES;
             $__res = smwfGetStore()->getQueryResult($__queryobj);
             $__resCount = $__res->getCount();
             for ($__i = 0; $__i < $__resCount; $__i++) {
                 $__resArray = $__res->getNext();
                 // SMWResultArray[]
                 foreach ($__resArray as $__resElement) {
                     // object from class SMWResultArray
                     $__tmpArr = $__resElement->getContent();
                     // SMWWikiPageValue[]
                     $__resPage = $__tmpArr[0];
                     // object from class SMWWikiPageValue - only 1 element is expected
                     // check if the substring matches
                     if ($substring != '') {
                         if (stristr($__resPage->getText(), $substring)) {
                             // now read the POM of each page and search for the template used by the SF
                             $__pcpPage = $__serverUtility->readPage(NULL, $__resPage->getText());
                             $__pom = new POMPage($__resPage->getText(), $__pcpPage->text, array('POMExtendedParser'));
                             // search for the template
                             foreach ($__referencingAnnotations[$__sformName]['sfobj'] as $template) {
                                 $__iterator = $__pom->getTemplateByTitle($template['tmpl_name'])->listIterator();
                                 if ($__iterator->hasNext()) {
                                     $__pageList['root'][str_replace(" ", "_", $__sformName)][str_replace(" ", "_", $__resPage->getText())] = array();
                                     $__pageList['root'][str_replace(" ", "_", $__sformName)][str_replace(" ", "_", $__resPage->getText())]['ns'] = $__pcpPage->ns;
                                     $__pageList['root'][str_replace(" ", "_", $__sformName)][str_replace(" ", "_", $__resPage->getText())]['rid'] = $__pcpPage->lastrevid;
                                 }
                             }
                         }
                     } else {
                         // now read the POM of each page and search for the template used by the SF
                         $__pcpPage = $__serverUtility->readPage(NULL, $__resPage->getText());
                         $__pom = new POMPage($__resPage->getText(), $__pcpPage->text, array('POMExtendedParser'));
                         // search for the template
                         foreach ($__referencingAnnotations[$__sformName]['sfobj'] as $template) {
                             $__iterator = $__pom->getTemplateByTitle($template['tmpl_name'])->listIterator();
                             if ($__iterator->hasNext()) {
                                 $__pageList['root'][str_replace(" ", "_", $__sformName)][str_replace(" ", "_", $__resPage->getText())] = array();
                                 $__pageList['root'][str_replace(" ", "_", $__sformName)][str_replace(" ", "_", $__resPage->getText())]['ns'] = $__pcpPage->ns;
                                 $__pageList['root'][str_replace(" ", "_", $__sformName)][str_replace(" ", "_", $__resPage->getText())]['rid'] = $__pcpPage->lastrevid;
                             }
                         }
                     }
                 }
             }
         }
     } else {
         // search only for a single SF
         // categories or properties which use a spcific SF
         // the structure is $__referencingAnnotations['FORMNAME'][NS-NUMBER]['PAGETITLE']
         // 				    $__referencingAnnotations['FORMNAME']['sfobj']
         $__referencingAnnotations = array();
         // first: get all categories / properties that have the SF as default form
         // workaround: trigger an ASK query
         $__queryobj = SMWQueryProcessor::createQuery("[[Has default form::{$__sfTitle}]]", array());
         $__queryobj->querymode = SMWQuery::MODE_INSTANCES;
         $__res = smwfGetStore()->getQueryResult($__queryobj);
         $__resCount = $__res->getCount();
         for ($__i = 0; $__i < $__resCount; $__i++) {
             $__resArray = $__res->getNext();
             // SMWResultArray[]
             foreach ($__resArray as $__resElement) {
                 // object from class SMWResultArray
                 $__tmpArr = $__resElement->getContent();
                 // SMWWikiPageValue[]
                 $__resPage = $__tmpArr[0];
                 // object from class SMWWikiPageValue - only 1 element is expected
                 $__referencingAnnotations[$__sfTitle][$__resPage->getNamespace()][$__resPage->getText()] = $__resPage->getTitle();
             }
         }
         // second: get all categories / properties that have the SF as an alternate form
         $__queryobj = array();
         $__res = array();
         // workaround: trigger an ASK query
         $__queryobj = SMWQueryProcessor::createQuery("[[Has alternate form::{$__sfTitle}]]", array());
         $__queryobj->querymode = SMWQuery::MODE_INSTANCES;
         $__res = smwfGetStore()->getQueryResult($__queryobj);
         $__resCount = $__res->getCount();
         for ($__i = 0; $__i < $__resCount; $__i++) {
             $__resArray = $__res->getNext();
             // SMWResultArray[]
             foreach ($__resArray as $__resElement) {
                 // object from class SMWResultArray
                 $__tmpArr = $__resElement->getContent();
                 // SMWWikiPageValue[]
                 $__resPage = $__tmpArr[0];
                 // object from class SMWWikiPageValue - only 1 element is expected
                 $__referencingAnnotations[$__sfTitle][$__resPage->getNamespace()][$__resPage->getText()] = $__resPage->getTitle();
             }
         }
         // now add the SF structure
         // we need at first the template title, but in future even comparision based on fields is possible
         if (isset($__referencingAnnotations[$__sfTitle][$__resPage->getNamespace()])) {
             $__referencingAnnotations[$__sfTitle]['sfobj'] = $this->serializedForm($__sfTitle);
         }
         // now determine the pages using the found categories / properties
         $__sfCategories = $__referencingAnnotations[$__sfTitle][NS_CATEGORY];
         $__sfProperties = $__referencingAnnotations[$__sfTitle][SMW_NS_PROPERTY];
         // build a complex ASK query for all categories and properties
         $__complexQuery = '';
         if (isset($__sfCategories)) {
             foreach (array_keys($__sfCategories) as $__sfCategory) {
                 if ($__complexQuery !== '') {
                     $__complexQuery .= " OR [[Category:{$__sfCategory}]]";
                 } else {
                     $__complexQuery .= "[[Category:{$__sfCategory}]]";
                 }
             }
         }
         if (isset($__sfProperties)) {
             foreach (array_keys($__sfProperties) as $__sfProperty) {
                 if ($__complexQuery !== '') {
                     $__complexQuery .= " OR [[{$__sfProperty}::+]]";
                 } else {
                     $__complexQuery .= "[[{$__sfProperty}::+]]";
                 }
             }
         }
         $__queryobj = SMWQueryProcessor::createQuery($__complexQuery, array());
         $__queryobj->querymode = SMWQuery::MODE_INSTANCES;
         $__res = smwfGetStore()->getQueryResult($__queryobj);
         $__resCount = $__res->getCount();
         for ($__i = 0; $__i < $__resCount; $__i++) {
             $__resArray = $__res->getNext();
             // SMWResultArray[]
             foreach ($__resArray as $__resElement) {
                 // object from class SMWResultArray
                 $__tmpArr = $__resElement->getContent();
                 // SMWWikiPageValue[]
                 $__resPage = $__tmpArr[0];
                 // object from class SMWWikiPageValue - only 1 element is expected
                 // check if the substring matches
                 if ($substring != '') {
                     if (stristr($__resPage->getText(), $substring)) {
                         // now read the POM of each page and search for the template used by the SF
                         $__pcpPage = $__serverUtility->readPage(NULL, $__resPage->getText());
                         $__pom = new POMPage($__resPage->getText(), $__pcpPage->text, array('POMExtendedParser'));
                         // search for the template
                         foreach ($__referencingAnnotations[$__sfTitle]['sfobj'] as $template) {
                             $__iterator = $__pom->getTemplateByTitle($template['tmpl_name'])->listIterator();
                             if ($__iterator->hasNext()) {
                                 $__pageList[str_replace(" ", "_", $__sfTitle)][str_replace(" ", "_", $__resPage->getText())] = array();
                                 $__pageList[str_replace(" ", "_", $__sfTitle)][str_replace(" ", "_", $__resPage->getText())]['ns'] = $__pcpPage->ns;
                                 $__pageList[str_replace(" ", "_", $__sfTitle)][str_replace(" ", "_", $__resPage->getText())]['rid'] = $__pcpPage->lastrevid;
                             }
                         }
                     }
                 } else {
                     // now read the POM of each page and search for the template used by the SF
                     $__pcpPage = $__serverUtility->readPage(NULL, $__resPage->getText());
                     $__pom = new POMPage($__resPage->getText(), $__pcpPage->text, array('POMExtendedParser'));
                     // search for the template
                     foreach ($__referencingAnnotations[$__sfTitle]['sfobj'] as $template) {
                         $__iterator = $__pom->getTemplateByTitle($template['tmpl_name'])->listIterator();
                         if ($__iterator->hasNext()) {
                             $__pageList[str_replace(" ", "_", $__sfTitle)][str_replace(" ", "_", $__resPage->getText())] = array();
                             $__pageList[str_replace(" ", "_", $__sfTitle)][str_replace(" ", "_", $__resPage->getText())]['ns'] = $__pcpPage->ns;
                             $__pageList[str_replace(" ", "_", $__sfTitle)][str_replace(" ", "_", $__resPage->getText())]['rid'] = $__pcpPage->lastrevid;
                         }
                     }
                 }
             }
         }
     }
     return $__pageList;
 }
示例#9
0
 function rcDoOutputFeed(&$feed, $type, $id, $limit)
 {
     wfProfileIn(__METHOD__);
     $feed->outHeader();
     if ($type == "nid") {
         $dbr = wfGetDB(DB_SLAVE);
         $showall = $dbr->selectField('smw_nm_query', 'show_all', array('notify_id' => $id), 'NotifyMeRSS');
         if ($showall) {
             $query = $dbr->selectField('smw_nm_query', 'query', array('notify_id' => $id), 'NotifyMeRSS');
             SMWQueryProcessor::processFunctionParams(SMWNotifyProcessor::getQueryRawParams($query), $querystring, $params, $printouts);
             $query = SMWQueryProcessor::createQuery($querystring, $params, SMWQueryProcessor::INLINE_QUERY, 'auto', $printouts);
             $res = smwfGetStore()->getQueryResult($query);
             $items = array();
             $labels = array();
             foreach ($res->getPrintRequests() as $pr) {
                 $labels[] = $pr->getText(SMW_OUTPUT_WIKI);
             }
             $row = $res->getNext();
             $linker = new Linker();
             while ($row !== false) {
                 $wikipage = $row[0]->getNextObject();
                 // get the object
                 $a = new Article($wikipage->getTitle());
                 $description = "<table style=\"width: 60em; font-size: 90%; border: 1px solid #aaaaaa; background-color: #f9f9f9; color: black; margin-bottom: 0.5em; margin-left: 1em; padding: 0.2em; clear: right; text-align:left;\"><tr><th style=\"text-align: center; background-color:#ccccff;\" colspan=\"2\"><big>" . $wikipage->getText() . "</big></th></tr>";
                 $idx = 0;
                 foreach ($row as $field) {
                     $description .= "<tr><td>" . $labels[$idx] . "</td><td>";
                     $first_value = true;
                     while (($object = $field->getNextObject()) !== false) {
                         if ($first_value) {
                             $first_value = false;
                         } else {
                             $description .= ', ';
                         }
                         $description .= $object->getShortText(SMW_OUTPUT_HTML, $linker);
                     }
                     $description .= "</td></tr>";
                     $idx++;
                 }
                 $description .= "</table>";
                 $items[] = array('title' => $wikipage->getText(), 'notify' => $description, 'timestamp' => $a->getTimestamp());
                 $row = $res->getNext();
             }
         } else {
             $items = NMStorage::getDatabase()->getNotifyRSS($type, $id, $limit);
         }
     } else {
         $items = NMStorage::getDatabase()->getNotifyRSS($type, $id, $limit);
     }
     foreach ($items as $i) {
         if (isset($i['link']) && $i['link']) {
             $item = new FeedItem($i['title'], $i['notify'], $i['link'], $i['timestamp']);
         } else {
             $title = Title::makeTitle(NS_MAIN, $i['title']);
             $talkpage = $title->getTalkPage();
             $item = new FeedItem($title->getPrefixedText(), $i['notify'], $title->getFullURL(), $i['timestamp'], "", $talkpage->getFullURL());
         }
         $feed->outItem($item);
     }
     $feed->outFooter();
     wfProfileOut(__METHOD__);
 }
示例#10
0
 /**
  *	This method renders the result set provided by SMW according to the printer
  * 
  *  @param res				SMWQueryResult, result set of the ask query provided by SMW
  *  @param outputmode		?
  *  @return				String, rendered HTML output of this printer for the ask-query
  *
  */
 protected function getResultText($res, $outputmode)
 {
     global $wgContLang;
     // content language object
     $result = '';
     $m_outlineLevel = 0;
     $hasChildren = array();
     $m_outlineLevel++;
     $m_seedCategory = "";
     $m_seedName = "";
     $m_categories = $this->m_projectmanagementclass->getCategories();
     $m_properties = $this->m_projectmanagementclass->getProperties();
     if ($outputmode == SMW_OUTPUT_FILE) {
         $queryparts = preg_split("/]]/", $res->getQueryString());
         $taskname = str_replace("[[", "", $queryparts[0]);
         if (strpos($taskname, "Category:") === false) {
             //case: [[{{PAGENAME}}]]
             if ($res->getCount() == 1) {
                 $m_seedName = trim(str_replace("[[", "", str_replace("]]", "", $res->getQueryString())));
                 $firstQuery = smwfGetStore()->getQueryResult(SMWQueryProcessor::createQuery('[[' . $m_seedName . ']]', array(), SMWQueryProcessor::INLINE_QUERY, '', $res->getPrintRequests()));
                 //$firstQuery = smwfGetStore()->getQueryResult(SMWQueryProcessor::createQuery('[[Part of::'.$m_seedName.']]',array(),SMWQueryProcessor::INLINE_QUERY,'',$res->getPrintRequests()));
             } else {
                 return "<html><body>ERROR: Query: " . $res->getQueryString() . "is invalid! Valid formats: [[Category:SampleCategory]] or: [[{{PAGENAME}}]]</body></html>";
             }
         } else {
             $m_seedCategory = trim(str_replace("Category:", "", $taskname));
             if (in_array($m_seedCategory, $m_categories)) {
                 $firstQuery = smwfGetStore()->getQueryResult(SMWQueryProcessor::createQuery('[[Category:' . $m_seedCategory . ']]', array(), SMWQueryProcessor::INLINE_QUERY, '', $res->getPrintRequests()));
             } else {
                 return "<html><body>ERROR: Category: " . $m_seedCategory . " has not been defined on Special:SemanticProjectManagement </body></html>";
             }
         }
         $this->m_projectmanagementclass->setName("ProjectManagementClass");
         //	echo "First Query: ".$firstQuery->getQueryString()."<br/>";
         //generate seed task
         $task = $this->m_projectmanagementclass->makeTask("seed", 0);
         $task->addWBS(0, 0);
         $task->setUid(0);
         $hasChildren = $this->m_projectmanagementclass->getTaskResults($firstQuery, $outputmode, $m_outlineLevel, $task);
         $processedChildren = array();
         $hasChild = true;
         while ($hasChild) {
             $hasChild = false;
             $allTempChildren = array();
             $m_outlineLevel++;
             foreach ($hasChildren as $child) {
                 if (in_array($child, $processedChildren)) {
                 } else {
                     if (isset($m_properties[$child->getLevel()]) && isset($m_categories[$child->getLevel()])) {
                         //build new Query
                         if ($child->getLevel() != 0) {
                             $res2 = smwfGetStore()->getQueryResult(SMWQueryProcessor::createQuery('[[Category:' . $m_categories[$child->getLevel()] . ']] [[' . $m_properties[$child->getLevel()] . '::' . $child->getPage() . ']]', array(), SMWQueryProcessor::INLINE_QUERY, '', $res->getPrintRequests()));
                         } else {
                             if (isset($m_properties[1])) {
                                 $res2 = smwfGetStore()->getQueryResult(SMWQueryProcessor::createQuery('[[Category:' . $m_categories[0] . ']] [[' . $m_properties[1] . '::' . $child->getPage() . ']]', array(), SMWQueryProcessor::INLINE_QUERY, '', $res->getPrintRequests()));
                             } else {
                                 $res2 = smwfGetStore()->getQueryResult(SMWQueryProcessor::createQuery('[[' . $child->getPage() . ']]', array(), SMWQueryProcessor::INLINE_QUERY, '', $res->getPrintRequests()));
                             }
                         }
                         //	echo "Next Query: ".$res2->getQueryString()." Level: ".$m_outlineLevel."<br/>";
                         $queryresults = $this->m_projectmanagementclass->getTaskResults($res2, $outputmode, $m_outlineLevel, $child);
                         $processedChildren[] = $child;
                         foreach ($queryresults as $temp) {
                             $allTempChildren[] = $temp;
                         }
                     }
                 }
             }
             $hasChildren = $allTempChildren;
             if (count($hasChildren) > 0) {
                 $hasChild = true;
             }
         }
         $task->addWBS(1, 0);
         $result .= $this->m_projectmanagementclass->getXML();
     } else {
         // just make xml file
         if ($this->getSearchLabel($outputmode)) {
             $label = $this->getSearchLabel($outputmode);
         } else {
             $label = wfMsgForContent('spm_wbs_link');
         }
         $link = $res->getQueryLink($label);
         $link->setParameter('wbs', 'format');
         if ($this->getSearchLabel(SMW_OUTPUT_WIKI) != '') {
             $link->setParameter($this->getSearchLabel(SMW_OUTPUT_WIKI), 'searchlabel');
         }
         if (array_key_exists('limit', $this->m_params)) {
             $link->setParameter($this->m_params['limit'], 'limit');
         } else {
             // use a reasonable default limit
             $link->setParameter(500, 'limit');
         }
         $result .= $link->getText($outputmode, $this->mLinker);
         $this->isHTML = $outputmode == SMW_OUTPUT_HTML;
         // yes, our code can be viewed as HTML if requested, no more parsing needed
         // make xml file
     }
     return $result;
 }
	function get_ask_feed() {
		global $wgSitename, $wgTitle, $wgRequest;
		// check for semantic wiki:
		if ( !defined( 'SMW_VERSION' ) ) {
			return false;
		}
		// bootstrap off of SMWAskPage:
		$SMWAskPage = new SMWAskPage();
		$SMWAskPage->extractQueryParameters( $wgRequest->getVal( 'q' ) );

		// print 'query string: ' . $SMWAskPage->m_querystring . "\n<br />";
		// print 'm_params: ' . print_r($SMWAskPage->m_params) . "\n<br />";
		// print 'print outs: ' .print_r($SMWAskPage->m_printouts) . "\n<br />";
		// set up the feed:
		$this->feed = new mvRSSFeed(
		$wgSitename . ' - ' . wfMsg( 'mediasearch' ) . ' : ' . strip_tags( $SMWAskPage->m_querystring ), // title
		strip_tags( $SMWAskPage->m_querystring ), // description
		$wgTitle->getFullUrl() // link
		);
		$this->feed->outHeader();

		$queryobj = SMWQueryProcessor::createQuery( $SMWAskPage->m_querystring, $SMWAskPage->m_params, false, '', $SMWAskPage->m_printouts );
		$res = smwfGetStore()->getQueryResult( $queryobj );
		$row = $res->getNext();
		while ( $row !== false ) {
			$wikititle = $row[0]->getNextObject();
			$this->feed->outPutItem( $wikititle->getTitle() );
			$row = $res->getNext();
		}
		$this->feed->outFooter();
	}
	public function notifyUsers() {
		global $wgSitename, $wgSMTP, $wgEmergencyContact, $wgEnotifyMeJob;
		$sStore = NMStorage::getDatabase();

		$nm_send_jobs = array();
		$id = 0;

		if ( count( $this->m_notifyHtmlMsgs ) > 0 ) {
			$notifications = $sStore->getNotifyMe( array_keys( $this->m_notifyHtmlMsgs ) );
		}
		$html_style = '';
		// <style>
		// table.smwtable{background-color: #EEEEFF;}
		// table.smwtable th{background-color: #EEEEFF;text-align: left;}
		// table.smwtable td{background-color: #FFFFFF;padding: 1px;padding-left: 5px;padding-right: 5px;text-align: left;vertical-align: top;}
		// table.smwtable tr.smwfooter td{font-size: 90%;line-height: 1;background-color: #EEEEFF;padding: 0px;padding-left: 5px;padding-right: 5px;text-align: right;vertical-align: top;}
		// </style>';
		$html_showall = array();
		foreach ( $this->m_notifyHtmlMsgs as $notify_id => $msg ) {
			$html_msg = $html_style;
			$showing_all = false;
			if ( isset( $notifications[$notify_id] ) && $notifications[$notify_id]['show_all'] ) {
				SMWQueryProcessor::processFunctionParams( SMWNotifyProcessor::getQueryRawParams( $notifications[$notify_id]['query'] ), $querystring, $params, $printouts );

				$format = 'auto';
				if ( array_key_exists( 'format', $params ) ) {
					$format = strtolower( trim( $params['format'] ) );
					global $smwgResultFormats;
					if ( !array_key_exists( $format, $smwgResultFormats ) ) {
						$format = 'auto';
					}
				}
				$query  = SMWQueryProcessor::createQuery( $querystring, $params, SMWQueryProcessor::INLINE_QUERY, $format, $printouts );
				$res = smwfGetStore()->getQueryResult( $query );
				$printer = SMWQueryProcessor::getResultPrinter( $format, SMWQueryProcessor::INLINE_QUERY, $res );
				$result = $printer->getResult( $res, $params, SMW_OUTPUT_HTML );
				// FIXME: hardcode switch to full url
				global $wgScriptPath, $wgServer;
				$result = str_replace ( $wgScriptPath, $wgServer . $wgScriptPath, $result );
				$html_msg .= $result . '<br/>';
				$html_showall[$notify_id] = array ( 'name' => $notifications[$notify_id]['name'], 'html' => $result );

				$showing_all = true;
				$link = $res->getQueryLink()->getURL();
			}
			global $smwgNMHideDiffWhenShowAll;
			if ( !( $smwgNMHideDiffWhenShowAll && $showing_all ) ) {
				$html_msg .= wfMsg( 'smw_nm_hint_notification_html', $this->m_notifyHtmlMsgs[$notify_id] );
				if ( isset( $this->m_notifyHtmlPropMsgs[$notify_id] ) ) {
					$html_msg .= wfMsg( 'smw_nm_hint_nmtable_html', $this->m_notifyHtmlPropMsgs[$notify_id] );
				}
			}
			if ( $showing_all ) {
				$id = $sStore->addNotifyRSS( 'nid', $notify_id, "All current items, " . date( 'Y-m-d H:i:s', time() ), $this->applyStyle( $html_msg ), $link );
			} else {
				$id = $sStore->addNotifyRSS( 'nid', $notify_id, $this->m_title->getText(), $this->applyStyle( $html_msg ) );
			}
		}
		foreach ( $this->m_userMsgs as $user_id => $msg ) {
			// generate RSS items
			$html_msg = $html_style;
			foreach ( array_unique( $this->m_userNMs[$user_id] ) as $showall_nid ) {
				if ( isset( $html_showall[$showall_nid] ) ) {
					$html_msg .= wfMsg( 'smw_nm_hint_item_html', $html_showall[$showall_nid]['name'], $html_showall[$showall_nid]['html'] );
				}
			}

			$html_msg .= wfMsg( 'smw_nm_hint_notification_html', $this->m_userHtmlNMMsgs[$user_id] );
			if ( isset( $this->m_userHtmlPropMsgs[$user_id] ) ) {
				$html_msg .= wfMsg( 'smw_nm_hint_nmtable_html', $this->m_userHtmlPropMsgs[$user_id] );
			}

			global $wgNMReportModifier, $wgUser;
			if ( $wgNMReportModifier ) {
				$userText = $wgUser->getName();
				if ( $wgUser->getId() == 0 ) {
					$page = SpecialPage::getTitleFor( 'Contributions', $userText );
				} else {
					$page = Title::makeTitle( NS_USER, $userText );
				}
				$l = '<a href="' . $page->getFullUrl() . '">' . htmlspecialchars( $userText ) . '</a>';
				$html_msg .= wfMsg( 'smw_nm_hint_modifier_html', $l );
				$msg .= wfMsg( 'smw_nm_hint_modifier', $wgUser->getName() );
			}

			$id = $sStore->addNotifyRSS( 'uid', $user_id, $this->m_title->getText(), $this->applyStyle( $html_msg ) );

			if ( $wgEnotifyMeJob ) {
				// send notifications by mail
				$user_info = $sStore->getUserInfo( $user_id );
				$user = User::newFromRow( $user_info );
				if ( ( $user_info->user_email != '' ) && $user->getOption( 'enotifyme' ) ) {
					$name = ( ( $user_info->user_real_name == '' ) ? $user_info->user_name:$user_info->user_real_name );

					$params = array( 'to' => new MailAddress( $user_info->user_email, $name ),
						'from' => new MailAddress( $wgEmergencyContact, 'Admin' ),
						'subj' => wfMsg( 'smw_nm_hint_mail_title', $this->m_title->getText(), $wgSitename ),
						'body' => wfMsg( 'smw_nm_hint_mail_body', $name, $msg ),
						'replyto' => new MailAddress( $wgEmergencyContact, 'Admin' ) );

					$nm_send_jobs[] = new SMW_NMSendMailJob( $this->m_title, $params );
				}
			}
		}

		if ( $wgEnotifyMeJob ) {
			if ( count( $nm_send_jobs ) ) {
				Job :: batchInsert( $nm_send_jobs );
			}
		} else {
			global $phpInterpreter;
			if ( !isset( $phpInterpreter ) ) {
				// if $phpInterpreter is not set, assume it is in search path
				// if not, starting of bot will FAIL!
				$phpInterpreter = "php";
			}
			// copy from SMW_GardeningBot.php
			ob_start();
			phpinfo();
			$info = ob_get_contents();
			ob_end_clean();
			// Get Systemstring
			preg_match( '!\nSystem(.*?)\n!is', strip_tags( $info ), $ma );
			// Check if it consists 'windows' as string
			preg_match( '/[Ww]indows/', $ma[1], $os );
			global $smwgNMIP ;
			if ( $os[0] == '' && $os[0] == null ) {

				// FIXME: $runCommand must allow whitespaces in paths too
				$runCommand = "$phpInterpreter -q $smwgNMIP/specials/SMWNotifyMe/SMW_NMSendMailAsync.php";
				// TODO: test async code for linux.
				// low prio
				$nullResult = `$runCommand > /dev/null &`;
			}
			else // windowze
			{
				$runCommand = "\"\"$phpInterpreter\" -q \"$smwgNMIP/specials/SMWNotifyMe/SMW_NMSendMailAsync.php\"\"";
				$wshShell = new COM( "WScript.Shell" );
				$runCommand = "cmd /C " . $runCommand;

				$oExec = $wshShell->Run( $runCommand, 7, false );
			}
		}
	}
示例#13
0
 /**
  * TODO: document
  */
 protected function makeHTMLResult()
 {
     global $wgOut;
     // TODO: hold into account $smwgAutocompleteInSpecialAsk
     $wgOut->addModules('ext.smw.ask');
     $result = '';
     $result_mime = false;
     // output in MW Special page as usual
     // build parameter strings for URLs, based on current settings
     $urlArgs['q'] = $this->m_querystring;
     $tmp_parray = array();
     foreach ($this->m_params as $key => $value) {
         if (!in_array($key, array('sort', 'order', 'limit', 'offset', 'title'))) {
             $tmp_parray[$key] = $value;
         }
     }
     $urlArgs['p'] = SMWInfolink::encodeParameters($tmp_parray);
     $printoutstring = '';
     /**
      * @var SMWPrintRequest $printout
      */
     foreach ($this->m_printouts as $printout) {
         $printoutstring .= $printout->getSerialisation() . "\n";
     }
     if ($printoutstring !== '') {
         $urlArgs['po'] = $printoutstring;
     }
     if (array_key_exists('sort', $this->m_params)) {
         $urlArgs['sort'] = $this->m_params['sort'];
     }
     if (array_key_exists('order', $this->m_params)) {
         $urlArgs['order'] = $this->m_params['order'];
     }
     if ($this->m_querystring !== '') {
         // FIXME: this is a hack
         SMWQueryProcessor::addThisPrintout($this->m_printouts, $this->m_params);
         $params = SMWQueryProcessor::getProcessedParams($this->m_params, $this->m_printouts);
         $this->m_params['format'] = $params['format']->getValue();
         $this->params = $params;
         $queryobj = SMWQueryProcessor::createQuery($this->m_querystring, $params, SMWQueryProcessor::SPECIAL_PAGE, $this->m_params['format'], $this->m_printouts);
         /**
          * @var SMWQueryResult $res
          */
         // Determine query results
         $res = $params['source']->getValue()->getQueryResult($queryobj);
         // Try to be smart for rss/ical if no description/title is given and we have a concept query:
         if ($this->m_params['format'] == 'rss') {
             $desckey = 'rssdescription';
             $titlekey = 'rsstitle';
         } elseif ($this->m_params['format'] == 'icalendar') {
             $desckey = 'icalendardescription';
             $titlekey = 'icalendartitle';
         } else {
             $desckey = false;
         }
         if ($desckey && $queryobj->getDescription() instanceof SMWConceptDescription && (!isset($this->m_params[$desckey]) || !isset($this->m_params[$titlekey]))) {
             $concept = $queryobj->getDescription()->getConcept();
             if (!isset($this->m_params[$titlekey])) {
                 $this->m_params[$titlekey] = $concept->getText();
             }
             if (!isset($this->m_params[$desckey])) {
                 // / @bug The current SMWStore will never return SMWConceptValue (an SMWDataValue) here; it might return SMWDIConcept (an SMWDataItem)
                 $dv = end(smwfGetStore()->getPropertyValues(SMWWikiPageValue::makePageFromTitle($concept), new SMWDIProperty('_CONC')));
                 if ($dv instanceof SMWConceptValue) {
                     $this->m_params[$desckey] = $dv->getDocu();
                 }
             }
         }
         $printer = SMWQueryProcessor::getResultPrinter($this->m_params['format'], SMWQueryProcessor::SPECIAL_PAGE);
         global $wgRequest;
         $hidequery = $wgRequest->getVal('eq') == 'no';
         if (!$printer->isExportFormat()) {
             if ($res->getCount() > 0) {
                 if ($this->m_editquery) {
                     $urlArgs['eq'] = 'yes';
                 } elseif ($hidequery) {
                     $urlArgs['eq'] = 'no';
                 }
                 $navigation = $this->getNavigationBar($res, $urlArgs);
                 $result .= '<div style="text-align: center;">' . "\n" . $navigation . "\n</div>\n";
                 $query_result = $printer->getResult($res, $params, SMW_OUTPUT_HTML);
                 if (is_array($query_result)) {
                     $result .= $query_result[0];
                 } else {
                     $result .= $query_result;
                 }
                 $result .= '<div style="text-align: center;">' . "\n" . $navigation . "\n</div>\n";
             } else {
                 $result = '<div style="text-align: center;">' . wfMessage('smw_result_noresults')->escaped() . '</div>';
             }
         }
     }
     if (isset($printer) && $printer->isExportFormat()) {
         $wgOut->disable();
         /**
          * @var SMWIExportPrinter $printer
          */
         $printer->outputAsFile($res, $params);
     } else {
         if ($this->m_querystring) {
             $wgOut->setHTMLtitle($this->m_querystring);
         } else {
             $wgOut->setHTMLtitle(wfMessage('ask')->text());
         }
         $urlArgs['offset'] = $this->m_params['offset'];
         $urlArgs['limit'] = $this->m_params['limit'];
         $result = $this->getInputForm($printoutstring, wfArrayToCGI($urlArgs)) . $result;
         $wgOut->addHTML($result);
     }
 }
示例#14
0
 private static function formatWSResultWithSMWQPs($wsResults, $configArgs, $wsParameters, $wsReturnValues, $smwQueryMode)
 {
     //do sorting
     $wsResults = self::sortWSResult($wsResults, $configArgs);
     //deal with limit and offset
     list($wsResults, $furtherResults) = self::formatWithLimitAndOffset($wsResults, $configArgs);
     $format = array_key_exists('format', $configArgs) ? $configArgs['format'] : '';
     //todo: create print requests array for constructor below
     $printRequests = array();
     $queryResults = array();
     $typeIds = array();
     //get Type ids
     $numTypeFormats = array('sum' => true, 'min' => true, 'max' => true, 'average' => true);
     foreach ($wsResults as $columnLabel => $values) {
         if (array_key_exists(strtolower($format), $numTypeFormats)) {
             $typeIds[$columnLabel] = '_num';
         } else {
             $typeIds[$columnLabel] = '_txt';
         }
     }
     //create print requests
     foreach ($wsReturnValues as $id => $label) {
         $id = ucfirst(substr($id, strpos($id, '.') + 1));
         if (!$label) {
             $label = $id;
         }
         $printRequests[$id] = new SMWPrintRequest(SMWPrintRequest::PRINT_THIS, $label, $id);
     }
     //transpose ws result
     foreach ($wsResults as $columnLabel => $values) {
         foreach ($values as $key => $value) {
             $queryResultColumnValues = array();
             $resultInstance = SMWDataValueFactory::newTypeIDValue('_wpg');
             $title = Title::newFromText(wfMsg('smw_ob_invalidtitle'), '');
             $resultInstance->setValues($title->getDBkey(), $title->getNamespace(), $title->getArticleID(), false, '', $title->getFragment());
             $dataValue = SMWDataValueFactory::newTypeIDValue($typeIds[$columnLabel]);
             $dataValue->setUserValue($value);
             $queryResultColumnValues[] = $dataValue;
             //this is necessary, because one can edit with the properties
             //parameter of the LDConnector additional columns
             if (!array_key_exists(ucfirst($columnLabel), $printRequests)) {
                 $printRequests[ucfirst($columnLabel)] = new SMWPrintRequest(SMWPrintRequest::PRINT_THIS, $columnLabel, ucfirst($columnLabel));
             }
             $queryResultColumnValues = new SMWWSResultArray($resultInstance, $printRequests[ucfirst($columnLabel)], $queryResultColumnValues);
             @($queryResults[$key][$columnLabel] = $queryResultColumnValues);
         }
     }
     //translate ws call to SMW ask query
     $queryParams = array();
     foreach ($wsParameters as $param => $value) {
         $queryParams['_' . $param] = $value;
     }
     foreach ($configArgs as $param => $value) {
         $queryParams[$param] = $value;
     }
     $queryParams['source'] = 'webservice';
     $queryParams['webservice'] = $configArgs['webservice'];
     //create query object
     $query = SMWQueryProcessor::createQuery('[[dummy]]', $queryParams, SMWQueryProcessor::INLINE_QUERY, $format, $printRequests);
     $query->params = $queryParams;
     //create query result object
     $queryResult = new SMWWSQueryResult($printRequests, $query, $queryResults, new SMWWSSMWStore(), $furtherResults);
     //deal with count mode
     if ($format == 'count') {
         return count($queryResults);
     }
     //return the query result object if this is called by special:ask
     if ($smwQueryMode) {
         return $queryResult;
     }
     $printer = SMWQueryProcessor::getResultPrinter($format, SMWQueryProcessor::INLINE_QUERY);
     $result = $printer->getResult($queryResult, $configArgs, SMW_OUTPUT_WIKI);
     return $result;
 }
 /**
  * Returns all results that have a value near to the searched for value
  * on the property, ordered, and sorted by ending with the smallest one.
  *
  * @param[in] $count int  How many entities have the exact same value on the property?
  * @param[in] $greater bool  Should the values be bigger? Set false for smaller values
  *
  * @return array of array of SMWWikiPageValue, SMWDataValue with the first being the entity, and the second the value
  */
 private function getNearbyResults($count, $greater = true)
 {
     $options = new SMWRequestOptions();
     $options->limit = $this->limit + 1;
     $options->sort = true;
     // Note: printrequests change the caption of properties they get (they expect properties to be given to them)
     // Since we want to continue using the property for our purposes, we give a clone to the print request.
     $printrequest = new SMWPrintRequest(SMWPrintRequest::PRINT_PROP, '', clone $this->property);
     $params = array();
     $params['format'] = 'ul';
     $params['sort'] = $this->propertystring;
     $params['order'] = 'DESC';
     if ($greater) {
         $params['order'] = 'ASC';
     }
     $cmp = '<';
     if ($greater) {
         $cmp = '>';
     }
     $querystring = '[[' . $this->propertystring . '::' . $cmp . $this->valuestring . ']]';
     $printouts = array($printrequest);
     SMWQueryProcessor::addThisPrintout($printouts, $params);
     $params = SMWQueryProcessor::getProcessedParams($params, $printouts);
     $queryobj = SMWQueryProcessor::createQuery($querystring, $params, SMWQueryProcessor::SPECIAL_PAGE, 'ul', $printouts);
     $queryobj->querymode = SMWQuery::MODE_INSTANCES;
     $queryobj->setLimit($this->limit);
     $queryobj->setOffset($count);
     $results = smwfGetStore()->getQueryResult($queryobj);
     /* array of SMWResultArray */
     $result = $results->getNext();
     $ret = array();
     while ($result) {
         $r = array($result[0]->getNextDataValue());
         if (array_key_exists(1, $result)) {
             $r[] = $result[1]->getNextDataValue();
         }
         $ret[] = $r;
         $result = $results->getNext();
     }
     if (!$greater) {
         $ret = array_reverse($ret);
     }
     return $ret;
 }
示例#16
0
 protected function getResults($input)
 {
     $query = "[[Collection::" . $input . "]]|?Expression|?Language";
     $rawParams = explode('|', $query);
     list($queryString, $parameters, $printouts) = SMWQueryProcessor::getComponentsFromFunctionParams($rawParams, false);
     SMWQueryProcessor::addThisPrintout($printouts, $parameters);
     $smwQuery = SMWQueryProcessor::createQuery($queryString, SMWQueryProcessor::getProcessedParams($parameters, $printouts), SMWQueryProcessor::SPECIAL_PAGE, '', $printouts);
     $smwQuery->setUnboundLimit(50000);
     $smwQueryResult = smwfGetStore()->getQueryResult($smwQuery);
     $results = $smwQueryResult->toArray()['results'];
     $modified_results = array();
     foreach (array_keys($results) as $key) {
         $short_key = explode("#", $key)[0];
         $lang = $results[$key]['printouts']['Language'][0];
         $langs[$lang] = null;
         $expression = explode(":", $results[$key]['printouts']['Expression'][0]['fulltext'])[1];
         $modified_results[$short_key][$lang][] = $expression;
     }
     return array('data' => $modified_results, 'langs' => array_keys($langs));
 }
 function get_wiki_name_from_maplightid($mapID)
 {
     if (!isset($this->mapLight_cache[$mapID])) {
         //$sql = 'SELECT * FROM `smw_attributes` WHERE `attribute_title` = \'MAPLight_Person_ID\'';
         $query_string = "[[MAPLight Person ID::{$mapID}]]";
         $params = array('format' => 'broadtable', 'offset' => 0, 'limit' => 1);
         $results = array();
         $queryobj = SMWQueryProcessor::createQuery($query_string, $params, false, '', array());
         $queryobj->querymode = SMWQuery::MODE_INSTANCES;
         $res = smwfGetStore()->getQueryResult($queryobj);
         for ($i = 0; $i < $res->getCount(); $i++) {
             $v = $res->getNext();
             $v = current(current($v)->getContent());
             $this->mapLight_cache[$mapID] = $v->getXSDValue();
         }
     }
     if (!isset($this->mapLight_cache[$mapID])) {
         $wgTitle = Title::newFromText('CongressVid:Missing_People');
         print "{$query_string} No {$mapID} found\n";
         // append_to_wiki_page($wgTitle, "Missing MapLight person: [http://maplight.org/map/us/legislator/$mapID $mapID]");
         return false;
     }
     return str_replace('_', ' ', $this->mapLight_cache[$mapID]);
 }
示例#18
0
 /**
  *	This method renders the result set provided by SMW according to the printer
  *
  *  @param res				SMWQueryResult, result set of the ask query provided by SMW
  *  @param outputmode		?
  *  @return				String, rendered HTML output of this printer for the ask-query
  *
  */
 protected function getResultText($res, $outputmode)
 {
     global $wgContLang;
     // content language object
     $this->isHTML = true;
     $result = '';
     $m_outlineLevel = 0;
     $hasChildren = array();
     $m_outlineLevel++;
     $m_seedCategory = "";
     $m_seedName = "";
     $m_categories = $this->m_projectmanagementclass->getCategories();
     $m_properties = $this->m_projectmanagementclass->getProperties();
     $queryparts = preg_split("/]]/", $res->getQueryString());
     $taskname = str_replace("[[", "", $queryparts[0]);
     if (strpos($taskname, "Category:") === false) {
         //case: [[{{PAGENAME}}]]
         if ($res->getCount() == 1) {
             $m_seedName = trim(str_replace("[[", "", str_replace("]]", "", $res->getQueryString())));
             $firstQuery = smwfGetStore()->getQueryResult(SMWQueryProcessor::createQuery('[[' . $m_seedName . ']]', array(), SMWQueryProcessor::INLINE_QUERY, '', $res->getPrintRequests()));
             //$firstQuery = smwfGetStore()->getQueryResult(SMWQueryProcessor::createQuery('[[Part of::'.$m_seedName.']]',array(),SMWQueryProcessor::INLINE_QUERY,'',$res->getPrintRequests()));
         } else {
             return "<html><body>ERROR: Query: " . $res->getQueryString() . "is invalid! Valid formats: [[Category:SampleCategory]] or: [[{{PAGENAME}}]]</body></html>";
         }
     } else {
         $m_seedCategory = trim(str_replace("Category:", "", $taskname));
         if (in_array($m_seedCategory, $m_categories)) {
             $firstQuery = smwfGetStore()->getQueryResult(SMWQueryProcessor::createQuery('[[Category:' . $m_seedCategory . ']]', array(), SMWQueryProcessor::INLINE_QUERY, '', $res->getPrintRequests()));
         } else {
             return "<html><body>ERROR: Category: " . $m_seedCategory . " has not been defined on Special:SemanticProjectManagement </body></html>";
         }
     }
     $this->m_projectmanagementclass->setName("ProjectManagementClass");
     //	echo "First Query: ".$firstQuery->getQueryString()."<br/>";
     //generate seed task
     $task = $this->m_projectmanagementclass->makeTask("seed", 0);
     $task->addWBS(0, 0);
     $task->setUid(0);
     $hasChildren = $this->m_projectmanagementclass->getTaskResults($firstQuery, $outputmode, $m_outlineLevel, $task);
     $processedChildren = array();
     $hasChild = true;
     while ($hasChild) {
         $hasChild = false;
         $allTempChildren = array();
         $m_outlineLevel++;
         foreach ($hasChildren as $child) {
             if (in_array($child, $processedChildren)) {
             } else {
                 if (isset($m_properties[$child->getLevel()]) && isset($m_categories[$child->getLevel()])) {
                     //build new Query
                     if ($child->getLevel() != 0) {
                         $res2 = smwfGetStore()->getQueryResult(SMWQueryProcessor::createQuery('[[Category:' . $m_categories[$child->getLevel()] . ']] [[' . $m_properties[$child->getLevel()] . '::' . $child->getPage() . ']]', array(), SMWQueryProcessor::INLINE_QUERY, '', $res->getPrintRequests()));
                     } else {
                         if (isset($m_properties[1])) {
                             $res2 = smwfGetStore()->getQueryResult(SMWQueryProcessor::createQuery('[[Category:' . $m_categories[0] . ']] [[' . $m_properties[1] . '::' . $child->getPage() . ']]', array(), SMWQueryProcessor::INLINE_QUERY, '', $res->getPrintRequests()));
                         } else {
                             $res2 = smwfGetStore()->getQueryResult(SMWQueryProcessor::createQuery('[[' . $child->getPage() . ']]', array(), SMWQueryProcessor::INLINE_QUERY, '', $res->getPrintRequests()));
                         }
                     }
                     //	echo "Next Query: ".$res2->getQueryString()." Level: ".$m_outlineLevel."<br/>";
                     $queryresults = $this->m_projectmanagementclass->getTaskResults($res2, $outputmode, $m_outlineLevel, $child);
                     $processedChildren[] = $child;
                     foreach ($queryresults as $temp) {
                         $allTempChildren[] = $temp;
                     }
                 }
             }
         }
         $hasChildren = $allTempChildren;
         if (count($hasChildren) > 0) {
             $hasChild = true;
         }
     }
     $task->addWBS(1, 0);
     $result .= $this->m_projectmanagementclass->getGanttChart();
     return $result;
 }
示例#19
0
 function execute()
 {
     global $wgRequest, $wgOut, $wgUser, $smwgQMaxInlineLimit, $smwgIP;
     $skin = $wgUser->getSkin();
     $limit = $wgRequest->getVal('limit');
     if ('' == $limit) {
         $limit = 20;
     }
     $offset = $wgRequest->getVal('offset');
     if ('' == $offset) {
         $offset = 0;
     }
     $html = '';
     $attributestring = 'Status';
     $action = $this->action;
     $userPageTitle = $this->article->getTitle();
     $user_nick = $userPageTitle->getDBkey();
     $user = User::newFromName($user_nick);
     $groups = $user->getGroups();
     include_once "{$smwgIP}/includes/SMW_QueryProcessor.php";
     $query = '[[Status::' . $action . ']]';
     if (in_array('reporter', $groups)) {
         $query .= ' [[Reported By::' . $user->getRealName() . ']]';
     }
     if (in_array('reader', $groups)) {
         $query .= ' [[Read By::' . $user->getRealName() . ']]';
     }
     if (in_array('editor', $groups)) {
         $query .= ' [[Edited By::' . $user->getRealName() . ']]';
     }
     $params = array('offset' => $offset, 'limit' => $limit, 'format' => 'broadtable', 'mainlabel' => ' ', 'link' => 'all', 'default' => wfMsg('smw_result_noresults'), 'sort' => $sort, 'order' => $order);
     $queryobj = SMWQueryProcessor::createQuery($query, $params, false);
     $res = smwfGetStore()->getQueryResult($queryobj);
     $printer = new SMWTableResultPrinter('broadtable', false);
     $result = $printer->getResultHTML($res, $params);
     // prepare navigation bar
     if ($offset > 0) {
         $navigation = '<a href="' . htmlspecialchars($skin->makeUrl("{$userPageTitle}", 'action=' . $action . '&offset=' . max(0, $offset - $limit) . '&limit=' . $limit . '&sort=' . urlencode($sort) . '&order=' . urlencode($order))) . '">' . wfMsg('smw_result_prev') . '</a>';
     } else {
         $navigation = wfMsg('smw_result_prev');
     }
     $navigation .= '&nbsp;&nbsp;&nbsp;&nbsp; <b>' . wfMsg('smw_result_results') . ' ' . ($offset + 1) . '&ndash; ' . ($offset + $res->getCount()) . '</b>&nbsp;&nbsp;&nbsp;&nbsp;';
     if ($res->hasFurtherResults()) {
         $navigation .= ' <a href="' . htmlspecialchars($skin->makeUrl("{$userPageTitle}", 'action=' . $action . '&offset=' . ($offset + $limit) . '&limit=' . $limit . '&sort=' . urlencode($sort) . '&order=' . urlencode($order))) . '">' . wfMsg('smw_result_next') . '</a>';
     } else {
         $navigation .= wfMsg('smw_result_next');
     }
     $max = false;
     $first = true;
     foreach (array(20, 50, 100, 250, 500) as $l) {
         if ($max) {
             continue;
         }
         if ($first) {
             $navigation .= '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(';
             $first = false;
         } else {
             $navigation .= ' | ';
         }
         if ($l > $smwgQMaxLimit) {
             $l = $smwgQMaxLimit;
             $max = true;
         }
         if ($limit != $l) {
             $navigation .= '<a href="' . htmlspecialchars($skin->makeSpecialUrl('Ask', 'offset=' . $offset . '&limit=' . $l . '&query=' . urlencode($query) . '&sort=' . urlencode($sort) . '&order=' . urlencode($order))) . '">' . $l . '</a>';
         } else {
             $navigation .= '<b>' . $l . '</b>';
         }
     }
     $navigation .= ')';
     $html .= '<br /><div style="text-align: center;">' . $navigation;
     $html .= '<br />' . $result;
     $html .= '<br />' . $navigation . '</div>';
     $wgOut->addHTML($html);
 }
 function getViaNickname($partname, $limit = 5)
 {
     //split the nickname via spaces:
     $nick_parts = split('_', str_replace(' ', '_', $partname));
     $query_string = '';
     $or = '';
     foreach ($nick_parts as $pname) {
         $query_string .= $or . ' [[Nickname::~*' . ucfirst($pname) . '*]] OR [[Nickname::' . ucfirst($pname) . ']] ';
         $or = ' OR ';
     }
     $params = array('format' => 'broadtable', 'offset' => 0, 'limit' => $limit);
     $results = array();
     $queryobj = SMWQueryProcessor::createQuery($query_string, $params, false, '', array());
     $queryobj->querymode = SMWQuery::MODE_INSTANCES;
     $res = smwfGetStore()->getQueryResult($queryobj);
     for ($i = 0; $i < $res->getCount(); $i++) {
         $v = $res->getNext();
         $v = current(current($v)->getContent());
         array_push($results, $v->getXSDValue());
     }
     //replace result text:
     return $results;
 }
示例#21
0
 /**
  * returns an array of pages that are result of the semantic query
  * @param $rawQueryString string - the query string like [[Category:Trees]][[age::>1000]]
  * @return array of SMWDIWikiPage objects representing the result
  */
 public static function getAllPagesForQuery($rawQuery)
 {
     $rawQueryArray = array($rawQuery);
     SMWQueryProcessor::processFunctionParams($rawQueryArray, $queryString, $processedParams, $printouts);
     SMWQueryProcessor::addThisPrintout($printouts, $processedParams);
     $processedParams = SMWQueryProcessor::getProcessedParams($processedParams, $printouts);
     $queryObj = SMWQueryProcessor::createQuery($queryString, $processedParams, SMWQueryProcessor::SPECIAL_PAGE, '', $printouts);
     $res = smwfGetStore()->getQueryResult($queryObj);
     $pages = $res->getResults();
     return $pages;
 }
示例#22
0
文件: utils.php 项目: hala54/DSMW
 /**
  *
  * @param <String> $query (e.g. [[ChangeSet:+]][[inPullFeed::Pullfeed:xxxxx]])
  * @param <String> $paramstring Printout parameters (e.g. ?hasPatch?changeSetID)
  * @return <Object> SMWQueryResult object
  */
 public static function getSemanticQuery($query, $paramstring = '')
 {
     $printouts = array();
     $rawparams = array();
     $params = array('format' => ' ', 'sort' => ' ', 'offset' => 0);
     $rawparams[] = $query;
     if ($paramstring != '') {
         $ps = explode("\n", $paramstring);
         foreach ($ps as $param) {
             $param = trim($param);
             if ($param != '' && $param[0] != '?') {
                 $param = '?' . $param;
             }
             $rawparams[] = $param;
         }
     }
     SMWQueryProcessor::processFunctionParams($rawparams, $query, $params, $printouts);
     $queryobj = SMWQueryProcessor::createQuery($query, $params, SMWQueryProcessor::SPECIAL_PAGE, '', $printouts);
     $queryobj->setLimit(5000);
     $res = smwfGetStore()->getQueryResult($queryobj);
     if (!$res instanceof SMWQueryResult) {
         return false;
     }
     return $res;
 }
 /**
  * This function returns to results of a certain query
  * This functions is part of the extension Semantic Tasks by Steren Giannini & Ryan Lane
  * released under GNU GPLv2 (or later)
  * http://www.mediawiki.org/wiki/Extension:Semantic_Tasks
  * @param $query_string String : the query
  * @param $properties_to_display array(String): array of property names to display
  * @param $display_title Boolean : add the page title in the result
  * @return TODO
  */
 static function getQueryResults($query_string, $properties_to_display, $display_title)
 {
     // We use the Semantic MediaWiki Processor
     // $smwgIP is defined by Semantic MediaWiki, and we don't allow
     // this file to be sourced unless Semantic MediaWiki is included.
     global $smwgIP;
     include_once $smwgIP . "/includes/query/SMW_QueryProcessor.php";
     $params = array();
     $inline = true;
     $printlabel = "";
     $printouts = array();
     // add the page name to the printouts
     if ($display_title) {
         if (version_compare(SMW_VERSION, '1.7', '>')) {
             SMWQueryProcessor::addThisPrintout($printouts, $params);
         } else {
             $to_push = new SMWPrintRequest(SMWPrintRequest::PRINT_THIS, $printlabel);
             array_push($printouts, $to_push);
         }
     }
     // Push the properties to display in the printout array.
     foreach ($properties_to_display as $property) {
         if (class_exists('SMWPropertyValue')) {
             // SMW 1.4
             $to_push = new SMWPrintRequest(SMWPrintRequest::PRINT_PROP, $property, SMWPropertyValue::makeUserProperty($property));
         } else {
             $to_push = new SMWPrintRequest(SMWPrintRequest::PRINT_PROP, $property, Title::newFromText($property, SMW_NS_PROPERTY));
         }
         array_push($printouts, $to_push);
     }
     if (version_compare(SMW_VERSION, '1.6.1', '>')) {
         $params = SMWQueryProcessor::getProcessedParams($params, $printouts);
         $format = null;
     } else {
         $format = 'auto';
     }
     $query = SMWQueryProcessor::createQuery($query_string, $params, $inline, $format, $printouts);
     $results = smwfGetStore()->getQueryResult($query);
     return $results;
 }
示例#24
0
 /**
  * #ask itself.
  * Delegate the treatments to SMWQueryProcessor
  *
  * @var SMWQueryProcessor
  * @param <type> $m_querystring
  * @param <type> $props
  * @return <type>
  */
 private function ask($m_querystring, $props = array(), $limit = null, $offset = 0)
 {
     $rawparams = array();
     if ($m_querystring != '') {
         $rawparams[] = $m_querystring;
     }
     foreach ($props as $prop) {
         $prop = trim($prop);
         if ($prop != '' && $prop != '?') {
             if ($prop[0] != '?') {
                 $prop = '?' . $prop;
             }
             $rawparams[] = $prop;
         }
     }
     $m_params = array();
     $m_printouts = array();
     SMWQueryProcessor::processFunctionParams($rawparams, $m_querystring, $m_params, $m_printouts);
     $m_params['offset'] = $offset;
     if (!is_null($limit)) {
         $m_params['limit'] = $limit;
     }
     $queryobj = SMWQueryProcessor::createQuery($m_querystring, $m_params, SMWQueryProcessor::SPECIAL_PAGE, null, $m_printouts);
     return smwfGetStore()->getQueryResult($queryobj);
 }
示例#25
0
 /**
  * @param String $term
  *
  * @return SMWQuery | null
  */
 private function getSearchQuery($term)
 {
     if (!is_string($term) || trim($term) === '') {
         return null;
     }
     if (!array_key_exists($term, $this->queryCache)) {
         $params = \SMWQueryProcessor::getProcessedParams(array());
         $query = \SMWQueryProcessor::createQuery($term, $params);
         $description = $query->getDescription();
         if ($description === null || is_a($description, 'SMWThingDescription')) {
             $query = null;
         }
         $this->queryCache[$term] = $query;
     }
     return $this->queryCache[$term];
 }
示例#26
0
 /**
  * Exectues ask-interface as done in SMW<=0.7, using a simple textbox interface and supporting only
  * certain parameters.
  */
 protected function executeSimpleAsk()
 {
     global $wgRequest, $wgOut, $smwgQEnabled, $smwgQMaxLimit, $wgUser, $smwgQSortingSupport, $smwgIP;
     $skin = $wgUser->getSkin();
     $query = $wgRequest->getVal('query');
     $sort = $wgRequest->getVal('sort');
     $order = $wgRequest->getVal('order');
     $limit = $wgRequest->getVal('limit');
     if ('' == $limit) {
         $limit = 20;
     }
     $offset = $wgRequest->getVal('offset');
     if ('' == $offset) {
         $offset = 0;
     }
     // display query form
     $spectitle = Title::makeTitle(NS_SPECIAL, 'Ask');
     $docutitle = Title::newFromText(wfMsg('smw_ask_doculink'), NS_HELP);
     $html = '<form name="ask" action="' . $spectitle->escapeLocalURL() . '" method="get">' . "\n" . '<input type="hidden" name="title" value="' . $spectitle->getPrefixedText() . '"/>';
     $html .= '<textarea name="query" cols="40" rows="6">' . htmlspecialchars($query) . '</textarea><br />' . "\n";
     if ($smwgQSortingSupport) {
         $html .= wfMsg('smw_ask_sortby') . ' <input type="text" name="sort" value="' . htmlspecialchars($sort) . '"/> <select name="order"><option ';
         if ($order == 'ASC') {
             $html .= 'selected="selected" ';
         }
         $html .= 'value="ASC">' . wfMsg('smw_ask_ascorder') . '</option><option ';
         if ($order == 'DESC') {
             $html .= 'selected="selected" ';
         }
         $html .= 'value="DESC">' . wfMsg('smw_ask_descorder') . '</option></select> <br />';
     }
     $html .= '<br /><input type="submit" value="' . wfMsg('smw_ask_submit') . '"/> <a href="' . $docutitle->getFullURL() . '">' . wfMsg('smw_ask_help') . "</a>\n</form>";
     // print results if any
     if ($smwgQEnabled && '' != $query) {
         include_once "{$smwgIP}/includes/SMW_QueryProcessor.php";
         $params = array('offset' => $offset, 'limit' => $limit, 'format' => 'broadtable', 'mainlabel' => ' ', 'link' => 'all', 'default' => wfMsg('smw_result_noresults'), 'sort' => $sort, 'order' => $order);
         $queryobj = SMWQueryProcessor::createQuery($query, $params, false);
         $res = smwfGetStore()->getQueryResult($queryobj);
         $printer = new SMWTableResultPrinter('broadtable', false);
         $result = $printer->getResultHTML($res, $params);
         // prepare navigation bar
         if ($offset > 0) {
             $navigation = '<a href="' . htmlspecialchars($skin->makeSpecialUrl('Ask', 'offset=' . max(0, $offset - $limit) . '&limit=' . $limit . '&query=' . urlencode($query) . '&sort=' . urlencode($sort) . '&order=' . urlencode($order))) . '">' . wfMsg('smw_result_prev') . '</a>';
         } else {
             $navigation = wfMsg('smw_result_prev');
         }
         $navigation .= '&nbsp;&nbsp;&nbsp;&nbsp; <b>' . wfMsg('smw_result_results') . ' ' . ($offset + 1) . '&ndash; ' . ($offset + $res->getCount()) . '</b>&nbsp;&nbsp;&nbsp;&nbsp;';
         if ($res->hasFurtherResults()) {
             $navigation .= ' <a href="' . htmlspecialchars($skin->makeSpecialUrl('Ask', 'offset=' . ($offset + $limit) . '&limit=' . $limit . '&query=' . urlencode($query) . '&sort=' . urlencode($sort) . '&order=' . urlencode($order))) . '">' . wfMsg('smw_result_next') . '</a>';
         } else {
             $navigation .= wfMsg('smw_result_next');
         }
         $max = false;
         $first = true;
         foreach (array(20, 50, 100, 250, 500) as $l) {
             if ($max) {
                 continue;
             }
             if ($first) {
                 $navigation .= '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(';
                 $first = false;
             } else {
                 $navigation .= ' | ';
             }
             if ($l > $smwgQMaxLimit) {
                 $l = $smwgQMaxLimit;
                 $max = true;
             }
             if ($limit != $l) {
                 $navigation .= '<a href="' . htmlspecialchars($skin->makeSpecialUrl('Ask', 'offset=' . $offset . '&limit=' . $l . '&query=' . urlencode($query) . '&sort=' . urlencode($sort) . '&order=' . urlencode($order))) . '">' . $l . '</a>';
             } else {
                 $navigation .= '<b>' . $l . '</b>';
             }
         }
         $navigation .= ')';
         $html .= '<br /><div style="text-align: center;">' . $navigation;
         $html .= '<br />' . $result;
         $html .= '<br />' . $navigation . '</div>';
     } elseif (!$smwgQEnabled) {
         $html .= '<br />' . wfMsgForContent('smw_iq_disabled');
     }
     $wgOut->addHTML($html);
 }
示例#27
0
 /**
  * Executes the query.
  *
  * This method can be called once $queryString, $parameters, $printOuts
  * are set either by using the setQueryString(), setParams() and
  * setPrintOuts() followed by extractParameters(), or one of the static
  * factory methods such as makeForInfoLink() or makeForUI().
  *
  * Errors, if any can be accessed from hasError() and getErrors().
  */
 public function execute()
 {
     $errors = array();
     if ($this->queryString !== '') {
         // FIXME: this is a hack
         SMWQueryProcessor::addThisPrintout($this->printOuts, $this->parameters);
         $params = SMWQueryProcessor::getProcessedParams($this->parameters, $this->printOuts);
         $this->parameters['format'] = $params['format'];
         $this->params = $params;
         $query = SMWQueryProcessor::createQuery($this->queryString, $params, SMWQueryProcessor::SPECIAL_PAGE, $this->parameters['format'], $this->printOuts);
         $res = smwfGetStore()->getQueryResult($query);
         $this->queryResult = $res;
         $errors = array_merge($errors, $res->getErrors());
         if (!empty($errors)) {
             $this->errorsOccured = true;
             $this->errors = array_merge($errors, $this->errors);
         }
         // BEGIN: Try to be smart for rss/ical if no description/title is given and we have a concept query
         if ($this->parameters['format'] == 'rss') {
             $descKey = 'rssdescription';
             $titleKey = 'rsstitle';
         } elseif ($this->parameters['format'] == 'icalendar') {
             $descKey = 'icalendardescription';
             $titleKey = 'icalendartitle';
         } else {
             $descKey = false;
         }
         if ($descKey && $query->getDescription() instanceof SMWConceptDescription && (!isset($this->parameters[$descKey]) || !isset($this->parameters[$titleKey]))) {
             $concept = $query->getDescription()->getConcept();
             if (!isset($this->parameters[$titleKey])) {
                 $this->parameters[$titleKey] = $concept->getText();
             }
             if (!isset($this->parameters[$descKey])) {
                 // / @bug The current SMWStore will never return SMWConceptValue (an SMWDataValue) here; it might return SMWDIConcept (an SMWDataItem)
                 $dv = end(smwfGetStore()->getPropertyValues(SMWWikiPageValue::makePageFromTitle($concept), new SMWDIProperty('_CONC')));
                 if ($dv instanceof SMWConceptValue) {
                     $this->parameters[$descKey] = $dv->getDocu();
                 }
             }
         }
         // END: Try to be smart for rss/ical if no description/title is given and we have a concept query
         /*
          * If parameters have been passed in the infolink-style and the
          * mimie-type of format is defined, generate the export, instead of
          * showing more html.
          */
         $printer = SMWQueryProcessor::getResultPrinter($this->parameters['format'], SMWQueryProcessor::SPECIAL_PAGE);
         $resultMime = $printer->getMimeType($res);
         if ($this->context == self::WIKI_LINK && $resultMime != false) {
             global $wgOut;
             $result = $printer->getResult($res, $this->parameters, SMW_OUTPUT_FILE);
             $resultName = $printer->getFileName($res);
             $wgOut->disable();
             header("Content-type: {$resultMime}; charset=UTF-8");
             if ($resultName !== false) {
                 header("content-disposition: attachment; filename={$resultName}");
             }
             echo $result;
         }
     }
 }
	static function smwfProcessInlineQueryParserFunctionGTP( &$parser ) {
		global $smwgQEnabled, $smwgIQRunningNumber;
		if ( $smwgQEnabled ) {
			$smwgIQRunningNumber++;
			$rawparams = func_get_args();
			array_shift( $rawparams ); // we already know the $parser ...

			SMWQueryProcessor::processFunctionParams( $rawparams, &$querystring, &$params, &$printouts );
			self::prequery( $params, $printouts, $label, $wom_id );

			$query  = SMWQueryProcessor::createQuery(
					$querystring,
					$params,
					SMWQueryProcessor::INLINE_QUERY,
					SMW_OUTPUT_WIKI,
					$printouts
				);
			$res = smwfGetStore()->getQueryResult( $query );

			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 '';
	}
示例#29
0
function getAnnotations($annotatedImage)
{
    global $wgExtensionCredits;
    $new = false;
    foreach ($wgExtensionCredits['semantic'] as $elem) {
        if ($elem['name'] == 'Semantic MediaWiki') {
            $vers = $elem['version'];
            $new = version_compare($vers, '1.7', '>=');
        }
    }
    $returnString = '{"shapes":[';
    $queryString = '[[SIAannotatedImage::' . $annotatedImage . ']]';
    $params = array();
    $params['link'] = 'none';
    $params['mainlabel'] = 'result';
    #$params = ['order'];
    #$params = ['sort'];
    if ($new) {
        $params['order'] = array('asc');
        $params['sort'] = array('SIAannotatedImage');
    } else {
        $params['order'] = 'asc';
        $params['sort'] = 'SIAannotatedImage';
    }
    //Generate all the extra printouts, eg all properties to retrieve:
    $printmode = SMWPrintRequest::PRINT_PROP;
    $customPrintouts = array('coordinates' => 'SIArectangleCoordinates', 'text' => 'ImageAnnotationText');
    $extraprintouts = array();
    foreach ($customPrintouts as $label => $property) {
        $extraprintouts[] = new SMWPrintRequest($printmode, $label, SMWPropertyValue::makeUserProperty($property));
    }
    $format = 'table';
    $context = SMWQueryProcessor::INLINE_QUERY;
    $query = SMWQueryProcessor::createQuery($queryString, $params, $context, $format, $extraprintouts);
    $store = smwfGetStore();
    // default store
    $res = $store->getQueryResult($query);
    $shapeCounter = 0;
    while (($resArrayArray = $res->getNext()) != false) {
        //Array of SMWResultArray Objects, eg. all retrieved Pages
        $shapeCounter++;
        if ($shapeCounter > 1) {
            $returnString .= ',';
        }
        $returnString .= '{';
        foreach ($resArrayArray as $resArray) {
            //SMWResultArray-Object, column of resulttable (pagename or propertyvalue)
            $currentPrintRequestLabel = $resArray->getPrintRequest()->getLabel();
            //The label as defined in the above array
            if ($currentPrintRequestLabel == 'coordinates') {
                $currentResultPage = $resArray->getResultSubject();
                $currentID = $currentResultPage->getTitle()->getFullText();
                $currentCoords = $resArray->getNextDataItem()->getSerialization();
                $returnString .= '"coords":"' . $currentCoords . '","id":"' . $currentID . '"';
            }
        }
        $returnString .= '}';
    }
    $returnString .= ']}';
    return $returnString;
}
	/**
	 * TODO: document
	 */
	protected function makeHTMLResult() {
		global $wgOut, $smwgAutocompleteInSpecialAsk;

		$delete_msg = wfMsg( 'delete' );

		// Javascript code for the dynamic parts of the page
		$javascript_text = <<<END
<script type="text/javascript">
function updateOtherOptions(strURL) {
	jQuery.ajax({ url: strURL, context: document.body, success: function(data){
		jQuery("#other_options").html(data);
	}});
}

// code for handling adding and removing the "sort" inputs
var num_elements = {$this->m_num_sort_values};

function addInstance(starter_div_id, main_div_id) {
	var starter_div = document.getElementById(starter_div_id);
	var main_div = document.getElementById(main_div_id);

	//Create the new instance
	var new_div = starter_div.cloneNode(true);
	var div_id = 'sort_div_' + num_elements;
	new_div.className = 'multipleTemplate';
	new_div.id = div_id;
	new_div.style.display = 'block';

	var children = new_div.getElementsByTagName('*');
	var x;
	for (x = 0; x < children.length; x++) {
		if (children[x].name)
			children[x].name = children[x].name.replace(/_num/, '[' + num_elements + ']');
	}

	//Create 'delete' link
	var remove_button = document.createElement('span');
	remove_button.innerHTML = '[<a href="javascript:removeInstance(\'sort_div_' + num_elements + '\')">{$delete_msg}</a>]';
	new_div.appendChild(remove_button);

	//Add the new instance
	main_div.appendChild(new_div);
	num_elements++;
}

function removeInstance(div_id) {
	var olddiv = document.getElementById(div_id);
	var parent = olddiv.parentNode;
	parent.removeChild(olddiv);
}
</script>

END;

		$wgOut->addScript( $javascript_text );

		if ( $smwgAutocompleteInSpecialAsk ) {
			self::addAutocompletionJavascriptAndCSS();
		}

		$result = '';
		$result_mime = false; // output in MW Special page as usual

		// build parameter strings for URLs, based on current settings
		$urlArgs['q'] = $this->m_querystring;

		$tmp_parray = array();
		foreach ( $this->m_params as $key => $value ) {
			if ( !in_array( $key, array( 'sort', 'order', 'limit', 'offset', 'title' ) ) ) {
				$tmp_parray[$key] = $value;
			}
		}

		$urlArgs['p'] = SMWInfolink::encodeParameters( $tmp_parray );
		$printoutstring = '';

		foreach ( $this->m_printouts as /* SMWPrintRequest */ $printout ) {
			$printoutstring .= $printout->getSerialisation() . "\n";
		}

		if ( $printoutstring !== '' ) $urlArgs['po'] = $printoutstring;
		if ( array_key_exists( 'sort', $this->m_params ) )  $urlArgs['sort'] = $this->m_params['sort'];
		if ( array_key_exists( 'order', $this->m_params ) ) $urlArgs['order'] = $this->m_params['order'];

		if ( $this->m_querystring !== '' ) {
			// FIXME: this is a hack
			SMWQueryProcessor::addThisPrintout( $this->m_printouts, $this->m_params );
			$params = SMWQueryProcessor::getProcessedParams( $this->m_params, $this->m_printouts );
			$this->m_params['format'] = $params['format'];

			$queryobj = SMWQueryProcessor::createQuery(
				$this->m_querystring,
				$params,
				SMWQueryProcessor::SPECIAL_PAGE ,
				$this->m_params['format'],
				$this->m_printouts
			);

			$res = smwfGetStore()->getQueryResult( $queryobj );

			// Try to be smart for rss/ical if no description/title is given and we have a concept query:
			if ( $this->m_params['format'] == 'rss' ) {
				$desckey = 'rssdescription';
				$titlekey = 'rsstitle';
			} elseif ( $this->m_params['format'] == 'icalendar' ) {
				$desckey = 'icalendardescription';
				$titlekey = 'icalendartitle';
			} else { $desckey = false; }

			if ( ( $desckey ) && ( $queryobj->getDescription() instanceof SMWConceptDescription ) &&
			     ( !isset( $this->m_params[$desckey] ) || !isset( $this->m_params[$titlekey] ) ) ) {
				$concept = $queryobj->getDescription()->getConcept();

				if ( !isset( $this->m_params[$titlekey] ) ) {
					$this->m_params[$titlekey] = $concept->getText();
				}

				if ( !isset( $this->m_params[$desckey] ) ) {
					// / @bug The current SMWStore will never return SMWConceptValue (an SMWDataValue) here; it might return SMWDIConcept (an SMWDataItem)
					$dv = end( smwfGetStore()->getPropertyValues( SMWWikiPageValue::makePageFromTitle( $concept ), new SMWDIProperty( '_CONC' ) ) );
					if ( $dv instanceof SMWConceptValue ) {
						$this->m_params[$desckey] = $dv->getDocu();
					}
				}
			}

			$printer = SMWQueryProcessor::getResultPrinter( $this->m_params['format'], SMWQueryProcessor::SPECIAL_PAGE );
			$result_mime = $printer->getMimeType( $res );

			global $wgRequest;

			$hidequery = $wgRequest->getVal( 'eq' ) == 'no';

			// if it's an export format (like CSV, JSON, etc.),
			// don't actually export the data if 'eq' is set to
			// either 'yes' or 'no' in the query string - just
			// show the link instead
			if ( $this->m_editquery || $hidequery ) $result_mime = false;

			if ( $result_mime == false ) {
				if ( $res->getCount() > 0 ) {
					if ( $this->m_editquery ) {
						$urlArgs['eq'] = 'yes';
					}
					elseif ( $hidequery ) {
						$urlArgs['eq'] = 'no';
					}

					$navigation = $this->getNavigationBar( $res, $urlArgs );
					$result .= '<div style="text-align: center;">' . "\n" . $navigation . "\n</div>\n";
					$query_result = $printer->getResult( $res, $params, SMW_OUTPUT_HTML );

					if ( is_array( $query_result ) ) {
						$result .= $query_result[0];
					} else {
						$result .= $query_result;
					}

					$result .= '<div style="text-align: center;">' . "\n" . $navigation . "\n</div>\n";
				} else {
					$result = '<div style="text-align: center;">' . wfMsgHtml( 'smw_result_noresults' ) . '</div>';
				}
			} else { // make a stand-alone file
				$result = $printer->getResult( $res, $params, SMW_OUTPUT_FILE );
				$result_name = $printer->getFileName( $res ); // only fetch that after initialising the parameters
			}
		}

		if ( $result_mime == false ) {
			if ( $this->m_querystring ) {
				$wgOut->setHTMLtitle( $this->m_querystring );
			} else {
				$wgOut->setHTMLtitle( wfMsg( 'ask' ) );
			}

			$urlArgs['offset'] = $this->m_params['offset'];
			$urlArgs['limit'] = $this->m_params['limit'];

			$result = $this->getInputForm(
				$printoutstring,
				wfArrayToCGI( $urlArgs )
			) . $result;

			$wgOut->addHTML( $result );
		} else {
			$wgOut->disable();

			header( "Content-type: $result_mime; charset=UTF-8" );

			if ( $result_name !== false ) {
				header( "content-disposition: attachment; filename=$result_name" );
			}

			echo $result;
		}
	}