private function doFormatFinalOutputFor($type, $linker)
 {
     $text = '';
     $languagecode = '';
     foreach ($this->dataValue->getPropertyDataItems() as $property) {
         // If we wanted to omit the language code display for some outputs then
         // this is the point to make it happen
         if (($type == self::HTML_LONG || $type == self::WIKI_SHORT) && $property->getKey() === '_LCODE') {
             //continue;
         }
         $dataItems = $this->dataValue->getDataItem()->getSemanticData()->getPropertyValues($property);
         // Should not happen but just in case
         if (!$dataItems === array()) {
             $this->dataValue->addErrorMsg('smw-datavalue-monolingual-dataitem-missing');
             continue;
         }
         $dataItem = reset($dataItems);
         if ($dataItem === false) {
             continue;
         }
         $dataValue = DataValueFactory::getInstance()->newDataValueByItem($dataItem, $property);
         $result = $this->findValueOutputFor($type, $dataValue, $linker);
         if ($property->getKey() === '_LCODE' && $type !== self::VALUE) {
             $languagecode = ' ' . Message::get(array('smw-datavalue-monolingual-lcode-parenthesis', $result));
         } elseif ($property->getKey() === '_LCODE' && $type === self::VALUE) {
             $languagecode = '@' . $result;
         } else {
             $text = $result;
         }
     }
     return $text . $languagecode;
 }
 /**
  * @since 2.5
  *
  * @return string
  */
 public function getForm()
 {
     $html = $this->htmlFormRenderer->setName('announce')->setMethod('get')->setActionUrl('https://wikiapiary.com/wiki/WikiApiary:Semantic_MediaWiki_Registry')->addHeader('h2', Message::get('smw_smwadmin_announce', Message::TEXT, Message::USER_LANGUAGE))->addParagraph(Message::get('smw_smwadmin_announce_text', Message::TEXT, Message::USER_LANGUAGE))->addSubmitButton(Message::get('smw_smwadmin_announce', Message::TEXT, Message::USER_LANGUAGE))->getForm();
     $html .= Html::element('p', array(), '');
     $html .= $this->htmlFormRenderer->setName('support')->addHeader('h2', Message::get('smw_smwadmin_support', Message::TEXT, Message::USER_LANGUAGE))->addParagraph(Message::get('smw_smwadmin_supportdocu', Message::TEXT, Message::USER_LANGUAGE))->addParagraph(Html::rawElement('ul', array(), Html::rawElement('li', array(), Message::get('smw_smwadmin_installfile', Message::TEXT, Message::USER_LANGUAGE)) . Html::rawElement('li', array(), Message::get('smw_smwadmin_smwhomepage', Message::TEXT, Message::USER_LANGUAGE)) . Html::rawElement('li', array(), Message::get('smw_smwadmin_mediazilla', Message::TEXT, Message::USER_LANGUAGE)) . Html::rawElement('li', array(), Message::get('smw_smwadmin_questions', Message::TEXT, Message::USER_LANGUAGE))))->getForm();
     return $html;
 }
 /**
  * @since 2.4
  *
  * @param Query $query
  *
  * @return Infolink
  */
 public static function get(Query $query)
 {
     $link = Infolink::newInternalLink('', ':Special:Ask', false, array());
     $params = self::getParameters($query);
     foreach ($params as $key => $param) {
         $link->setParameter($param, is_string($key) ? $key : false);
     }
     $link->setCaption(' ' . Message::get('smw_iq_moreresults', Message::TEXT, Message::USER_LANGUAGE));
     return $link;
 }
 /**
  * @see SpecialPage::execute
  */
 public function execute($query)
 {
     if (!$this->userCanExecute($this->getUser())) {
         // $this->mRestriction is private MW 1.23-
         throw new ExtendedPermissionsError('smw-admin', array('smw-smwadmin-permission-missing'));
     }
     $output = $this->getOutput();
     $output->setPageTitle(Message::get('smwadmin', Message::TEXT, Message::USER_LANGUAGE));
     $applicationFactory = ApplicationFactory::getInstance();
     $mwCollaboratorFactory = $applicationFactory->newMwCollaboratorFactory();
     $htmlFormRenderer = $mwCollaboratorFactory->newHtmlFormRenderer($this->getContext()->getTitle(), $this->getLanguage());
     $store = $applicationFactory->getStore();
     $connection = $store->getConnection('mw.db');
     $outputFormatter = new OutputFormatter($output);
     $dataRepairSection = new DataRepairSection($connection, $htmlFormRenderer, $outputFormatter);
     $dataRepairSection->enabledRefreshStore($applicationFactory->getSettings()->get('smwgAdminRefreshStore'));
     $linkSection = new LinkSection($htmlFormRenderer, $outputFormatter);
     $tableSchemaUpdaterSection = new TableSchemaUpdaterSection($store, $htmlFormRenderer, $outputFormatter);
     $tableSchemaUpdaterSection->enabledSetupStore($applicationFactory->getSettings()->get('smwgAdminSetupStore'));
     $idHandlerSection = new IdHandlerSection($connection, $htmlFormRenderer, $outputFormatter);
     $idHandlerSection->enabledIdDisposal($applicationFactory->getSettings()->get('smwgAdminIdDisposal'));
     $supportSection = new SupportSection($htmlFormRenderer);
     // Actions
     switch ($this->getRequest()->getText('action')) {
         case 'settings':
             return $linkSection->outputConfigurationList();
         case 'stats':
             return $linkSection->outputStatistics();
         case 'updatetables':
             return $tableSchemaUpdaterSection->doUpdate($this->getRequest());
         case 'idlookup':
             return $idHandlerSection->outputActionForm($this->getRequest(), $this->getUser());
         case 'refreshstore':
             return $dataRepairSection->doRefresh($this->getRequest());
     }
     // General intro
     $html = Message::get('smw_smwadmin_docu', Message::TEXT, Message::USER_LANGUAGE);
     $html .= $tableSchemaUpdaterSection->getForm();
     $html .= $dataRepairSection->getForm();
     $html .= $linkSection->getForm();
     $html .= $supportSection->getForm();
     $output->addHTML($html);
 }
 /**
  * @since 2.4
  *
  * @param string $msgKey
  */
 public function addErrorWithMsgKey($msgKey)
 {
     $this->errors[] = Message::encode(func_get_args());
 }
Example #6
0
 /**
  * Apply structural restrictions to the current description.
  */
 public function applyRestrictions()
 {
     global $smwgQMaxSize, $smwgQMaxDepth, $smwgQConceptMaxSize, $smwgQConceptMaxDepth;
     if (!is_null($this->description)) {
         if ($this->isUsedInConcept) {
             $maxsize = $smwgQConceptMaxSize;
             $maxdepth = $smwgQConceptMaxDepth;
         } else {
             $maxsize = $smwgQMaxSize;
             $maxdepth = $smwgQMaxDepth;
         }
         $log = array();
         $this->description = $this->description->prune($maxsize, $maxdepth, $log);
         if (count($log) > 0) {
             $this->errors[] = Message::encode(array('smw_querytoolarge', str_replace('[', '[', implode(', ', $log))));
         }
     }
 }
 /**
  * Parse parameters and set internal properties
  *
  * @since 1.9
  *
  * @param array $parameters
  */
 private function parse(array $parameters)
 {
     // Initialize variables.
     $all_date_strings = array();
     $start_date = $end_date = $unit = $period = $week_num = null;
     $included_dates = array();
     $excluded_dates = array();
     $excluded_dates_jd = array();
     // Parse parameters and assign values
     foreach ($parameters as $name => $values) {
         foreach ($values as $value) {
             switch ($name) {
                 case 'property':
                     $this->property = $value;
                     break;
                 case 'start':
                     $start_date = DataValueFactory::getInstance()->newTypeIDValue('_dat', $value);
                     break;
                 case 'end':
                     $end_date = DataValueFactory::getInstance()->newTypeIDValue('_dat', $value);
                     break;
                 case 'limit':
                     // Override default limit with query specific limit
                     $this->defaultNumRecurringEvents = (int) $value;
                     break;
                 case 'unit':
                     $unit = $value;
                     break;
                 case 'period':
                     $period = (int) $value;
                     break;
                 case 'week number':
                     $week_num = (int) $value;
                     break;
                 case 'include':
                     // This is for compatibility only otherwise we break
                     // to much at once. Instead of writing include=...;...
                     // it should be include=...;...|+sep=; because the
                     // ParameterParser class is conditioned to split those
                     // parameter accordingly
                     if (strpos($value, ';')) {
                         $included_dates = explode(';', $value);
                     } else {
                         $included_dates[] = $value;
                     }
                     break;
                 case 'exclude':
                     // Some as above
                     if (strpos($value, ';')) {
                         $excluded_dates = explode(';', $value);
                     } else {
                         $excluded_dates[] = $value;
                     }
                     break;
                 default:
                     $this->parameters[$name][] = $value;
             }
         }
     }
     if ($start_date === null) {
         $this->errors[] = Message::get('smw-events-start-date-missing');
         return;
     } elseif (!$start_date->getDataItem() instanceof SMWDITime) {
         $this->setError($start_date->getErrors());
         return;
     }
     // Check property
     if (is_null($this->property)) {
         $this->errors[] = Message::get('smw-events-property-missing');
         return;
     }
     // Exclude dates
     foreach ($excluded_dates as $date_str) {
         $excluded_dates_jd[] = $this->getJulianDay(DataValueFactory::getInstance()->newTypeIDValue('_dat', $date_str));
     }
     // 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 = $this->getJulianDay($end_date);
     $cur_date = $start_date;
     $cur_date_jd = $this->getJulianDay($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 = DataValueFactory::getInstance()->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 = $this->getJulianDayTimeValue($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 = $this->getJulianDayTimeValue($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 = $this->getJulianDayTimeValue($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 = $this->getJulianDayTimeValue($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 = $this->getJulianDayTimeValue($cur_date_jd);
         }
         // should we stop?
         if (is_null($end_date)) {
             $reached_end_date = $i > $this->defaultNumRecurringEvents;
         } else {
             $reached_end_date = $cur_date_jd > $end_date_jd || $i > $this->maxNumRecurringEvents;
         }
     } while (!$reached_end_date);
     // Handle the 'include' dates as well.
     $all_date_strings = array_filter(array_merge($all_date_strings, $included_dates));
     // Set dates
     $this->dates = str_replace(' 00:00:00', '', $all_date_strings);
 }
 /**
  * Builds Html container
  *
  * Content that is being invoked has to be escaped
  * @see Highlighter::setContent
  *
  * @since 1.9
  *
  * @return string
  */
 private function getContainer()
 {
     $captionclass = $this->options['captionclass'];
     // 2.4+ can display context for user-defined properties, here we ensure
     // to keep the style otherwise it displays italic which is by convention
     // reserved for predefined properties
     if ($this->type === self::TYPE_PROPERTY && isset($this->options['userDefined'])) {
         $captionclass = $this->options['userDefined'] ? 'smwtext' : $captionclass;
     }
     $language = is_string($this->language) ? $this->language : Message::USER_LANGUAGE;
     return Html::rawElement('span', array('class' => 'smw-highlighter', 'data-type' => $this->options['type'], 'data-content' => isset($this->options['data-content']) ? $this->options['data-content'] : null, 'data-state' => $this->options['state'], 'data-title' => Message::get($this->options['title'], Message::TEXT, $language), 'title' => strip_tags(htmlspecialchars_decode(str_replace("[", "&#x005B;", $this->options['content'])))), Html::rawElement('span', array('class' => $captionclass), $this->options['caption']) . Html::rawElement('div', array('class' => 'smwttcontent'), $this->options['content']));
 }
 private function getListOfFormattedPropertyDataItems($type, $linker, $propertyDataItems)
 {
     $results = array();
     foreach ($propertyDataItems as $propertyDataItem) {
         $propertyValues = $this->dataValue->getDataItem()->getSemanticData()->getPropertyValues($propertyDataItem);
         $dataItem = reset($propertyValues);
         // By definition the first element in the list is the VALUE other
         // members are referencing to
         $isValue = $results === array();
         $dataValue = null;
         if ($dataItem !== false) {
             $dataValue = DataValueFactory::getInstance()->newDataValueByItem($dataItem, $propertyDataItem);
             $output = $this->findValueOutputFor($isValue, $type, $dataValue, $linker);
         } else {
             $output = '?';
         }
         // Return a plain value in case no linker object is available
         if ($dataValue !== null && $linker === null) {
             return array($dataValue->getWikiValue());
         }
         $dataValue = DataValueFactory::getInstance()->newDataValueByItem($propertyDataItem);
         // Tooltip in tooltip isn't expected to work therefore avoid them
         // when generating property labels in a reference output
         $dataValue->setOption(PropertyValue::OPT_NO_HIGHLIGHT, true);
         if (!$isValue && $type !== self::VALUE) {
             $output = Message::get(array('smw-datavalue-reference-outputformat', $dataValue->getShortHTMLText(smwfGetLinker()), $output), Message::TEXT);
         }
         $results[] = $output;
     }
     return $results;
 }
 private function parseFromJson($results)
 {
     if (!isset($results['@json']) || !isset($results['@json'][0])) {
         return $results;
     }
     // Restrict the depth to avoid resolving recursive assignment
     // that can not be handled beyond the 2:n
     $depth = 3;
     $params = json_decode($results['@json'][0], true, $depth);
     if ($params === null || json_last_error() !== JSON_ERROR_NONE) {
         $this->addError(Message::encode(array('smw-parser-invalid-json-format', ErrorCode::getStringFromJsonErrorCode(json_last_error()))));
         return $results;
     }
     array_walk($params, function (&$value, $key) {
         if ($value === '') {
             $value = array();
         }
         if (!is_array($value)) {
             $value = array($value);
         }
     });
     unset($results['@json']);
     return array_merge($results, $params);
 }
 private function constructErrorText($linker = null)
 {
     if (!$this->isValid() || $this->getDataItem() === array()) {
         return '';
     }
     $string = $this->getDataItem()->getString();
     $type = $linker !== null ? Message::PARSE : Message::TEXT;
     if (($message = Message::decode($string, $type, $this->getOptionBy(self::OPT_USER_LANGUAGE))) !== false) {
         return $message;
     }
     return $string;
 }
Example #12
0
 protected function parseUserValue($value)
 {
     $value = trim($value);
     $this->m_wikitext = $value;
     if ($this->m_caption === false) {
         $this->m_caption = $this->m_wikitext;
     }
     $scheme = $hierpart = $query = $fragment = '';
     if ($value === '') {
         // do not accept empty strings
         $this->addErrorMsg(array('smw_emptystring'));
         return;
     }
     switch ($this->m_mode) {
         case SMW_URI_MODE_URI:
         case SMW_URI_MODE_ANNOURI:
             // Whether the the url value was externally encoded or not
             if (strpos($value, "%") === false) {
                 $this->showUrlContextInRawFormat = false;
             }
             // If somehow the slash was encoded bring into one format
             $value = str_replace("%2F", "/", $value);
             $parts = explode(':', $value, 2);
             // try to split "schema:rest"
             if (count($parts) == 1) {
                 // possibly add "http" as default
                 $value = 'http://' . $value;
                 $parts[1] = $parts[0];
                 $parts[0] = 'http';
             }
             // check against blacklist
             $uri_blacklist = explode("\n", Message::get('smw_uri_blacklist', Message::TEXT, Message::CONTENT_LANGUAGE));
             foreach ($uri_blacklist as $uri) {
                 $uri = trim($uri);
                 if ($uri !== '' && $uri == mb_substr($value, 0, mb_strlen($uri))) {
                     // disallowed URI!
                     $this->addErrorMsg(array('smw_baduri', $value));
                     return;
                 }
             }
             // decompose general URI components
             $scheme = $parts[0];
             $parts = explode('?', $parts[1], 2);
             // try to split "hier-part?queryfrag"
             if (count($parts) == 2) {
                 $hierpart = $parts[0];
                 $parts = explode('#', $parts[1], 2);
                 // try to split "query#frag"
                 $query = $parts[0];
                 $fragment = count($parts) == 2 ? $parts[1] : '';
             } else {
                 $query = '';
                 $parts = explode('#', $parts[0], 2);
                 // try to split "hier-part#frag"
                 $hierpart = $parts[0];
                 $fragment = count($parts) == 2 ? $parts[1] : '';
             }
             // We do not validate the URI characters (the data item will do this) but we do some escaping:
             // encode most characters, but leave special symbols as given by user:
             $hierpart = str_replace(array('%3A', '%2F', '%23', '%40', '%3F', '%3D', '%26', '%25'), array(':', '/', '#', '@', '?', '=', '&', '%'), rawurlencode($hierpart));
             $query = str_replace(array('%3A', '%2F', '%23', '%40', '%3F', '%3D', '%26', '%25'), array(':', '/', '#', '@', '?', '=', '&', '%'), rawurlencode($query));
             $fragment = str_replace(array('%3A', '%2F', '%23', '%40', '%3F', '%3D', '%26', '%25'), array(':', '/', '#', '@', '?', '=', '&', '%'), rawurlencode($fragment));
             /// NOTE: we do not support raw [ (%5D) and ] (%5E), although they are needed for ldap:// (but rarely in a wiki)
             /// NOTE: "+" gets encoded, as it is interpreted as space by most browsers when part of a URL;
             ///       this prevents tel: from working directly, but we have a datatype for this anyway.
             if (substr($hierpart, 0, 2) === '//') {
                 $hierpart = substr($hierpart, 2);
             }
             break;
         case SMW_URI_MODE_TEL:
             $scheme = 'tel';
             if (substr($value, 0, 4) === 'tel:') {
                 // accept optional "tel"
                 $value = substr($value, 4);
                 $this->m_wikitext = $value;
             }
             $hierpart = preg_replace('/(?<=[0-9]) (?=[0-9])/', '\\1-\\2', $value);
             $hierpart = str_replace(' ', '', $hierpart);
             if (substr($hierpart, 0, 2) == '00') {
                 $hierpart = '+' . substr($hierpart, 2);
             }
             if (!$this->getOptionBy(self::OPT_QUERY_CONTEXT) && (strlen(preg_replace('/[^0-9]/', '', $hierpart)) < 6 || preg_match('<[-+./][-./]>', $hierpart) || !self::isValidTelURI('tel:' . $hierpart))) {
                 /// TODO: introduce error-message for "bad" phone number
                 $this->addErrorMsg(array('smw_baduri', $this->m_wikitext));
                 return;
             }
             break;
         case SMW_URI_MODE_EMAIL:
             $scheme = 'mailto';
             if (strpos($value, 'mailto:') === 0) {
                 // accept optional "mailto"
                 $value = substr($value, 7);
                 $this->m_wikitext = $value;
             }
             if (!$this->getOptionBy(self::OPT_QUERY_CONTEXT) && !Sanitizer::validateEmail($value)) {
                 /// TODO: introduce error-message for "bad" email
                 $this->addErrorMsg(array('smw_baduri', $value));
                 return;
             }
             $hierpart = str_replace(array('%3A', '%2F', '%23', '%40', '%3F', '%3D', '%26', '%25'), array(':', '/', '#', '@', '?', '=', '&', '%'), rawurlencode($value));
     }
     // Now create the URI data item:
     try {
         $this->m_dataitem = new SMWDIUri($scheme, $hierpart, $query, $fragment, $this->m_typeid);
     } catch (SMWDataItemException $e) {
         $this->addErrorMsg(array('smw_baduri', $this->m_wikitext));
     }
 }
 private function doCreatePage($page, $namespace)
 {
     $pageContentLanguage = isset($page['contentlanguage']) ? $page['contentlanguage'] : '';
     if (isset($page['message-cache']) && $page['message-cache'] === 'clear') {
         Message::clear();
     }
     $name = isset($page['name']) ? $page['name'] : $page['page'];
     $title = Title::newFromText($name, $namespace);
     if ($namespace === NS_FILE && isset($page['contents']['upload'])) {
         return $this->doUploadFile($title, $page['contents']['upload']);
     }
     if (is_array($page['contents']) && isset($page['contents']['import-from'])) {
         $contents = $this->getFileContentsWithEncodingDetection($this->getTestCaseLocation() . $page['contents']['import-from']);
     } else {
         $contents = $page['contents'];
     }
     $this->pageCreator->createPage($title, $contents, $pageContentLanguage);
     $this->itemsMarkedForDeletion[] = $this->pageCreator->getPage();
     if (isset($page['move-to'])) {
         $this->doMovePage($page, $namespace);
     }
     if (isset($page['do-purge'])) {
         $this->pageCreator->getPage()->doPurge();
     }
     if (isset($page['do-delete']) && $page['do-delete']) {
         $this->pageDeleter->deletePage($title);
     }
 }
 public function testDecode()
 {
     $this->assertEquals(false, Message::decode('Foo'));
     $this->assertEquals('Foo', Message::decode('[2,"Foo"]'));
 }
 private function getPredefinedPropertyDescription($property, $linker, $languageCode)
 {
     $description = '';
     $key = $property->getKey();
     if (($msgKey = PropertyRegistry::getInstance()->findPropertyDescriptionMsgKeyById($key)) === '') {
         $msgKey = 'smw-pa-property-predefined' . strtolower($key);
     }
     if (!Message::exists($msgKey)) {
         return $description;
     }
     $dataValue = DataValueFactory::getInstance()->newDataValueByItem($property);
     $label = $dataValue->getFormattedLabel();
     $message = Message::get(array($msgKey, $label), $linker === null ? Message::ESCAPED : Message::PARSE, $languageCode);
     return $message;
 }
 private function getHtml($webRequest, $isEmptyRequest)
 {
     if ($isEmptyRequest) {
         return HtmlContentBuilder::getPageSearchQuickForm();
     }
     if (!$this->subjectDV->isValid()) {
         foreach ($this->subjectDV->getErrors() as $error) {
             $error = Message::decode($error);
         }
         $html = Html::rawElement('div', array('class' => 'smw-callout smw-callout-error'), Message::get(array('smw-browse-invalid-subject', $error), Message::ESCAPED));
         return $html . HtmlContentBuilder::getPageSearchQuickForm();
     }
     $htmlContentBuilder = $this->newHtmlContentBuilder($webRequest);
     if ($webRequest->getVal('output') === 'legacy' || !$htmlContentBuilder->getOption('byApi')) {
         return $htmlContentBuilder->getHtml();
     }
     $options = array('dir' => $htmlContentBuilder->getOption('dir'), 'offset' => $htmlContentBuilder->getOption('offset'), 'printable' => $htmlContentBuilder->getOption('printable'), 'showInverse' => $htmlContentBuilder->getOption('showInverse'), 'showAll' => $htmlContentBuilder->getOption('showAll'));
     // Ajax/API is doing the data fetch
     $html = Html::rawElement('div', array('class' => 'smwb-container', 'data-subject' => $this->subjectDV->getDataItem()->getHash(), 'data-options' => json_encode($options)), Html::rawElement('div', array('class' => 'smwb-status'), Html::rawElement('noscript', array(), Html::rawElement('div', array('class' => 'smw-callout smw-callout-error'), Message::get('smw-browse-js-disabled', Message::PARSE)))) . Html::rawElement('div', array('class' => 'smwb-content is-disabled'), Html::rawElement('span', array('class' => 'smw-overlay-spinner large inline')) . $htmlContentBuilder->getEmptyHtml()));
     return $html;
 }
 /**
  * Continuation of getResult that only gets executed for non file outputs.
  *
  * @since 1.6
  *
  * @param string $result
  * @param SMWQueryResult $results
  * @param integer $outputmode
  *
  * @return string
  */
 protected function handleNonFileResult($result, SMWQueryResult $results, $outputmode)
 {
     /**
      * @var \Parser $wgParser
      */
     global $wgParser;
     $result .= $this->getErrorString($results);
     // append errors
     // MW 1.21+
     // Block recursive import of annotations unless otherwise specified for
     // a specific use case
     if (method_exists($wgParser->getOutput(), 'setExtensionData')) {
         $wgParser->getOutput()->setExtensionData('smw-blockannotation', $this->params['format'] === 'embedded');
     }
     // Apply intro parameter
     if ($this->mIntro && $results->getCount() > 0) {
         if ($outputmode == SMW_OUTPUT_HTML) {
             $result = Message::get(array('smw-parse', $this->mIntro), Message::PARSE) . $result;
         } else {
             $result = $this->mIntro . $result;
         }
     }
     // Apply outro parameter
     if ($this->mOutro && $results->getCount() > 0) {
         if ($outputmode == SMW_OUTPUT_HTML) {
             $result = $result . Message::get(array('smw-parse', $this->mOutro), Message::PARSE);
         } else {
             $result = $result . $this->mOutro;
         }
     }
     // Preprocess embedded templates if needed
     if (!$this->isHTML && $this->hasTemplates) {
         if ($wgParser->getTitle() instanceof Title && $wgParser->getOptions() instanceof ParserOptions) {
             self::$mRecursionDepth++;
             if (self::$mRecursionDepth <= self::$maxRecursionDepth) {
                 // restrict recursion
                 $result = isset($this->params['import-annotation']) && $this->params['import-annotation'] ? $wgParser->recursivePreprocess($result) : '[[SMW::off]]' . $wgParser->replaceVariables($result) . '[[SMW::on]]';
             } else {
                 $result = '';
                 /// TODO: explain problem (too much recursive parses)
             }
             self::$mRecursionDepth--;
         } else {
             // not during parsing, no preprocessing needed, still protect the result
             $result = isset($this->params['import-annotation']) && $this->params['import-annotation'] ? $result : '[[SMW::off]]' . $result . '[[SMW::on]]';
         }
     }
     if ($this->isHTML && $outputmode == SMW_OUTPUT_WIKI) {
         $result = array($result, 'isHTML' => true);
     } elseif (!$this->isHTML && $outputmode == SMW_OUTPUT_HTML) {
         self::$mRecursionDepth++;
         // check whether we are in an existing parse, or if we should start a new parse for $wgTitle
         if (self::$mRecursionDepth <= self::$maxRecursionDepth) {
             // retrict recursion
             if ($wgParser->getTitle() instanceof Title && $wgParser->getOptions() instanceof ParserOptions) {
                 $result = $wgParser->recursiveTagParse($result);
             } else {
                 global $wgTitle;
                 $popt = new ParserOptions();
                 $popt->setEditSection(false);
                 $pout = $wgParser->parse($result . '__NOTOC__', $wgTitle, $popt);
                 /// NOTE: as of MW 1.14SVN, there is apparently no better way to hide the TOC
                 \SMWOutputs::requireFromParserOutput($pout);
                 $result = $pout->getText();
             }
         } else {
             $result = '';
             /// TODO: explain problem (too much recursive parses)
         }
         self::$mRecursionDepth--;
     }
     if (method_exists($wgParser->getOutput(), 'setExtensionData')) {
         $wgParser->getOutput()->setExtensionData('smw-blockannotation', false);
     }
     return $result;
 }
 private function getMessage($key, $type = Message::TEXT)
 {
     return Message::get($key, $type, Message::USER_LANGUAGE);
 }
 public function testGetInfolinkTextOnStringValueWithServiceLinks()
 {
     $service = 'testGetInfolinkTextOnStringValueWithServiceLinks';
     $this->cachedPropertyValuesPrefetcher->expects($this->atLeastOnce())->method('getPropertyValues')->will($this->returnValue(array($this->dataItemFactory->newDIBlob($service))));
     // Manipulating the Message cache is a hack!!
     $parameters = array("smw_service_" . $service, 'Bar');
     Message::getCache()->save(Message::getHash($parameters, Message::TEXT, Message::CONTENT_LANGUAGE), 'SERVICELINK-A|SERVICELINK-B');
     $stringValue = new StringValue('_txt');
     $stringValue->setOption(StringValue::OPT_USER_LANGUAGE, 'en');
     $stringValue->setOption(StringValue::OPT_CONTENT_LANGUAGE, 'en');
     $stringValue->setProperty($this->dataItemFactory->newDIProperty('Foo'));
     $stringValue->setUserValue('Bar');
     $instance = new InfoLinksProvider($stringValue);
     $this->assertContains('<div class="smwttcontent">&#x005B;SERVICELINK-B SERVICELINK-A]</div>', $instance->getInfolinkText(SMW_OUTPUT_WIKI));
     $this->assertContains('<div class="smwttcontent"><a href="SERVICELINK-B">SERVICELINK-A</a></div>', $instance->getInfolinkText(SMW_OUTPUT_HTML));
 }
 private function doHighlightText($text, $linker = null)
 {
     $content = '';
     if (!$this->canHighlight($content, $linker)) {
         return $text;
     }
     $highlighter = Highlighter::factory(Highlighter::TYPE_PROPERTY, $this->dataValue->getOptionBy(PropertyValue::OPT_USER_LANGUAGE));
     $highlighter->setContent(array('userDefined' => $this->dataValue->getDataItem()->isUserDefined(), 'caption' => $text, 'content' => $content !== '' ? $content : Message::get('smw_isspecprop')));
     return $highlighter->getHtml();
 }
 protected function addDataValuesToSubobject(ParserParameterProcessor $parserParameterProcessor)
 {
     // Named subobjects containing a "." in the first five characters are reserved to be
     // used by extensions only in order to separate them from user land and avoid having
     // them accidentally to refer to the same named ID
     // (i.e. different access restrictions etc.)
     if (strpos(mb_substr($parserParameterProcessor->getFirst(), 0, 5), '.') !== false) {
         return $this->parserData->addError(Message::encode(array('smw-subobject-parser-invalid-naming-scheme', $parserParameterProcessor->getFirst())));
     }
     list($parameters, $id) = $this->getParameters($parserParameterProcessor);
     $this->subobject->setEmptyContainerForId($id);
     $subject = $this->subobject->getSubject();
     foreach ($parameters as $property => $values) {
         if ($property === self::PARAM_SORTKEY) {
             $property = DIProperty::TYPE_SORTKEY;
         }
         if ($property === self::PARAM_CATEGORY) {
             $property = DIProperty::TYPE_CATEGORY;
         }
         foreach ($values as $value) {
             $dataValue = DataValueFactory::getInstance()->newDataValueByText($property, $value, false, $subject);
             $this->subobject->addDataValue($dataValue);
         }
     }
     $this->doAugmentSortKeyForWhenDisplayTitleIsAccessible($this->subobject->getSemanticData());
     return true;
 }
 /**
  * Messages are not resolved until the output and instead will be kept with the
  * message and argument keys (e.g. `[2,"smw_baduri","~*0123*"]`). This allows to
  * switch the a representation without requiring language context by the object
  * that reports an error.
  *
  * @since 2.4
  *
  * @param $parameters
  * @param integer|null $type
  * @param integer|null $language
  */
 public function addErrorMsg($parameters, $type = null)
 {
     $this->mErrors[] = Message::encode($parameters, $type);
     $this->mHasErrors = true;
 }
 /**
  * @since 2.5
  *
  * @param DataValue $dataValue
  *
  * @return DIContainer|null
  */
 public function getErrorContainerFromDataValue(DataValue $dataValue)
 {
     if ($dataValue->getErrors() === array()) {
         return null;
     }
     $property = $dataValue->getProperty();
     $hash = '';
     if ($property !== null) {
         $hash = $property->getKey();
     }
     $containerSemanticData = $this->newContainerSemanticData($hash);
     foreach ($dataValue->getErrors() as $error) {
         $this->addToContainerSemanticData($containerSemanticData, $property, Message::encode($error));
     }
     return new DIContainer($containerSemanticData);
 }
 private function getBooleanWordsFrom($msgKey, $languageCode = null)
 {
     $vals = explode(',', Message::get($msgKey, Message::TEXT, $languageCode));
     return $vals;
 }
 private function createParentLink()
 {
     return Html::rawElement('div', array('class' => 'smw-breadcrumb-link'), Html::rawElement('span', array('class' => 'smw-breadcrumb-arrow-right'), '') . Html::rawElement('a', array('href' => \SpecialPage::getTitleFor('SMWAdmin')->getFullURL()), Message::get('smwadmin', Message::TEXT, Message::USER_LANGUAGE)));
 }
 private function getPreferredLocalizedSeparator($custom, $standard, $language)
 {
     if ($this->options->has($custom) && ($separator = $this->options->get($custom)) !== false) {
         return $separator;
     }
     return Message::get($standard, Message::TEXT, $language);
 }
Example #27
0
 private function registerMessageCallbackHandler()
 {
     Message::registerCallbackHandler(Message::TEXT, function ($arguments, $language) {
         if ($language === Message::CONTENT_LANGUAGE) {
             $language = Localizer::getInstance()->getContentLanguage();
         }
         if ($language === Message::USER_LANGUAGE) {
             $language = Localizer::getInstance()->getUserLanguage();
         }
         return call_user_func_array('wfMessage', $arguments)->inLanguage($language)->text();
     });
     Message::registerCallbackHandler(Message::ESCAPED, function ($arguments, $language) {
         if ($language === Message::CONTENT_LANGUAGE) {
             $language = Localizer::getInstance()->getContentLanguage();
         }
         if ($language === Message::USER_LANGUAGE) {
             $language = Localizer::getInstance()->getUserLanguage();
         }
         return call_user_func_array('wfMessage', $arguments)->inLanguage($language)->escaped();
     });
     Message::registerCallbackHandler(Message::PARSE, function ($arguments, $language) {
         if ($language === Message::CONTENT_LANGUAGE) {
             $language = Localizer::getInstance()->getContentLanguage();
         }
         if ($language === Message::USER_LANGUAGE) {
             $language = Localizer::getInstance()->getUserLanguage();
         }
         // 1.27+
         // [GlobalTitleFail] MessageCache::parse called by ... Message::parseText/MessageCache::parse with no title set.
         return call_user_func_array('wfMessage', $arguments)->inLanguage($language)->title($GLOBALS['wgTitle'])->parse();
     });
 }
 /**
  * A function to describe the allowed parameters of a query using
  * any specific format - most query printers should override this
  * function.
  *
  * @since 1.6.2, return element type changed in 1.8
  *
  * @return IParamDefinition[]
  */
 public static function getParameters()
 {
     $params = array();
     $allowedFormats = $GLOBALS['smwgResultFormats'];
     foreach ($GLOBALS['smwgResultAliases'] as $aliases) {
         $allowedFormats += $aliases;
     }
     $allowedFormats[] = 'auto';
     $params['format'] = array('type' => 'smwformat', 'default' => 'auto');
     // TODO $params['format']->setToLower( true );
     // TODO $allowedFormats
     $params['source'] = self::getSourceParam();
     $params['limit'] = array('type' => 'integer', 'default' => $GLOBALS['smwgQDefaultLimit'], 'negatives' => false);
     $params['offset'] = array('type' => 'integer', 'default' => 0, 'negatives' => false, 'upperbound' => $GLOBALS['smwgQUpperbound']);
     $params['link'] = array('default' => 'all', 'values' => array('all', 'subject', 'none'));
     $params['sort'] = array('islist' => true, 'default' => array(''));
     $params['order'] = array('islist' => true, 'default' => array(), 'values' => array('descending', 'desc', 'asc', 'ascending', 'rand', 'random'));
     $params['headers'] = array('default' => 'show', 'values' => array('show', 'hide', 'plain'));
     $params['mainlabel'] = array('default' => false);
     $params['intro'] = array('default' => '');
     $params['outro'] = array('default' => '');
     $params['searchlabel'] = array('default' => Message::get('smw_iq_moreresults', Message::TEXT, Message::USER_LANGUAGE));
     $params['default'] = array('default' => '');
     // Give grep a chance to find the usages:
     // smw-paramdesc-format, smw-paramdesc-source, smw-paramdesc-limit, smw-paramdesc-offset,
     // smw-paramdesc-link, smw-paramdesc-sort, smw-paramdesc-order, smw-paramdesc-headers,
     // smw-paramdesc-mainlabel, smw-paramdesc-intro, smw-paramdesc-outro, smw-paramdesc-searchlabel,
     // smw-paramdesc-default
     foreach ($params as $name => &$param) {
         if (is_array($param)) {
             $param['message'] = 'smw-paramdesc-' . $name;
         }
     }
     return ParamDefinition::getCleanDefinitions($params);
 }
 /**
  * Gets the contents for a table cell for all values of a property of a subject.
  *
  * @since 1.6.1
  *
  * @param SMWDataValue[] $dataValues
  * @param $outputMode
  * @param boolean $isSubject
  *
  * @return string
  */
 protected function getCellContent(array $dataValues, $outputMode, $isSubject)
 {
     $values = array();
     foreach ($dataValues as $dv) {
         // FILE parsing for HTML requested output (e.g. Special:Ask)
         if ($outputMode === SMW_OUTPUT_HTML && $dv->getDataItem() instanceof DIWikiPage && $dv->getDataItem()->getNamespace() === NS_FILE) {
             // Too lazy to handle the Parser object and besides the Message
             // parse does the job and ensures no other hook is executed
             $value = Message::get(array('smw-parse', $dv->getShortText(SMW_OUTPUT_WIKI, $this->getLinker($isSubject))), Message::PARSE);
         } else {
             $value = $dv->getShortText($outputMode, $this->getLinker($isSubject));
         }
         $values[] = $value === '' ? '&nbsp;' : $value;
     }
     return implode($this->params['sep'], $values);
 }