/** * Gets the set of all properties that point to this page, anywhere * in the wiki. */ static function getIncomingProperties($title) { $store = smwfGetStore(); // SMW 1.6+ if (class_exists('SMWDataItem')) { $value = SMWDIWikiPage::newFromTitle($title); } else { $title_text = SFUtils::titleString($title); $value = SMWDataValueFactory::newTypeIDValue('_wpg', $title_text); } $properties = $store->getInProperties($value); $propertyNames = array(); foreach ($properties as $property) { // SMW 1.6+ if ($property instanceof SMWDIProperty) { $property_name = $property->getKey(); } else { $property_name = $property->getWikiValue(); } if (!empty($property_name)) { $propertyNames[] = $property_name; } } return $propertyNames; }
protected function getTypeProperties($typeLabel) { global $wgRequest, $smwgTypePagingLimit; if ($smwgTypePagingLimit <= 0) { return ''; } // not too useful, but we comply to this request $from = $wgRequest->getVal('from'); $until = $wgRequest->getVal('until'); $typeValue = SMWDataValueFactory::newTypeIDValue('__typ', $typeLabel); $store = smwfGetStore(); $options = SMWPageLister::getRequestOptions($smwgTypePagingLimit, $from, $until); $diWikiPages = $store->getPropertySubjects(new SMWDIProperty('_TYPE'), $typeValue->getDataItem(), $options); if (!$options->ascending) { $diWikiPages = array_reverse($diWikiPages); } $result = ''; if (count($diWikiPages) > 0) { $pageLister = new SMWPageLister($diWikiPages, null, $smwgTypePagingLimit, $from, $until); $title = $this->getTitleFor('Types', $typeLabel); $title->setFragment('#SMWResults'); // Make navigation point to the result list. $navigation = $pageLister->getNavigationLinks($title); $resultNumber = min($smwgTypePagingLimit, count($diWikiPages)); $typeName = $typeValue->getLongWikiText(); $result .= "<a name=\"SMWResults\"></a><div id=\"mw-pages\">\n" . '<h2>' . wfMsg('smw_type_header', $typeName) . "</h2>\n<p>" . wfMsgExt('smw_typearticlecount', array('parsemag'), $resultNumber) . "</p>\n" . $navigation . $pageLister->formatList() . $navigation . "\n</div>"; } return $result; }
function setTypeAndPossibleValues() { $proptitle = Title::makeTitleSafe(SMW_NS_PROPERTY, $this->mSemanticProperty); if ($proptitle === null) { return; } $store = smwfGetStore(); // this returns an array of objects $allowed_values = SFUtils::getSMWPropertyValues($store, $proptitle, "Allows value"); $label_formats = SFUtils::getSMWPropertyValues($store, $proptitle, "Has field label format"); $propValue = SMWDIProperty::newFromUserLabel($this->mSemanticProperty); $this->mPropertyType = $propValue->findPropertyTypeID(); foreach ($allowed_values as $allowed_value) { // HTML-unencode each value $this->mPossibleValues[] = html_entity_decode($allowed_value); if (count($label_formats) > 0) { $label_format = $label_formats[0]; $prop_instance = SMWDataValueFactory::findTypeID($this->mPropertyType); $label_value = SMWDataValueFactory::newTypeIDValue($prop_instance, $wiki_value); $label_value->setOutputFormat($label_format); $this->mValueLabels[$wiki_value] = html_entity_decode($label_value->getWikiValue()); } } // HACK - if there were any possible values, set the property // type to be 'enumeration', regardless of what the actual type is if (count($this->mPossibleValues) > 0) { $this->mPropertyType = 'enumeration'; } }
/** * Main entry point for Special Pages * * @param[in] $query string Given by MediaWiki */ public function execute($query) { global $wgRequest, $wgOut, $smwgBrowseShowAll; $this->setHeaders(); // get the GET parameters $this->articletext = $wgRequest->getVal('article'); // no GET parameters? Then try the URL if (is_null($this->articletext)) { $params = SMWInfolink::decodeParameters($query, false); reset($params); $this->articletext = current($params); } $this->subject = SMWDataValueFactory::newTypeIDValue('_wpg', $this->articletext); $offsettext = $wgRequest->getVal('offset'); $this->offset = is_null($offsettext) ? 0 : intval($offsettext); $dir = $wgRequest->getVal('dir'); if ($smwgBrowseShowAll) { $this->showoutgoing = true; $this->showincoming = true; } if ($dir === 'both' || $dir === 'in') { $this->showincoming = true; } if ($dir === 'in') { $this->showoutgoing = false; } if ($dir === 'out') { $this->showincoming = false; } $wgOut->addHTML($this->displayBrowse()); SMWOutputs::commitToOutputPage($wgOut); // make sure locally collected output data is pushed to the output! }
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; }
static function getXMLForPage($title, $simplified_format, $groupings, $depth = 0) { if ($depth > 5) { return ""; } global $wgContLang, $dtgContLang; $namespace_labels = $wgContLang->getNamespaces(); $template_label = $namespace_labels[NS_TEMPLATE]; $namespace_str = str_replace(' ', '_', wfMsgForContent('dt_xml_namespace')); $page_str = str_replace(' ', '_', wfMsgForContent('dt_xml_page')); $field_str = str_replace(' ', '_', wfMsgForContent('dt_xml_field')); $name_str = str_replace(' ', '_', wfMsgForContent('dt_xml_name')); $title_str = str_replace(' ', '_', wfMsgForContent('dt_xml_title')); $id_str = str_replace(' ', '_', wfMsgForContent('dt_xml_id')); $free_text_str = str_replace(' ', '_', wfMsgForContent('dt_xml_freetext')); // if this page belongs to the exclusion category, exit $parent_categories = $title->getParentCategoryTree(array()); $dt_props = $dtgContLang->getPropertyLabels(); // $exclusion_category = $title->newFromText($dt_props[DT_SP_IS_EXCLUDED_FROM_XML], NS_CATEGORY); $exclusion_category = $wgContLang->getNSText(NS_CATEGORY) . ':' . str_replace(' ', '_', $dt_props[DT_SP_IS_EXCLUDED_FROM_XML]); if (self::treeContainsElement($parent_categories, $exclusion_category)) { return ""; } $article = new Article($title); $page_title = str_replace('"', '"', $title->getText()); $page_title = str_replace('&', '&', $page_title); $page_namespace = $title->getNamespace(); if ($simplified_format) { $text = "<{$page_str}><{$id_str}>{$article->getID()}</{$id_str}><{$title_str}>{$page_title}</{$title_str}>\n"; } else { $text = "<{$page_str} {$id_str}=\"" . $article->getID() . "\" {$title_str}=\"" . $page_title . '" >'; } // traverse the page contents, one character at a time $uncompleted_curly_brackets = 0; $page_contents = $article->getContent(); // escape out variables like "{{PAGENAME}}" $page_contents = str_replace('{{PAGENAME}}', '{{PAGENAME}}', $page_contents); // escape out parser functions $page_contents = preg_replace('/{{(#.+)}}/', '{{$1}}', $page_contents); // escape out transclusions $page_contents = preg_replace('/{{(:.+)}}/', '{{$1}}', $page_contents); // escape out variable names $page_contents = str_replace('{{{', '{{{', $page_contents); $page_contents = str_replace('}}}', '}}}', $page_contents); // escape out tables $page_contents = str_replace('{|', '{|', $page_contents); $page_contents = str_replace('|}', '|}', $page_contents); $free_text = ""; $free_text_id = 1; $template_name = ""; $field_name = ""; $field_value = ""; $field_has_name = false; for ($i = 0; $i < strlen($page_contents); $i++) { $c = $page_contents[$i]; if ($uncompleted_curly_brackets == 0) { if ($c == "{" || $i == strlen($page_contents) - 1) { if ($i == strlen($page_contents) - 1) { $free_text .= $c; } $uncompleted_curly_brackets++; $free_text = trim($free_text); $free_text = str_replace('&', '&', $free_text); $free_text = str_replace('[', '[', $free_text); $free_text = str_replace(']', ']', $free_text); $free_text = str_replace('<', '<', $free_text); $free_text = str_replace('>', '>', $free_text); if ($free_text != "") { $text .= "<{$free_text_str} id=\"{$free_text_id}\">{$free_text}</{$free_text_str}>"; $free_text = ""; $free_text_id++; } } elseif ($c == "{") { // do nothing } else { $free_text .= $c; } } elseif ($uncompleted_curly_brackets == 1) { if ($c == "{") { $uncompleted_curly_brackets++; $creating_template_name = true; } elseif ($c == "}") { $uncompleted_curly_brackets--; // is this needed? // if ($field_name != "") { // $field_name = ""; // } if ($page_contents[$i - 1] == '}') { if ($simplified_format) { $text .= "</" . $template_name . ">"; } else { $text .= "</{$template_label}>"; } } $template_name = ""; } } else { // 2 or greater - probably 2 if ($c == "}") { $uncompleted_curly_brackets--; } if ($c == "{") { $uncompleted_curly_brackets++; } else { if ($creating_template_name) { if ($c == "|" || $c == "}") { $template_name = str_replace(' ', '_', trim($template_name)); $template_name = str_replace('&', '&', $template_name); if ($simplified_format) { $text .= "<" . $template_name . ">"; } else { $text .= "<{$template_label} {$name_str}=\"{$template_name}\">"; } $creating_template_name = false; $creating_field_name = true; $field_id = 1; } else { $template_name .= $c; } } else { if ($c == "|" || $c == "}") { if ($field_has_name) { $field_value = str_replace('&', '&', $field_value); if ($simplified_format) { $field_name = str_replace(' ', '_', trim($field_name)); $text .= "<" . $field_name . ">"; $text .= trim($field_value); $text .= "</" . $field_name . ">"; } else { $text .= "<{$field_str} {$name_str}=\"" . trim($field_name) . "\">"; $text .= trim($field_value); $text .= "</{$field_str}>"; } $field_value = ""; $field_has_name = false; } else { // "field_name" is actually the value if ($simplified_format) { $field_name = str_replace(' ', '_', $field_name); // add "Field" to the beginning of the file name, since // XML tags that are simply numbers aren't allowed $text .= "<" . $field_str . '_' . $field_id . ">"; $text .= trim($field_name); $text .= "</" . $field_str . '_' . $field_id . ">"; } else { $text .= "<{$field_str} {$name_str}=\"{$field_id}\">"; $text .= trim($field_name); $text .= "</{$field_str}>"; } $field_id++; } $creating_field_name = true; $field_name = ""; } elseif ($c == "=") { // handle case of = in value if (!$creating_field_name) { $field_value .= $c; } else { $creating_field_name = false; $field_has_name = true; } } elseif ($creating_field_name) { $field_name .= $c; } else { $field_value .= $c; } } } } } // handle groupings, if any apply here; first check if SMW is installed global $smwgIP; if (isset($smwgIP)) { $store = smwfGetStore(); foreach ($groupings as $pair) { list($property_page, $grouping_label) = $pair; $options = new SMWRequestOptions(); $options->sort = "subject_title"; // get actual property from the wiki-page of the property if (class_exists('SMWDIProperty')) { $wiki_page = new SMWDIWikiPage($page_title, $page_namespace, null); $property = SMWDIProperty::newFromUserLabel($property_page->getTitle()->getText()); } else { $wiki_page = SMWDataValueFactory::newTypeIDValue('_wpg', $page_title); $property = SMWPropertyValue::makeProperty($property_page->getTitle()->getText()); } $res = $store->getPropertySubjects($property, $wiki_page, $options); $num = count($res); if ($num > 0) { $grouping_label = str_replace(' ', '_', $grouping_label); $text .= "<{$grouping_label}>\n"; foreach ($res as $subject) { $subject_title = $subject->getTitle(); $text .= self::getXMLForPage($subject_title, $simplified_format, $groupings, $depth + 1); } $text .= "</{$grouping_label}>\n"; } } } $text .= "</{$page_str}>\n"; // escape back the curly brackets that were escaped out at the beginning $text = str_replace('&#123;', '{', $text); $text = str_replace('&#125;', '}', $text); return $text; }
/** * Helper function used in this class, as well as by the * Semantic Internal Objects extension * * @param Parser &$parser The current parser * @return either null, or an array of main property name, set of * all date strings, and the unused params */ public static function getDatesForRecurringEvent($params) { // Initialize variables. $all_date_strings = array(); $unused_params = array(); $property_name = $start_date = $end_date = $unit = $period = $week_num = null; $included_dates = array(); $excluded_dates_jd = array(); // Set values from the parameters. foreach ($params as $param) { $parts = explode('=', trim($param)); if (count($parts) != 2) { continue; } list($name, $value) = $parts; switch ($name) { case 'property': $property_name = $value; break; case 'start': $start_date = SMWDataValueFactory::newTypeIDValue('_dat', $value); break; case 'end': $end_date = SMWDataValueFactory::newTypeIDValue('_dat', $value); break; case 'unit': $unit = $value; break; case 'period': $period = (int) $value; break; case 'week number': $week_num = (int) $value; break; case 'include': $included_dates = explode(';', $value); break; case 'exclude': $excluded_dates = explode(';', $value); foreach ($excluded_dates as $date_str) { $date = SMWDataValueFactory::newTypeIDValue('_dat', $date_str); $excluded_dates_jd[] = self::getJD($date); } break; default: $unused_params[] = $param; } } // We need at least a property and start date - if either one is null, exit here. if (is_null($property_name) || is_null($start_date)) { return; } // If the period is null, or outside of normal bounds, set it to 1. if (is_null($period) || $period < 1 || $period > 500) { $period = 1; } // Handle 'week number', but only if it's of unit 'month'. if ($unit == 'month' && !is_null($week_num)) { $unit = 'dayofweekinmonth'; if ($week_num < -4 || $week_num > 5 || $week_num == 0) { $week_num = null; } } if ($unit == 'dayofweekinmonth' && is_null($week_num)) { $week_num = ceil($start_date->getDay() / 7); } // Get the Julian day value for both the start and end date. $end_date_jd = self::getJD($end_date); $cur_date = $start_date; $cur_date_jd = self::getJD($cur_date); $i = 0; do { $i++; $exclude_date = in_array($cur_date_jd, $excluded_dates_jd); if (!$exclude_date) { $all_date_strings[] = $cur_date->getLongWikiText(); } // Now get the next date. // Handling is different depending on whether it's // month/year or week/day since the latter is a set // number of days while the former isn't. if ($unit === 'year' || $unit == 'month') { $cur_year = $cur_date->getYear(); $cur_month = $cur_date->getMonth(); $cur_day = $start_date->getDay(); $cur_time = $cur_date->getTimeString(); if ($unit == 'year') { $cur_year += $period; $display_month = $cur_month; } else { // $unit === 'month' $cur_month += $period; $cur_year += (int) (($cur_month - 1) / 12); $cur_month %= 12; $display_month = $cur_month == 0 ? 12 : $cur_month; } // If the date is February 29, and this isn't // a leap year, change it to February 28. if ($cur_month == 2 && $cur_day == 29) { if (!date('L', strtotime("{$cur_year}-1-1"))) { $cur_day = 28; } } $date_str = "{$cur_year}-{$display_month}-{$cur_day} {$cur_time}"; $cur_date = SMWDataValueFactory::newTypeIDValue('_dat', $date_str); $all_date_strings = array_merge($all_date_strings, $included_dates); $cur_date_jd = $cur_date->getDataItem()->getJD(); } elseif ($unit == 'dayofweekinmonth') { // e.g., "3rd Monday of every month" $prev_month = $cur_date->getMonth(); $prev_year = $cur_date->getYear(); $new_month = ($prev_month + $period) % 12; if ($new_month == 0) { $new_month = 12; } $new_year = $prev_year + floor(($prev_month + $period - 1) / 12); $cur_date_jd += 28 * $period - 7; // We're sometime before the actual date now - // keep incrementing by a week, until we get there. do { $cur_date_jd += 7; $cur_date = self::jdToTimeValue($cur_date_jd); $right_month = $cur_date->getMonth() == $new_month; if ($week_num < 0) { $next_week_jd = $cur_date_jd; do { $next_week_jd += 7; $next_week_date = self::jdToTimeValue($next_week_jd); $right_week = $next_week_date->getMonth() != $new_month || $next_week_date->getYear() != $new_year; } while (!$right_week); $cur_date_jd = $next_week_jd + 7 * $week_num; $cur_date = self::jdToTimeValue($cur_date_jd); } else { $cur_week_num = ceil($cur_date->getDay() / 7); $right_week = $cur_week_num == $week_num; if ($week_num == 5 && $cur_date->getMonth() % 12 == ($new_month + 1) % 12) { $cur_date_jd -= 7; $cur_date = self::jdToTimeValue($cur_date_jd); $right_month = $right_week = true; } } } while (!$right_month || !$right_week); } else { // $unit == 'day' or 'week' // Assume 'day' if it's none of the above. $cur_date_jd += $unit === 'week' ? 7 * $period : $period; $cur_date = self::jdToTimeValue($cur_date_jd); } // should we stop? if (is_null($end_date)) { global $smwgDefaultNumRecurringEvents; $reached_end_date = $i > $smwgDefaultNumRecurringEvents; } else { global $smwgMaxNumRecurringEvents; $reached_end_date = $cur_date_jd > $end_date_jd || $i > $smwgMaxNumRecurringEvents; } } while (!$reached_end_date); // Handle the 'include' dates as well. $all_date_strings = array_filter(array_merge($all_date_strings, $included_dates)); return array($property_name, $all_date_strings, $unused_params); }
function smwf_qi_QIAccess($method, $params) { $p_array = explode(",", $params); global $smwgQEnabled; if ($method == "getPropertyInformation") { return qiGetPropertyInformation($p_array[0]); } else { if ($method == "getPropertyTypes") { $p_array = func_get_args(); $types = "<propertyTypes>"; for ($i = 1; $i < count($p_array); $i++) { $types .= qiGetPropertyInformation($p_array[$i]); } $types .= "</propertyTypes>"; return $types; } else { if ($method == "getNumericTypes") { $numtypes = array(); $types = SMWDataValueFactory::getKnownTypeLabels(); foreach ($types as $v) { $id = SMWDataValueFactory::findTypeID($v); if (SMWDataValueFactory::newTypeIDValue($id)->isNumeric()) { array_push($numtypes, strtolower($v)); } } return implode(",", $numtypes); } else { if ($method == "getQueryResult") { $result = "null"; if ($smwgQEnabled) { // read fix parameters from QI GUI $params = count($p_array) > 1 ? explode("|", $p_array[1]) : array(); $fixparams = array(); foreach ($params as $p) { if (strlen($p) > 0 && strpos($p, "=") !== false) { list($key, $value) = explode("=", $p); $fixparams[trim($key)] = str_replace('%2C', ',', $value); } } // indicate that it comes from an ajax call $fixparams['ajaxCall'] = true; // fix bug 10812: if query string contains a , $p_array[0] = str_replace('%2C', ',', $p_array[0]); // read query with printouts and (possibly) other parameters like sort, order, limit, etc... $pos = strpos($p_array[0], "|?"); if ($pos > 0) { $rawparams[] = trim(substr($p_array[0], 0, $pos)); $ps = explode("|?", trim(substr($p_array[0], $pos + 2))); foreach ($ps as $param) { $rawparams[] = "?" . trim($param); } } else { $ps = preg_split('/[^\\|]{1}\\|{1}(?!\\|)/s', $p_array[0]); if (count($ps) > 1) { // last char of query condition is missing (matched with [^\|]{1}) therefore copy from original $rawparams[] = trim(substr($p_array[0], 0, strlen($ps[0]) + 1)); array_shift($ps); // remove the query condition // add other params for formating etc. foreach ($ps as $param) { $rawparams[] = trim($param); } } else { $rawparams[] = trim($p_array[0]); } } $rawparams = array_merge($rawparams, $fixparams); // set some default values, if params are not set if (!in_array('reasoner', array_keys($fixparams))) { $fixparams['reasoner'] = 'ask'; } if (!in_array('format', array_keys($fixparams))) { $fixparams['format'] = 'table'; } // use SMW classes or TSC classes and parse params and answer query if ($fixparams['reasoner'] == 'ask') { SMWQueryProcessor::processFunctionParams($rawparams, $querystring, $params, $printouts); } else { if ($fixparams['reasoner'] == 'sparql') { SMWSPARQLQueryProcessor::processFunctionParams($rawparams, $querystring, $params, $printouts); } } // check if there is any result and if it corresponds to the selected format $mainlabel = isset($rawparams['mainlabel']) && $rawparams['mainlabel'] == '-'; $invalidRes = smwf_qi_CheckValidResult($printouts, $fixparams['format'], $mainlabel); if ($invalidRes != 0) { return wfMsg('smw_qi_printout_err' . $invalidRes); } // quickfix: unset conflicting params for maps if (in_array($fixparams['format'], array("map", "googlemaps2", "openlayers", "yahoomaps"))) { if (isset($params['reasoner'])) { unset($params['reasoner']); } if (isset($params['ajaxcall'])) { unset($params['ajaxcall']); } if (isset($params['merge'])) { unset($params['merge']); } } // answer query using the SMW classes or TSC classes if ($fixparams['reasoner'] == 'ask') { $result = SMWQueryProcessor::getResultFromQueryString($querystring, $params, $printouts, SMW_OUTPUT_WIKI); } else { if ($fixparams['reasoner'] == 'sparql') { $result = SMWSPARQLQueryProcessor::getResultFromQueryString($querystring, $params, $printouts, SMW_OUTPUT_WIKI); } } // check for empty result if (is_array($result) && trim($result[0]) == '' || trim($result == '')) { return wfMsg('smw_qi_printout_err4'); } switch ($fixparams['format']) { case 'timeline': case 'exhibit': case 'eventline': return $result; break; case 'gallery': case 'googlepie': case 'googlebar': case 'ofc-pie': case 'ofc-bar': case 'ofc-bar_3d': case 'ofc-line': case 'ofc-scatterline': return is_array($result) ? $result[0] : $result; break; case 'map': case 'googlemaps2': case 'openlayers': case 'yahoomaps': return wfMsg('smw_qi_printout_notavailable'); default: } $result = parseWikiText($result); // add target="_new" for all links $pattern = "|<a|i"; $result = preg_replace($pattern, '<a target="_new"', $result); return $result; } } else { if ($method == "getQueryResultForDownload") { $result = "null"; if ($smwgQEnabled) { $params = array('format' => $p_array[1], 'link' => $p_array[2], 'intro' => $p_array[3], 'sort' => $p_array[4], 'limit' => $p_array[5], 'mainlabel' => $p_array[6], 'order' => $p_array[7], 'default' => $p_array[8], 'headers' => $p_array[9]); $result = applyQueryHighlighting($p_array[0], $params); // add target="_new" for all links $pattern = "|<a|i"; $result = preg_replace($pattern, '<a target="_new"', $result); } if ($result != "null" && $result != "") { global $request_query; $request_query = true; } return $result; } else { if ($method == "getSupportedParameters") { global $smwgResultFormats; wfLoadExtensionMessages('SemanticMediaWiki'); $format = $p_array[0]; if (array_key_exists($format, $smwgResultFormats)) { $formatclass = $smwgResultFormats[$format]; } else { $formatclass = "SMWListResultPrinter"; } // fix for missing parameter order $order_missing = true; $intro_missing = true; $outro_missing = true; $qp = new $formatclass($format, false); $params = $qp->getParameters(); // repair some misplaced parameters for ($i = 0; $i < count($params); $i++) { switch ($params[$i]['name']) { case "order": $order_missing = false; break; case "template": if ($format != "template") { array_splice($params, $i, 1); } break; case "intro": if (substr($format, 0, 4) != "ofc-") { $intro_missing = false; } break; case "outro": if (substr($format, 0, 4) != "ofc-") { $outro_missing = false; } break; case "headers": if ($format != "table" && $format != "broadtable") { array_splice($params, $i, 1); } break; } } if ($order_missing) { $params[] = array('name' => 'order', 'type' => 'enumeration', 'description' => wfMsg('smw_qi_tt_order'), 'values' => array('ascending', 'descending')); } if ($intro_missing) { $params[] = array('name' => 'intro', 'type' => 'string', 'description' => wfMsg('smw_qi_tt_intro')); } if ($outro_missing) { $params[] = array('name' => 'outro', 'type' => 'string', 'description' => wfMsg('smw_qi_tt_outro')); } $jsonEnc = new Services_JSON(); return $jsonEnc->encode($params); } else { return "false"; } } } } } } }
private function getLiteral($literal, $predicate) { list($literalValue, $literalType) = $literal; if (!empty($literalValue)) { // create SMWDataValue either by property or if that is not possible by the given XSD type if ($predicate instanceof SMWPropertyValue) { $value = SMWDataValueFactory::newPropertyObjectValue($predicate, $literalValue); } else { $value = SMWDataValueFactory::newTypeIDValue(WikiTypeToXSD::getWikiType($literalType)); } if ($value->getTypeID() == '_dat') { // exception for dateTime if ($literalValue != '') { $value->setDBkeys(array(str_replace("-", "/", $literalValue))); } } else { if ($value->getTypeID() == '_ema') { // exception for email $value->setDBkeys(array($literalValue)); } else { $value->setUserValue($literalValue); } } } else { if ($predicate instanceof SMWPropertyValue) { $value = SMWDataValueFactory::newPropertyObjectValue($predicate); } else { $value = SMWDataValueFactory::newTypeIDValue('_wpg'); } } return $value; }
/** * Check if property is range restricted and, if so, whether the current value is allowed. * Creates an error if the value is illegal. */ protected function checkAllowedValues() { if (!is_null($this->m_property)) { $propertyDiWikiPage = $this->m_property->getDiWikiPage(); } if (is_null($this->m_property) || is_null($propertyDiWikiPage) || !isset($this->m_dataitem)) { return; // no property known, or no data to check } $allowedvalues = smwfGetStore()->getPropertyValues($propertyDiWikiPage, new SMWDIProperty('_PVAL')); if (count($allowedvalues) == 0) { return; } $hash = $this->m_dataitem->getHash(); $testdv = SMWDataValueFactory::newTypeIDValue($this->getTypeID()); $accept = false; $valuestring = ''; foreach ($allowedvalues as $di) { if ($di instanceof SMWDIBlob) { $testdv->setUserValue($di->getString()); if ($hash === $testdv->getDataItem()->getHash()) { $accept = true; break; } else { if ($valuestring !== '') { $valuestring .= ', '; } $valuestring .= $di->getString(); } } } if (!$accept) { $this->addError(wfMessage('smw_notinenum', $this->getWikiValue(), $valuestring)->inContentLanguage()->text()); } }
/** * * Similar to getSemanticData(), but in this case regarding the Semantic Web. * @param String $uri */ private function getSemanticWebData( $graph, $uri ) { // Several possibilities: URI with redirect to RDF, URL with RDFa (but talking about what?),... // $data is of type SMWSemanticData $semanticDataResult = new SMWSemanticData( $this->subject->getDataItem() ); // I want to show all incoming and outcoming links // ...ideally in the same style // Get the representation of the URI $theResource = $graph->resource( $uri ); // Outgoing $theOutgoingProperties = $graph->propertyUris( $theResource ); // for each, ask for the objects foreach ( $theOutgoingProperties as $outProp ) { $outPropResult = $this->getArrayObjects( $graph, $theResource, $outProp ); // now, we have the subject, the property, the object (uri/literal) foreach ( $outPropResult as $outPropObject ) { /* * The question now is, what kind of propert. * If there is a page in the wiki, we simply use it as property. * Otherwise, we need to invent a new page with the URI as name */ $uriPageName = $this->getInternalMapping( $outProp ); $dataProperty = null; if ( !isset( $uriPageName ) || $uriPageName == null) { // There is no, we create a new property page /* * TODO: maybe register new property type that can display the property more * conveniently, e.g., with browse further: smwInitProperties */ $dataProperty = SMWDIProperty::newFromUserLabel( $outProp ); } else { $dataProperty = SMWDIProperty::newFromUserLabel( $uriPageName ); } // SMWDataItem, we only distinguish uri and literal // TODO: Maybe distinguish more, later, e.g., language $dataValue = null; if ( $outPropObject["type"] == "uri" ) { /* * If there is a page in the wiki with the value as equivalent URI, we * just use this page. */ $uriPageName = $this->getInternalMapping( $outPropObject["value"] ); if ( !isset( $uriPageName ) && $uriPageName == null ) { // URI value $dataValue = SMWDataValueFactory::newTypeIDValue( '_rur', $outPropObject["value"], $property = $dataProperty ); } else { $dataValue = SMWDataValueFactory::newTypeIDValue( '_wpg', $uriPageName, $property = $dataProperty ); } } else { // literal $this->debug($outPropObject["value"],"vis:"); $dataValue = SMWDataValueFactory::newTypeIDValue( '_txt', $outPropObject["value"], $property = $dataProperty ); //$dataItem = new SMWDIString($outPropObject["value"]); } // some objects have invalid type and print warning triangle instead of object info //in this case object has class SMWDIError // in this case this object wouldn't be printed if( !( get_class( $dataValue->getDataItem() ) == "SMWDIError" ) ){ $semanticDataResult->addPropertyObjectValue( $dataProperty, $dataValue->getDataItem() ); } } } return $semanticDataResult; }
/** * Creates SMWWikiPageValue object from a (possibly) merged result. * * @param string $uri Full URI * @param hash array $metadata (propertyName=>value) * @param string $nsFragment NS-prefix * @param int $ns Namespace index * @return SMWWikiPageValue */ protected function createSMWDataValue($uri, $metadata, $nsFragment, $ns) { $local = substr($uri, strlen($nsFragment)); $title = Title::newFromText($local, $ns); if (is_null($title)) { $title = Title::newFromText(wfMsg('smw_ob_invalidtitle'), $ns); } $v = SMWDataValueFactory::newTypeIDValue('_wpg'); $v->setValues($title->getDBkey(), $ns, $title->getArticleID()); foreach ($metadata as $mdProperty => $mdValue) { if (strpos($mdProperty, "_meta_") === 0) { $v->setMetadata(substr($mdProperty, 6), explode("|||", $mdValue)); } } return $v; }
static function getXMLForPage($title, $simplified_format, $groupings, $depth = 0) { if ($depth > 5) { return ""; } global $wgContLang, $dtgContLang; // if this page belongs to the exclusion category, exit $parent_categories = $title->getParentCategoryTree(array()); $dt_props = $dtgContLang->getPropertyLabels(); // $exclusion_category = $title->newFromText($dt_props[DT_SP_IS_EXCLUDED_FROM_XML], NS_CATEGORY); $exclusion_category = $wgContLang->getNSText(NS_CATEGORY) . ':' . str_replace(' ', '_', $dt_props[DT_SP_IS_EXCLUDED_FROM_XML]); if (self::treeContainsElement($parent_categories, $exclusion_category)) { return ""; } $pageStructure = DTPageStructure::newFromTitle($title); $text = $pageStructure->toXML($simplified_format); // handle groupings, if any apply here; first check if SMW is installed global $smwgIP; if (isset($smwgIP)) { $store = smwfGetStore(); $page_title = $title->getText(); $page_namespace = $title->getNamespace(); // Escaping is needed for SMWSQLStore3 - this may be a bug in SMW. $escaped_page_title = str_replace(' ', '_', $page_title); foreach ($groupings as $pair) { list($property_page, $grouping_label) = $pair; $options = new SMWRequestOptions(); $options->sort = "subject_title"; // get actual property from the wiki-page of the property if (class_exists('SMWDIProperty')) { $wiki_page = new SMWDIWikiPage($escaped_page_title, $page_namespace, null); $property = SMWDIProperty::newFromUserLabel($property_page->getTitle()->getText()); } else { $wiki_page = SMWDataValueFactory::newTypeIDValue('_wpg', $escaped_page_title); $property = SMWPropertyValue::makeProperty($property_page->getTitle()->getText()); } $res = $store->getPropertySubjects($property, $wiki_page, $options); $num = count($res); if ($num > 0) { $grouping_label = str_replace(' ', '_', $grouping_label); $text .= "<{$grouping_label}>\n"; foreach ($res as $subject) { $subject_title = $subject->getTitle(); $text .= self::getXMLForPage($subject_title, $simplified_format, $groupings, $depth + 1); } $text .= "</{$grouping_label}>\n"; } } } // escape back the curly brackets that were escaped out at the beginning $text = str_replace('&#123;', '{', $text); $text = str_replace('&#125;', '}', $text); return $text; }
/** * Extract a date string formatted for iCalendar from a SMWTimeValue object. */ static private function parsedate( SMWTimeValue $dv, $isend = false ) { $year = $dv->getYear(); if ( ( $year > 9999 ) || ( $year < -9998 ) ) return ''; // ISO range is limited to four digits $year = number_format( $year, 0, '.', '' ); $time = str_replace( ':', '', $dv->getTimeString( false ) ); if ( ( $time == false ) && ( $isend ) ) { // increment by one day, compute date to cover leap years etc. $dv = SMWDataValueFactory::newTypeIDValue( '_dat', $dv->getWikiValue() . 'T00:00:00-24:00' ); } $month = $dv->getMonth(); if ( strlen( $month ) == 1 ) $month = '0' . $month; $day = $dv->getDay(); if ( strlen( $day ) == 1 ) $day = '0' . $day; $result = $year . $month . $day; if ( $time != false ) $result .= "T$time"; return $result; }
/** * Modify the given query object to account for some property condition for the given property. * The parameter $property may be a property object or an internal storage id. This is what makes * this method useful: it can be used even with internal properties that have no MediaWiki Title. * $typeid is set if property ids are used, since internal properties may not have a defined type. * Some properties cannot be queried for; in this case, the query type is changed to SMW_SQL2_NOQUERY. * Callers need to check for this. */ protected function compilePropertyCondition(&$query, $property, SMWDescription $valuedesc, $typeid = false) { $query->joinfield = "{$query->alias}.s_id"; if ($property instanceof SMWPropertyValue) { $typeid = $property->getPropertyTypeID(); $mode = SMWSQLStore2::getStorageMode($typeid); $pid = $this->m_store->getSMWPropertyID($property); $sortkey = $property->getDBkey(); // / TODO: strictly speaking, the DB key is not what we want here, since sortkey is based on a "wiki value" if ($mode != SMW_SQL2_SUBS2) { // also make property hierarchy (though not for all properties) $pqid = SMWSQLStore2Query::$qnum; $pquery = new SMWSQLStore2Query(); $pquery->type = SMW_SQL2_PROP_HIERARCHY; $pquery->joinfield = array($pid); $query->components[$pqid] = "{$query->alias}.p_id"; $this->m_queries[$pqid] = $pquery; } } else { $pid = $property; $sortkey = false; $mode = SMWSQLStore2::getStorageMode($typeid); if ($mode != SMW_SQL2_SUBS2) { // no property hierarchy, but normal query (not for all properties) $query->where = "{$query->alias}.p_id=" . $this->m_dbs->addQuotes($pid); } } $mode = SMWSQLStore2::getStorageMode($typeid); $sortfield = ''; // used if we should sort by this property switch ($mode) { case SMW_SQL2_RELS2: case SMW_SQL2_SUBS2: // subconditions as subqueries (compiled) $query->jointable = $mode == SMW_SQL2_RELS2 ? 'smw_rels2' : 'smw_subs2'; $sub = $this->compileQueries($valuedesc); if ($sub >= 0) { $query->components[$sub] = "{$query->alias}.o_id"; } if ($sortkey && array_key_exists($sortkey, $this->m_sortkeys)) { $query->from = ' INNER JOIN ' . $this->m_dbs->tableName('smw_ids') . " AS ids{$query->alias} ON ids{$query->alias}.smw_id={$query->alias}.o_id"; $sortfield = "ids{$query->alias}.smw_title"; // / TODO: as below, smw_ids here is possibly duplicated! Can we prevent that? (PERFORMANCE) } break; case SMW_SQL2_NARY2: $query->jointable = 'smw_rels2'; if ($valuedesc instanceof SMWValueList) { // anything else is ignored! $typevalue = $property->getTypesValue(); $typelabels = $typevalue->getTypeLabels(); reset($typelabels); $subqid = SMWSQLStore2Query::$qnum; $subquery = new SMWSQLStore2Query(); $subquery->type = SMW_SQL2_CONJUNCTION; $query->components[$subqid] = "{$query->alias}.o_id"; $this->m_queries[$subqid] = $subquery; for ($i = 0; $i < $valuedesc->getCount(); $i++) { $desc = $valuedesc->getDescription($i); if ($desc !== NULL) { $stypeid = SMWDataValueFactory::findTypeID(current($typelabels)); $valpid = $this->m_store->getSMWPageID(strval($i), SMW_NS_PROPERTY, SMW_SQL2_SMWIW); $valqid = SMWSQLStore2Query::$qnum; $valquery = new SMWSQLStore2Query(); $this->compilePropertyCondition($valquery, $valpid, $desc, $stypeid); if ($valquery->type != SMW_SQL2_NOQUERY) { $subquery->components[$valqid] = true; $this->m_queries[$valqid] = $valquery; } } next($typelabels); } } break; case SMW_SQL2_TEXT2: // no subconditions $query->jointable = 'smw_text2'; break; case SMW_SQL2_ATTS2: case SMW_SQL2_SPEC2: // subquery only conj/disj of values, compile to single "where" $query->jointable = $mode == SMW_SQL2_ATTS2 ? 'smw_atts2' : 'smw_spec2'; $aw = $this->compileAttributeWhere($valuedesc, "{$query->alias}"); if ($aw != '') { $query->where .= ($query->where ? ' AND ' : '') . $aw; } if ($sortkey && array_key_exists($sortkey, $this->m_sortkeys)) { if ($mode == SMW_SQL2_ATTS2) { $sortfield = "{$query->alias}." . (SMWDataValueFactory::newTypeIDValue($typeid)->isNumeric() ? 'value_num' : 'value_xsd'); } else { $sortfield = "{$query->alias}.value_string"; } } break; default: // drop this query $query->type = SMW_SQL2_NOQUERY; $sortfield = false; } if ($sortfield) { $query->sortfields[$sortkey] = $sortfield; } }
/** * Insert new pages into endpoint. Used to import data. * @param $title */ private function insertData(Title $title, $pageid) { $newpage = SMWDataValueFactory::newTypeIDValue('_wpg'); $newpage->setValues($title->getDBkey(), $title->getNamespace(), $pageid); $semdata = $this->getSemanticData($newpage); $this->updateData($semdata); }
/** * This method extract a date string formatted for ganttchart from a SMWTimeValue object. * * @param $dv SMWTimeValue, date that is to be converted * @return string in form MM/DD/YYYY HH:MM:SS */ public function getGanttDate(SMWTimeValue $dv, $isend = false) { $year = $dv->getYear(); if ($year > 9999 || $year < -9998) { return ''; } // ISO range is limited to four digits $year = number_format($year, 0, '.', ''); $time = $dv->getTimeString(false); if ($time == false && $isend) { // increment by one day, compute date to cover leap years etc. $dv = SMWDataValueFactory::newTypeIDValue('_dat', $dv->getWikiValue() . 'T00:00:00+24:00'); } $month = $dv->getMonth(); if (strlen($month) == 1) { $month = '0' . $month; } $day = $dv->getDay(); if (strlen($day) == 1) { $day = '0' . $day; } $result = $month . '/' . $day . '/' . $year; if ($time != false) { $result .= " {$time}"; } return $result; }
/** * Parse an article description (the part of an inline query that * is in between "[[" and the closing "]]" assuming it is not specifying * a category or property) and create a suitable description. * The first chunk behind the "[[" has already been read and is * passed as a parameter. */ protected function getArticleDescription($firstchunk, &$setNS) { $chunk = $firstchunk; $result = null; $continue = true; // $innerdesc = null; while ($continue) { if ($chunk == '<q>') { // no subqueries of the form [[<q>...</q>]] (not needed) $this->m_errors[] = wfMessage('smw_misplacedsubquery')->inContentLanguage()->text(); return null; } $list = preg_split('/:/', $chunk, 3); // ":Category:Foo" "User:bar" ":baz" ":+" if ($list[0] === '' && count($list) == 3) { $list = array_slice($list, 1); } if (count($list) == 2 && $list[1] == '+') { // try namespace restriction global $wgContLang; $idx = $wgContLang->getNsIndex(str_replace(' ', '_', $list[0])); if ($idx !== false) { $result = $this->addDescription($result, new SMWNamespaceDescription($idx), false); } } else { $value = SMWDataValueFactory::newTypeIDValue('_wpg', $chunk); if ($value->isValid()) { $result = $this->addDescription($result, new SMWValueDescription($value->getDataItem(), null), false); } } $chunk = $this->readChunk('\\[\\[|\\]\\]|\\|\\||\\|'); if ($chunk == '||') { $chunk = $this->readChunk('\\[\\[|\\]\\]|\\|\\||\\|'); $continue = true; } else { $continue = false; } } return $this->finishLinkDescription($chunk, true, $result, $setNS); }
/** * Having a title of a page, what is the URI that is described by that page? * The result still requires expandURI() * @param string $title * @return string $uri */ protected function getURI( $title ) { $uri = ""; if ( $title instanceof Title ) { $dv = SMWDataValueFactory::newTypeIDValue( '_wpg' ); $dv->setTitle( $title ); $exp = $dv->getExportData(); $uri = $exp->getSubject()->getUri(); } else { // There could be other types as well that we do NOT handle here } return $uri; // still requires expandURI() }
private static function formatWSResultWithSMWQPs($wsResults, $configArgs, $wsParameters, $wsReturnValues, $smwQueryMode) { //do sorting $wsResults = self::sortWSResult($wsResults, $configArgs); //deal with limit and offset list($wsResults, $furtherResults) = self::formatWithLimitAndOffset($wsResults, $configArgs); $format = array_key_exists('format', $configArgs) ? $configArgs['format'] : ''; //todo: create print requests array for constructor below $printRequests = array(); $queryResults = array(); $typeIds = array(); //get Type ids $numTypeFormats = array('sum' => true, 'min' => true, 'max' => true, 'average' => true); foreach ($wsResults as $columnLabel => $values) { if (array_key_exists(strtolower($format), $numTypeFormats)) { $typeIds[$columnLabel] = '_num'; } else { $typeIds[$columnLabel] = '_txt'; } } //create print requests foreach ($wsReturnValues as $id => $label) { $id = ucfirst(substr($id, strpos($id, '.') + 1)); if (!$label) { $label = $id; } $printRequests[$id] = new SMWPrintRequest(SMWPrintRequest::PRINT_THIS, $label, $id); } //transpose ws result foreach ($wsResults as $columnLabel => $values) { foreach ($values as $key => $value) { $queryResultColumnValues = array(); $resultInstance = SMWDataValueFactory::newTypeIDValue('_wpg'); $title = Title::newFromText(wfMsg('smw_ob_invalidtitle'), ''); $resultInstance->setValues($title->getDBkey(), $title->getNamespace(), $title->getArticleID(), false, '', $title->getFragment()); $dataValue = SMWDataValueFactory::newTypeIDValue($typeIds[$columnLabel]); $dataValue->setUserValue($value); $queryResultColumnValues[] = $dataValue; //this is necessary, because one can edit with the properties //parameter of the LDConnector additional columns if (!array_key_exists(ucfirst($columnLabel), $printRequests)) { $printRequests[ucfirst($columnLabel)] = new SMWPrintRequest(SMWPrintRequest::PRINT_THIS, $columnLabel, ucfirst($columnLabel)); } $queryResultColumnValues = new SMWWSResultArray($resultInstance, $printRequests[ucfirst($columnLabel)], $queryResultColumnValues); @($queryResults[$key][$columnLabel] = $queryResultColumnValues); } } //translate ws call to SMW ask query $queryParams = array(); foreach ($wsParameters as $param => $value) { $queryParams['_' . $param] = $value; } foreach ($configArgs as $param => $value) { $queryParams[$param] = $value; } $queryParams['source'] = 'webservice'; $queryParams['webservice'] = $configArgs['webservice']; //create query object $query = SMWQueryProcessor::createQuery('[[dummy]]', $queryParams, SMWQueryProcessor::INLINE_QUERY, $format, $printRequests); $query->params = $queryParams; //create query result object $queryResult = new SMWWSQueryResult($printRequests, $query, $queryResults, new SMWWSSMWStore(), $furtherResults); //deal with count mode if ($format == 'count') { return count($queryResults); } //return the query result object if this is called by special:ask if ($smwQueryMode) { return $queryResult; } $printer = SMWQueryProcessor::getResultPrinter($format, SMWQueryProcessor::INLINE_QUERY); $result = $printer->getResult($queryResult, $configArgs, SMW_OUTPUT_WIKI); return $result; }
public function execute($query) { global $wgRequest, $wgOut; $linker = smwfGetLinker(); $this->setHeaders(); // Get parameters $pagename = $wgRequest->getVal('from'); $propname = $wgRequest->getVal('type'); $limit = $wgRequest->getVal('limit'); $offset = $wgRequest->getVal('offset'); if ($limit === '') { $limit = 20; } if ($offset === '') { $offset = 0; } if ($propname === '') { // No GET parameters? Try the URL: $queryparts = explode('::', $query); $propname = $query; if (count($queryparts) > 1) { $pagename = $queryparts[0]; $propname = implode('::', array_slice($queryparts, 1)); } } $subject = SMWDataValueFactory::newTypeIDValue('_wpg', $pagename); $pagename = $subject->isValid() ? $subject->getPrefixedText() : ''; $property = SMWPropertyValue::makeUserProperty($propname); $propname = $property->isValid() ? $property->getWikiValue() : ''; // Produce output $html = ''; if ($propname === '') { // no property given, show a message $html .= wfMsg('smw_pp_docu') . "\n"; } else { // property given, find and display results // FIXME: very ugly, needs i18n $wgOut->setPagetitle(($pagename !== '' ? $pagename . ' ' : '') . $property->getWikiValue()); // get results (get one more, to see if we have to add a link to more) $options = new SMWRequestOptions(); $options->limit = $limit + 1; $options->offset = $offset; $options->sort = true; $results = smwfGetStore()->getPropertyValues($pagename !== '' ? $subject->getDataItem() : null, $property->getDataItem(), $options); // prepare navigation bar if needed if ($offset > 0 || count($results) > $limit) { if ($offset > 0) { $navigation = Html::element('a', array('href' => $this->getTitle()->getLocalURL(array('offset' => max(0, $offset - $limit), 'limit' => $limit, 'type' => $propname, 'from' => $pagename))), wfMsg('smw_result_prev')); } else { $navigation = wfMsg('smw_result_prev'); } $navigation .= '     <b>' . wfMsg('smw_result_results') . ' ' . ($offset + 1) . '– ' . ($offset + min(count($results), $limit)) . '</b>    '; if (count($results) == $limit + 1) { $navigation = Html::element('a', array('href' => $this->getTitle()->getLocalURL(array('offset' => $offset + $limit, 'limit' => $limit, 'type' => $propname, 'from' => $pagename))), wfMsg('smw_result_next')); } else { $navigation .= wfMsg('smw_result_next'); } } else { $navigation = ''; } // display results $html .= '<br />' . $navigation; if (count($results) == 0) { $html .= wfMsg('smw_result_noresults'); } else { $html .= "<ul>\n"; $count = $limit + 1; foreach ($results as $di) { $count--; if ($count < 1) { continue; } $dv = SMWDataValueFactory::newDataItemValue($di, $property->getDataItem()); $html .= '<li>' . $dv->getLongHTMLText($linker); // do not show infolinks, the magnifier "+" is ambiguous with the browsing '+' for '_wpg' (see below) if ($property->getDataItem()->findPropertyTypeID() == '_wpg') { $browselink = SMWInfolink::newBrowsingLink('+', $dv->getLongWikiText()); $html .= '  ' . $browselink->getHTML($linker); } $html .= "</li> \n"; } $html .= "</ul>\n"; } $html .= $navigation; } // Display query form $spectitle = $this->getTitle(); $html .= '<p> </p>'; $html .= '<form name="pageproperty" action="' . htmlspecialchars($spectitle->getLocalURL()) . '" method="get">' . "\n" . '<input type="hidden" name="title" value="' . $spectitle->getPrefixedText() . '"/>'; $html .= wfMsg('smw_pp_from') . ' <input type="text" name="from" value="' . htmlspecialchars($pagename) . '" />' . "   \n"; $html .= wfMsg('smw_pp_type') . ' <input type="text" name="type" value="' . htmlspecialchars($propname) . '" />' . "\n"; $html .= '<input type="submit" value="' . wfMsg('smw_pp_submit') . "\"/>\n</form>\n"; $wgOut->addHTML($html); SMWOutputs::commitToOutputPage($wgOut); // make sure locally collected output data is pushed to the output! }
protected function getArticleDescription( $firstchunk, &$setNS, &$label, &$relatedArticles ) { wfLoadExtensionMessages( 'SemanticMediaWiki' ); $chunk = $firstchunk; $result = NULL; $continue = true; // $innerdesc = NULL; while ( $continue ) { if ( $chunk == '<q>' ) { // no subqueries of the form [[<q>...</q>]] (not needed) $this->m_errors[] = wfMsgForContent( 'smw_misplacedsubquery' ); return NULL; } $list = preg_split( '/:/', $chunk, 3 ); // ":Category:Foo" "User:bar" ":baz" ":+" if ( ( $list[0] == '' ) && ( count( $list ) == 3 ) ) { $list = array_slice( $list, 1 ); } if ( ( count( $list ) == 2 ) && ( $list[1] == '+' ) ) { // try namespace restriction global $wgContLang; $idx = $wgContLang->getNsIndex( $list[0] ); if ( $idx !== false ) { $result = $this->addDescription( $result, new SMWNamespaceDescription( $idx ), false ); } } else { $value = SMWDataValueFactory::newTypeIDValue( '_wpg', $chunk ); if ( $value->isValid() ) { $result = $this->addDescription( $result, new SMWValueDescription( $value ), false ); // added by ning $relatedArticles[] = array( 'namespace' => NS_MAIN, 'title' => Title::makeTitle( NS_MAIN, $chunk )->getDBkey() ); } } $chunk = $this->readChunk( '\[\[|\]\]|\|\||\|' ); if ( $chunk == '||' ) { $chunk = $this->readChunk( '\[\[|\]\]|\|\||\|' ); $continue = true; } else { $continue = false; } } return $this->finishLinkDescription( $chunk, true, $result, $setNS, $label ); }
protected function parseAnnotations($response, &$annotations) { 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); $results = $dom->xpath('//result'); foreach ($results as $r) { $children = $r->children(); // binding nodes $b = $children->binding[0]; // predicate $sv = $b->children()->uri[0]; $title = TSHelper::getTitleFromURI((string) $sv); if (is_null($title)) { continue; } $predicate = SMWPropertyValue::makeUserProperty($title->getText()); $categories = array(); $b = $children->binding[1]; // categories $values = array(); foreach ($b->children()->uri as $sv) { $object = TSHelper::getTitleFromURI((string) $sv); if (TSHelper::isLocalURI((string) $sv)) { $value = SMWDataValueFactory::newPropertyObjectValue($predicate, $object); } else { $value = SMWDataValueFactory::newTypeIDValue('_uri', (string) $sv); } // add metadata $metadata = array(); foreach ($sv->attributes() as $mdProperty => $mdValue) { if (strpos($mdProperty, "_meta_") === 0) { $value->setMetadata(strtoupper($mdProperty), explode("|||", $mdValue)); } } $values[] = $value; } foreach ($b->children()->literal as $sv) { $literal = array((string) $sv, $sv->attributes()->datatype); $value = $this->getLiteral($literal, $predicate); // add metadata $metadata = array(); foreach ($sv->attributes() as $mdProperty => $mdValue) { if (strpos($mdProperty, "_meta_") === 0) { $value->setMetadata(strtoupper($mdProperty), explode("|||", $mdValue)); } } $values[] = $value; } $annotations[] = array($predicate, $values); } }
function setTypeAndPossibleValues() { if (!defined('SMW_NS_PROPERTY')) { return; } // The presence of "-" at the beginning of a property name // (which happens if SF tries to parse an inverse query) // leads to an error in SMW - just exit if that's the case. if (strpos($this->mSemanticProperty, '-') === 0) { return; } $proptitle = Title::makeTitleSafe(SMW_NS_PROPERTY, $this->mSemanticProperty); if ($proptitle === null) { return; } $store = SFUtils::getSMWStore(); // this returns an array of objects $allowed_values = SFUtils::getSMWPropertyValues($store, $proptitle, "Allows value"); $label_formats = SFUtils::getSMWPropertyValues($store, $proptitle, "Has field label format"); $propValue = SMWDIProperty::newFromUserLabel($this->mSemanticProperty); $this->mPropertyType = $propValue->findPropertyTypeID(); foreach ($allowed_values as $allowed_value) { // HTML-unencode each value $this->mPossibleValues[] = html_entity_decode($allowed_value); if (count($label_formats) > 0) { $label_format = $label_formats[0]; $prop_instance = SMWDataValueFactory::findTypeID($this->mPropertyType); $label_value = SMWDataValueFactory::newTypeIDValue($prop_instance, $wiki_value); $label_value->setOutputFormat($label_format); $this->mValueLabels[$wiki_value] = html_entity_decode($label_value->getWikiValue()); } } // HACK - if there were any possible values, set the property // type to be 'enumeration', regardless of what the actual type is if (count($this->mPossibleValues) > 0) { $this->mPropertyType = 'enumeration'; } }
/** * Callback function for hook 'SMW_SpecialValue'. It returns a data value for * the special type "_siu" (SI-Units), if requested. */ function smwfHaloSpecialValues($typeID, $value, $caption, &$result) { if ($typeID == "___cfsi") { $result = SMWDataValueFactory::newTypeIDValue('_siu', $value, $caption); } return true; }