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; }
/** * 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; } } }
/** * 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); } }
public function deleteSubject(Title $subject) { wfProfileIn('SMWSQLStoreLight::deleteSubject (SMW)'); wfRunHooks('SMWSQLStoreLight::deleteSubjectBefore', array($this, $subject)); $this->deleteSemanticData(SMWWikiPageValue::makePageFromTitle($subject)); /// FIXME: if a property page is deleted, more pages may need to be updated by jobs! /// TODO: who is responsible for these updates? Some update jobs are currently created in SMW_Hooks, some internally in the store /// FIXME: clean internal caches here wfRunHooks('SMWSQLStoreLight::deleteSubjectAfter', array($this, $subject)); wfProfileOut('SMWSQLStoreLight::deleteSubject (SMW)'); }
/** * 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; }
/** * 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; }
/** * 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; }
/** * 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); } }
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); }
/** * 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; } }
/** * 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'); } }
/** * Formats the content of this object into a SMWSemanticData object * * @param Title $title Title of the page this SMWWriterData refers to * @return SMWSemanticData The conent of this SMWWriterData object as a * SMWSemanticData object */ public function getSemanticData( Title $title ) { $result = new SMWSemanticData( SMWWikiPageValue::makePageFromTitle( $title ), 0 ); $propertynames = $this->getPropertynames(); foreach ( $propertynames as $propertyname ) { $property = SMWPropertyValue::makeUserProperty( $propertyname ); $values = $this->getPropertyValues( $propertyname ); foreach ( $values as $value ) { $result->addPropertyObjectValue( $property, $value ); } } return $result; }
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; } }