コード例 #1
0
ファイル: SMW_DV_Property.php プロジェクト: whysasse/kmwiki
 /**
  * Return a wiki page value that can be used for displaying this
  * property, or null if no such wiki page exists (for predefined
  * properties without any label).
  * @return SMWWikiPageValue or null
  */
 public function getWikiPageValue()
 {
     if (!isset($this->m_wikipage)) {
         $diWikiPage = $this->m_dataitem->getDiWikiPage();
         if (!is_null($diWikiPage)) {
             $this->m_wikipage = \SMW\DataValueFactory::getInstance()->newDataItemValue($diWikiPage, null, $this->m_caption);
             $this->m_wikipage->setOutputFormat($this->m_outformat);
             $this->addError($this->m_wikipage->getErrors());
         } else {
             // should rarely happen ($value is only changed if the input $value really was a label for a predefined prop)
             $this->m_wikipage = null;
         }
     }
     return $this->m_wikipage;
 }
コード例 #2
0
 public function storeQueryMetadata($title, $query)
 {
     global $wgParser;
     // initialize a new semdata object and append it to parser output if this was not yet done.
     // the semdata object will then be stored to the db by smw at the end of the parse process
     if (!isset($wgParser->getOutput()->mSMWData)) {
         $wgParser->getOutput()->mSMWData = new SMWSemanticData(SMWWikiPageValue::makePageFromTitle($title));
     }
     $semanticData = $wgParser->getOutput()->mSMWData;
     $propertyValue = SMWPropertyValue::makeProperty('___QRC_UQC');
     $dataValue = SMWDataValueFactory::newTypeIDValue('_qcm');
     $dataValue->setQueryId($this->getQueryId($query));
     $dataValue->setQueryString($query->getQueryString());
     if ($query->getLimit()) {
         $dataValue->setQueryLimit($query->getLimit());
     }
     if ($query->getOffset()) {
         $dataValue->setQueryOffset($query->getOffset());
     }
     if ($query instanceof SMWSPARQLQuery) {
         $prProperties = $this->getPrintRequestsProperties($query->getExtraPrintouts());
         $dataValue->setExtraPropertyPrintouts(implode(';', array_keys($prProperties)));
         $dataValue->setExtraCategoryPrintouts($this->isCategoryRequestedInPrintRequests($query->getExtraPrintouts()));
         $dataValue->setIsSPQRQLQuery(true);
     } else {
         $dataValue->setIsSPQRQLQuery(false);
     }
     $properties = array();
     $categories = array();
     if ($query instanceof SMWSPARQLQuery) {
         list($properties, $categories) = $this->getSPARQLQueryParts($query);
     } else {
         if ($query instanceof SMWQuery) {
             list($properties, $categories) = $this->getQueryParts($query->getDescription());
         }
     }
     foreach ($properties as $p => $dontCare) {
         $dataValue->addPropertyDependency($p);
     }
     foreach ($categories as $c => $dontCare) {
         $dataValue->addCategoryDependency($c);
     }
     $semanticData->addPropertyObjectValue($propertyValue, $dataValue);
     $wgParser->getOutput()->mSMWData = $semanticData;
 }
コード例 #3
0
 /**
  * Return a wiki page value that can be used for displaying this
  * property, or null if no such wiki page exists (for predefined
  * properties without any label).
  * @return SMWWikiPageValue or null
  */
 public function getWikiPageValue()
 {
     if (isset($this->m_wikipage)) {
         return $this->m_wikipage;
     }
     $diWikiPage = $this->m_dataitem->getCanonicalDiWikiPage();
     if ($diWikiPage !== null) {
         $this->m_wikipage = DataValueFactory::getInstance()->newDataValueByItem($diWikiPage, null, $this->m_caption);
         $this->m_wikipage->setOutputFormat($this->m_outformat);
         $this->m_wikipage->setLinkAttributes($this->linkAttributes);
         $this->m_wikipage->setOptions($this->getOptions());
         $this->addError($this->m_wikipage->getErrors());
     } else {
         // should rarely happen ($value is only changed if the input $value really was a label for a predefined prop)
         $this->m_wikipage = null;
     }
     return $this->m_wikipage;
 }
コード例 #4
0
 /**
  * Return a wiki page value that can be used for displaying this
  * property, or null if no such wiki page exists (for predefined
  * properties without any label).
  * @return SMWWikiPageValue or null
  */
 public function getWikiPageValue()
 {
     if (!isset($this->m_wikipage)) {
         $diWikiPage = $this->m_dataitem->getDiWikiPage();
         // A page representation for an inverse property is not possible
         // therefore construct its non-inverse representation (label/caption
         // remains and will show with an inverse indicator)
         if ($diWikiPage === null && $this->m_dataitem->isInverse()) {
             $property = new SMWDIProperty($this->m_dataitem->getKey());
             $diWikiPage = $property->getDiWikiPage();
         }
         if ($diWikiPage !== null) {
             $this->m_wikipage = \SMW\DataValueFactory::getInstance()->newDataItemValue($diWikiPage, null, $this->m_caption);
             $this->m_wikipage->setOutputFormat($this->m_outformat);
             $this->addError($this->m_wikipage->getErrors());
         } else {
             // should rarely happen ($value is only changed if the input $value really was a label for a predefined prop)
             $this->m_wikipage = null;
         }
     }
     return $this->m_wikipage;
 }
コード例 #5
0
ファイル: SM_QueryHandler.php プロジェクト: Tjorriemorrie/app
 /**
  * Handles a SMWWikiPageValue subject value.
  * Gets the plain text title and creates the HTML text with headers and the like.
  *
  * @since 1.0
  *
  * @param SMWWikiPageValue $object
  *
  * @return array with title and text
  */
 protected function handleResultSubject(SMWWikiPageValue $object)
 {
     $title = $object->getLongText($this->outputmode, null);
     $text = '';
     if ($this->showSubject) {
         if (!$this->titleLinkSeparate && $this->linkAbsolute) {
             $text = Html::element('a', array('href' => $object->getTitle()->getFullUrl()), $object->getTitle()->getText());
         } else {
             $text = $object->getLongHTMLText(smwfGetLinker());
         }
         if ($this->boldSubject) {
             $text = '<b>' . $text . '</b>';
         }
         if ($this->titleLinkSeparate) {
             $txt = $object->getTitle()->getText();
             if ($this->pageLinkText !== '') {
                 $txt = str_replace('$1', $txt, $this->pageLinkText);
             }
             $text .= Html::element('a', array('href' => $object->getTitle()->getFullUrl()), $txt);
         }
     }
     return array($title, $text);
 }
コード例 #6
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;
         }
     }
 }
コード例 #7
0
ファイル: SMW_SpecialAsk.php プロジェクト: Tjorriemorrie/app
 /**
  * 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);
     }
 }
コード例 #8
0
 /**
  * Delete all semantic data stored for the given subject. Used for update
  * purposes.
  */
 protected function deleteSemanticData(SMWWikiPageValue $subject)
 {
     $db = wfGetDB(DB_MASTER);
     $id = $subject->getTitle()->getArticleID();
     if ($id == 0) {
         return;
     }
     // no data can be deleted (and hopefully no data exists)
     foreach (array('smwsimple_data', 'smwsimple_special') as $tablename) {
         $db->delete($tablename, array('pageid' => $id), 'SMW::deleteSemanticData');
     }
     wfRunHooks('smwDeleteSemanticData', array($subject));
 }
コード例 #9
0
ファイル: utils.php プロジェクト: hala54/DSMW
    /**
     * Used to get properties (and/or) categories (and/or) templates (and/or)
     * linked with the given page(s)
     *
     * @param <String or array> $pages pagename
     * @param <bool> $properties True if you want to get the properties pages
     * @param <bool> $categories True if you want to get the categories pages
     * @param <bool> $templates True if you want to get the templates pages
     * @param <bool> $pagelinks True if you want to get the link pages
     * @return <array> $result An array of pages (cat, prop, templ or articles)
     */
    static function getDependencies($pages, $properties = true, $categories = false, $templates = false, $pagelinks = false)
    {
        $result = array();
        if (is_string($pages)) {
            $pages = array($pages);
        } elseif (!is_string($pages) && !is_array($pages)) {
            throw new MWException(__METHOD__ . ': $pages parameter is neither an
 array nor a string');
        }
        foreach ($pages as $page) {
            if ($properties) {
                // get the properties
                $title = Title::newFromText($page);
                $dbkey = $title->getDBkey();
                $namespace = $title->getNamespace();
                $value = SMWWikiPageValue::makePage($dbkey, $namespace);
                $data = smwfGetStore()->getSemanticData($value, false);
                // data instance of SMWSemanticData
                $props = $data->getProperties();
                foreach ($props as $property) {
                    if ($property->isUserDefined()) {
                        // user defined property
                        $property->setCaption(preg_replace('/[ ]/u', '&nbsp;', $property->getWikiValue(), 2));
                        if ($property->getWikiPageValue() != null) {
                            $obj = $property->getWikiPageValue();
                            $text = $obj->getPrefixedText();
                            $result[] = $text;
                        }
                    }
                }
            }
            if ($categories) {
                // get the categories
                $tables = array();
                $where = array();
                $fields = array('cl_from', 'cl_to');
                $options = array();
                $join_conds = array();
                $tables[] = 'categorylinks';
                $db = wfGetDB(DB_SLAVE);
                $pageid = $db->selectField('page', 'page_id', array('page_title' => $page));
                $where['cl_from'] = $pageid;
                $options['USE INDEX'] = array('categorylinks' => 'cl_from');
                $options['ORDER BY'] = 'cl_to';
                $res = $db->select($tables, $fields, $where, __METHOD__, $options, $join_conds);
                while ($row = $db->fetchObject($res)) {
                    $title = Title::makeTitle(NS_CATEGORY, $row->cl_to);
                    $pageName = $title->getPrefixedDBkey();
                    $result[] = $pageName;
                }
                $db->freeResult($res);
            }
            //end if categories
            if ($templates) {
                // get the templates
                $tables = array('templatelinks');
                $where = array();
                $options = array();
                $join_conds = array();
                $prefix = 'tl';
                $fields = array($prefix . '_from AS pl_from', $prefix . '_namespace AS pl_namespace', $prefix . '_title AS pl_title');
                $db = wfGetDB(DB_SLAVE);
                $pageid = $db->selectField('page', 'page_id', array('page_title' => $page));
                $where[$prefix . '_from'] = $pageid;
                //$this->addWhereFld($this->prefix . '_namespace', $params['namespace']);
                $options['ORDER BY'] = "{$prefix}_title";
                $options['USE INDEX'] = "{$prefix}_from";
                //$options['LIMIT'] = $params['limit'] + 1;
                $res = $db->select($tables, $fields, $where, __METHOD__, $options, $join_conds);
                while ($row = $db->fetchObject($res)) {
                    $title = Title::makeTitle($row->pl_namespace, $row->pl_title);
                    $pageName = $title->getPrefixedDBkey();
                    $result[] = $pageName;
                }
                $db->freeResult($res);
            }
            //end if templates
            if ($pagelinks) {
                // get the templates
                $tables = array('pagelinks');
                $where = array();
                $options = array();
                $join_conds = array();
                $prefix = 'pl';
                $fields = array($prefix . '_from AS pl_from', $prefix . '_namespace AS pl_namespace', $prefix . '_title AS pl_title');
                $db = wfGetDB(DB_SLAVE);
                $pageid = $db->selectField('page', 'page_id', array('page_title' => $page));
                $where[$prefix . '_from'] = $pageid;
                //$this->addWhereFld($this->prefix . '_namespace', $params['namespace']);
                $options['ORDER BY'] = "{$prefix}_title";
                $options['USE INDEX'] = "{$prefix}_from";
                //$options['LIMIT'] = $params['limit'] + 1;
                $res = $db->select($tables, $fields, $where, __METHOD__, $options, $join_conds);
                while ($row = $db->fetchObject($res)) {
                    $title = Title::makeTitle($row->pl_namespace, $row->pl_title);
                    $pageName = $title->getPrefixedDBkey();
                    $result[] = $pageName;
                }
                $db->freeResult($res);
            }
            //end if $pagelinks
        }
        //end foreach
        return $result;
    }
コード例 #10
0
	/**
	 * 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;
		}
	}
コード例 #11
0
ファイル: RDFIO_SMWPageWriter.php プロジェクト: rdfio/RDFIO
 /**
  * Main function, that takes an array of RDFIOWikiPage objects, and writes to
  * MediaWiki using the WikiObjectModel extension.
  * @param array $wikiPages
  */
 public function import($wikiPages)
 {
     global $wgOut;
     foreach ($wikiPages as $wikiTitle => $wikiPage) {
         // Get properties, categories, templates and related data from the page
         $newWikiContent = "";
         $mwTitleObj = Title::newFromText($wikiTitle);
         // If page exists, get its data
         $titleIsObj = is_object($mwTitleObj);
         $titleExists = $mwTitleObj->exists();
         $newTemplateCalls = null;
         if ($titleIsObj && $titleExists) {
             $mwPageObj = WikiPage::factory($mwTitleObj);
             $oldWikiContent = $mwPageObj->getText();
             $mwProperties = array();
             $mwCategories = array();
             $mwTemplates = array();
             preg_match('/^\\s?$/', $oldWikiContent, $isBlank);
             // Find all the properties stored in the conventional way within the page
             preg_match_all('/\\[\\[(.*)::(.*)\\]\\]/', $oldWikiContent, $propertyMatches);
             $propertyWikitextInPage = $propertyMatches[0];
             $propertyNameInPage = $propertyMatches[1];
             $propertyValueInPage = $propertyMatches[2];
             foreach ($propertyNameInPage as $index => $propertyName) {
                 $mwProperties[$propertyName] = array('value' => $propertyValueInPage[$index], 'wikitext' => $propertyWikitextInPage[$index]);
             }
             // Find all the categories, in the same way
             preg_match_all('/\\[\\[Category:(.*)\\]\\]/', $oldWikiContent, $categoryMatches);
             $categoryWikitextInPage = $categoryMatches[0];
             $categoryNameInPage = $categoryMatches[1];
             foreach ($categoryNameInPage as $index => $categoryName) {
                 $mwCategories[$categoryName] = array('wikitext' => $categoryWikitextInPage[$index]);
             }
             // Find all the templates
             preg_match_all('/\\{\\{\\s?([^#][a-zA-Z0-9]+)\\s?\\|(.*)\\}\\}/U', $oldWikiContent, $templateMatches);
             $templateCallInPage = $templateMatches[0];
             $templateNameInPage = $templateMatches[1];
             $templateParamsInPage = $templateMatches[2];
             foreach ($templateNameInPage as $index => $templateName) {
                 $mwTemplates[$templateName]['templateCallText'] = $templateCallInPage[$index];
                 $mwTemplates[$templateName]['templateParamsValues'] = $templateParamsInPage[$index];
             }
             if (!empty($isBlank)) {
                 $newTemplates = $this->getTemplatesForCategories($wikiPage);
                 foreach ($newTemplates as $name => $callText) {
                     $mwTemplates[$name]['templateCallText'] = $callText;
                     $newTemplateCalls .= $callText . "\n";
                 }
             }
             if (!empty($mwTemplates)) {
                 // Extract the wikitext from each template
                 foreach ($mwTemplates as $templateName => $array) {
                     $mwTemplatePageTitle = Title::newFromText($templateName, $defaultNamespace = NS_TEMPLATE);
                     $mwTemplateObj = WikiPage::factory($mwTemplatePageTitle);
                     $mwTemplateText = $mwTemplateObj->getText();
                     $mwTemplates[$templateName]['wikitext'] = $mwTemplateText;
                     // Get the properties and parameter names used in the templates
                     preg_match_all('/\\[\\[(.*)::\\{\\{\\{(.*)\\|?\\}\\}\\}\\]\\]/', $mwTemplateText, $templateParameterMatches);
                     $propertyNameInTemplate = $templateParameterMatches[1];
                     $parameterNameInTemplate = $templateParameterMatches[2];
                     foreach ($parameterNameInTemplate as $index => $templateParameter) {
                         // Store parameter-property pairings both ways round for easy lookup
                         $mwTemplates[$templateName]['parameters'][$templateParameter]['property'] = $propertyNameInTemplate[$index];
                         $mwTemplates[$templateName]['properties'][$propertyNameInTemplate[$index]] = $parameterNameInTemplate[$index];
                     }
                     $hasTemplateParams = array_key_exists('templateParamsValues', $mwTemplates[$templateName]);
                     // Get the parameter values used in the templates
                     if ($hasTemplateParams) {
                         $templateParameterValues = explode('|', $mwTemplates[$templateName]['templateParamsValues']);
                         foreach ($templateParameterValues as $paramPair) {
                             $paramValueArray = explode('=', $paramPair);
                             $paramName = $paramValueArray[0];
                             $paramValue = $paramValueArray[1];
                             $mwTemplates[$templateName]['parameters'][$paramName]['value'] = $paramValue;
                         }
                     }
                 }
             }
             // put existing template calls into an array for updating more than one fact
             foreach ($mwTemplates as $name => $array) {
                 $updatedTemplateCalls[$name] = $array['templateCallText'];
             }
         }
         $newWikiContent = $oldWikiContent;
         // using new variable to separate extraction from editing
         if (!$titleExists) {
             // if page doesn't exist, check for categories in the wikipage data, and add an empty template call to the page wikitext
             $newTemplates = $this->getTemplatesForCategories($wikiPage);
             foreach ($newTemplates as $name => $callText) {
                 $mwTemplates[$name]['templateCallText'] = $callText;
                 $newTemplateCalls .= $callText . "\n";
             }
         }
         if ($newTemplateCalls) {
             $newWikiContent .= $newTemplateCalls;
         }
         // Add categories to the wiki text
         // The new wikitext is actually added to the page at the end.
         // This allows us to add a template call associated with the category and then populate it with parameters in the facts section
         $newCategoriesAsWikiText = "\n";
         foreach ($wikiPage->getCategories() as $category) {
             $categoryTitle = Title::newFromText($category, $defaultNamespace = NS_CATEGORY);
             $categoryTitleWikified = $categoryTitle->getText();
             if (!array_key_exists($categoryTitleWikified, $mwCategories)) {
                 $newCategoriesAsWikiText .= '[[Category:' . $categoryTitleWikified . "]]\n";
                 // Is there an inbuilt class method to do this?  Can't find one in Category.
             }
         }
         // Add facts (properties) to the wiki text
         $newPropertiesAsWikiText = "\n";
         foreach ($wikiPage->getFacts() as $fact) {
             $pred = $fact['p'];
             $obj = $fact['o'];
             $predTitle = Title::newFromText($pred);
             $predTitleWikified = $predTitle->getText();
             $isEquivURI = strpos($pred, "Equivalent URI") !== false;
             $hasLocalUrl = strpos($obj, "Special:URIResolver") !== false;
             $templatesWithProperty = array();
             $isInTemplate = null;
             // Find whether the property is in any template(s) on the page
             if (!empty($mwTemplates)) {
                 foreach ($mwTemplates as $templateName => $array) {
                     $isInTemplate = array_key_exists($predTitleWikified, $mwTemplates[$templateName]['properties']);
                     if ($isInTemplate && !in_array($templateName, $templatesWithProperty)) {
                         $templatesWithProperty[] = $templateName;
                     }
                 }
             }
             $isInPage = array_key_exists($predTitleWikified, $mwProperties);
             // Set new value - this will be used in different ways depending on whether property is inside or outside template
             if ($isEquivURI) {
                 // FIXME: Should be done for all "URL type" facts, not just
                 //        Equivalent URI:s
                 // Since this is a URL, it should not be made into a WikiTitle
                 $newSMWValue = SMWDataValueFactory::newTypeIdValue('_uri', $obj);
             } else {
                 // Create an updated property
                 $objTitle = Title::newFromText($obj);
                 $newSMWValue = SMWWikiPageValue::makePageFromTitle($objTitle);
             }
             $newValueText = $newSMWValue->getWikiValue();
             // Handle updating differently depending on whether property exists in/outside template
             if ($hasLocalUrl && $isEquivURI) {
                 // Don't update Equivalent URI if the URL is a local URL (thus containing
                 // "Special:URIResolver").
             } else {
                 if ($isInTemplate) {
                     // Code to update/add property to template call(s)
                     foreach ($templatesWithProperty as $index => $templateName) {
                         $oldTemplateCall = $updatedTemplateCalls[$templateName];
                         // use temp value as may be updated more than once
                         $parameter = $mwTemplates[$templateName]['properties'][$predTitleWikified];
                         $oldValue = null;
                         $hasOldValue = array_key_exists('value', $mwTemplates[$templateName]['parameters'][$parameter]);
                         if ($hasOldValue) {
                             $oldValue = $mwTemplates[$templateName]['parameters'][$parameter]['value'];
                         }
                         $newParamValueText = $parameter . '=' . $newValueText;
                         $newTemplateCall = $oldTemplateCall;
                         if ($hasOldValue) {
                             // if the parameter already had a value and there's a new value, replace this value in the template call
                             if ($newValueText != $oldValue) {
                                 $oldParamValueText = $parameter . '=' . $oldValue;
                                 $newTemplateCall = str_replace($oldParamValueText, $newParamValueText, $oldTemplateCall);
                             }
                         } else {
                             // if the parameter wasn't previously populated, add it to the parameter list in the template call
                             preg_match('/(\\{\\{\\s?.*\\s?\\|?.?)(\\}\\})/', $oldTemplateCall, $templateCallMatch);
                             if (!empty($templateCallMatch)) {
                                 $templateCallBeginning = $templateCallMatch[1];
                                 $templateCallEnd = $templateCallMatch[2];
                                 $newTemplateCall = $templateCallBeginning . '|' . $newParamValueText . $templateCallEnd;
                             }
                         }
                     }
                     if ($newTemplateCall != $oldTemplateCall) {
                         //  if the template call has been updated, change it in the page wikitext and update the placeholder variable
                         $newWikiContent = str_replace($oldTemplateCall, $newTemplateCall, $newWikiContent);
                         $updatedTemplateCalls[$templateName] = $newTemplateCall;
                     }
                 } else {
                     if ($isInPage) {
                         // if it's a standard property in the page, replace value with new one if different
                         $oldPropertyText = $mwProperties[$predTitleWikified]['wikitext'];
                         // Store the old wiki text for the fact, in order to replace later
                         $newPropertyText = '[[' . $predTitleWikified . '::' . $newValueText . ']]';
                         // Replace the existing property with new value
                         if ($newPropertyText != $oldPropertyText) {
                             $newWikiContent = str_replace($oldPropertyText, $newPropertyText, $newWikiContent);
                         }
                     } else {
                         if (!$isInPage) {
                             // If property isn't in the page (outside of templates) ...
                             $newPropertyAsWikiText = '[[' . $predTitleWikified . '::' . $obj . ']]';
                             $newPropertiesAsWikiText .= $newPropertyAsWikiText . "\n";
                         }
                     }
                 }
             }
         }
         $newWikiContent .= $newPropertiesAsWikiText;
         $newWikiContent .= $newCategoriesAsWikiText;
         // Write to wiki
         $this->writeToArticle($wikiTitle, $newWikiContent, 'Update by RDFIO');
     }
 }
コード例 #12
0
ファイル: SRF_Process.php プロジェクト: Tjorriemorrie/app
 /**
  *	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(SMWQueryResult $res, $outputmode)
 {
     if (!is_callable('renderGraphviz')) {
         wfWarn('The SRF Graph printer needs the GraphViz extension to be installed.');
         return '';
     }
     global $wgContLang;
     // content language object
     //
     //	GraphViz settings
     //
     global $wgGraphVizSettings;
     $this->isHTML = true;
     //
     //	Iterate all rows in result set
     //
     $row = $res->getNext();
     // get initial row (i.e. array of SMWResultArray)
     while ($row !== false) {
         /* SMWDataItem */
         $subject = $row[0]->getResultSubject();
         // get Subject of the Result
         // creates a new node if $val has type wikipage
         if ($subject->getDIType() == SMWDataItem::TYPE_WIKIPAGE) {
             $wikiPageValue = new SMWWikiPageValue('_wpg');
             $wikiPageValue->setDataItem($subject);
             $node = $this->m_process->makeNode($wikiPageValue->getShortWikiText(), $wikiPageValue->getShortWikiText());
         }
         //
         //	Iterate all colums of the row (which describe properties of the proces node)
         //
         // FIXME: this does not work with SMW >= 1.6, see
         // https://bugzilla.wikimedia.org/show_bug.cgi?id=35003
         // FIXME: got _a bit_ of redundancy here looks like... :/
         foreach ($row as $field) {
             // check column title
             $req = $field->getPrintRequest();
             switch (strtolower($req->getLabel())) {
                 case strtolower($wgContLang->getNsText(NS_CATEGORY)):
                     foreach ($field->getContent() as $value) {
                         $val = $value->getShortWikiText();
                         if ($val == $wgContLang->getNsText(NS_CATEGORY) . ':' . $this->m_processCategory) {
                             $node->setAtomic(false);
                         }
                     }
                     break;
                 case "haslabel":
                     $value = current($field->getContent());
                     // save only the first
                     if ($value !== false) {
                         $val = $value->getLongWikiText();
                         if ($this->m_process->getUseOtherLabels()) {
                             $val = str_replace("&", "and", $val);
                             $node->setLabel($val);
                         }
                     }
                     break;
                 case "hasrole":
                     foreach ($field->getContent() as $value) {
                         $val = $value->getShortWikiText();
                         $role = $this->m_process->makeRole($val, $val);
                         $node->addRole($role);
                     }
                     break;
                 case "usesresource":
                     foreach ($field->getContent() as $value) {
                         $val = $value->getShortWikiText();
                         $xres = $this->m_process->makeRessource($val, $val);
                         $node->addUsedRessource($xres);
                     }
                     break;
                 case "producesresource":
                     foreach ($field->getContent() as $value) {
                         $val = $value->getShortWikiText();
                         $xres = $this->m_process->makeRessource($val, $val);
                         $node->addProducedRessource($xres);
                     }
                     break;
                 case "hassuccessor":
                     if (count($field->getContent()) > 1) {
                         // SplitParallel
                         $edge = new SplitParallelEdge();
                         $edge->setFrom($node);
                         foreach ($field->getContent() as $value) {
                             $val = $value->getShortWikiText();
                             $edge->addTo($this->m_process->makeNode($val, $val));
                         }
                     } else {
                         // Sequence
                         foreach ($field->getContent() as $value) {
                             $val = $value->getShortWikiText();
                             $edge = new SequentialEdge();
                             $edge->setFrom($node);
                             $edge->setTo($this->m_process->makeNode($val, $val));
                         }
                     }
                     break;
                 case "hasorsuccessor":
                     if (count($field->getContent()) > 0) {
                         // SplitExclusiveOr
                         $edge = new SplitExclusiveOrEdge();
                         $edge->setFrom($node);
                         foreach ($field->getContent() as $value) {
                             $val = $value->getShortWikiText();
                             $edge->addTo($this->m_process->makeNode($val, $val));
                         }
                     }
                     break;
                 case "hascontruesuccessor":
                     if (count($field->getContent()) > 0) {
                         // SplitConditional
                         if (!isset($cond_edge)) {
                             $cond_edge = new SplitConditionalOrEdge();
                             $cond_edge->setFrom($node);
                         }
                         // should be only one
                         foreach ($field->getContent() as $value) {
                             $val = $value->getShortWikiText();
                             $cond_edge->setToTrue($this->m_process->makeNode($val, $val));
                         }
                     }
                     break;
                 case "hasconfalsesuccessor":
                     if (count($field->getContent()) > 0) {
                         // SplitConditional
                         if (!isset($cond_edge)) {
                             $cond_edge = new SplitConditionalOrEdge();
                             $cond_edge->setFrom($node);
                         }
                         // should be only one
                         foreach ($field->getContent() as $value) {
                             $val = $value->getShortWikiText();
                             $cond_edge->setToFalse($this->m_process->makeNode($val, $val));
                         }
                     }
                     break;
                 case "hascondition":
                     if (count($field->getContent()) > 0) {
                         // SplitConditional
                         if (!isset($cond_edge)) {
                             $cond_edge = new SplitConditionalOrEdge();
                             $cond_edge->setFrom($node);
                         }
                         // should be only one
                         foreach ($field->getContent() as $value) {
                             $val = $value->getShortWikiText();
                             $cond_edge->setConditionText($val);
                         }
                     }
                     break;
                 case "hasstatus":
                     // should be only one
                     foreach ($field->getContent() as $value) {
                         $val = $value->getShortWikiText();
                         $node->setStatus($val);
                     }
                     break;
                 default:
                     // TODO - redundant column in result
             }
         }
         // reset row variables
         unset($node);
         unset($cond_edge);
         $row = $res->getNext();
         // switch to next row
     }
     //
     // generate graphInput
     //
     $graphInput = $this->m_process->getGraphVizCode();
     //
     // render graphViz code
     //
     $result = renderGraphviz($graphInput);
     $debug = '';
     if ($this->m_isDebugSet) {
         $debug = '<pre>' . $graphInput . '</pre>';
     }
     return $result . $debug;
 }
コード例 #13
0
 /**
  * @see superclass
  */
 function getPropertySubjects(SMWPropertyValue $property, $value, $requestoptions = NULL)
 {
     if (!$property->isUserDefined()) {
         return parent::getPropertySubjects($property, $value, $requestoptions);
     }
     if (smwfCheckIfPredefinedSMWHaloProperty($property)) {
         return parent::getPropertyValues($subject, $property, $requestoptions, $outputformat);
     }
     global $smwgTripleStoreGraph;
     $client = TSConnection::getConnector();
     $client->connect();
     $values = array();
     $propertyName = $property->getWikiPageValue()->getTitle()->getDBkey();
     $limit = isset($requestoptions->limit) ? " LIMIT " . $requestoptions->limit : "";
     $offset = isset($requestoptions->offset) ? " OFFSET " . $requestoptions->offset : "";
     $nsPrefixProp = $this->tsNamespace->getNSPrefix($property->getWikiPageValue()->getTitle()->getNamespace());
     try {
         if (is_null($value)) {
             $response = $client->query("SELECT ?s WHERE { GRAPH ?g { ?s <{$smwgTripleStoreGraph}/{$nsPrefixProp}#{$propertyName}> ?o. } } {$limit} {$offset}", "merge=false|graph={$smwgTripleStoreGraph}");
         } else {
             if ($value instanceof SMWWikiPageValue) {
                 $objectName = $value->getTitle()->getDBkey();
                 $nsPrefixObj = $this->tsNamespace->getNSPrefix($value->getTitle()->getNamespace());
                 $response = $client->query("SELECT ?s WHERE { GRAPH ?g { ?s <{$smwgTripleStoreGraph}/{$nsPrefixProp}#{$propertyName}> <{$smwgTripleStoreGraph}/{$nsPrefixObj}#{$objectName}>. } } {$limit} {$offset}", "merge=false");
             } else {
                 $objectvalue = str_replace('"', '\\"', array_shift($value->getDBkeys()));
                 $objecttype = WikiTypeToXSD::getXSDType($value->getTypeID());
                 $response = $client->query("SELECT ?s WHERE { GRAPH ?g { ?s <{$smwgTripleStoreGraph}/{$nsPrefixProp}#{$propertyName}> \"{$objectvalue}\"^^{$objecttype}. } } {$limit} {$offset}", "merge=false");
             }
         }
     } catch (Exception $e) {
         wfDebug("Triplestore does probably not run.\n");
         $response = TSNamespaces::$EMPTY_SPARQL_XML;
     }
     // query
     global $smwgSPARQLResultEncoding;
     // PHP strings are always interpreted in ISO-8859-1 but may be actually encoded in
     // another charset.
     if (isset($smwgSPARQLResultEncoding) && $smwgSPARQLResultEncoding == 'UTF-8') {
         $response = utf8_decode($response);
     }
     $dom = simplexml_load_string($response);
     $annotations = array();
     $results = $dom->xpath('//result');
     foreach ($results as $r) {
         $children = $r->children();
         // binding nodes
         $b = $children->binding[0];
         // predicate
         $sv = $b->children()->uri[0];
         $title = $this->getTitleFromURI((string) $sv);
         $value = SMWWikiPageValue::makePage($title->getDBkey(), $title->getNamespace());
         $metadata = $sv->attributes();
         foreach ($metadata as $mdProperty => $mdValue) {
             if (strpos($mdProperty, "_meta_") === 0) {
                 $value->setMetadata(substr($mdProperty, 6), explode("|||", $mdValue));
             }
         }
         $values[] = $value;
     }
     return $values;
 }
コード例 #14
0
	/**
	 * Resolves a redirect from a page, if any
	 *
	 * @param SMWWikiPageValue $value page to resolve
	 * @return SMWWikiPageValue resolved page
	 */
	public static function resolveRedirect( SMWWikiPageValue $value ) {
		$entity = smwfGetStore()->getSemanticData( $value->getTitle() );
		return $entity->getSubject();
	}
コード例 #15
0
 private function getDvShortHtmlText($subject, $linker = null)
 {
     $dataValue = new WikiPageValue('_wpg');
     $dataValue->setDataItem($subject);
     $dataValue->setCaption($subject->getTitle()->getSubpageText());
     return $dataValue->getShortHtmlText($linker);
 }
コード例 #16
0
ファイル: SD_BrowseData.php プロジェクト: seedbank/old-repo
 function addSemanticResultWrapper($dbr, $res, $num, $query, $mainlabel, $printouts)
 {
     $qr = array();
     $count = 0;
     $store = smwfGetStore();
     while ($count < $num && ($row = $dbr->fetchObject($res))) {
         $count++;
         if (class_exists('SMWDIWikiPage')) {
             // SMW 1.6
             $qr[] = new SMWDIWikiPage($row->t, $row->ns, null);
         } else {
             $qr[] = SMWWikiPageValue::makePage($row->t, $row->ns, $row->sortkey);
         }
         if (method_exists($store, 'cacheSMWPageID')) {
             if (method_exists('SMWDIWikiPage', 'getSubobjectName')) {
                 // SMW 1.6
                 $store->cacheSMWPageID($row->id, $row->t, $row->ns, $row->iw, '');
             } else {
                 $store->cacheSMWPageID($row->id, $row->t, $row->ns, $row->iw);
             }
         }
     }
     if ($dbr->fetchObject($res)) {
         $count++;
     }
     $dbr->freeResult($res);
     $printrequest = new SMWPrintRequest(SMWPrintRequest::PRINT_THIS, $mainlabel);
     $main_printout = array();
     $main_printout[$printrequest->getHash()] = $printrequest;
     $printouts = array_merge($main_printout, $printouts);
     return new SMWQueryResult($printouts, $query, $qr, $store, $count > $num);
 }
コード例 #17
0
function renderFolkTagCloud($input, $args, $parser)
{
    # definition of variables
    $append = '';
    $count = 0;
    $max_tags = 1000;
    $min_count = 1;
    $increase_factor = 100;
    $min_font_size = 77;
    $font_size = 0;
    $htmlout = '';
    # disable cache
    $parser->disableCache();
    # not needed with searchlink data
    # build URL path
    # global $wgServer, $wgArticlePath;
    # $path = $wgServer . $wgArticlePath;
    # default tagging property
    $tag_name = 'FolkTag';
    # use a user-defined tagging property as default
    global $wgFTCTagName;
    if (isset($wgFTCTagName)) {
        $tag_name = $wgFTCTagName;
    }
    # use a user-defined tagging property for this tag cloud
    if (isset($args['property'])) {
        $tag_name = str_replace(' ', '_', ucfirst($args['property']));
    }
    # maximum of tags shown
    if (isset($args['maxtags'])) {
        $max_tags = intval($args['maxtags']);
    }
    # minimum frequency for tags to be shown
    if (isset($args['mincount'])) {
        $min_count = intval($args['mincount']);
    }
    # increase factor
    if (isset($args['increasefactor'])) {
        $increase_factor = intval($args['increasefactor']);
    }
    # minimum font size
    if (isset($args['minfontsize'])) {
        $min_font_size = intval($args['minfontsize']);
    }
    # get database
    $db =& wfGetDB(DB_SLAVE);
    $store = new SMWSQLStore2();
    extract($db->tableNames('categorylinks', 'page'));
    # make tagging property an SMWPorpertyValue in order to access store
    $property = SMWPropertyValue::makeProperty($tag_name);
    # initialising result arrays
    $values = array();
    $result = array();
    $links = array();
    # if there is no filter category:
    if ($input == NULL) {
        $values = ft_getPropertyValues($property, $store);
        # $values = $store->getPropertyValues(NULL, $property);
    } else {
        $categories = explode(',', $input);
        # include subcategories:
        if (isset($args['subcategorylevel'])) {
            $subcategories = array();
            foreach ($categories as $category) {
                $subcategories = array_merge($subcategories, getSubCategories($category, intval($args['subcategorylevel'])));
            }
            $categories = array_merge($categories, $subcategories);
        }
        # start building sql
        $sql = "SELECT page_title, page_namespace\n\t\t\t\tFROM {$page}\n\t\t\t\tINNER JOIN {$categorylinks}\n\t\t\t\tON {$page}.page_id = {$categorylinks}.cl_from\n\t\t\t\tAND (";
        # disjunction of filter categories
        foreach ($categories as $category) {
            $category = trim($category);
            $category = str_replace(' ', '_', $category);
            $category = str_replace("'", "\\'", $category);
            $sql .= "{$categorylinks}.cl_to = '{$category}' OR ";
        }
        # remainder of sql (FALSE is required to absorb the last OR)
        $sql .= "FALSE) GROUP BY page_title";
        # query
        $res = $db->query($sql);
        # parsing result of sql query: get name and namespace of pages placed in the
        # filter categories and look up all values of the given property for each page
        for ($i = 0; $i < $db->numRows($res); $i++) {
            $row = $db->fetchObject($res);
            $pagename = $row->page_title;
            $namespace = $row->page_namespace;
            $values = array_merge($values, $store->getPropertyValues(SMWWikiPageValue::makePage($pagename, $namespace), $property));
        }
        $db->freeResult($res);
    }
    # counting frequencies
    foreach ($values as $value) {
        # get surface form of property value
        $tag = $value->getShortHTMLText();
        # get Searchlink data for property and current property value
        $link = SMWInfolink::newPropertySearchLink($tag, $tag_name, $tag)->getHTML();
        if (array_key_exists($tag, $result)) {
            $result[$tag] += 1;
        } else {
            $result[$tag] = 1;
            $links[$tag] = $link;
        }
    }
    # sorting results
    arsort($result);
    # if too many tags are found, remove rear part of result array
    if (count($result) > $max_tags) {
        $result = array_slice($result, 0, $max_tags, true);
    }
    # get minimum and maximum frequency for computing font sizes
    $min = end($result) or $min = 0;
    $max = reset($result) or $max = 1;
    if ($max == $min) {
        $max += 1;
    }
    # sorting results by frequency
    if (isset($args['order'])) {
        if ($args['order'] != "frequency") {
            # ksort($result, SORT_STRING);
            uksort($result, 'compareLowercase');
        }
    } else {
        uksort($result, 'compareLowercase');
    }
    # start building html output
    $htmlOut = $htmlOut . "<div align=justify>";
    foreach ($result as $label => $count) {
        if ($count >= $min_count) {
            if (isset($args['increase'])) {
                # computing font size (logarithmic)
                if ($args[increase] = 'log') {
                    $font_size = $min_font_size + $increase_factor * (log($count) - log($min)) / (log($max) - log($min));
                } else {
                    $font_size = $min_font_size + $increase_factor * ($count - $min) / ($max - $min);
                }
            } else {
                $font_size = $min_font_size + $increase_factor * ($count - $min) / ($max - $min);
            }
            $style = "font-size: {$font_size}%;";
            # link to special page search by property with parameters
            # property=tagging property and value=current tag
            # find URL in searchlink data
            $matches = array();
            preg_match('/href="(.)*"/U', $links[$label], $matches);
            $url = $matches[0];
            # include freqency in brackets in output
            if ($args['count']) {
                $append = " ({$count})";
            }
            # appending tag
            $currentRow = "<a style=\"{$style}\" {$url}>" . $label . $append . "</a>&#160; ";
            $htmlOut = $htmlOut . $currentRow;
        }
    }
    $htmlOut = $htmlOut . "</div>";
    return $htmlOut;
}
コード例 #18
0
 private function createTriples($wsResult, $subjectCreationPattern, $wsId, $unwantedPropertys, $previewTitle)
 {
     $unwantedPropertys = array_flip($unwantedPropertys);
     global $wgParser, $IP;
     require_once $IP . "/extensions/SMWHalo/includes/storage/SMW_TS_Helper.php";
     $subjects = array();
     //get number of rows and property types
     $lineCount = 0;
     $types = array();
     foreach ($wsResult as $propertyName => $resultPart) {
         $lineCount = max($lineCount, count($resultPart));
         $title = Title::newFromText($propertyName, SMW_NS_PROPERTY);
         $semData = smwfGetStore()->getSemanticData(SMWWikiPageValue::makePageFromTitle($title));
         $property = SMWPropertyValue::makeProperty('Has_type');
         $value = $semData->getPropertyValues($property);
         if (count($value) > 0) {
             $fK = array_keys($value);
             $fK = $fK[0];
             @($types[$propertyName] = '' . $value[$fK]->getShortWikiText());
             $types[$propertyName] = str_replace('http://www.w3.org/2001/XMLSchema#', 'xsd:', $types[$propertyName]);
             //@ $types[$propertyName] = SMWDataValueFactory::findTypeID($value[$fK]->getShortWikiText());
         } else {
             $types[$propertyName] = '';
         }
     }
     $triples = array();
     $allAliases = WebService::newFromId($wsId)->getAllResultPartAliases();
     $subjectCreationPatternParts = array();
     foreach ($allAliases as $alias => $dc) {
         if (strpos($subjectCreationPattern, "?" . $alias . "?") !== false) {
             $alias = explode(".", $alias);
             $subjectCreationPatternParts[$alias[1]] = $alias[0] . "." . $alias[1];
         }
     }
     for ($i = 0; $i < $lineCount; $i++) {
         $tempTriples = array();
         $subject = $subjectCreationPattern;
         foreach ($wsResult as $property => $objects) {
             if (array_key_exists($i, $objects) && strlen($objects[$i]) > 0) {
                 if (array_key_exists($property, $subjectCreationPatternParts)) {
                     $subject = str_replace("?" . $subjectCreationPatternParts[$property] . "?", $objects[$i], $subject);
                 }
                 $triple = array();
                 $triple['property'] = $property;
                 $triple['object'] = $objects[$i];
                 if (!array_key_exists($property, $types) || strlen($types[$property]) == 0) {
                     $triple['type'] = '__objectURI';
                     $triple['object'] = trim($triple['object']);
                 } else {
                     //$typeDataValue = SMWDataValueFactory::newTypeIDValue($types[$property], $triple['object']);
                     //if($typeDataValue->isValid()){
                     //	$triple['type'] = WikiTypeToXSD::getXSDType($types[$property]);
                     //} else {
                     //	$triple['type'] = null;
                     //}
                     $triple['type'] = $types[$property];
                 }
                 if (!array_key_exists($property, $unwantedPropertys)) {
                     $tempTriples[] = $triple;
                 }
             } else {
                 if (array_key_exists($property, $subjectCreationPatternParts)) {
                     $subject = str_replace("?" . $subjectCreationPatternParts[$property] . "?", '', $subject);
                 }
             }
         }
         if (is_string($previewTitle)) {
             //we are in preview mode
             $t = Title::makeTitleSafe(0, $previewTitle);
             $popts = new ParserOptions();
             $wgParser->startExternalParse($t, $popts, Parser::OT_HTML);
             $subject = $wgParser->internalParse($subject);
             //$subject = $wgParser->doBlockLevels($subject, true);
             $subject = trim($subject);
         } else {
             $subject = trim($wgParser->replaceVariables($subject));
         }
         if (strlen($subject) > 0) {
             foreach ($tempTriples as $triple) {
                 $triple['subject'] = $subject;
                 $triples[] = $triple;
             }
         }
         if (strlen($subject) > 0 && !is_string($previewTitle)) {
             $subject = "[[" . $subject . "]]";
         }
         $subjects[] = $subject;
     }
     return array($triples, $subjects);
 }
コード例 #19
0
    /**
     * Initialize SMWWriter for the page corresponding to title
     * in object variable
     * @param boolean $delete
     */
    private function initSMWWriter( $delete = false ) {
        // Create add and remove objects, to use in SMWWriter calls
		
        // TODO: Should rather use (but not possible with current SMWWriter API?):
    	// $page_di = SMWDIWikiPage::newFromTitle( Title::makeTitle($this->m_ns, $this->m_wikititle) );
    	$page = SMWWikiPageValue::makePage( $this->m_wikititle, $this->m_ns );
    	$page_di = $page->getDataItem(); 
    	$page_data = new SMWSemanticData( $page_di ); 
    	
    	$dummypage = SMWWikiPageValue::makePage( false, $this->m_ns );
    	$dummypage_di = $dummypage->getDataItem();
        $dummypag_data = new SMWSemanticData( $dummypage_di ); 
    	
        
        $this->m_smwwriter = new SMWWriter( $page->getTitle() );
        if ( $delete ) {
            $this->m_smwwriter_add    = $page_data;
            $this->m_smwwriter_remove = $dummypag_data;
        } else {
            $this->m_smwwriter_add    = $dummypag_data;
            $this->m_smwwriter_remove = $page_data;
        }
    }
コード例 #20
0
 /**
  * TODO: document
  */
 protected function makeHTMLResult()
 {
     global $wgOut;
     // TODO: hold into account $smwgAutocompleteInSpecialAsk
     $result = '';
     $res = null;
     $htmlContentBuilder = new HtmlContentBuilder();
     // 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 = '';
     $duration = 0;
     $navigation = '';
     $queryobj = null;
     /**
      * @var PrintRequest $printout
      */
     foreach ($this->m_printouts as $printout) {
         $printoutstring .= $printout->getSerialisation(true) . "\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->getRequest()->getCheck('bTitle')) {
         $urlArgs['bTitle'] = $this->getRequest()->getVal('bTitle');
         $urlArgs['bMsg'] = $this->getRequest()->getVal('bMsg');
     }
     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
         $duration = microtime(true);
         $res = $this->getStoreFromParams($params)->getQueryResult($queryobj);
         $duration = number_format(microtime(true) - $duration, 4, '.', '');
         // 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(\SMW\StoreFactory::getStore()->getPropertyValues(SMWWikiPageValue::makePageFromTitle($concept), new SMW\DIProperty('_CONC')));
                 if ($dv instanceof SMWConceptValue) {
                     $this->m_params[$desckey] = $dv->getDocu();
                 }
             }
         }
         $printer = SMWQueryProcessor::getResultPrinter($this->m_params['format'], SMWQueryProcessor::SPECIAL_PAGE);
         $printer->setShowErrors(false);
         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);
                 $query_result = $printer->getResult($res, $params, SMW_OUTPUT_HTML);
                 if (is_array($query_result)) {
                     $result .= $query_result[0];
                 } else {
                     $result .= $query_result;
                 }
             } else {
                 $result = Html::element('div', array('class' => 'smw-callout smw-callout-info'), wfMessage('smw_result_noresults')->escaped());
             }
         }
     }
     // FileExport will override the header and cause issues during the unit
     // test when fetching the output stream therefore use the plain output
     if (defined('MW_PHPUNIT_TEST') && isset($printer) && $printer->isExportFormat()) {
         $result = $printer->getResult($res, $params, SMW_OUTPUT_FILE);
         $printer = null;
     }
     if (isset($printer) && $printer->isExportFormat()) {
         $wgOut->disable();
         /**
          * @var SMWIExportPrinter $printer
          */
         $printer->outputAsFile($res, $params);
     } else {
         if ($this->m_querystring) {
             $this->getOutput()->setHTMLtitle($this->m_querystring);
         } else {
             $this->getOutput()->setHTMLtitle(wfMessage('ask')->text());
         }
         $urlArgs['offset'] = $this->m_params['offset'];
         $urlArgs['limit'] = $this->m_params['limit'];
         $isFromCache = $res !== null ? $res->isFromCache() : false;
         $result = $this->getInputForm($printoutstring, wfArrayToCGI($urlArgs), $navigation, $duration, $isFromCache) . $htmlContentBuilder->getFormattedErrorString($queryobj) . $result;
         $this->getOutput()->addHTML($result);
     }
 }
コード例 #21
0
ファイル: SMW_DI_WikiPage.php プロジェクト: yusufchang/app
 /**
  * Create a MediaWiki Title object for this SMWDIWikiPage. The result
  * can be null if an error occurred.
  *
  * @todo From MW 1.17 on, makeTitleSafe supports interwiki prefixes.
  * This function can be simplified when compatibility to MW 1.16 is
  * dropped.
  * @return mixed Title or null
  */
 public function getTitle()
 {
     if ($this->m_interwiki === '') {
         return Title::makeTitleSafe($this->m_namespace, $this->m_dbkey, $this->m_subobjectname);
     } else {
         // TODO inefficient; incomplete for fragments (see above commment)
         $datavalue = new SMWWikiPageValue('_wpg');
         $datavalue->setDataItem($this);
         return Title::newFromText($datavalue->getPrefixedText());
     }
 }
コード例 #22
0
ファイル: SMW_SQLStore3.php プロジェクト: whysasse/kmwiki
 /**
  * Return status of the concept cache for the given concept as an array
  * with key 'status' ('empty': not cached, 'full': cached, 'no': not
  * cachable). If status is not 'no', the array also contains keys 'size'
  * (query size), 'depth' (query depth), 'features' (query features). If
  * status is 'full', the array also contains keys 'date' (timestamp of
  * cache), 'count' (number of results in cache).
  *
  * @since 1.8
  * @param Title|SMWWikiPageValue $concept
  *
  * @return SMW\DIConcept|null
  */
 public function getConceptCacheStatus($concept)
 {
     $db = $this->getConnection();
     $cid = $this->smwIds->getSMWPageID($concept->getDBkey(), $concept->getNamespace(), '', '', false);
     $row = $db->selectRow('smw_fpt_conc', array('concept_txt', 'concept_features', 'concept_size', 'concept_depth', 'cache_date', 'cache_count'), array('s_id' => $cid), __METHOD__);
     if ($row !== false) {
         $dataItem = new SMW\DIConcept($concept, null, $row->concept_features, $row->concept_size, $row->concept_depth);
         if ($row->cache_date) {
             $dataItem->setCacheStatus('full');
             $dataItem->setCacheDate($row->cache_date);
             $dataItem->setCacheCount($row->cache_count);
         } else {
             $dataItem->setCacheStatus('empty');
         }
         $result = $dataItem;
     } else {
         $result = null;
     }
     return $result;
 }
コード例 #23
0
 /**
  * returns an array that contains already existing term import annotations
  * 
  * @param $title
  * @return array
  */
 public function getExistingTermAnnotations($title)
 {
     $existingAnnotations = array();
     $existingAnnotations['added'] = array();
     $existingAnnotations['updated'] = array();
     $existingAnnotations['ignored'] = array();
     if ($title == null) {
         return $existingAnnotations;
     }
     if ($title->exists()) {
         $semdata = smwfGetStore()->getSemanticData(SMWWikiPageValue::makePageFromTitle($title));
         $property = SMWPropertyValue::makeProperty('WasAddedDuringTermImport');
         $values = $semdata->getPropertyValues($property);
         foreach ($values as $value) {
             $existingAnnotations['added'][] = $value->getShortWikiText();
         }
         $property = SMWPropertyValue::makeProperty('WasUpdatedDuringTermImport');
         $values = $semdata->getPropertyValues($property);
         foreach ($values as $value) {
             $existingAnnotations['updated'][] = $value->getShortWikiText();
         }
         $property = SMWPropertyValue::makeProperty('WasIgnoredDuringTermImport');
         $values = $semdata->getPropertyValues($property);
         foreach ($values as $value) {
             $existingAnnotations['ignored'][] = $value->getShortWikiText();
         }
     }
     return $existingAnnotations;
 }
コード例 #24
0
ファイル: SRF_Dygraphs.php プロジェクト: Tjorriemorrie/app
 /**
  * Returns an array with numerical data
  *
  * @since 1.8
  *
  * @param SMWQueryResult $result
  * @param $outputMode
  *
  * @return array
  */
 protected function getResultData(SMWQueryResult $result, $outputMode)
 {
     $aggregatedValues = array();
     while ($rows = $result->getNext()) {
         // Objects (pages)
         $annotation = array();
         $dataSource = false;
         /**
          * @var SMWResultArray $field
          * @var SMWDataValue $dataValue
          */
         foreach ($rows as $field) {
             // Use the subject marker to identify a possible data file
             $subject = $field->getResultSubject();
             if ($this->params['datasource'] === 'file' && $subject->getTitle()->getNamespace() === NS_FILE && !$dataSource) {
                 $aggregatedValues['subject'] = SMWWikiPageValue::makePageFromTitle($subject->getTitle())->getLongHTMLText($this->getLinker($field->getResultSubject()));
                 $aggregatedValues['url'] = wfFindFile($subject->getTitle())->getUrl();
                 $dataSource = true;
             }
             // Proceed only where a label is known otherwise items are of no use
             // for being a potential object identifier
             if ($field->getPrintRequest()->getLabel() !== '') {
                 $propertyLabel = $field->getPrintRequest()->getLabel();
             } else {
                 continue;
             }
             while (($dataValue = $field->getNextDataValue()) !== false) {
                 // Data values
                 // Jump the column (indicated by continue) because we don't want the data source being part of the annotation array
                 if ($dataValue->getDataItem()->getDIType() == SMWDataItem::TYPE_WIKIPAGE && $this->params['datasource'] === 'raw' && !$dataSource) {
                     // Support data source = raw which pulls the url from a wikipage in raw format
                     $aggregatedValues['subject'] = SMWWikiPageValue::makePageFromTitle($dataValue->getTitle())->getLongHTMLText($this->getLinker($field->getResultSubject()));
                     $aggregatedValues['url'] = $dataValue->getTitle()->getLocalURL('action=raw');
                     $dataSource = true;
                     continue;
                 } elseif ($dataValue->getDataItem()->getDIType() == SMWDataItem::TYPE_WIKIPAGE && $this->params['datasource'] === 'file' && $dataValue->getTitle()->getNamespace() === NS_FILE && !$dataSource) {
                     // Support data source = file which pulls the url from a uploaded file
                     $aggregatedValues['subject'] = SMWWikiPageValue::makePageFromTitle($dataValue->getTitle())->getLongHTMLText($this->getLinker($field->getResultSubject()));
                     $aggregatedValues['url'] = wfFindFile($dataValue->getTitle())->getUrl();
                     $dataSource = true;
                     continue;
                 } elseif ($dataValue->getDataItem()->getDIType() == SMWDataItem::TYPE_URI && $this->params['datasource'] === 'url' && !$dataSource) {
                     // Support data source = url, pointing to an url data source
                     $aggregatedValues['link'] = $dataValue->getShortHTMLText($this->getLinker(false));
                     $aggregatedValues['url'] = $dataValue->getURL();
                     $dataSource = true;
                     continue;
                 }
                 // The annotation should adhere outlined conventions as the label identifies the array object key
                 // series -> Required The name of the series to which the annotated point belongs
                 // x -> Required The x value of the point
                 // shortText -> Text that will appear as annotation flag
                 // text -> A longer description of the annotation
                 // @see  http://dygraphs.com/annotations.html
                 if (in_array($propertyLabel, array('series', 'x', 'shortText', 'text'))) {
                     if ($dataValue->getDataItem()->getDIType() == SMWDataItem::TYPE_NUMBER) {
                         // Set unit if available
                         $dataValue->setOutputFormat($this->params['unit']);
                         // Check if unit is available
                         $annotation[$propertyLabel] = $dataValue->getUnit() !== '' ? $dataValue->getShortWikiText() : $dataValue->getNumber();
                     } else {
                         $annotation[$propertyLabel] = $dataValue->getWikiValue();
                     }
                 }
             }
         }
         // Sum-up collected row items in a single array
         if ($annotation !== array()) {
             $aggregatedValues['annotation'][] = $annotation;
         }
     }
     return $aggregatedValues;
 }
コード例 #25
0
ファイル: SMW_DV_WikiPage.php プロジェクト: whysasse/kmwiki
 /**
  * Static function for creating a new wikipage object from a
  * MediaWiki Title object.
  *
  * @deprecated This method will vanish before SMW 1.7. If you really need this, simply copy its code.
  *
  * @return SMWWikiPageValue
  */
 public static function makePageFromTitle(Title $title)
 {
     $dvWikiPage = new SMWWikiPageValue('_wpg');
     $diWikiPage = SMWDIWikiPage::newFromTitle($title);
     $dvWikiPage->setDataItem($diWikiPage);
     $dvWikiPage->m_title = $title;
     // optional, just for efficiency
     return $dvWikiPage;
 }
コード例 #26
0
	/**
	 * Reads the paramstring for remove and add and turns it into
	 * SMWSemanticData object that can be used with the SMWWriter API
	 *
	 * @param Title $title Title of the page to be modified
	 * @param string $text The param value
	 * @return SMWSemanticData Object with the interpreted data from the param value
	 */
	private function readData( Title $title, /* string */ $text ) {
		if ( empty( $text ) )
			return new SMWSemanticData( SMWWikiPageValue::makePage( false, 0 ) );
		if ( $text == '*' )
			return new SMWSemanticData( SMWWikiPageValue::makePage( $title, 0 ) );

		$result = new SMWSemanticData( SMWWikiPageValue::makePageFromTitle( $title ) );

		$matches = array();
		preg_match_all( "/\[\[([^\[\]]*)\]\]/", $text, $matches, PREG_PATTERN_ORDER );
		foreach ( $matches[1] as $match ) {
			$parts = explode( "::", $match );
			if ( count( $parts ) != 2 ) continue;
			$property = SMWPropertyValue::makeUserProperty( trim( $parts[0] ) );
			if ( trim( $parts[1] ) == '*' )
				$value = SMWDataValueFactory::newPropertyObjectValue( $property, false );
			else
				$value = SMWDataValueFactory::newPropertyObjectValue( $property, trim( $parts[1] ) );
			$result->addPropertyObjectValue( $property, $value );
		}
		return $result;
	}
コード例 #27
0
ファイル: SMW_SQLStore3.php プロジェクト: seedbank/old-repo
 /**
  * Return status of the concept cache for the given concept as an array
  * with key 'status' ('empty': not cached, 'full': cached, 'no': not
  * cachable). If status is not 'no', the array also contains keys 'size'
  * (query size), 'depth' (query depth), 'features' (query features). If
  * status is 'full', the array also contains keys 'date' (timestamp of
  * cache), 'count' (number of results in cache).
  *
  * @since 1.8
  * @param Title|SMWWikiPageValue $concept
  * @return array
  */
 public function getConceptCacheStatus($concept)
 {
     wfProfileIn('SMWSQLStore3::getConceptCacheStatus (SMW)');
     $db = wfGetDB(DB_SLAVE);
     $cid = $this->smwIds->getSMWPageID($concept->getDBkey(), $concept->getNamespace(), '', '', false);
     $row = $db->selectRow('smw_fpt_conc', array('concept_txt', 'concept_features', 'concept_size', 'concept_depth', 'cache_date', 'cache_count'), array('s_id' => $cid), 'SMWSQLStore3::getConceptCacheStatus (SMW)');
     if ($row !== false) {
         $result = array('size' => $row->concept_size, 'depth' => $row->concept_depth, 'features' => $row->concept_features);
         if ($row->cache_date) {
             $result['status'] = 'full';
             $result['date'] = $row->cache_date;
             $result['count'] = $row->cache_count;
         } else {
             $result['status'] = 'empty';
         }
     } else {
         $result = array('status' => 'no');
     }
     wfProfileOut('SMWSQLStore3::getConceptCacheStatus (SMW)');
     return $result;
 }
コード例 #28
0
    protected function makeHTMLResult()
    {
        $this->checkIfThisIsAWSCALL();
        global $wgOut, $smwgAutocompleteInSpecialAsk;
        $delete_msg = wfMsg('delete');
        // Javascript code for the dynamic parts of the page
        $javascript_text = <<<END
<script type="text/javascript">       
jQuery.noConflict();
function xmlhttpPost(strURL) {
\tjQuery.ajax({ url: strURL, data: getquerystring(), context: document.body, success: function(data){
\t\tdocument.getElementById("other_options").innerHTML = data;
\t}});   
}
function getquerystring() {
\tvar format_selector = document.getElementById('formatSelector');
\treturn format_selector.value;
}

// 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) {
\tvar starter_div = document.getElementById(starter_div_id);
\tvar main_div = document.getElementById(main_div_id);

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

\tvar children = new_div.getElementsByTagName('*');
\tvar x;
\tfor (x = 0; x < children.length; x++) {
\t\tif (children[x].name)
\t\t\tchildren[x].name = children[x].name.replace(/_num/, '[' + num_elements + ']');
\t}

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

\t//Add the new instance
\tmain_div.appendChild(new_div);
\tnum_elements++;
}

function removeInstance(div_id) {
\tvar olddiv = document.getElementById(div_id);
\tvar parent = olddiv.parentNode;
\tparent.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
        $urltail = '&q=' . urlencode($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;
            }
        }
        $urltail .= '&p=' . urlencode(SMWInfolink::encodeParameters($tmp_parray));
        $printoutstring = '';
        foreach ($this->m_printouts as $printout) {
            $printoutstring .= $printout->getSerialisation() . "\n";
        }
        if ($printoutstring != '') {
            $urltail .= '&po=' . urlencode($printoutstring);
        }
        if (array_key_exists('sort', $this->m_params)) {
            $urltail .= '&sort=' . $this->m_params['sort'];
        }
        if (array_key_exists('order', $this->m_params)) {
            $urltail .= '&order=' . $this->m_params['order'];
        }
        if ($this->m_querystring != '') {
            $queryobj = SMWQueryProcessor::createQuery($this->m_querystring, $this->m_params, SMWQueryProcessor::SPECIAL_PAGE, $this->m_params['format'], $this->m_printouts);
            $queryobj->params = $this->m_params;
            $store = $this->getStore();
            $res = $store->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])) {
                    $dv = end(smwfGetStore()->getPropertyValues(SMWWikiPageValue::makePageFromTitle($concept), SMWPropertyValue::makeProperty('_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) {
                        $urltail .= '&eq=yes';
                    }
                    if ($hidequery) {
                        $urltail .= '&eq=no';
                    }
                    $navigation = $this->getNavigationBar($res, $urltail);
                    $result .= '<div style="text-align: center;">' . "\n" . $navigation . "\n</div>\n";
                    $query_result = $printer->getResult($res, $this->m_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;">' . 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'));
            }
            $result = $this->getInputForm($printoutstring, 'offset=' . $this->m_params['offset'] . '&limit=' . $this->m_params['limit'] . $urltail) . $result;
            $result = $this->postProcessHTML($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}");
            }
            print $result;
        }
    }