public function execute() { $params = $this->extractRequestParams(); $rawParams = preg_split("/(?<=[^\\|])\\|(?=[^\\|])/", $params['query']); list($queryString, $this->parameters, $printouts) = SMWQueryProcessor::getComponentsFromFunctionParams($rawParams, false); $queryResult = $this->getQueryResult($this->getQuery($queryString, $printouts)); $this->addQueryResult($queryResult); }
/** * @see ItemParameterManipulation::doManipulation * * @since 1.6.2 */ public function doManipulation(&$value, Parameter $parameter, array &$parameters) { // Make sure the format value is valid. $value = self::getValidFormatName($value); // Add the formats parameters to the parameter list. $queryPrinter = SMWQueryProcessor::getResultPrinter($value); $parameters = array_merge($parameters, $queryPrinter->getValidatorParameters()); }
public function execute() { $params = $this->extractRequestParams(); // TODO: this prevents doing [[Category:Foo||bar||baz]], must document. $rawParams = explode('|', $params['query']); $queryString = ''; $printouts = array(); SMWQueryProcessor::processFunctionParams($rawParams, $queryString, $this->parameters, $printouts); $queryResult = $this->getQueryResult($this->getQuery($queryString, $printouts)); $this->addQueryResult($queryResult); }
public function execute() { $params = $this->extractRequestParams(); $this->requireParameters($params, array('query')); $rawParams = explode('|', $params['query']); $queryString = ''; $printouts = array(); SMWQueryProcessor::processFunctionParams($rawParams, $queryString, $this->parameters, $printouts); $queryResult = $this->getQueryResult($this->getQuery($queryString, $printouts)); $this->addQueryResult($queryResult); }
/** * * @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 ); }
private function doProcessQueryFor($query, $sep = ",") { $query = str_replace(array("<", ">", "sep=;"), array("<", ">", "sep={$sep};"), $query); $params = explode(";", $query); $f = str_replace(";", "|", $params[0]); $params[0] = $this->parser->replaceVariables($f); if ($this->debugFlag) { error_log(implode("|", $params)); } $values = $this->getFormattedValuesFrom($sep, QueryProcessor::getResultFromFunctionParams($params, SMW_OUTPUT_WIKI)); return json_encode(array("values" => $values, "count" => count($values))); }
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); }
/** * Display a form section showing the options for a given format, * based on the getParameters() value for that format's query printer. * * @since 1.8 * * @param string $format * @param array $paramValues The current values for the parameters (name => value) * * @return string */ protected function showFormatOptions($format, array $paramValues) { $definitions = SMWQueryProcessor::getFormatParameters($format); $optionsHtml = array(); /** * @var ParamProcessor\ParamDefinition $definition */ foreach ($definitions as $name => $definition) { // Ignore the format parameter, as we got a special control in the GUI for it already. if ($name == 'format') { continue; } // Maybe there is a better way but somehow I couldn't find one therefore // 'source' display will be omitted where no alternative source was found or // a source that was marked as default but had no other available options $allowedValues = $definition->getAllowedValues(); if ($name == 'source' && (count($allowedValues) == 0 || in_array('default', $allowedValues) && count($allowedValues) < 2)) { continue; } $currentValue = array_key_exists($name, $paramValues) ? $paramValues[$name] : false; $dataInfo = $definition->getMessage() !== null ? $this->msg($definition->getMessage())->text() : ''; $optionsHtml[] = '<td>' . Html::rawElement('span', array('class' => $this->isTooltipDisplay() == true ? 'smw-ask-info' : '', 'word-wrap' => 'break-word', 'data-info' => $dataInfo), htmlspecialchars($name) . ': ') . '</td>' . $this->showFormatOption($definition, $currentValue); } $i = 0; $n = 0; $rowHtml = ''; $resultHtml = ''; // Top info text for a collapsed option box if ($this->isTooltipDisplay() == true) { $resultHtml .= Html::element('div', array('style' => 'margin-bottom:10px;'), wfMessage('smw-ask-otheroptions-info')->text()); } // Table $resultHtml .= Html::openElement('table', array('class' => 'smw-ask-otheroptions', 'width' => '100%')); $resultHtml .= Html::openElement('tbody'); while ($option = array_shift($optionsHtml)) { $i++; // Collect elements for a row $rowHtml .= $option; // Create table row if ($i % 3 == 0) { $resultHtml .= Html::rawElement('tr', array('style' => 'background: ' . ($i % 6 == 0 ? 'white' : '#eee')), $rowHtml); $rowHtml = ''; $n++; } } // Ensure left over elements are collected as well $resultHtml .= Html::rawElement('tr', array('style' => 'background: ' . ($n % 2 == 0 ? '#eee' : 'white')), $rowHtml); $resultHtml .= Html::closeElement('tbody'); $resultHtml .= Html::closeElement('table'); return $resultHtml; }
/** * 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('>', '<'), 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('[', '[', $concept_text) . "</pre>\n</div>"; if (!is_null($wgTitle) && $wgTitle->isSpecialPage()) { global $wgOut; SMWOutputs::commitToOutputPage($wgOut); } else { SMWOutputs::commitToParser($parser); } return $result; }
/** * * Retrieve all internal objects and their properties. * @param String $pagename * @param String $internalproperty * @return an array. Each element is an associative array and represents an internal object. * * E.G: {{#ptest:Chross|Is a parameter in an application}} * */ public static function getSemanticInternalObjects($pagename, $internalproperty, $namespace = NS_MAIN) { $params = array("[[{$internalproperty}::{$pagename}]]", "format=list", "link=none", "headers=hide", "sep=;", "limit=5000"); $result = SMWQueryProcessor::getResultFromFunctionParams($params, SMW_OUTPUT_WIKI); $result = trim($result); $sios = array(); if ($result) { $sios = explode(";", $result); } $ret = array(); foreach ($sios as $sio) { #remove namespace prefix. $sio = preg_replace("/^[^:]+:/", "", $sio); $sio = str_replace(" ", "_", $sio); #remove fragment to - #$sio=str_replace("#", "-23", $sio); array_push($ret, self::loadSemanticProperties($sio, $namespace, true)); } return $ret; }
/** * Method for handling the ask parser function. * * @since 1.5.3 * * @param Parser $parser */ public static function render(Parser &$parser) { global $smwgQEnabled, $smwgIQRunningNumber, $wgTitle; if ($smwgQEnabled) { $smwgIQRunningNumber++; $params = func_get_args(); array_shift($params); // We already know the $parser ... $result = SMWQueryProcessor::getResultFromFunctionParams($params, SMW_OUTPUT_WIKI); } else { $result = smwfEncodeMessages(array(wfMessage('smw_iq_disabled')->inContentLanguage()->text())); } if (!is_null($wgTitle) && $wgTitle->isSpecialPage()) { global $wgOut; SMWOutputs::commitToOutputPage($wgOut); } else { SMWOutputs::commitToParser($parser); } return $result; }
function execute($p) { global $wgOut, $wgRequest, $smwgQEnabled, $smwgRSSEnabled, $smwgMW_1_14; wfProfileIn('doSpecialAskTSC (SMWHalo)'); $this->extractQueryParameters($p); $format = $this->getResultFormat($this->m_params); $query = SMWSPARQLQueryProcessor::createQuery($this->m_querystring, $this->m_params, SMWQueryProcessor::SPECIAL_PAGE, $format, $this->m_printouts); $res = smwfGetStore()->getQueryResult($query); $printer = SMWQueryProcessor::getResultPrinter($format, SMWQueryProcessor::SPECIAL_PAGE, $res); $result_mime = $printer->getMimeType($res); if ($result_mime == false) { if ($res->getCount() > 0) { $result = '<div style="text-align: center;">'; $result .= '</div>' . $printer->getResult($res, $this->m_params, SMW_OUTPUT_HTML); $result .= '<div style="text-align: center;"></div>'; } else { $result = '<div style="text-align: center;">' . wfMsg('smw_result_noresults') . '</div>'; } } else { // make a stand-alone file $result = $printer->getResult($res, $this->m_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')); } $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}"); } print $result; } wfProfileOut('doSpecialAskTSC (SMWHalo)'); }
/** * Method for handling the show parser function. * * @since 1.5.3 * * @param Parser $parser */ public static function render(Parser &$parser) { global $smwgQEnabled, $smwgIQRunningNumber, $wgTitle; if ($smwgQEnabled) { $smwgIQRunningNumber++; $rawParams = func_get_args(); array_shift($rawParams); // We already know the $parser ... list($query, $params) = SMWQueryProcessor::getQueryAndParamsFromFunctionParams($rawParams, SMW_OUTPUT_WIKI, SMWQueryProcessor::INLINE_QUERY, true); $result = SMWQueryProcessor::getResultFromQuery($query, $params, SMW_OUTPUT_WIKI, SMWQueryProcessor::INLINE_QUERY); $queryKey = hash('md4', implode('|', $rawParams), false); SMWAsk::addQueryData($queryKey, $query, $params, $parser); } else { $result = smwfEncodeMessages(array(wfMessage('smw_iq_disabled')->inContentLanguage()->text())); } if (!is_null($wgTitle) && $wgTitle->isSpecialPage()) { global $wgOut; SMWOutputs::commitToOutputPage($wgOut); } else { SMWOutputs::commitToParser($parser); } 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(); }
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; }
/** * 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; }
/** * Returns the results in HTML, or in case of exports, a link to the * result. * * This method can only be called after execute() has been called. * * @return string of all the HTML generated */ public function getHTMLResult() { $result = ''; $res = $this->queryResult; $printer = SMWQueryProcessor::getResultPrinter($this->parameters['format'], SMWQueryProcessor::SPECIAL_PAGE); if ($res->getCount() > 0) { $queryResult = $printer->getResult($res, $this->params, SMW_OUTPUT_HTML); if (is_array($queryResult)) { $result .= $queryResult[0]; } else { $result .= $queryResult; } } else { $result = wfMsg('smw_result_noresults'); } return $result; }
/** * @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]; }
/** * @param string $format * * @return array of IParamDefinition */ protected function getFormatParameters($format) { if (array_key_exists($format, $GLOBALS['smwgResultFormats'])) { return ParamDefinition::getCleanDefinitions(SMWQueryProcessor::getResultPrinter($format)->getParamDefinitions(SMWQueryProcessor::getParameters())); } else { return array(); } }
/** * 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; }
/** * Build the format drop down * * @param array * * @return string */ protected static function getFormatSelection($params) { $result = ''; $printer = SMWQueryProcessor::getResultPrinter('broadtable', SMWQueryProcessor::SPECIAL_PAGE); $url = SpecialPage::getSafeTitleFor('Ask')->getLocalURL('showformatoptions=this.value'); foreach ($params as $param => $value) { if ($param !== 'format') { $url .= '¶ms[' . rawurlencode($param) . ']=' . rawurlencode($value); } } $result .= '<br /><span style=vertical-align:middle;">' . wfMessage('smw_ask_format_as')->text() . ' <input type="hidden" name="eq" value="yes"/>' . "\n" . Html::openElement('select', array('id' => 'formatSelector', 'name' => 'p[format]', 'data-url' => $url)) . "\n" . ' <option value="broadtable"' . ($params['format'] == 'broadtable' ? ' selected' : '') . '>' . $printer->getName() . ' (' . wfMessage('smw_ask_defaultformat')->text() . ')</option>' . "\n"; $formats = array(); foreach (array_keys($GLOBALS['smwgResultFormats']) as $format) { // Special formats "count" and "debug" currently not supported. if ($format != 'broadtable' && $format != 'count' && $format != 'debug') { $printer = SMWQueryProcessor::getResultPrinter($format, SMWQueryProcessor::SPECIAL_PAGE); $formats[$format] = $printer->getName(); } } natcasesort($formats); foreach ($formats as $format => $name) { $result .= ' <option value="' . $format . '"' . ($params['format'] == $format ? ' selected' : '') . '>' . $name . "</option>\n"; } $result .= "</select></span>\n"; return $result; }
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 ); } } }
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); }
private function getQueryResultFor($queryString) { list($query, $formattedParams) = QueryProcessor::getQueryAndParamsFromFunctionParams($queryString, SMW_OUTPUT_WIKI, QueryProcessor::INLINE_QUERY, false); return $this->getStore()->getQueryResult($query); }
/** * @param $querystring * @param array $params * @param $extraprintouts * @param $outputmode * @param $context * * @return SMWQueryResult */ protected static function getQueryResultFromQueryString( $querystring, array $params, $extraprintouts, $outputmode, $context = SMWQueryProcessor::INLINE_QUERY ) { wfProfileIn( 'SCQQueryProcessor::getQueryResultFromQueryString' ); if ( version_compare( SMW_VERSION, '1.6.1', '>' ) ) { SMWQueryProcessor::addThisPrintout( $extraprintouts, $params ); $params = self::getProcessedParams( $params, $extraprintouts, false ); } $query = self::createQuery( $querystring, $params, $context, null, $extraprintouts ); $query_result = smwfGetStore()->getQueryResult( $query ); foreach ( $query_result->getResults() as $wiki_page ) { $wiki_page->display_options = $params; } wfProfileOut( 'SCQQueryProcessor::getQueryResultFromQueryString' ); return $query_result; }
/** * Returns the definitions of all parameters supported by the specified format. * * @since 1.8 * * @param string $format * * @return array of IParamDefinition */ public static function getFormatParameters($format) { SMWParamFormat::resolveFormatAliases($format); if (array_key_exists($format, $GLOBALS['smwgResultFormats'])) { return ParamDefinition::getCleanDefinitions(SMWQueryProcessor::getResultPrinter($format)->getParamDefinitions(SMWQueryProcessor::getParameters())); } else { return array(); } }
/** * 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; }
/** * Function for handling the {{\#missingvalues }} parser function. */ public static function doMissingValues($parser, $querystring, $propertyname, $values) { $all_values = explode(',', $values); $all_values_clean = array(); foreach ($all_values as $cur_value) { // remove whitespaces $cur_value = trim($cur_value); // ignore a value if it's null if ('' != $cur_value) { $all_values_clean[] = $cur_value; } } $params = array(); $params['format'] = 'list'; $params['link'] = 'none'; $params['mainlabel'] = '-'; $extraprintouts = array(); $printmode = SMWPrintRequest::PRINT_PROP; $data = SMWPropertyValue::makeUserProperty(trim($propertyname)); $label = ''; $printout = new SMWPrintRequest($printmode, $label, $data); $extraprintouts[] = $printout; $outputmode = SMW_OUTPUT_WIKI; $result = SMWQueryProcessor::getResultFromQueryString($querystring, $params, $extraprintouts, $outputmode); $found_values = explode(', ', $result); $missing_values = array_diff($all_values_clean, $found_values); return join(', ', $missing_values); }
/** * 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; }
/** * Formats the parameter value to it's final result. * * @since 1.8 * * @param mixed $value * @param IParam $param * @param IParamDefinition[] $definitions * @param IParam[] $params * * @return mixed */ protected function formatValue($value, IParam $param, array &$definitions, array $params) { $value = parent::formatValue($value, $param, $definitions, $params); // Make sure the format value is valid. $value = self::getValidFormatName($value); // Add the formats parameters to the parameter list. $queryPrinter = SMWQueryProcessor::getResultPrinter($value); $definitions = $queryPrinter->getParamDefinitions($definitions); return $value; }