/**
 * Entrypoint
 * @param string $par parent page we will look at
 */
function wfSpecialRecentchangeslinked($par = NULL)
{
    global $wgUser, $wgOut, $wgLang, $wgContLang, $wgTitle, $wgRequest;
    $fname = 'wfSpecialRecentchangeslinked';
    $days = $wgRequest->getInt('days');
    $target = isset($par) ? $par : $wgRequest->getText('target');
    $hideminor = $wgRequest->getBool('hideminor') ? 1 : 0;
    $wgOut->setPagetitle(wfMsg('recentchangeslinked'));
    $sk = $wgUser->getSkin();
    if (is_null($target)) {
        $wgOut->errorpage('notargettitle', 'notargettext');
        return;
    }
    $nt = Title::newFromURL($target);
    if (!$nt) {
        $wgOut->errorpage('notargettitle', 'notargettext');
        return;
    }
    $id = $nt->getArticleId();
    $wgOut->setSubtitle(htmlspecialchars(wfMsg('rclsub', $nt->getPrefixedText())));
    if (!$days) {
        $days = $wgUser->getOption('rcdays');
        if (!$days) {
            $days = 7;
        }
    }
    $days = (int) $days;
    list($limit, $offset) = wfCheckLimits(100, 'rclimit');
    $dbr =& wfGetDB(DB_SLAVE);
    $cutoff = $dbr->timestamp(time() - $days * 86400);
    $hideminor = $hideminor ? 1 : 0;
    if ($hideminor) {
        $mlink = $sk->makeKnownLink($wgContLang->specialPage('Recentchangeslinked'), WfMsg('show'), 'target=' . htmlspecialchars($nt->getPrefixedURL()) . "&days={$days}&limit={$limit}&hideminor=0");
    } else {
        $mlink = $sk->makeKnownLink($wgContLang->specialPage("Recentchangeslinked"), WfMsg("hide"), "target=" . htmlspecialchars($nt->getPrefixedURL()) . "&days={$days}&limit={$limit}&hideminor=1");
    }
    if ($hideminor) {
        $cmq = 'AND rev_minor_edit=0';
    } else {
        $cmq = '';
    }
    extract($dbr->tableNames('categorylinks', 'pagelinks', 'revision', 'page'));
    // If target is a Category, use categorylinks and invert from and to
    if ($nt->getNamespace() == NS_CATEGORY) {
        $catkey = $dbr->addQuotes($nt->getDBKey());
        $sql = "SELECT page_id,page_namespace,page_title,rev_id,rev_user,rev_comment,\n         rev_user_text,rev_timestamp,rev_minor_edit,\n         page_is_new\n    FROM {$categorylinks}, {$revision}, {$page}\n   WHERE rev_timestamp > '{$cutoff}'\n         {$cmq}\n     AND rev_page=page_id\n     AND cl_from=page_id\n     AND cl_to={$catkey}\nGROUP BY page_id,page_namespace,page_title,\n         rev_user,rev_comment,rev_user_text,rev_timestamp,rev_minor_edit,\n         page_is_new\nORDER BY rev_timestamp DESC\n   LIMIT {$limit}";
    } else {
        $sql = "SELECT page_id,page_namespace,page_title,\n         rev_user,rev_comment,rev_user_text,rev_id,rev_timestamp,rev_minor_edit,\n         page_is_new\n    FROM {$pagelinks}, {$revision}, {$page}\n   WHERE rev_timestamp > '{$cutoff}'\n         {$cmq}\n     AND rev_page=page_id\n     AND pl_namespace=page_namespace\n     AND pl_title=page_title\n     AND pl_from={$id}\nGROUP BY page_id,page_namespace,page_title,\n         rev_user,rev_comment,rev_user_text,rev_timestamp,rev_minor_edit,\n         page_is_new\nORDER BY rev_timestamp DESC\n   LIMIT {$limit}";
    }
    $res = $dbr->query($sql, $fname);
    $wgOut->addHTML("&lt; " . $sk->makeKnownLinkObj($nt, "", "redirect=no") . "<br />\n");
    $note = wfMsg("rcnote", $limit, $days);
    $wgOut->addHTML("<hr />\n{$note}\n<br />");
    $note = rcDayLimitlinks($days, $limit, "Recentchangeslinked", "target=" . $nt->getPrefixedURL() . "&hideminor={$hideminor}", false, $mlink);
    $wgOut->addHTML($note . "\n");
    $list =& new ChangesList($sk);
    $s = $list->beginRecentChangesList();
    $count = $dbr->numRows($res);
    $counter = 1;
    while ($limit) {
        if (0 == $count) {
            break;
        }
        $obj = $dbr->fetchObject($res);
        --$count;
        $rc = RecentChange::newFromCurRow($obj);
        $rc->counter = $counter++;
        $s .= $list->recentChangesLine($rc);
        --$limit;
    }
    $s .= $list->endRecentChangesList();
    $dbr->freeResult($res);
    $wgOut->addHTML($s);
}
Example #2
0
 /**
  * Insert an image upload into the mediawiki database tables.  If the
  * image insert was successful, a page showing the wiki text for their
  * image is shown.  Otherwise, if the image file name already exists in 
  * the database, a conflict page is returned to the user.
  *
  * @param $type string with either 'overwrite' or blank -- specifies
  *   whether to force-overwrite an existing image
  * @param $name filename chosen by user for uploaded image
  * @param $mwname filename of the file in mediawiki DB
  * @param $fromIIA true iff source of call is Special:IntroImageAdder
  * @param $image_comment a comment attached to the image upload (only
  *   used if $fromIIA == true)
  * @return outputs either a wikitext results page (if image filename 
  *   didn't exist or force overwrite was selected) or a conflict page.
  *   Returns an error string or empty string if no error.
  */
 private function insertImage($type, $name, $mwname, $fromIIA = false, $image_comment = '')
 {
     global $wgRequest, $wgUser, $wgOut, $wgFileExtensions;
     if (!$fromIIA) {
         $license = $wgRequest->getVal('wpLicense', '');
         if (!empty($license)) {
             $attrib = $wgRequest->getVal('attribution');
             $comment = '{{' . $license . (!empty($attrib) ? '|' . $attrib : '') . '}}';
             if ($license != '') {
                 $wgUser->setOption('image_license', $license);
                 $wgUser->saveSettings();
             }
         } else {
             $comment = $wgRequest->getVal('ImageAttribution', '');
         }
     } else {
         $comment = $image_comment;
     }
     if (wfReadOnly()) {
         return wfMsg('eiu-readonly');
     }
     if (!empty($mwname) && !empty($name)) {
         $name = urldecode($name);
         $name = preg_replace('/[^' . Title::legalChars() . ']|[:\\/\\\\]|\\?/', '-', $name);
         $name = preg_replace('@&amp;@', '&', $name);
         $name = trim($name);
         // did they give no extension at all when they changed the name?
         list($first, $ext) = self::splitFilenameExt($name);
         $ext = strtolower($ext);
         $title = Title::makeTitleSafe(NS_IMAGE, $name);
         if (is_null($title) || !in_array($ext, $wgFileExtensions)) {
             return wfMsg('eiu-filetype-incorrect');
         }
         $newFile = true;
         $titleExists = $title->exists();
         if (!$titleExists || $fromIIA) {
             //
             // DB entry for file doesn't exist. User renamed their
             // upload or it never existed.
             //
             if ($titleExists) {
                 $suggestedName = self::generateNewFilename($name);
                 $title = Title::makeTitleSafe(NS_IMAGE, $suggestedName);
             }
             // is the target protected?
             $permErrors = $title->getUserPermissionsErrors('edit', $wgUser);
             $permErrorsUpload = $title->getUserPermissionsErrors('upload', $wgUser);
             if ($permErrors || $permErrorsUpload) {
                 return wfMsg('This image is protected');
             }
             $temp_file = new LocalFile(Title::newFromText($mwname, NS_IMAGE), RepoGroup::singleton()->getLocalRepo());
             $file = new LocalFile($title, RepoGroup::singleton()->getLocalRepo());
             $file->upload($temp_file->getPath(), $comment, $comment);
             $temp_file->delete('');
         } elseif ($type == 'overwrite') {
             //
             // DB entry exists and user selected to overwrite it
             //
             $title = Title::newFromText($name, NS_IMAGE);
             // is the target protected?
             $permErrors = $title->getUserPermissionsErrors('edit', $wgUser);
             $permErrorsUpload = $title->getUserPermissionsErrors('upload', $wgUser);
             $permErrorsCreate = $title->exists() ? array() : $title->getUserPermissionsErrors('create', $wgUser);
             if ($permErrors || $permErrorsUpload || $permErrorsCreate) {
                 return wfMsg('This image is protected');
             }
             $file_name = new LocalFile($title, RepoGroup::singleton()->getLocalRepo());
             $file_mwname = new TempLocalFile(Title::newFromText($mwname, NS_IMAGE), RepoGroup::singleton()->getLocalRepo());
             $file_name->upload($file_mwname->getPath(), $comment, $comment);
             $file_mwname->delete('');
             $newFile = false;
         } elseif ($type == 'existing') {
             //
             // DB entry exists and user doesn't want to overwrite or
             // rename, so they use the existing file from the DB.
             //
             $title = Title::newFromText($name, NS_IMAGE);
         } else {
             //
             // There was a conflict with an existing file in the
             // DB.  Title exists and overwrite action not taken yet.
             //
             $data = array('wpUpload' => 1, 'wpSourceType' => 'web', 'wpUploadFileURL' => '');
             $form = new UploadForm(new FauxRequest($data, true));
             // generate title if current one is taken
             $suggestedName = self::generateNewFilename($name);
             // extensions check
             list($first, $ext) = self::splitFilenameExt($suggestedName);
             $title = Title::newFromText($name, NS_IMAGE);
             $file = wfFindFile($title);
             $vars = array('suggestedFirstPart' => $first, 'extension' => strtolower($ext), 'name' => $name, 'mwname' => $mwname, 'file' => $file, 'image_comment' => $comment);
             $wgOut->setStatusCode(200);
             $wgOut->addHTML(EasyTemplate::html('eiu_conflict.tmpl.php', $vars));
             // return no error
             return '';
         }
         // add watch to file is user needs it
         if ($wgUser->getOption('watchdefault') || $newFile && $wgUser->getOption('watchcreations')) {
             $wgUser->addWatch($title);
         }
         $db =& wfGetDB(DB_MASTER);
         $db->commit();
     } elseif (empty($mwname)) {
         $title = Title::makeTitleSafe(NS_IMAGE, $name);
     } elseif ($name !== null) {
         return WfMsg('eiu-warn3');
     } else {
         // name === null
         $title = Title::newFromText($mwname, NS_IMAGE);
     }
     $file = wfFindFile($title);
     if (!is_object($file)) {
         return wfMsg('File not found');
     }
     $details = self::splitValuePairs($wgRequest->getVal('image-details'));
     $tag = self::makeImageWikiTag($title, $file, $details);
     $vars = array('tag' => $tag, 'file' => $file, 'width' => $details['chosen-width'], 'height' => $details['chosen-height'], 'imageFilename' => $title->getText());
     if (!$fromIIA) {
         $vars['details'] = $details;
         $html = EasyTemplate::html('eiu_upload_summary.tmpl.php', $vars);
     } else {
         $html = IntroImageAdder::addIntroImage($vars);
     }
     $wgOut->setStatusCode(200);
     $wgOut->addHTML($html);
     // return no error
     return '';
 }
Example #3
0
    /**
     * Generates the forms elements(s) for choosing printouts and sorting
     * options. Use its complement processPoSortFormBox() to decode data
     * sent by these elements.
     *
     * @global boolean $smwgQSortingSupport
     * @global boolean $smwgQRandSortingSupport
     * @global WebRequest $wgRequest
     * @global string $smwgScriptPath
     * @global integer $smwgQPrintoutLimit
     * @param mixed $enableAutocomplete
     * @return string
     */
    protected function getPoSortFormBox($enableAutocomplete = SMWQueryUI::ENABLE_AUTO_SUGGEST)
    {
        global $smwgQSortingSupport, $wgRequest, $smwgScriptPath;
        global $smwgQRandSortingSupport, $smwgQPrintoutLimit;
        SMWOutputs::requireResource('jquery.ui.autocomplete');
        SMWOutputs::requireResource('jquery.ui.dialog');
        SMWOutputs::requireResource('ext.smw.style');
        $result = '<span id="smwposortbox">';
        $params = $this->uiCore->getParameters();
        // mainlabel
        if (is_array($params) && array_key_exists('mainlabel', $params)) {
            $mainLabel = $params['mainlabel'];
        } else {
            $mainLabel = '';
        }
        if ($mainLabel == '-') {
            $mainLabelText = '';
            $formDisplay = 'none';
        } else {
            $mainLabelText = $mainLabel;
            $formDisplay = 'block';
        }
        $result .= Html::openElement('div', array('id' => 'smwmainlabel', 'class' => 'smwsort', 'style' => "display:{$formDisplay};")) . Html::openElement('span', array('class' => 'smwquisortlabel')) . Html::openElement('span', array('class' => 'smw-remove')) . Html::openElement('a', array('href' => 'javascript:smwRemoveMainLabel()')) . '<img src="' . $smwgScriptPath . '/skins/images/close-button.png" alt="' . wfMsg('smw_qui_delete') . '">' . '</a>' . '</span><strong>' . wfMsg('smw_qui_rescol') . '</strong></span>' . Xml::openElement('div', array('id' => 'mainlabel-dialog', 'title' => wfMsg('smw_qui_mainlabopts'), 'class' => 'smwmainlabdialog')) . '<table align="center" ><tr>' . '<td>' . wfMsg('smw_qui_dlabel') . '</td>' . '<td><input size="25" value="' . $mainLabelText . '" id="mainlabelvis" /></td>' . '</tr></table>' . '</div>' . '<input type="hidden" name="pmainlabel" value="' . $mainLabel . '" id="mainlabelhid" /> ' . '<a class="smwq-more" href="javascript:smw_makeMainlabelDialog()">' . wfMsg('smw_qui_options') . '</a> ' . '</div>';
        $urlArgs = array();
        $urlArgs['pmainlabel'] = $mainLabel;
        // START: create form elements already submitted earlier via form
        // attempting to load parameters from $wgRequest
        $propertyValues = $wgRequest->getArray('property', array());
        $propertyLabelValues = $wgRequest->getArray('prop_label', array());
        $propertyFormatValues = $wgRequest->getArray('prop_format', array());
        $propertyLimitValues = $wgRequest->getArray('prop_limit', array());
        $orderValues = $wgRequest->getArray('order', array());
        $displayValues = $wgRequest->getArray('display', array());
        $categoryValues = $wgRequest->getArray('category', array());
        $categoryLabelValues = $wgRequest->getArray('cat_label', array());
        $categoryYesValues = $wgRequest->getArray('cat_yes', array());
        $categoryNoValues = $wgRequest->getArray('cat_no', array());
        $mainColumnLabels = $wgRequest->getArray('maincol_label', array());
        $mainLabelCheck = $wgRequest->getCheck('pmainlabel');
        if (!$mainLabelCheck) {
            /*
             * Printouts and sorting might be set via another widget/form/source, so
             * create elements by fetching data from $uiCore. The exact ordering
             * of Ui elements might not be preserved, if the above check were to
             * be removed.
             */
            if (array_key_exists('sort', $params) && array_key_exists('order', $params)) {
                $sortVal = explode(',', trim(strtolower($params['sort'])));
                $orderVal = explode(',', $params['order']);
                reset($sortVal);
                reset($orderVal);
                // give up if sort and order dont have equal number of elements
                if (count($sortVal) !== count($orderVal)) {
                    $orderVal = array();
                    $sortVal = array();
                }
            } else {
                $orderVal = array();
                $sortVal = array();
            }
            $printOuts = $this->uiCore->getPrintOuts();
            $counter = 0;
            foreach ($printOuts as $poValue) {
                if ($poValue->getMode() == SMWPrintRequest::PRINT_CATS) {
                    $categoryValues[$counter] = ' ';
                    $categoryLabelValues[$counter] = $poValue->getLabel();
                    $categoryYesValues[$counter] = '';
                    $categoryNoValues[$counter] = '';
                    $counter++;
                } elseif ($poValue->getMode() == SMWPrintRequest::PRINT_PROP) {
                    $tempProperty = trim(strtolower($poValue->getData()->getText()));
                    $searchKey = array_search($tempProperty, $sortVal);
                    if (!($searchKey === false)) {
                        while ($searchKey != 0) {
                            $propertyValues[$counter] = array_shift($sortVal);
                            $orderValues[$counter] = array_shift($orderVal);
                            $propertyLabelValues[$counter] = '';
                            $propertyFormatValues[$counter] = '';
                            $propertyLimitValues[$counter] = '';
                            $counter++;
                            $searchKey--;
                        }
                        $propertyValues[$counter] = $poValue->getData()->getText();
                        $propertyLabelValues[$counter] = $poValue->getLabel() == $propertyValues[$counter] ? '' : $poValue->getLabel();
                        $propertyFormatValues[$counter] = $poValue->getOutputFormat();
                        $propertyLimitValues[$counter] = $poValue->getParameter('limit') ? $poValue->getParameter('limit') : '';
                        $orderValues[$counter] = $orderVal[0];
                        $displayValues[$counter] = '1';
                        $counter++;
                        array_shift($orderVal);
                        array_shift($sortVal);
                    } else {
                        $propertyValues[$counter] = $poValue->getData()->getText();
                        $propertyLabelValues[$counter] = $poValue->getLabel() == $propertyValues[$counter] ? '' : $poValue->getLabel();
                        $propertyFormatValues[$counter] = $poValue->getOutputFormat();
                        $propertyLimitValues[$counter] = $poValue->getParameter('limit') ? $poValue->getParameter('limit') : '';
                        $displayValues[$counter] = '1';
                        $counter++;
                    }
                } elseif ($poValue->getMode() == SMWPrintRequest::PRINT_THIS) {
                    $mainColumnLabels[$counter] = $poValue->getLabel();
                    $counter++;
                } elseif ($poValue->getMode() == SMWPrintRequest::PRINT_CCAT) {
                    $outputFormat = explode(',', $poValue->getOutputFormat());
                    if (!array_key_exists(1, $outputFormat)) {
                        $outputFormat[1] = '';
                    }
                    $categoryValues[$counter] = $poValue->getData()->getText();
                    $categoryLabelValues[$counter] = $poValue->getLabel();
                    $categoryYesValues[$counter] = $outputFormat[0];
                    $categoryNoValues[$counter] = $outputFormat[1];
                    $counter++;
                }
            }
            while (!empty($sortVal)) {
                $propertyValues[$counter] = array_shift($sortVal);
                $orderValues[$counter] = array_shift($orderVal);
                $propertyLabelValues[$counter] = '';
                $propertyFormatValues[$counter] = '';
                $propertyLimitValues[$counter] = '';
                $counter++;
            }
        }
        $i = 0;
        $additionalPOs = array();
        $keys = array_keys($propertyValues);
        foreach ($keys as $value) {
            $additionalPOs[$value] = $propertyValues[$value];
            // array_merge won't work because numeric keys need to be preserved
        }
        $keys = array_keys($categoryValues);
        foreach ($keys as $value) {
            $additionalPOs[$value] = $categoryValues[$value];
            // array_merge won't work because numeric keys need to be preserved
        }
        $keys = array_keys($mainColumnLabels);
        foreach ($keys as $value) {
            $additionalPOs[$value] = $mainColumnLabels[$value];
            // array_merge won't work because numeric keys need to be preserved
        }
        ksort($additionalPOs);
        foreach ($additionalPOs as $key => $value) {
            if (array_key_exists($key, $propertyValues)) {
                /*
                 * Make an element for additional properties
                 */
                $result .= Html::openElement('div', array('id' => "sort_div_{$i}", 'class' => 'smwsort'));
                $result .= '<span class="smwquisortlabel">' . '<span class="smw-remove">' . '<a href="javascript:removePOInstance(\'sort_div_' . $i . '\')">' . '<img src="' . $smwgScriptPath . '/skins/images/close-button.png"' . 'alt="' . wfMsg('smw_qui_delete') . '">' . '</a></span>';
                $result .= wfMsg('smw_qui_property') . '</span>';
                $result .= Html::input('property[' . $i . ']', $propertyValues[$key], 'text', array('size' => '25', 'id' => "property{$i}")) . "\n";
                $urlArgs["property[{$i}]"] = $propertyValues[$key];
                if ($smwgQSortingSupport) {
                    $result .= Html::openElement('select', array('name' => "order[{$i}]"));
                    if (array_key_exists($key, $orderValues)) {
                        $urlArgs["order[{$i}]"] = $orderValues[$key];
                    }
                    $if1 = !array_key_exists($key, $orderValues) || $orderValues[$key] == 'NONE';
                    $result .= Xml::option(wfMsg('smw_qui_nosort'), "NONE", $if1);
                    $if2 = array_key_exists($key, $orderValues) && $orderValues[$key] == 'ASC';
                    $result .= Xml::option(wfMsg('smw_qui_ascorder'), "ASC", $if2);
                    $if3 = array_key_exists($key, $orderValues) && $orderValues[$key] == 'DESC';
                    $result .= Xml::option(wfMsg('smw_qui_descorder'), "DESC", $if3);
                    if ($smwgQRandSortingSupport) {
                        $if4 = array_key_exists($key, $orderValues) && $orderValues[$key] == 'RANDOM';
                        $result .= Xml::option(wfMsg('smw_qui_randorder'), "RANDOM", $if4);
                    }
                    $result .= Xml::closeElement('select');
                    $if5 = array_key_exists($key, $displayValues);
                    $result .= Xml::checkLabel(wfMsg('smw_qui_shownresults'), "display[{$i}]", "display{$i}", $if5);
                    if ($if5) {
                        $urlArgs["display[{$i}]"] = '1';
                    }
                }
                if (array_key_exists($key, $propertyLabelValues)) {
                    $result .= Html::hidden("prop_label[{$i}]", $propertyLabelValues[$key], array('id' => "prop_label{$i}"));
                    $urlArgs["prop_label[{$i}]"] = $propertyLabelValues[$key];
                } else {
                    $result .= Html::hidden("prop_label[{$i}]", '', array('id' => "prop_label{$i}"));
                }
                if (array_key_exists($key, $propertyFormatValues)) {
                    $result .= Html::hidden("prop_format[{$i}]", $propertyFormatValues[$key], array('id' => "prop_format{$i}"));
                    $urlArgs["prop_format[{$i}]"] = $propertyFormatValues[$key];
                } else {
                    $result .= Html::hidden("prop_format[{$i}]", '', array('id' => "prop_format{$i}"));
                }
                if (array_key_exists($key, $propertyLimitValues)) {
                    $result .= Html::hidden("prop_limit[{$i}]", $propertyLimitValues[$key], array('id' => "prop_limit{$i}"));
                    $urlArgs["prop_limit[{$i}]"] = $propertyLimitValues[$key];
                } else {
                    $result .= Html::hidden("prop_limit[{$i}]", '', array('id' => "prop_limit{$i}"));
                }
                $result .= Html::element('a', array('id' => "more{$i}", 'class' => 'smwq-more', 'href' => "javascript:smw_makePropDialog('{$i}')"), WfMsg('smw_qui_options'));
                $result .= Xml::closeElement('div');
                $i++;
            }
            if (array_key_exists($key, $categoryValues)) {
                if (!array_key_exists($key, $categoryLabelValues)) {
                    $categoryLabelValues[$key] = '';
                }
                if (!array_key_exists($key, $categoryYesValues)) {
                    $categoryYesValues[$key] = '';
                }
                if (!array_key_exists($key, $categoryNoValues)) {
                    $categoryNoValues[$key] = '';
                }
                /*
                 * Make an element for additional categories
                 */
                $result .= Html::openElement('div', array('id' => "sort_div_{$i}", 'class' => 'smwsort'));
                $result .= '<span class="smwquisortlabel">' . '<span class="smw-remove">' . Html::openElement('a', array('href' => "javascript:removePOInstance('sort_div_{$i}')")) . '<img src="' . $smwgScriptPath . '/skins/images/close-button.png" alt="' . wfMsg('smw_qui_delete') . '">' . '</a>' . '</span>' . wfMsg('smw_qui_category') . '</span>' . Xml::input("category[{$i}]", '25', $categoryValues[$key], array('id' => "category{$i}")) . " " . Html::hidden("cat_label[{$i}]", $categoryLabelValues[$key], array('id' => "cat_label{$i}")) . Html::hidden("cat_yes[{$i}]", $categoryYesValues[$key], array('id' => "cat_yes{$i}")) . Html::hidden("cat_no[{$i}]", $categoryNoValues[$key], array('id' => "cat_no{$i}")) . Html::element('a', array('id' => "more{$i}", 'class' => 'smwq-more', 'href' => "javascript:smw_makeCatDialog('{$i}')"), WfMsg('smw_qui_options')) . Xml::closeElement('div');
                $urlArgs["category[{$i}]"] = $categoryValues[$key] === '' ? ' ' : $categoryValues[$key];
                $urlArgs["cat_label[{$i}]"] = $categoryLabelValues[$key];
                $urlArgs["cat_yes[{$i}]"] = $categoryYesValues[$key];
                $urlArgs["cat_no[{$i}]"] = $categoryNoValues[$key];
                $i++;
            }
            if (array_key_exists($key, $mainColumnLabels)) {
                /*
                 * Make an element for main column aka query-matches
                 */
                $result .= Html::openElement('div', array('id' => "sort_div_{$i}", 'class' => 'smwsort')) . '<span class="smwquisortlabel">' . '<span class="smw-remove">' . Html::openelement('a', array('href' => "javascript:removePOInstance('sort_div_{$i}')")) . '<img src="' . $smwgScriptPath . '/skins/images/close-button.png" alt="' . wfMsg('smw_qui_delete') . '">' . '</a>' . '</span><strong>' . wfMsg('smw_qui_rescol') . '</strong></span>' . Html::hidden("maincol_label[{$i}]", $mainColumnLabels[$key], array('id' => "maincol_label{$i}")) . " " . '<a class="smwq-more" href="javascript:smw_makeQueryMatchesDialog(\'' . $i . '\')">' . wfMsg('smw_qui_options') . '</a> ' . '</div>';
                $urlArgs["maincol_label[{$i}]"] = $mainColumnLabels[$key] === '' ? ' ' : $mainColumnLabels[$key];
                $i++;
            }
        }
        $numSortValues = $i;
        $this->setUrlArgs($urlArgs);
        // END: create form elements already submitted earlier via form
        // create hidden form elements to be cloned later
        // property
        $hiddenProperty = Html::openElement('div', array('id' => 'property_starter', 'style' => 'display:none')) . '<span class="smwquisortlabel">' . '<span class="smw-remove">' . '<a>' . '<img src="' . $smwgScriptPath . '/skins/images/close-button.png" alt="' . wfMsg('smw_qui_delete') . '">' . '</a>' . '</span>' . wfMsg('smw_qui_property') . '</span>' . Xml::input('property_num', '25') . " ";
        if ($smwgQSortingSupport) {
            $hiddenProperty .= Html::openElement('select', array('name' => 'order_num')) . Xml::option(wfMsg('smw_qui_nosort'), 'NONE') . Xml::option(wfMsg('smw_qui_ascorder'), 'ASC') . Xml::option(wfMsg('smw_qui_descorder'), 'DESC');
            if ($smwgQRandSortingSupport) {
                $hiddenProperty .= Xml::option(wfMsg('smw_qui_randorder'), 'RANDOM');
            }
            $hiddenProperty .= Xml::closeElement('select') . Xml::checkLabel(wfMsg('smw_qui_shownresults'), "display_num", '', true);
        }
        $hiddenProperty .= Html::hidden('prop_label_num', '') . Html::hidden('prop_format_num', '') . Html::hidden('prop_limit_num', '') . Xml::closeElement('div');
        $hiddenProperty = json_encode($hiddenProperty);
        // category
        $hiddenCategory = Html::openElement('div', array('id' => 'category_starter', 'style' => 'display:none')) . '<span class="smwquisortlabel">' . '<span class="smw-remove">' . '<a>' . '<img src="' . $smwgScriptPath . '/skins/images/close-button.png" alt="' . wfMsg('smw_qui_delete') . '">' . '</a>' . '</span>' . wfMsg('smw_qui_category') . '</span>' . Xml::input("category_num", '25') . " " . '<input type="hidden" name="cat_label_num" />' . '<input type="hidden" name="cat_yes_num" />' . '<input type="hidden" name="cat_no_num" />' . Xml::closeElement('div');
        $hiddenCategory = json_encode($hiddenCategory);
        // For '?' printouts
        $hiddenMainColumn = Html::openElement('div', array('id' => 'maincol_starter', 'style' => 'display:none')) . '<span class="smwquisortlabel">' . '<span class="smw-remove">' . '<a>' . '<img src="' . $smwgScriptPath . '/skins/images/close-button.png" alt="' . wfMsg('smw_qui_delete') . '">' . '</a>' . '</span><strong>' . wfMsg('smw_qui_rescol') . '</strong></span>' . Html::hidden("maincol_label_num", '') . " " . Xml::closeElement('div');
        $hiddenMainColumn = json_encode($hiddenMainColumn);
        // Create dialog-boxes
        // create dialogbox for Property options
        $propertyHtml = Xml::inputLabelSep(wfMsg('smw_qui_prop'), '', 'd-property', 'd-property');
        $propertyLabelHtml = Xml::inputLabelSep(wfMsg('smw_qui_labl'), '', 'd-prop-label', 'd-prop-label');
        $propertyFormatHtml = Xml::inputLabelSep(wfMsg('smw_qui_formt'), '', 'd-prop-format', 'd-prop-format');
        $propertyLimitHtml = Xml::inputLabelSep(wfMsg('smw_qui_limt'), 'd-prop-limit', 'd-prop-limit');
        $propertyDialogBox = Xml::openElement('div', array('id' => 'prop-dialog', 'title' => wfMsg('smw_prp_options'), 'class' => 'smwpropdialog')) . '<table align="center">' . '<tr><td>' . $propertyHtml[0] . '</td><td>' . $propertyHtml[1] . '</td></tr>' . '<tr><td>' . $propertyLabelHtml[0] . '</td><td>' . $propertyLabelHtml[1] . '</td></tr>' . '<tr><td>' . $propertyLimitHtml[0] . '</td><td>' . $propertyLimitHtml[1] . '</td></tr>' . '<tr><td>' . $propertyFormatHtml[0] . '</td><td>' . $propertyFormatHtml[1] . '</td></tr>' . '</table>' . Xml::closeElement('div');
        // create dialogbox for Category options
        $categoryHtml = Xml::inputLabelSep(wfMsg('smw_qui_dcategory'), '', 'd-category', 'd-category');
        $categoryLabelHtml = Xml::inputLabelSep(wfMsg('smw_qui_dlabel'), '', 'd-category-label', 'd-category-label');
        $categoryYesHtml = Xml::inputLabelSep(wfMsg('smw_qui_dcatyes'), '', 'd-category-yes', 'd-category-yes');
        $categoryNoHtml = Xml::inputLabelSep(wfMsg('smw_qui_dcatno'), '', 'd-category-no', 'd-category-no');
        $categoryDialogBox = Xml::openElement('div', array('id' => 'cat-dialog', 'title' => wfMsg('smw_qui_catopts'), 'class' => 'smwcatdialog')) . '<table align="center">' . '<tr><td>' . $categoryHtml[0] . '</td><td>' . $categoryHtml[1] . '</td></tr>' . '<tr><td>' . $categoryLabelHtml[0] . '</td><td>' . $categoryLabelHtml[1] . '</td></tr>' . '</table><br/><table align="center">' . '<tr><td>' . $categoryYesHtml[0] . '</td><td>' . $categoryYesHtml[1] . '</td></tr>' . '<tr><td>' . $categoryNoHtml[0] . '</td><td>' . $categoryNoHtml[1] . '</td></tr>' . '</table>' . Xml::closeElement('div');
        // Create dialog box for QueryMatches
        $mainResLabelHtml = Xml::inputLabelSep(wfMsg('smw_qui_dlabel'), '', 'd-mainres-label');
        $mainResDialogBox = Xml::openElement('div', array('id' => 'mainres-dialog', 'title' => wfMsg('smw_qui_mainlabopts'), 'class' => 'smwmainlabdialog')) . '<table align="center">' . '<tr><td>' . $mainResLabelHtml[0] . '</td><td>' . $mainResLabelHtml[1] . '</td></tr>' . '</table>' . Xml::closeElement('div');
        $result .= '<div id="sorting_main"></div>' . "\n";
        $result .= '[<a href="javascript:smw_addPropertyInstance(\'property_starter\', \'sorting_main\')">' . wfMsg('smw_qui_addnprop') . '</a>]' . '[<a href="javascript:smw_addCategoryInstance(\'category_starter\', \'sorting_main\')">' . wfMsg('smw_qui_addcategory') . '</a>]' . '[<a href="javascript:smw_addMainColInstance(\'maincol_starter\', \'sorting_main\')">' . wfMsg('smw_qui_addrescol') . '</a>]' . "\n";
        // Javascript code for handling adding and removing the "sort" inputs
        if ($enableAutocomplete == SMWQueryUI::ENABLE_AUTO_SUGGEST) {
            $this->enableAutocompletion();
        }
        // localisation messages for javascript
        $optionsMsg = wfMsg('smw_qui_options');
        $okMsg = wfMsg('smw_qui_ok');
        $cancelMsg = wfMsg('smw_qui_cancel');
        $javascriptText = <<<EOT
<script type="text/javascript">
\tvar num_elements = {$numSortValues};
\tvar smwgQPrintoutLimit={$smwgQPrintoutLimit};
EOT;
        // add autocomplete
        if ($enableAutocomplete == SMWQueryUI::ENABLE_AUTO_SUGGEST) {
            $javascriptText .= <<<EOT

\tfunction smw_property_autocomplete(){
\t\tjQuery( '[name*="property"]' ).autocomplete( {
\t\t\tminLength: 2,
\t\t\tsource: function( request, response ) {
\t\t\t\turl = wgScriptPath+'/api.php?action=opensearch&limit=10&namespace='+wgNamespaceIds['property']+'&format=jsonfm';

\t\t\t\tjQuery.getJSON( url, 'search='+request.term, function( data ) {
\t\t\t\t\t//remove the namespace prefix 'Property:' from returned data
\t\t\t\t\tfor( i=0; i < data[1].length; i++ ){
\t\t\t\t\t\tdata[1][i]=data[1][i].substr(data[1][i].indexOf(':')+1);
\t\t\t\t\t}
\t\t\t\t\tresponse(data[1]);
\t\t\t\t});
\t\t\t}
\t\t} );
\t}

\tfunction smw_category_autocomplete(){
\t\t\tjQuery( '[name*="category"]' ).autocomplete( {
\t\t\tminLength: 2,
\t\t\tsource: function(request, response) {
\t\t\t\turl = wgScriptPath+'/api.php?action=opensearch&limit=10&namespace='+wgNamespaceIds['category']+'&format=jsonfm';

\t\t\t\tjQuery.getJSON( url, 'search='+request.term, function( data ){
\t\t\t\t\t//remove the namespace prefix 'Category:' from returned data
\t\t\t\t\tfor( i=0; i<data[1].length; i++ ){
\t\t\t\t\t\tdata[1][i]=data[1][i].substr(data[1][i].indexOf(':')+1);
\t\t\t\t\t}
\t\t\t\t\tresponse(data[1]);
\t\t\t\t});
\t\t\t}
\t\t});
\t}
EOT;
        } else {
            $javascriptText .= <<<EOT
\tfunction smw_property_autocomplete(){
\t}

\tfunction smw_category_autocomplete(){
\t}

EOT;
        }
        $javascriptText .= <<<EOT

\tfunction smw_makeMainlabelDialog(){
\t\tjQuery('#mainlabel-dialog').dialog("open");
\t}

\tfunction smwRemoveMainLabel(){
\t\t\tjQuery( '#mainlabelhid' ).attr( 'value', '-' );
\t\t\tjQuery( '#mainlabelvis' ).attr( 'value', '' );
\t\t\tjQuery( '#smwmainlabel' ).hide();
\t}


\tfunction smw_makeQueryMatchesDialog( qm_id ){
\t\tqmLabel=jQuery('#maincol_label'+qm_id).attr('value');
\t\tjQuery('#d-mainres-label').attr('value', qmLabel);
\t\tjQuery( '#mainres-dialog' ).dialog.sortid = qm_id;
\t\tjQuery( '#mainres-dialog' ).dialog( 'open' );
\t}

\tfunction smw_makeCatDialog( cat_id ){
\t\tjQuery( '#prop-cat input' ).attr('value','');

\t\tcat=jQuery('#category'+cat_id)[0].value;
\t\tlabel=jQuery('#cat_label'+cat_id)[0].value;
\t\tyes = jQuery('#cat_yes'+cat_id)[0].value;
\t\tno = jQuery('#cat_no'+cat_id)[0].value;

\t\tjQuery('#d-category-yes').attr('value',yes);
\t\tjQuery('#d-category-no').attr('value',no);
\t\tjQuery('#d-category-label').attr('value',label);
\t\tjQuery('#d-category').attr('value',cat);

\t\tjQuery('#cat-dialog').dialog.id=cat_id;
\t\tjQuery('#cat-dialog').dialog('open');
\t}

\tfunction smw_makePropDialog(prop_id){
\t\tjQuery('#prop-dialog input').attr('value','');
\t\tprop=jQuery('#property'+prop_id).attr('value');
\t\tlabel=jQuery('#prop_label'+prop_id).attr('value');
\t\tformat=jQuery('#prop_format'+prop_id).attr('value');
\t\tlimit=jQuery('#prop_limit'+prop_id).attr('value');
\t\tjQuery('#d-property').attr('value', prop);
\t\tjQuery('#d-prop-label').attr('value', label);
\t\tjQuery('#d-prop-limit').attr('value', limit);
\t\tjQuery('#d-prop-format').attr('value', format);
\t\tjQuery('#prop-dialog').dialog.id=prop_id;
\t\tjQuery('#prop-dialog').dialog('open');
\t}
\t// code for handling adding and removing the "sort" inputs

\tfunction smw_addPropertyInstance(starter_div_id, main_div_id) {
\t\tif( jQuery( '.smwsort' ).length > smwgQPrintoutLimit ) return;

\t\tvar starter_div = document.getElementById(starter_div_id);
\t\tvar main_div = document.getElementById(main_div_id);

\t\t//Create the new instance
\t\tvar new_div = starter_div.cloneNode(true);
\t\tvar div_id = 'sort_div_' + num_elements;
\t\tnew_div.id = div_id;
\t\tnew_div.style.display = 'block';
\t\tjQuery(new_div.getElementsByTagName('label')).attr('for', 'display'+num_elements);
\t\tjQuery(new_div).addClass( 'smwsort' );
\t\tvar children = new_div.getElementsByTagName('*');
\t\tvar x;
\t\tfor (x = 0; x < children.length; x++) {
\t\t\tif (jQuery(children[x]).attr('for')) jQuery(children[x]).attr('for',"display"+num_elements);
\t\t\tif (children[x].name){
\t\t\t\tchildren[x].id = children[x].name.replace(/_num/, ''+num_elements);
\t\t\t\tchildren[x].name = children[x].name.replace(/_num/, '[' + num_elements + ']');
\t\t\t}
\t\t}

\t\t//Create 'options' link
\t\tvar more_button =document.createElement('span');
\t\tmore_button.innerHTML = ' <a class="smwq-more" href="javascript:smw_makePropDialog(\\'' + num_elements + '\\')">{$optionsMsg}</a> ';
\t\tmore_button.id = 'more'+num_elements;
\t\tnew_div.appendChild(more_button);

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

\t\t// initialize delete button
\t\tst='sort_div_'+num_elements;
\t\tjQuery('#'+new_div.id).find(".smw-remove a")[0].href="javascript:removePOInstance('"+st+"')";
\t\tnum_elements++;
\t\tsmw_property_autocomplete();
\t}

\tfunction smw_addCategoryInstance(starter_div_id, main_div_id) {
\t\tif( jQuery( '.smwsort' ).length > smwgQPrintoutLimit ) return;

\t\tvar starter_div = document.getElementById(starter_div_id);
\t\tvar main_div = document.getElementById(main_div_id);

\t\t//Create the new instance
\t\tvar new_div = starter_div.cloneNode(true);
\t\tvar div_id = 'sort_div_' + num_elements;
\t\tnew_div.id = div_id;
\t\tnew_div.style.display = 'block';
\t\tjQuery(new_div.getElementsByTagName('label')).attr('for', 'display'+num_elements);
\t\tjQuery(new_div).addClass( 'smwsort' );
\t\tvar children = new_div.getElementsByTagName('*');
\t\tvar x;
\t\tfor (x = 0; x < children.length; x++) {
\t\t\tif (jQuery(children[x]).attr('for')) jQuery(children[x]).attr('for',"display"+num_elements);
\t\t\tif (children[x].name){
\t\t\t\tchildren[x].id = children[x].name.replace(/_num/, ''+num_elements);
\t\t\t\tchildren[x].name = children[x].name.replace(/_num/, '[' + num_elements + ']');
\t\t\t}
\t\t}

\t\t//Create 'options' link
\t\tvar more_button =document.createElement('span');
\t\tmore_button.innerHTML = ' <a class="smwq-more" href="javascript:smw_makeCatDialog(\\'' + num_elements + '\\')">{$optionsMsg}</a> ';
\t\tmore_button.id = 'more'+num_elements;
\t\tnew_div.appendChild(more_button);

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

\t\t// initialize delete button
\t\tst='sort_div_'+num_elements;
\t\tjQuery('#'+new_div.id).find(".smw-remove a")[0].href="javascript:removePOInstance('"+st+"')";
\t\tnum_elements++;
\t\tsmw_category_autocomplete();
\t}

\tfunction smw_addMainColInstance(starter_div_id, main_div_id) {
\t\tif( (jQuery('#smwmainlabel').css('display')=='none')
\t\t\t&& (jQuery('.smwsort').length==1)
\t\t){
\t\t\tjQuery('#mainlabelhid').attr('value','');
\t\t\tjQuery('#mainlabelvis').attr('value','');
\t\t\tjQuery('#smwmainlabel').show();
\t\t} else {
\t\t\tif( jQuery( '.smwsort' ).length > smwgQPrintoutLimit ){
\t\t\t\treturn;
\t\t\t}
\t\t\tvar starter_div = document.getElementById(starter_div_id);
\t\t\tvar main_div = document.getElementById(main_div_id);

\t\t\t//Create the new instance
\t\t\tvar new_div = starter_div.cloneNode(true);
\t\t\tvar div_id = 'sort_div_' + num_elements;
\t\t\tnew_div.id = div_id;
\t\t\tnew_div.style.display = 'block';
\t\t\tjQuery(new_div.getElementsByTagName('label')).attr('for', 'display'+num_elements);
\t\t\tjQuery(new_div).addClass( 'smwsort' );
\t\t\tvar children = new_div.getElementsByTagName('*');
\t\t\tvar x;
\t\t\tfor (x = 0; x < children.length; x++) {
\t\t\t\tif (jQuery(children[x]).attr('for')) jQuery(children[x]).attr('for',"display"+num_elements);
\t\t\t\tif (children[x].name){
\t\t\t\t\tchildren[x].id = children[x].name.replace(/_num/, ''+num_elements);
\t\t\t\t\tchildren[x].name = children[x].name.replace(/_num/, '[' + num_elements + ']');
\t\t\t\t}
\t\t\t}
\t\t\t//Create 'options' link
\t\t\tvar more_button =document.createElement('span');
\t\t\tmore_button.innerHTML = ' <a class="smwq-more" href="javascript:smw_makeQueryMatchesDialog(\\'' + num_elements + '\\')">{$optionsMsg}</a> ';
\t\t\tmore_button.id = 'more'+num_elements;
\t\t\tnew_div.appendChild(more_button);

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

\t\t\t// initialize delete button
\t\t\tst='sort_div_'+num_elements;
\t\t\tjQuery('#'+new_div.id).find(".smw-remove a")[0].href="javascript:removePOInstance('"+st+"')";
\t\t\tnum_elements++;
\t\t}
\t}

\tfunction removePOInstance(div_id) {
\t\tvar olddiv = document.getElementById(div_id);
\t\tvar parent = olddiv.parentNode;
\t\tparent.removeChild(olddiv);
\t}

\tjQuery(function(){
\t\tjQuery('{$hiddenProperty}').appendTo(document.body);
\t\tjQuery('{$hiddenCategory}').appendTo(document.body);
\t\tjQuery('{$hiddenMainColumn}').appendTo(document.body);
\t\tjQuery('{$propertyDialogBox}').appendTo(document.body);
\t\tjQuery('{$categoryDialogBox}').appendTo(document.body);
\t\tjQuery('{$mainResDialogBox}').appendTo(document.body);

\t\tjQuery( '#mainlabel-dialog' ).dialog( {
\t\t\tautoOpen: false,
\t\t\tmodal: true,
\t\t\tresizable: true,
\t\t\tminWidth: 400,
\t\t\tbuttons: {
\t\t\t\t"{$okMsg}": function(){
\t\t\t\t\tjQuery('#mainlabelhid').attr('value',jQuery('#mainlabelvis').attr('value'));
\t\t\t\t\tjQuery(this).dialog("close");
\t\t\t\t},
\t\t\t\t"{$cancelMsg}": function(){
\t\t\t\t\tjQuery(this).dialog("close");
\t\t\t\t}
\t\t\t}
\t\t} );

\t\tjQuery( '#mainres-dialog' ).dialog( {
\t\t\tautoOpen: false,
\t\t\tmodal: true,
\t\t\tresizable: true,
\t\t\tminWidth: 400,
\t\t\tbuttons: {
\t\t\t\t"{$okMsg}": function(){
\t\t\t\t\tid = jQuery( this ).dialog.sortid;
\t\t\t\t\tlabel = jQuery('#d-mainres-label');
\t\t\t\t\tjQuery('#maincol_label'+id).attr('value', label);
\t\t\t\t\tjQuery(this).dialog("close");
\t\t\t\t},
\t\t\t\t"{$cancelMsg}": function(){
\t\t\t\t\tjQuery(this).dialog("close");
\t\t\t\t}
\t\t\t}
\t\t} );

\t\tjQuery( '#cat-dialog' ).dialog( {
\t\t\tautoOpen: false,
\t\t\tmodal: true,
\t\t\tresizable: true,
\t\t\tminHeight: 200,
\t\t\tminWidth: 400,
\t\t\tbuttons: {
\t\t\t\t"{$okMsg}": function(){
\t\t\t\t\tcat = jQuery('#d-category').attr('value');
\t\t\t\t\tlabel = jQuery('#d-category-label').attr('value');
\t\t\t\t\tyes = jQuery('#d-category-yes').attr('value');
\t\t\t\t\tno = jQuery('#d-category-no').attr('value');
\t\t\t\t\tid=jQuery(this).dialog.id;

\t\t\t\t\tjQuery('#category'+id).attr('value',cat);
\t\t\t\t\tjQuery('#cat_label'+id).attr('value',label);
\t\t\t\t\tjQuery('#cat_yes'+id).attr('value',yes);
\t\t\t\t\tjQuery('#cat_no'+id).attr('value',no);
\t\t\t\t\tjQuery(this).dialog("close");
\t\t\t\t},
\t\t\t\t"{$cancelMsg}": function(){
\t\t\t\t\tjQuery('#cat-dialog input').attr('value','');
\t\t\t\t\tjQuery(this).dialog("close");
\t\t\t\t}
\t\t\t}
\t\t});

\t\tjQuery('#prop-dialog').dialog({
\t\t\tautoOpen: false,
\t\t\tmodal: true,
\t\t\tresizable: true,
\t\t\tminWidth: 400,
\t\t\tbuttons: {
\t\t\t\t"{$okMsg}": function(){
\t\t\t\t\tid=jQuery(this).dialog.id;
\t\t\t\t\tproperty=jQuery('#d-property').attr('value');
\t\t\t\t\tlabel=jQuery('#d-prop-label').attr('value');
\t\t\t\t\tlimit=jQuery('#d-prop-limit').attr('value');
\t\t\t\t\tformat=jQuery('#d-prop-format').attr('value');


\t\t\t\t\tjQuery('#property'+id).attr('value',property);
\t\t\t\t\tjQuery('#prop_label'+id).attr('value',label);
\t\t\t\t\tjQuery('#prop_limit'+id).attr('value',limit);
\t\t\t\t\tjQuery('#prop_format'+id).attr('value',format);
\t\t\t\t\tjQuery(this).dialog("close");
\t\t\t\t},
\t\t\t\t"{$cancelMsg}": function(){
\t\t\t\t\tjQuery('#prop-dialog input').attr('value','');
\t\t\t\t\tjQuery(this).dialog("close");
\t\t\t\t}
\t\t\t}
\t\t});
\t\tjQuery('#sort-more').click(function(){jQuery('#prop-dialog').dialog("open");});
\t\tjQuery('#d-category').bind('change keyup focus click',function(){
\t\t\tif(jQuery(this).attr('value')==''){
\t\t\t\tjQuery('#d-category-yes').css('visibility','hidden');
\t\t\t\tjQuery('#d-category-no').css('visibility','hidden');
\t\t\t\tjQuery('#cat-dialog [for="d-category-no"]').css('visibility','hidden');
\t\t\t\tjQuery('#cat-dialog [for="d-category-yes"]').css('visibility','hidden');
\t\t\t} else {
\t\t\t\tjQuery('#d-category-yes').css('visibility','visible');
\t\t\t\tjQuery('#d-category-no').css('visibility','visible');
\t\t\t\tjQuery('#cat-dialog [for="d-category-no"]').css('visibility','visible');
\t\t\t\tjQuery('#cat-dialog [for="d-category-yes"]').css('visibility','visible');
\t\t\t}
\t\t});
\t});

\tjQuery(document).ready(smw_property_autocomplete);
\tjQuery(document).ready(smw_category_autocomplete);
</script>

EOT;
        SMWOutputs::requireScript('smwAutocompleteQueryUI', $javascriptText);
        $result .= '</span>';
        return $result;
    }
 /**
  * This functions handle the third step of the WMU, image insertion
  *
  * @return bool|String
  */
 function insertImage()
 {
     global $wgRequest, $wgUser, $wgContLang;
     $type = $wgRequest->getVal('type');
     $name = $wgRequest->getVal('name');
     $mwname = $wgRequest->getVal('mwname');
     $tempid = $wgRequest->getVal('tempid');
     $gallery = $wgRequest->getVal('gallery', '');
     $title_main = urldecode($wgRequest->getVal('article', ''));
     $ns = $wgRequest->getVal('ns', '');
     $link = urldecode($wgRequest->getVal('link', ''));
     // Are we in the ck editor?
     $ck = $wgRequest->getVal('ck');
     $extraId = $wgRequest->getVal('extraId');
     $newFile = true;
     $file = null;
     if ($name !== NULL) {
         $name = urldecode($name);
         if ($name == '') {
             header('X-screen-type: error');
             return WfMsg('wmu-warn3');
         } else {
             $name = preg_replace("/[^" . Title::legalChars() . "]|:/", '-', $name);
             // did they give no extension at all when they changed the name?
             $ext = explode('.', $name);
             array_shift($ext);
             if (count($ext)) {
                 $finalExt = $ext[count($ext) - 1];
             } else {
                 $finalExt = '';
             }
             if ('' == $finalExt) {
                 header('X-screen-type: error');
                 return wfMsg('wmu-filetype-missing');
             }
             $title = Title::makeTitleSafe(NS_IMAGE, $name);
             if (is_null($title)) {
                 header('X-screen-type: error');
                 return wfMsg('wmu-filetype-incorrect');
             }
             if ($title->exists()) {
                 if ($type == 'overwrite') {
                     $title = Title::newFromText($name, 6);
                     // is the target protected?
                     $permErrors = $title->getUserPermissionsErrors('edit', $wgUser);
                     $permErrorsUpload = $title->getUserPermissionsErrors('upload', $wgUser);
                     $permErrorsCreate = $title->exists() ? array() : $title->getUserPermissionsErrors('create', $wgUser);
                     if ($permErrors || $permErrorsUpload || $permErrorsCreate) {
                         header('X-screen-type: error');
                         return wfMsg('wmu-file-protected');
                     }
                     $file_name = new LocalFile($title, RepoGroup::singleton()->getLocalRepo());
                     $file_mwname = new FakeLocalFile(Title::newFromText($mwname, 6), RepoGroup::singleton()->getLocalRepo());
                     if (!empty($extraId)) {
                         $flickrResult = $this->getFlickrPhotoInfo($extraId);
                         $nsid = $flickrResult['owner']['nsid'];
                         // e.g. 49127042@N00
                         $username = $flickrResult['owner']['username'];
                         // e.g. bossa67
                         $license = $flickrResult['license'];
                         $caption = '{{MediaWiki:Flickr' . intval($license) . '|1=' . wfEscapeWikiText($extraId) . '|2=' . wfEscapeWikiText($nsid) . '|3=' . wfEscapeWikiText($username) . '}}';
                     } else {
                         $caption = '';
                     }
                     $file_name->upload($file_mwname->getPath(), '', $caption);
                     $file_mwname->delete('');
                     $this->tempFileClearInfo($tempid);
                     $newFile = false;
                 } else {
                     if ($type == 'existing') {
                         $file = wfFindFile(Title::newFromText($name, 6));
                         if (!empty($file)) {
                             header('X-screen-type: existing');
                             $props = array();
                             $props['file'] = $file;
                             $props['mwname'] = $name;
                             $props['default_caption'] = Wikia::getProps($file->getTitle()->getArticleID(), 'default_caption');
                             return $this->detailsPage($props);
                         } else {
                             header('X-screen-type: error');
                             return wfMsg('wmu-file-error');
                         }
                     } else {
                         header('X-screen-type: conflict');
                         $tmpl = new EasyTemplate(dirname(__FILE__) . '/templates/');
                         // extensions check
                         list($partname, $ext) = UploadBase::splitExtensions($name);
                         if (count($ext)) {
                             $finalExt = $ext[count($ext) - 1];
                         } else {
                             $finalExt = '';
                         }
                         // for more than one "extension"
                         if (count($ext) > 1) {
                             for ($i = 0; $i < count($ext) - 1; $i++) {
                                 $partname .= '.' . $ext[$i];
                             }
                         }
                         $tmpl->set_vars(array('partname' => $partname, 'extension' => strtolower($finalExt), 'mwname' => $mwname, 'extraId' => $extraId));
                         return $tmpl->render('conflict');
                     }
                 }
             } else {
                 // is the target protected?
                 $permErrors = $title->getUserPermissionsErrors('edit', $wgUser);
                 $permErrorsUpload = $title->getUserPermissionsErrors('upload', $wgUser);
                 $permErrorsCreate = $title->exists() ? array() : $title->getUserPermissionsErrors('create', $wgUser);
                 if ($permErrors || $permErrorsUpload || $permErrorsCreate) {
                     header('X-screen-type: error');
                     return wfMsg('wmu-file-protected');
                 }
                 $temp_file = new FakeLocalFile(Title::newFromText($mwname, 6), RepoGroup::singleton()->getLocalRepo());
                 $file = new LocalFile($title, RepoGroup::singleton()->getLocalRepo());
                 if (!empty($extraId)) {
                     $flickrResult = $this->getFlickrPhotoInfo($extraId);
                     $nsid = $flickrResult['owner']['nsid'];
                     // e.g. 49127042@N00
                     $username = $flickrResult['owner']['username'];
                     // e.g. bossa67
                     $license = $flickrResult['license'];
                     $caption = '{{MediaWiki:Flickr' . intval($license) . '|1=' . wfEscapeWikiText($extraId) . '|2=' . wfEscapeWikiText($nsid) . '|3=' . wfEscapeWikiText($username) . '}}';
                 } else {
                     // get the supplied license value
                     $license = $wgRequest->getVal('ImageUploadLicense');
                     if ($license != '') {
                         $caption = '== ' . wfMsgForContent('license') . " ==\n" . '{{' . $license . '}}' . "\n";
                     } else {
                         $caption = "";
                     }
                 }
                 $file->upload($temp_file->getPath(), '', $caption);
                 $temp_file->delete('');
                 $this->tempFileClearInfo($tempid);
             }
             if ($wgUser->getGLobalPreference('watchdefault') || $newFile && $wgUser->getGlobalPreference('watchcreations')) {
                 $wgUser->addWatch($title);
             }
             $db =& wfGetDB(DB_MASTER);
             $db->commit();
         }
     } else {
         $title = Title::newFromText($mwname, 6);
     }
     if (is_null($file)) {
         $file = wfFindFile($title);
     }
     if (!is_object($file)) {
         header('X-screen-type: error');
         return wfMessage('wmu-file-not-found')->plain();
     }
     // Test if this violates the size requirements we've been given
     if ($msg = $this->invalidSize($file)) {
         header('X-screen-type: error');
         return $msg;
     }
     $ns_img = $wgContLang->getFormattedNsText(NS_IMAGE);
     if (-2 == $gallery && !$ck) {
         // this went in from the single placeholder...
         $name = $title->getText();
         $size = $wgRequest->getVal('size');
         $width = $wgRequest->getVal('width');
         $layout = $wgRequest->getVal('layout');
         // clear the old caption for upload
         $caption = $wgRequest->getVal('caption');
         $slider = $wgRequest->getVal('slider');
         $title_obj = Title::newFromText($title_main, $ns);
         $article_obj = new Article($title_obj);
         $text = $article_obj->getContent();
         wfRunHooks('WikiaMiniUpload::fetchTextForImagePlaceholder', array(&$title_obj, &$text));
         $box = $wgRequest->getVal('box', '');
         $placeholder = MediaPlaceholderMatch($text, $box);
         $success = false;
         if ($placeholder) {
             $our_gallery = $placeholder[0];
             $gallery_split = explode(':', $our_gallery);
             $thumb = false;
             $tag = $gallery_split[0] . ":" . $name;
             if ($size != 'full') {
                 $tag .= '|thumb';
                 $thumb = true;
             }
             if (isset($width)) {
                 $tag .= '|' . $width;
             }
             $tag .= '|' . $layout;
             if ($link != '') {
                 $tag .= '|link=' . $link;
             }
             if ($caption != '') {
                 $tag .= '|' . $caption;
             }
             $tag .= "]]";
             $text = substr_replace($text, $tag, $placeholder[1], strlen($our_gallery));
             // return the proper embed code with all fancies around it
             $embed_code = $this->generateImage($file, $name, $title_obj, $thumb, (int) str_replace('px', '', $width), $layout, $caption);
             $message = wfMsg('wmu-success');
             Wikia::setVar('EditFromViewMode', true);
             $summary = wfMsg('wmu-added-from-plc');
             $success = $article_obj->doEdit($text, $summary);
         }
         if ($success) {
             header('X-screen-type: summary');
         } else {
             // failure signal opens js alert (BugId:4935)
             header('X-screen-type: error');
             return;
         }
     } else {
         header('X-screen-type: summary');
         $size = $wgRequest->getVal('size');
         $width = $wgRequest->getVal('width');
         $layout = $wgRequest->getVal('layout');
         $caption = $wgRequest->getVal('caption');
         $slider = $wgRequest->getVal('slider');
         $tag = '[[' . $ns_img . ':' . $title->getDBkey();
         if ($size != 'full' && ($file->getMediaType() == 'BITMAP' || $file->getMediaType() == 'DRAWING')) {
             $tag .= '|thumb';
             if ($layout != 'right') {
                 $tag .= '|' . $layout;
             }
             if ($slider == 'true') {
                 $tag .= '|' . $width;
             }
         }
         if ($link != '' && $size == 'full') {
             $tag .= '|link=' . $link;
         }
         if ($caption != '') {
             if ($size == 'full') {
                 $tag .= '|frame';
                 if ($layout != 'right') {
                     $tag .= '|' . $layout;
                 }
             }
             $tag .= '|' . $caption . ']]';
         } else {
             if ($size == 'full') {
                 $tag .= '|' . $layout;
             }
             $tag .= ']]';
         }
     }
     $message = wfMsg('wmu-success');
     if ($wgRequest->getVal('update_caption') == 'on') {
         Wikia::setProps($title->getArticleID(), array('default_caption' => $caption));
     }
     $tmpl = new EasyTemplate(dirname(__FILE__) . '/templates/');
     $tmpl->set_vars(array('tag' => $tag, 'filename' => $ns_img . ':' . $title->getDBkey(), 'message' => $message, 'code' => isset($embed_code) ? $embed_code : ''));
     return $tmpl->render('summary');
 }
 function getFieldNames()
 {
     return array('cpc_timestamp' => wfMsg('code-field-timestamp'), 'cpc_user_text' => wfMsg('code-field-user'), 'cpc_rev_id' => wfMsg('code-field-id'), 'cr_author' => WfMsg('code-field-author'), 'cr_message' => wfMsg('code-field-message'), 'cpc_removed' => wfMsg('code-old-status'), 'cpc_added' => wfMsg('code-new-status'), 'cr_status' => wfMsg('code-field-status'));
 }