Ejemplo n.º 1
0
 /**
  * Prepare data output
  *
  * @since 1.8
  *
  * @param array $data label => value
  */
 protected function getFormatOutput(array $data)
 {
     //Init
     $dataObject = array();
     static $statNr = 0;
     $chartID = 'sparkline-' . $this->params['charttype'] . '-' . ++$statNr;
     $this->isHTML = true;
     // Prepare data array
     foreach ($data as $key => $value) {
         if ($value >= $this->params['min']) {
             $dataObject['label'][] = $key;
             $dataObject['value'][] = $value;
         }
     }
     $dataObject['charttype'] = $this->params['charttype'];
     // Encode data objects
     $requireHeadItem = array($chartID => FormatJson::encode($dataObject));
     SMWOutputs::requireHeadItem($chartID, Skin::makeVariablesScript($requireHeadItem));
     // RL module
     SMWOutputs::requireResource('ext.srf.sparkline');
     // Processing placeholder
     $processing = SRFUtils::htmlProcessingElement(false);
     // Chart/graph placeholder
     $chart = Html::rawElement('div', array('id' => $chartID, 'class' => 'container', 'style' => "display:none;"), null);
     // Beautify class selector
     $class = $this->params['class'] ? ' ' . $this->params['class'] : '';
     // Chart/graph wrappper
     return Html::rawElement('span', array('class' => 'srf-sparkline' . $class), $processing . $chart);
 }
	/**
	 * Method for handling the set_recurring_event parser function.
	 * 
	 * @since 1.5.3
	 * 
	 * @param Parser $parser
	 */
	public static function render( Parser &$parser ) {
		$params = func_get_args();
		array_shift( $params ); // We already know the $parser ...

		// Almost all of the work gets done by
		// getDatesForRecurringEvent().
		$results = self::getDatesForRecurringEvent( $params );
		if ( $results == null ) {
			return null;
		}

		list( $property_name, $all_date_strings, $unused_params ) = $results;

		// Do the actual saving of the data.
		foreach ( $all_date_strings as $date_str ) {
			SMWParseData::addProperty( $property_name, $date_str, false, $parser, true );
		}

		global $wgTitle;
		if ( !is_null( $wgTitle ) && $wgTitle->isSpecialPage() ) {
			global $wgOut;
			SMWOutputs::commitToOutputPage( $wgOut );
		}
		else {
			SMWOutputs::commitToParser( $parser );
		}	
	}
	/**
	 * This method will be called before an article is displayed or previewed.
	 * For display and preview we strip out the semantic properties and append them
	 * at the end of the article.
	 *
	 * @param Parser $parser
	 * @param string $text
	 */
	static public function onInternalParseBeforeLinks( &$parser, &$text ) {
		global $smwgStoreAnnotations, $smwgLinksInValues;

		SMWParseData::stripMagicWords( $text, $parser );

		// Store the results if enabled (we have to parse them in any case,
		// in order to clean the wiki source for further processing).
		$smwgStoreAnnotations = smwfIsSemanticsProcessed( $parser->getTitle()->getNamespace() );
		SMWParserExtensions::$mTempStoreAnnotations = true; // used for [[SMW::on]] and [[SMW:off]]

		// Process redirects, if any (it seems that there is indeed no more direct way of getting this info from MW)
		if ( $smwgStoreAnnotations ) {
			$rt = Title::newFromRedirect( $text );
			
			if ( !is_null( $rt ) ) {
				$p = new SMWDIProperty( '_REDI' );
				$di = SMWDIWikiPage::newFromTitle( $rt, '__red' );
				SMWParseData::getSMWData( $parser )->addPropertyObjectValue( $p, $di );
			}
		}

		// only used in subsequent callbacks, forgotten afterwards
		SMWParserExtensions::$mTempParser = $parser;

		// In the regexp matches below, leading ':' escapes the markup, as known for Categories.
		// Parse links to extract semantic properties.
		if ( $smwgLinksInValues ) { // More complex regexp -- lib PCRE may cause segfaults if text is long :-(
			$semanticLinkPattern = '/\[\[                 # Beginning of the link
			                        (?:([^:][^]]*):[=:])+ # Property name (or a list of those)
			                        (                     # After that:
			                          (?:[^|\[\]]         #   either normal text (without |, [ or ])
			                          |\[\[[^]]*\]\]      #   or a [[link]]
			                          |\[[^]]*\]          #   or an [external link]
			                        )*)                   # all this zero or more times
			                        (?:\|([^]]*))?        # Display text (like "text" in [[link|text]]), optional
			                        \]\]                  # End of link
			                        /xu';
			$text = preg_replace_callback( $semanticLinkPattern, array( 'SMWParserExtensions', 'parsePropertiesCallback' ), $text );
		} else { // Simpler regexps -- no segfaults found for those, but no links in values.
			$semanticLinkPattern = '/\[\[                 # Beginning of the link
			                        (?:([^:][^]]*):[=:])+ # Property name (or a list of those)
			                        ([^\[\]]*)            # content: anything but [, |, ]
			                        \]\]                  # End of link
			                        /xu';
			$text = preg_replace_callback( $semanticLinkPattern, array( 'SMWParserExtensions', 'simpleParsePropertiesCallback' ), $text );
		}

		// Add link to RDF to HTML header.
		// TODO: do escaping via Html or Xml class.
		SMWOutputs::requireHeadItem(
			'smw_rdf', '<link rel="alternate" type="application/rdf+xml" title="' .
			htmlspecialchars( $parser->getTitle()->getPrefixedText() ) . '" href="' .
			htmlspecialchars(
				SpecialPage::getTitleFor( 'ExportRDF', $parser->getTitle()->getPrefixedText() )->getLocalUrl( 'xmlmime=rdf' )
			) . "\" />"
		);

		SMWOutputs::commitToParser( $parser );
		return true; // always return true, in order not to stop MW's hook processing!
	}
 /**
  * Return serialised results in specified format.
  * Implemented by subclasses.
  */
 protected function getResultText(SMWQueryResult $res, $outputmode)
 {
     $html = '';
     $id = uniqid();
     // build an array of article IDs contained in the result set
     $objects = array();
     foreach ($res->getResults() as $key => $object) {
         $objects[] = array($object->getTitle()->getArticleId());
         $html .= $key . ': ' . $object->getSerialization() . "<br>\n";
     }
     // build an array of data about the printrequests
     $printrequests = array();
     foreach ($res->getPrintRequests() as $key => $printrequest) {
         $data = $printrequest->getData();
         if ($data instanceof SMWPropertyValue) {
             $name = $data->getDataItem()->getKey();
         } else {
             $name = null;
         }
         $printrequests[] = array($printrequest->getMode(), $printrequest->getLabel(), $name, $printrequest->getOutputFormat(), $printrequest->getParameters());
     }
     // write out results and query params into JS arrays
     // Define the srf_filtered_values array
     SMWOutputs::requireScript('srf_slideshow', Html::inlineScript('srf_slideshow = {};'));
     SMWOutputs::requireScript('srf_slideshow' . $id, Html::inlineScript('srf_slideshow["' . $id . '"] = ' . json_encode(array($objects, $this->params['template'], $this->params['delay'] * 1000, $this->params['height'], $this->params['width'], $this->params['nav controls'], $this->params['effect'], json_encode($printrequests))) . ';'));
     SMWOutputs::requireResource('ext.srf.slideshow');
     if ($this->params['nav controls']) {
         SMWOutputs::requireResource('jquery.ui.slider');
     }
     return Html::element('div', array('id' => $id, 'class' => 'srf-slideshow ' . $id . ' ' . $this->params['class']));
 }
Ejemplo n.º 5
0
 /**
  * Main entrypoint for the special page.
  *
  * @param string $p
  */
 public function execute($p)
 {
     global $wgOut, $wgRequest, $smwgQEnabled;
     $wgOut->addModules('ext.smw.style');
     $wgOut->addModules('ext.smw.ask');
     $wgOut->addModules('ext.smw.property');
     $this->setHeaders();
     if (!$smwgQEnabled) {
         $wgOut->addHTML('<br />' . wfMessage('smw_iq_disabled')->escaped());
     } else {
         if ($wgRequest->getCheck('showformatoptions')) {
             // handle Ajax action
             $format = $wgRequest->getVal('showformatoptions');
             $params = $wgRequest->getArray('params');
             $wgOut->disable();
             echo $this->showFormatOptions($format, $params);
         } else {
             $this->extractQueryParameters($p);
             $this->makeHTMLResult();
         }
     }
     $this->addExternalHelpLinkFor('smw_ask_doculink');
     SMWOutputs::commitToOutputPage($wgOut);
     // make sure locally collected output data is pushed to the output!
 }
Ejemplo n.º 6
0
 /**
  * @see SMWResultPrinter::getFormatOutput
  *
  * @since 1.8
  *
  * @param array $data label => value
  * @return string
  */
 protected function getFormatOutput(array $data)
 {
     // Object count
     static $statNr = 0;
     $d3chartID = 'd3-chart-' . ++$statNr;
     $this->isHTML = true;
     // Reorganize the raw data
     foreach ($data as $name => $value) {
         if ($value >= $this->params['min']) {
             $dataObject[] = array('label' => $name, 'value' => $value);
         }
     }
     // Ensure right conversion
     $width = strstr($this->params['width'], "%") ? $this->params['width'] : $this->params['width'] . 'px';
     // Prepare transfer objects
     $d3data = array('data' => $dataObject, 'parameters' => array('colorscheme' => $this->params['colorscheme'] ? $this->params['colorscheme'] : null, 'charttitle' => $this->params['charttitle'], 'charttext' => $this->params['charttext'], 'datalabels' => $this->params['datalabels']));
     // Encoding
     $requireHeadItem = array($d3chartID => FormatJson::encode($d3data));
     SMWOutputs::requireHeadItem($d3chartID, Skin::makeVariablesScript($requireHeadItem));
     // RL module
     $resource = 'ext.srf.d3.chart.' . $this->params['charttype'];
     SMWOutputs::requireResource($resource);
     // Chart/graph placeholder
     $chart = Html::rawElement('div', array('id' => $d3chartID, 'class' => 'container', 'style' => 'display:none;'), null);
     // Processing placeholder
     $processing = SRFUtils::htmlProcessingElement($this->isHTML);
     // Beautify class selector
     $class = $this->params['charttype'] ? '-' . $this->params['charttype'] : '';
     $class = $this->params['class'] ? $class . ' ' . $this->params['class'] : $class . ' d3-chart-common';
     // D3 wrappper
     return Html::rawElement('div', array('class' => 'srf-d3-chart' . $class, 'style' => "width:{$width}; height:{$this->params['height']}px;"), $processing . $chart);
 }
Ejemplo n.º 7
0
 /**
  * Main method for adding all additional HTML to the output stream.
  */
 protected function showList()
 {
     global $wgOut, $wgRequest;
     $this->from = $wgRequest->getVal('from', '');
     $this->until = $wgRequest->getVal('until', '');
     if ($this->initParameters()) {
         $wgOut->addHTML($this->getHtml());
         SMWOutputs::commitToOutputPage($wgOut);
     }
 }
Ejemplo n.º 8
0
 /**
  * Main method for adding all additional HTML to the output stream.
  */
 protected function showList()
 {
     global $wgOut, $wgRequest;
     wfProfileIn(__METHOD__ . ' (SMW)');
     $this->from = $wgRequest->getVal('from', '');
     $this->until = $wgRequest->getVal('until', '');
     if ($this->initParameters()) {
         $wgOut->addHTML("<br id=\"smwfootbr\"/>\n" . $this->getHtml());
         SMWOutputs::commitToOutputPage($wgOut);
     }
     wfProfileOut(__METHOD__ . ' (SMW)');
 }
 public function execute($param)
 {
     wfProfileIn('smwfDoSpecialUnusedProperties (SMW)');
     global $wgOut;
     $wgOut->setPageTitle(wfMsg('unusedproperties'));
     $rep = new SMWUnusedPropertiesPage();
     list($limit, $offset) = wfCheckLimits();
     $rep->doQuery($offset, $limit);
     // Ensure locally collected output data is pushed to the output!
     SMWOutputs::commitToOutputPage($wgOut);
     wfProfileOut('smwfDoSpecialUnusedProperties (SMW)');
 }
Ejemplo n.º 10
0
 /**
  * Method for handling the declare parser function.
  * 
  * @since 1.5.3
  * 
  * @param Parser $parser
  * @param PPFrame $frame
  * @param array $args
  */
 public static function render(Parser &$parser, PPFrame $frame, array $args)
 {
     if ($frame->isTemplate()) {
         foreach ($args as $arg) {
             if (trim($arg) !== '') {
                 $expanded = trim($frame->expand($arg));
                 $parts = explode('=', $expanded, 2);
                 if (count($parts) == 1) {
                     $propertystring = $expanded;
                     $argumentname = $expanded;
                 } else {
                     $propertystring = $parts[0];
                     $argumentname = $parts[1];
                 }
                 $property = SMWPropertyValue::makeUserProperty($propertystring);
                 $argument = $frame->getArgument($argumentname);
                 $valuestring = $frame->expand($argument);
                 if ($property->isValid()) {
                     $type = $property->getPropertyTypeID();
                     if ($type == '_wpg') {
                         $matches = array();
                         preg_match_all('/\\[\\[([^\\[\\]]*)\\]\\]/u', $valuestring, $matches);
                         $objects = $matches[1];
                         if (count($objects) == 0) {
                             if (trim($valuestring) !== '') {
                                 SMWParseData::addProperty($propertystring, $valuestring, false, $parser, true);
                             }
                         } else {
                             foreach ($objects as $object) {
                                 SMWParseData::addProperty($propertystring, $object, false, $parser, true);
                             }
                         }
                     } elseif (trim($valuestring) !== '') {
                         SMWParseData::addProperty($propertystring, $valuestring, false, $parser, true);
                     }
                     // $value = SMWDataValueFactory::newPropertyObjectValue( $property->getDataItem(), $valuestring );
                     // if (!$value->isValid()) continue;
                 }
             }
         }
     } else {
         // @todo Save as metadata
     }
     global $wgTitle;
     if (!is_null($wgTitle) && $wgTitle->isSpecialPage()) {
         global $wgOut;
         SMWOutputs::commitToOutputPage($wgOut);
     } else {
         SMWOutputs::commitToParser($parser);
     }
     return '';
 }
Ejemplo n.º 11
0
 public function getResultText(SMWQueryResult $results, $outputmode)
 {
     global $wgUser, $wgParser;
     $ig = new ImageGallery();
     $ig->setShowBytes(false);
     $ig->setShowFilename(false);
     $ig->setParser($wgParser);
     $ig->setCaption($this->mIntro);
     // set caption to IQ header
     if ($this->params['galleryformat'] == 'carousel') {
         static $carouselNr = 0;
         // Set attributes for jcarousel
         $dataAttribs = array('wrap' => 'both', 'vertical' => 'false', 'rtl' => 'false');
         // Use perrow parameter to determine the scroll sequence.
         if (empty($this->params['perrow'])) {
             $dataAttribs['scroll'] = 1;
             // default 1
         } else {
             $dataAttribs['scroll'] = $this->params['perrow'];
             $dataAttribs['visible'] = $this->params['perrow'];
         }
         $attribs = array('id' => 'carousel' . ++$carouselNr, 'class' => 'jcarousel jcarousel-skin-smw', 'style' => 'display:none;');
         foreach ($dataAttribs as $name => $value) {
             $attribs['data-' . $name] = $value;
         }
         $ig->setAttributes($attribs);
         // Load javascript module
         SMWOutputs::requireResource('ext.srf.jcarousel');
     }
     // In case galleryformat = carousel, perrow should not be set
     if ($this->params['perrow'] !== '' && $this->params['galleryformat'] !== 'carousel') {
         $ig->setPerRow($this->params['perrow']);
     }
     if ($this->params['widths'] !== '') {
         $ig->setWidths($this->params['widths']);
     }
     if ($this->params['heights'] !== '') {
         $ig->setHeights($this->params['heights']);
     }
     $printReqLabels = array();
     foreach ($results->getPrintRequests() as $printReq) {
         $printReqLabels[] = $printReq->getLabel();
     }
     if ($this->params['imageproperty'] !== '' && in_array($this->params['imageproperty'], $printReqLabels)) {
         $this->addImageProperties($results, $ig, $this->params['imageproperty'], $this->params['captionproperty']);
     } else {
         $this->addImagePages($results, $ig);
     }
     return array($ig->toHTML(), 'nowiki' => true, 'isHTML' => true);
 }
Ejemplo n.º 12
0
 /**
  * Renders and returns the output.
  * @see ParserHook::render
  * 
  * @since 1.7
  * 
  * @param array $parameters
  * 
  * @return string
  */
 public function render(array $parameters)
 {
     /**
      * Non-escaping is safe bacause a user's message is passed through parser, which will
      * handle unsafe HTM elements.
      */
     $result = smwfEncodeMessages(array($parameters['message']), $parameters['icon'], ' <!--br-->', false);
     if (!is_null($this->parser->getTitle()) && $this->parser->getTitle()->isSpecialPage()) {
         global $wgOut;
         SMWOutputs::commitToOutputPage($wgOut);
     } else {
         SMWOutputs::commitToParser($this->parser);
     }
     return $result;
 }
 /**
  * @see StringValueFormatter::doFormatFinalOutputFor
  */
 protected function doFormatFinalOutputFor($type, $linker)
 {
     $abbreviate = $type === self::WIKI_LONG || $type === self::HTML_LONG;
     $text = $this->dataValue->getDataItem()->getString();
     // Escape and wrap values of type Code. The result is escaped to be
     // HTML-safe (it will also work in wiki context). The result will
     // contain mark-up that must not be escaped again.
     Outputs::requireResource('ext.smw.style');
     // This disables all active wiki and HTML markup:
     $result = str_replace(array('<', '>', ' ', '[', '{', '=', "'", ':', "\n"), array('&lt;', '&gt;', '&#160;', '&#x005B;', '&#x007B;', '&#x003D;', '&#x0027;', '&#58;', "<br />"), $text);
     if ($abbreviate) {
         $result = "<div style=\"height:5em; overflow:auto;\">{$result}</div>";
     }
     return "<div class=\"smwpre\">{$result}</div>";
 }
Ejemplo n.º 14
0
 public function execute($param)
 {
     global $wgOut;
     $params = SMWInfolink::decodeParameters($param, false);
     $typeLabel = reset($params);
     if ($typeLabel == false) {
         $wgOut->setPageTitle(wfMessage('types')->text());
         $html = $this->getTypesList();
     } else {
         $typeName = str_replace('_', ' ', $typeLabel);
         $wgOut->setPageTitle($typeName);
         // Maybe add a better message for this
         $html = $this->getTypeProperties($typeLabel);
     }
     $wgOut->addHTML($html);
     SMWOutputs::commitToOutputPage($wgOut);
 }
 /**
  * @see SMWResultPrinter::getResultText
  *
  * @param SMWQueryResult $res
  * @param $outputMode
  *
  * @return string
  */
 protected function getResultText(SMWQueryResult $res, $outputMode)
 {
     // Initialize
     static $statNr = 0;
     // Get results from SMWListResultPrinter
     $result = parent::getResultText($res, $outputMode);
     // Count widgets
     $widgetID = 'pagewidget-' . ++$statNr;
     // Container items
     $result = Html::rawElement('div', array('id' => $widgetID, 'class' => 'container', 'data-embedonly' => $this->params['embedonly'], 'style' => 'display:none;'), $result);
     // Placeholder
     $processing = SRFUtils::htmlProcessingElement($this->isHTML);
     // RL module
     SMWOutputs::requireResource('ext.srf.pagewidget.carousel');
     // Beautify class selector
     $class = $this->params['class'] ? ' ' . $this->params['class'] : '';
     // Wrap results
     return Html::rawElement('div', array('class' => 'srf-pagewidget' . $class), $processing . $result);
 }
Ejemplo n.º 16
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;
 }
 public static function embedWiki($input, $argv)
 {
     //		if(!ETParserFunctions::$inlineParser) {
     //			global $wgParserConf;
     //			ETParserFunctions::$inlineParser = wfCreateObject( $wgParserConf['class'], array( $wgParserConf ) );
     //		}
     global $wgParser;
     if ($wgParser->getTitle() instanceof Title && $wgParser->getOptions() instanceof ParserOptions) {
         $result = $wgParser->recursiveTagParse($input);
     } else {
         global $wgTitle;
         $popt = new ParserOptions();
         $popt->setEditSection(false);
         $pout = $wgParser->parse($input . '__NOTOC__', $wgTitle, $popt);
         // / NOTE: as of MW 1.14SVN, there is apparently no better way to hide the TOC
         SMWOutputs::requireFromParserOutput($pout);
         $result = $pout->getText();
     }
     return $result;
 }
Ejemplo n.º 18
0
 /**
  * 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;
 }
 /**
  * @see SMWResultPrinter::getResultText
  *
  * @param SMWQueryResult $res
  * @param array $params
  * @param $outputmode
  *
  * @return string
  */
 protected function getResultText(SMWQueryResult $res, $outputmode)
 {
     // Initialize
     static $statNr = 0;
     //$this->isHTML = true;
     // Set output type for the parent
     $this->mFormat = $this->params['listtype'] == 'ordered' || $this->params['listtype'] == 'ol' ? 'ol' : 'ul';
     // Get results from SMWListResultPrinter
     $result = parent::getResultText($res, $outputmode);
     // Count widgets
     $listwidgetID = 'listwidget-' . ++$statNr;
     // OL/UL container items
     $result = Html::rawElement('div', array('id' => $listwidgetID, 'class' => 'container', 'style' => 'display:none; position: relative; margin-bottom:5px; margin-top:5px;'), $result);
     // Placeholder
     $processing = SRFUtils::htmlProcessingElement($this->isHTML);
     // RL module
     $resource = 'ext.srf.listwidget.' . $this->params['widget'];
     SMWOutputs::requireResource($resource);
     // Wrap results
     return Html::rawElement('div', array('class' => 'srf-listwidget ' . htmlspecialchars($this->params['class']), 'data-listtype' => $this->mFormat, 'data-widget' => $this->params['widget'], 'data-pageitems' => $this->params['pageitems']), $processing . $result);
 }
Ejemplo n.º 20
0
 /**
  * Return serialised results in specified format
  *
  * @param SMWQueryResult $results
  * @param $outputmode
  *
  * @return string
  */
 public function getResultText(SMWQueryResult $results, $outputmode)
 {
     // Check output conditions
     if ($this->params['widget'] == 'sphere' && $this->params['link'] !== 'all' && $this->params['template'] === '') {
         return $results->addErrors(array(wfMessage('srf-error-option-link-all', 'sphere')->inContentLanguage()->text()));
     }
     // Template support
     $this->hasTemplates = $this->params['template'] !== '';
     // Prioritize HTML setting
     $this->isHTML = $this->params['widget'] !== '';
     $this->isHTML = $this->params['template'] === '';
     $outputmode = SMW_OUTPUT_HTML;
     // Sphere widget
     if ($this->params['widget'] === 'sphere') {
         SMWOutputs::requireResource('ext.srf.tagcloud.sphere');
     }
     // Wordcloud widget
     if ($this->params['widget'] === 'wordcloud') {
         SMWOutputs::requireResource('ext.srf.tagcloud.wordcloud');
     }
     return $this->getTagCloud($this->getTagSizes($this->getTags($results, $outputmode)));
 }
Ejemplo n.º 21
0
 /**
  * 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;
 }
Ejemplo n.º 22
0
 /**
  * Main entrypoint for the special page.
  *
  * @param string $p
  */
 public function execute($p)
 {
     global $wgOut, $wgRequest, $smwgQEnabled;
     $this->setHeaders();
     wfProfileIn('doSpecialAsk (SMW)');
     if (!$smwgQEnabled) {
         $wgOut->addHTML('<br />' . wfMessage('smw_iq_disabled')->text());
     } else {
         if ($wgRequest->getCheck('showformatoptions')) {
             // handle Ajax action
             $format = $wgRequest->getVal('showformatoptions');
             $params = $wgRequest->getArray('params');
             $wgOut->disable();
             echo $this->showFormatOptions($format, $params);
         } else {
             $this->extractQueryParameters($p);
             $this->makeHTMLResult();
         }
     }
     SMWOutputs::commitToOutputPage($wgOut);
     // make sure locally collected output data is pushed to the output!
     wfProfileOut('doSpecialAsk (SMW)');
 }
 /**
  * Creates the HTML for the query form for this special page.
  *
  * @return string  HTML for the query form
  */
 private function queryForm()
 {
     SMWOutputs::requireResource('ext.smw.property');
     $spectitle = SpecialPage::getTitleFor('SearchByProperty');
     $html = '<form name="searchbyproperty" action="' . htmlspecialchars($spectitle->getLocalURL()) . '" method="get">' . "\n" . '<input type="hidden" name="title" value="' . $spectitle->getPrefixedText() . '"/>';
     $html .= wfMessage('smw_sbv_property')->text() . ' <input type="text" id="property_box" name="property" value="' . htmlspecialchars($this->propertystring) . '" />' . "&#160;&#160;&#160;\n";
     $html .= wfMessage('smw_sbv_value')->text() . ' <input type="text" name="value" value="' . htmlspecialchars($this->valuestring) . '" />' . "\n";
     $html .= '<input type="submit" value="' . wfMessage('smw_sbv_submit')->text() . "\"/>\n</form>\n";
     return $html;
 }
Ejemplo n.º 24
0
 public function execute($query)
 {
     global $wgRequest, $wgOut;
     $linker = smwfGetLinker();
     $this->setHeaders();
     // Get parameters
     $pagename = $wgRequest->getVal('from');
     $propname = $wgRequest->getVal('type');
     $limit = $wgRequest->getVal('limit');
     $offset = $wgRequest->getVal('offset');
     if ($limit === '') {
         $limit = 20;
     }
     if ($offset === '') {
         $offset = 0;
     }
     if ($propname === '') {
         // No GET parameters? Try the URL:
         $queryparts = explode('::', $query);
         $propname = $query;
         if (count($queryparts) > 1) {
             $pagename = $queryparts[0];
             $propname = implode('::', array_slice($queryparts, 1));
         }
     }
     $subject = SMWDataValueFactory::newTypeIDValue('_wpg', $pagename);
     $pagename = $subject->isValid() ? $subject->getPrefixedText() : '';
     $property = SMWPropertyValue::makeUserProperty($propname);
     $propname = $property->isValid() ? $property->getWikiValue() : '';
     // Produce output
     $html = '';
     if ($propname === '') {
         // no property given, show a message
         $html .= wfMsg('smw_pp_docu') . "\n";
     } else {
         // property given, find and display results
         // FIXME: very ugly, needs i18n
         $wgOut->setPagetitle(($pagename !== '' ? $pagename . ' ' : '') . $property->getWikiValue());
         // get results (get one more, to see if we have to add a link to more)
         $options = new SMWRequestOptions();
         $options->limit = $limit + 1;
         $options->offset = $offset;
         $options->sort = true;
         $results = smwfGetStore()->getPropertyValues($pagename !== '' ? $subject->getDataItem() : null, $property->getDataItem(), $options);
         // prepare navigation bar if needed
         if ($offset > 0 || count($results) > $limit) {
             if ($offset > 0) {
                 $navigation = Html::element('a', array('href' => $this->getTitle()->getLocalURL(array('offset' => max(0, $offset - $limit), 'limit' => $limit, 'type' => $propname, 'from' => $pagename))), wfMsg('smw_result_prev'));
             } else {
                 $navigation = wfMsg('smw_result_prev');
             }
             $navigation .= '&#160;&#160;&#160;&#160; <b>' . wfMsg('smw_result_results') . ' ' . ($offset + 1) . '– ' . ($offset + min(count($results), $limit)) . '</b>&#160;&#160;&#160;&#160;';
             if (count($results) == $limit + 1) {
                 $navigation = Html::element('a', array('href' => $this->getTitle()->getLocalURL(array('offset' => $offset + $limit, 'limit' => $limit, 'type' => $propname, 'from' => $pagename))), wfMsg('smw_result_next'));
             } else {
                 $navigation .= wfMsg('smw_result_next');
             }
         } else {
             $navigation = '';
         }
         // display results
         $html .= '<br />' . $navigation;
         if (count($results) == 0) {
             $html .= wfMsg('smw_result_noresults');
         } else {
             $html .= "<ul>\n";
             $count = $limit + 1;
             foreach ($results as $di) {
                 $count--;
                 if ($count < 1) {
                     continue;
                 }
                 $dv = SMWDataValueFactory::newDataItemValue($di, $property->getDataItem());
                 $html .= '<li>' . $dv->getLongHTMLText($linker);
                 // do not show infolinks, the magnifier "+" is ambiguous with the browsing '+' for '_wpg' (see below)
                 if ($property->getDataItem()->findPropertyTypeID() == '_wpg') {
                     $browselink = SMWInfolink::newBrowsingLink('+', $dv->getLongWikiText());
                     $html .= ' &#160;' . $browselink->getHTML($linker);
                 }
                 $html .= "</li> \n";
             }
             $html .= "</ul>\n";
         }
         $html .= $navigation;
     }
     // Display query form
     $spectitle = $this->getTitle();
     $html .= '<p>&#160;</p>';
     $html .= '<form name="pageproperty" action="' . htmlspecialchars($spectitle->getLocalURL()) . '" method="get">' . "\n" . '<input type="hidden" name="title" value="' . $spectitle->getPrefixedText() . '"/>';
     $html .= wfMsg('smw_pp_from') . ' <input type="text" name="from" value="' . htmlspecialchars($pagename) . '" />' . "&#160;&#160;&#160;\n";
     $html .= wfMsg('smw_pp_type') . ' <input type="text" name="type" value="' . htmlspecialchars($propname) . '" />' . "\n";
     $html .= '<input type="submit" value="' . wfMsg('smw_pp_submit') . "\"/>\n</form>\n";
     $wgOut->addHTML($html);
     SMWOutputs::commitToOutputPage($wgOut);
     // make sure locally collected output data is pushed to the output!
 }
Ejemplo n.º 25
0
 /**
  * @see SMWDataValue::getLongWikiText
  * 
  * @since 0.6
  */
 public function getLongWikiText($linked = null)
 {
     if ($this->isValid()) {
         SMWOutputs::requireHeadItem(SMW_HEADER_TOOLTIP);
         // TODO: fix lang keys so they include the space and coordinates.
         $coordinateSet = $this->m_dataitem->getCoordinateSet();
         $text = $this->getFormattedCoord($this->m_dataitem);
         $lines = array(wfMessage('semanticmaps-latitude', $coordinateSet['lat'])->inContentLanguage()->escaped(), wfMessage('semanticmaps-longitude', $coordinateSet['lon'])->inContentLanguage()->escaped());
         if (array_key_exists('alt', $coordinateSet)) {
             $lines[] = wfMessage('semanticmaps-altitude', $coordinateSet['alt'])->inContentLanguage()->escaped();
         }
         return '<span class="smwttinline">' . htmlspecialchars($text) . '<span class="smwttcontent">' . implode('<br />', $lines) . '</span></span>';
     } else {
         return $this->getErrorText();
     }
 }
    /**
     * Creates the JS needed for adding auto-completion to queryForm(). Uses the
     * MW API to fetch suggestions.
     *
     */
    protected static function addAutoComplete()
    {
        SMWOutputs::requireResource('jquery.ui.autocomplete');
        $javascript_autocomplete_text = <<<END
<script type="text/javascript">
jQuery(document).ready(function(){
\tjQuery("#property_box").autocomplete({
\t\tminLength: 2,
\t\tsource: function(request, response) {
\t\t\tjQuery.getJSON(wgScriptPath+'/api.php?action=opensearch&limit=10&namespace='+wgNamespaceIds['property']+'&format=jsonfm&search='+request.term, function(data){
\t\t\t\t//remove the word 'Property:' from returned data
\t\t\t\tfor(i=0;i<data[1].length;i++) data[1][i]=data[1][i].substr(data[1][i].indexOf(':')+1);
\t\t\t\tresponse(data[1]);
\t\t\t});
\t\t}
\t});
});
</script>

END;
        SMWOutputs::requireScript('smwAutocompleteSpecialSearchByProperty', $javascript_autocomplete_text);
    }
	/**
	 * Creates the JS needed for adding auto-completion to queryForm(). Uses the
	 * MW API to fetch suggestions.
	 */
	private static function addAutoComplete() {
		SMWOutputs::requireResource( 'jquery.ui.autocomplete' );

		$javascript_autocomplete_text = <<<END
<script type="text/javascript">
jQuery(document).ready(function(){
	jQuery("#page_input_box").autocomplete({
		minLength: 3,
		source: function(request, response) {
			jQuery.getJSON(wgScriptPath+'/api.php?action=opensearch&limit=10&namespace=0&format=jsonfm&search='+request.term, function(data){
				response(data[1]);
			});
		}
	});
});
</script>

END;

		SMWOutputs::requireScript( 'smwAutocompleteSpecialBrowse', $javascript_autocomplete_text );
	}
Ejemplo n.º 28
0
 /**
  * Continuation of getResult that only gets executed for non file outputs.
  *
  * @since 1.6
  *
  * @param string $result
  * @param SMWQueryResult $results
  * @param integer $outputmode
  *
  * @return string
  */
 protected function handleNonFileResult($result, SMWQueryResult $results, $outputmode)
 {
     /**
      * @var \Parser $wgParser
      */
     global $wgParser, $smwgEnabledResultFormatsWithRecursiveAnnotationSupport;
     $result .= $this->getErrorString($results);
     // append errors
     // Apply intro parameter
     if ($this->mIntro && $results->getCount() > 0) {
         if ($outputmode == SMW_OUTPUT_HTML && $wgParser->getTitle() instanceof Title) {
             global $wgParser;
             $result = $wgParser->recursiveTagParse($this->mIntro) . $result;
         } else {
             $result = $this->mIntro . $result;
         }
     }
     // Apply outro parameter
     if ($this->mOutro && $results->getCount() > 0) {
         if ($outputmode == SMW_OUTPUT_HTML && $wgParser->getTitle() instanceof Title) {
             $result = $result . $wgParser->recursiveTagParse($this->mOutro);
         } else {
             $result = $result . $this->mOutro;
         }
     }
     // Preprocess embedded templates if needed
     if (!$this->isHTML && $this->hasTemplates) {
         if ($wgParser->getTitle() instanceof Title && $wgParser->getOptions() instanceof ParserOptions) {
             self::$mRecursionDepth++;
             if (self::$mRecursionDepth <= self::$maxRecursionDepth) {
                 // restrict recursion
                 $result = in_array($this->params['format'], $smwgEnabledResultFormatsWithRecursiveAnnotationSupport) ? $wgParser->recursivePreprocess($result) : '[[SMW::off]]' . $wgParser->replaceVariables($result) . '[[SMW::on]]';
             } else {
                 $result = '';
                 /// TODO: explain problem (too much recursive parses)
             }
             self::$mRecursionDepth--;
         } else {
             // not during parsing, no preprocessing needed, still protect the result
             $result = in_array($this->params['format'], $smwgEnabledResultFormatsWithRecursiveAnnotationSupport) ? $result : '[[SMW::off]]' . $result . '[[SMW::on]]';
         }
     }
     if ($this->isHTML && $outputmode == SMW_OUTPUT_WIKI) {
         $result = array($result, 'isHTML' => true);
     } elseif (!$this->isHTML && $outputmode == SMW_OUTPUT_HTML) {
         self::$mRecursionDepth++;
         // check whether we are in an existing parse, or if we should start a new parse for $wgTitle
         if (self::$mRecursionDepth <= self::$maxRecursionDepth) {
             // retrict recursion
             if ($wgParser->getTitle() instanceof Title && $wgParser->getOptions() instanceof ParserOptions) {
                 $result = $wgParser->recursiveTagParse($result);
             } else {
                 global $wgTitle;
                 $popt = new ParserOptions();
                 $popt->setEditSection(false);
                 $pout = $wgParser->parse($result . '__NOTOC__', $wgTitle, $popt);
                 /// NOTE: as of MW 1.14SVN, there is apparently no better way to hide the TOC
                 \SMWOutputs::requireFromParserOutput($pout);
                 $result = $pout->getText();
             }
         } else {
             $result = '';
             /// TODO: explain problem (too much recursive parses)
         }
         self::$mRecursionDepth--;
     }
     return $result;
 }
Ejemplo n.º 29
0
/**
 * Provide a consistent interface for context hightlighting.
 *
 * Escaping should be dealt with before calling this function to ensure proper
 * handling of html encoded strings
 *
 * @var options
 * context = described as either inline or persitent
 * title   = a text or null
 * class   = assigned class which will control if an icon is displayed or not
 * type    = identifies the entity type
 * content = ...
 *
 * @since 1.8
 *
 * @param array options
 *
 * @return string
 */
function smwfContextHighlighter(array $options)
{
    // Load RL module
    SMWOutputs::requireResource('ext.smw.tooltips');
    // Tooltip
    return Html::rawElement('span', array('class' => $options['context'] === 'inline' ? 'smwttinline' : 'smwttpersist', 'data-type' => $options['type'], 'data-context' => $options['context']), Html::rawElement('span', array('class' => $options['class']), $options['title']) . Html::rawElement('span', array('class' => 'smwttcontent'), $options['content']));
}
Ejemplo n.º 30
0
/**
 * Formats an array of message strings so that it appears as a tooltip.
 * $icon should be one of: 'warning' (default), 'info'.
 *
 * @param array $messages
 * @param string $icon Acts like an enum. Callers must ensure safety, since this value is used directly in the output.
 * @param string $seperator
 * @param boolean $escape Should the messages be escaped or not (ie when they already are)
 *
 * @return string
 */
function smwfEncodeMessages(array $messages, $icon = 'warning', $seperator = ' <!--br-->', $escape = true)
{
    if (count($messages) > 0) {
        SMWOutputs::requireResource('ext.smw.tooltips');
        if ($escape) {
            $messages = array_map('htmlspecialchars', $messages);
        }
        if (count($messages) == 1) {
            $errorList = $messages[0];
        } else {
            foreach ($messages as &$message) {
                $message = '<li>' . $message . '</li>';
            }
            $errorList = '<ul>' . implode($seperator, $messages) . '</ul>';
        }
        return '<span class="smwttpersist">' . '<span class="smwtticon">' . htmlspecialchars($icon) . '.png</span>' . '<span class="smwttcontent">' . $errorList . '</span>' . '</span>';
    } else {
        return '';
    }
}