/**
 * Main execution point
 * @param $par Namespace to select the redirect from
 */
function wfSpecialRandomredirect($par = NULL)
{
    global $wgOut, $wgExtraRandompageSQL, $wgContLang;
    $fname = 'wfSpecialRandomredirect';
    # Validate the namespace
    $namespace = $wgContLang->getNsIndex($par);
    if ($namespace === false || $namespace < NS_MAIN) {
        $namespace = NS_MAIN;
    }
    # Same logic as RandomPage
    $randstr = wfRandom();
    $dbr =& wfGetDB(DB_SLAVE);
    $use_index = $dbr->useIndexClause('page_random');
    $page = $dbr->tableName('page');
    $extra = $wgExtraRandompageSQL ? "AND ({$wgExtraRandompageSQL})" : '';
    $sql = "SELECT page_id,page_title\n\t\tFROM {$page} {$use_index}\n\t\tWHERE page_namespace = {$namespace} AND page_is_redirect = 1 {$extra}\n\t\tAND page_random > {$randstr}\n\t\tORDER BY page_random";
    $sql = $dbr->limitResult($sql, 1, 0);
    $res = $dbr->query($sql, $fname);
    $title = NULL;
    if ($row = $dbr->fetchObject($res)) {
        $title = Title::makeTitleSafe($namespace, $row->page_title);
    }
    # Catch dud titles and return to the main page
    if (is_null($title)) {
        $title = Title::newMainPage();
    }
    $wgOut->reportTime();
    $wgOut->redirect($title->getFullUrl('redirect=no'));
}
 /**
  * main()
  */
 public function execute($par)
 {
     global $wgOut;
     $fname = 'SpecialAdvancedRandom::execute';
     wfProfileIn($fname);
     list($page, $namespace) = $this->extractParamaters($par);
     $ft = Title::newFromText($page);
     if (is_null($ft)) {
         $this->redirect(Title::newMainPage());
         wfProfileOut($fname);
         return;
     }
     $rand = wfRandom();
     $dbr = wfGetDB(DB_SLAVE);
     if ($ft->getNamespace() == NS_TEMPLATE) {
         $res = $dbr->selectRow(array('page', 'templatelinks'), array('page_namespace', 'page_title', 'page_random'), array('page_id = tl_from', 'tl_namespace' => NS_TEMPLATE, 'page_namespace' => $namespace, 'tl_title' => $ft->getDBkey(), "page_random > {$rand}"), $fname, array('ORDER BY' => 'page_random', 'USE INDEX' => array('page' => 'page_random')));
     } else {
         $res = $dbr->selectRow(array('page', 'pagelinks'), array('page_namespace', 'page_title', 'page_random'), array('page_id = pl_from', 'pl_namespace' => $ft->getNamespace(), 'page_namespace' => $namespace, 'pl_title' => $ft->getDBkey(), "page_random > {$rand}"), $fname, array('ORDER BY' => 'page_random', 'USE INDEX' => array('page' => 'page_random')));
     }
     $title =& Title::makeTitle(MWNamespace::getSubject($namespace), $res->page_title);
     if (is_null($title) || $title->getText() == '') {
         $title = Title::newMainPage();
     }
     $this->redirect($title);
     wfProfileOut($fname);
 }
 /**
  * @param string $name
  * @param array $params
  * @dataProvider provideGet
  * @covers GlobalConfig::get
  */
 public function testGet($name, $params)
 {
     $rand = wfRandom();
     $old = isset($GLOBALS[$name]) ? $GLOBALS[$name] : null;
     $GLOBALS[$name] = $rand;
     $out = call_user_func_array(array($this->config, 'get'), $params);
     $this->assertEquals($rand, $out);
     if ($old) {
         $GLOBALS[$name] = $old;
     }
 }
Example #4
0
 private function quickTestBackend()
 {
     $dbr = wfGetDB(DB_SLAVE);
     try {
         $res = $dbr->selectField('page', 'page_id', array('page_is_redirect' => 0, 'page_namespace' => NS_MAIN, 'page_random >= ' . wfRandom()), __METHOD__, array('ORDER BY' => 'page_random', 'USE INDEX' => 'page_random'));
     } catch (DBError $e) {
         $res = null;
     }
     if (is_string($res) && intval($res) > 0) {
         return true;
     } else {
         return false;
     }
 }
Example #5
0
 public function execute()
 {
     $pages = $this->getOption('maxpages');
     $dbr = $this->getDB(DB_REPLICA);
     $totalsec = 0.0;
     $scanned = 0;
     $withcache = 0;
     $withdiff = 0;
     while ($pages-- > 0) {
         $row = $dbr->selectRow('page', '*', ['page_namespace' => $this->getOption('namespace'), 'page_is_redirect' => 0, 'page_random >= ' . wfRandom()], __METHOD__, ['ORDER BY' => 'page_random']);
         if (!$row) {
             continue;
         }
         ++$scanned;
         $title = Title::newFromRow($row);
         $page = WikiPage::factory($title);
         $revision = $page->getRevision();
         $content = $revision->getContent(Revision::RAW);
         $parserOptions = $page->makeParserOptions('canonical');
         $parserOutputOld = ParserCache::singleton()->get($page, $parserOptions);
         if ($parserOutputOld) {
             $t1 = microtime(true);
             $parserOutputNew = $content->getParserOutput($title, $revision->getId(), $parserOptions, false);
             $sec = microtime(true) - $t1;
             $totalsec += $sec;
             $this->output("Parsed '{$title->getPrefixedText()}' in {$sec} seconds.\n");
             $this->output("Found cache entry found for '{$title->getPrefixedText()}'...");
             $oldHtml = trim(preg_replace('#<!-- .+-->#Us', '', $parserOutputOld->getText()));
             $newHtml = trim(preg_replace('#<!-- .+-->#Us', '', $parserOutputNew->getText()));
             $diff = wfDiff($oldHtml, $newHtml);
             if (strlen($diff)) {
                 $this->output("differences found:\n\n{$diff}\n\n");
                 ++$withdiff;
             } else {
                 $this->output("No differences found.\n");
             }
             ++$withcache;
         } else {
             $this->output("No parser cache entry found for '{$title->getPrefixedText()}'.\n");
         }
     }
     $ave = $totalsec ? $totalsec / $scanned : 0;
     $this->output("Checked {$scanned} pages; {$withcache} had prior cache entries.\n");
     $this->output("Pages with differences found: {$withdiff}\n");
     $this->output("Average parse time: {$ave} sec\n");
 }
 /**
  * Choose a random title.
  * @return Title object (or null if nothing to choose from)
  */
 public function getRandomTitle()
 {
     $randstr = wfRandom();
     $row = $this->selectRandomPageFromDB($randstr);
     /* If we picked a value that was higher than any in
      * the DB, wrap around and select the page with the
      * lowest value instead!  One might think this would
      * skew the distribution, but in fact it won't cause
      * any more bias than what the page_random scheme
      * causes anyway.  Trust me, I'm a mathematician. :)
      */
     if (!$row) {
         $row = $this->selectRandomPageFromDB("0");
     }
     if ($row) {
         return Title::makeTitleSafe($this->namespace, $row->page_title);
     } else {
         return null;
     }
 }
/**
 * Constructor
 *
 * @param string $par the namespace to get a random page from (default NS_MAIN), 
 *               used as e.g. Special:Randompage/Category
 */
function wfSpecialRandompage($par = NS_MAIN)
{
    global $wgOut, $wgTitle, $wgArticle, $wgExtraRandompageSQL, $wgContLang;
    $fname = 'wfSpecialRandompage';
    # Determine the namespace to get a random page from.
    $namespace = $wgContLang->getNsIndex($par);
    if ($namespace === false || $namespace < NS_MAIN) {
        $namespace = NS_MAIN;
    }
    # NOTE! We use a literal constant in the SQL instead of the RAND()
    # function because RAND() will return a different value for every row
    # in the table. That's both very slow and returns results heavily
    # biased towards low values, as rows later in the table will likely
    # never be reached for comparison.
    #
    # Using a literal constant means the whole thing gets optimized on
    # the index, and the comparison is both fast and fair.
    # interpolation and sprintf() can muck up with locale-specific decimal separator
    $randstr = wfRandom();
    $db =& wfGetDB(DB_SLAVE);
    $use_index = $db->useIndexClause('page_random');
    $page = $db->tableName('page');
    $extra = $wgExtraRandompageSQL ? "AND ({$wgExtraRandompageSQL})" : '';
    $sql = "SELECT page_id,page_title\n\t\tFROM {$page} {$use_index}\n\t\tWHERE page_namespace={$namespace} AND page_is_redirect=0 {$extra}\n\t\tAND page_random>{$randstr}\n\t\tORDER BY page_random\n\t\tLIMIT 1";
    $res = $db->query($sql, $fname);
    $title = null;
    if ($s = $db->fetchObject($res)) {
        $title =& Title::makeTitle($namespace, $s->page_title);
    }
    if (is_null($title)) {
        # That's not supposed to happen :)
        $title =& Title::newFromText(wfMsg('mainpage'));
    }
    $wgOut->reportTime();
    # for logfile
    $wgOut->redirect($title->getFullUrl());
}
 /**
 		Makes a decision as to if the event should be logged or not.
 */
 private function shouldLog()
 {
     $rnd = wfRandom();
     return $rnd < self::probLog ? true : false;
 }
 function add_to_wiki()
 {
     self::text_size();
     $this->wDB->commit();
     $this->wDB->begin();
     $page_id = $this->wDB->nextSequenceValue('page_page_id_seq');
     $this->wDB->insert('page', array('page_id' => $page_id, 'page_namespace' => NS_AWC_FORUM, 'page_title' => "Special:AWCforum/st/id{$this->tID}/" . self::page_title(), 'page_counter' => 0, 'page_restrictions' => '', 'page_is_redirect' => 0, 'page_is_new' => 1, 'page_random' => wfRandom(), 'page_touched' => $this->time, 'page_latest' => 0, 'page_len' => $this->size));
     $this->pageID = $this->wDB->insertId();
     $this->wDB->commit();
     // die(">". $this->pageID);
     if ($this->pageID == 0) {
         return;
     }
     $this->wDB->begin();
     self::insert_text();
     self::insert_rev();
     /*        
             use the first text inserted and rev_id to "update" 
             when a post is added to the thread, this is used in the search options
     */
     $this->wDB->update('page', array('page_latest' => $this->insert_revID), array('page_id' => $this->pageID), '');
     /*insert text a second time
       use this second inputed text-rev_id as the Main Threads Posts text
       use first inputed text-rev_id for search resultes
       add 'rev_parent_id' so we can call this text later... if we want.*/
     /*
             self::insert_text();
             
             
                           
             $this->wDB->insert( 'revision', array(
                     'rev_page'        => $this->pageID,
                     'rev_len'        => $this->size,
                     'rev_text_id'       => $this->insert_textID,
                     'rev_comment'        => 'main_thread_post',
                     'rev_user'        => $this->mId,
                     'rev_user_text'       => $this->mName,
                     'rev_timestamp'        => $this->time,
                     'rev_minor_edit'        => 0,
                     'rev_deleted'       => 0,
                     'rev_len'        => $this->size,
                     'rev_parent_id'        => $this->pageID,
                 ) );
     */
     $this->wDB->insert('searchindex', array('si_page' => $this->pageID, 'si_title' => $this->title, 'si_text' => $this->text_to_save));
     $this->wDB->commit();
 }
Example #10
0
 /**
  * Insert a new empty page record for this article.
  * This *must* be followed up by creating a revision
  * and running $this->updateToLatest( $rev_id );
  * or else the record will be left in a funky state.
  * Best if all done inside a transaction.
  *
  * @param Database $dbw
  * @param string   $restrictions
  * @return int     The newly created page_id key
  * @private
  */
 function insertOn(&$dbw, $restrictions = '')
 {
     wfProfileIn(__METHOD__);
     $page_id = $dbw->nextSequenceValue('page_page_id_seq');
     $dbw->insert('page', array('page_id' => $page_id, 'page_namespace' => $this->mTitle->getNamespace(), 'page_title' => $this->mTitle->getDBkey(), 'page_counter' => 0, 'page_restrictions' => $restrictions, 'page_is_redirect' => 0, 'page_is_new' => 1, 'page_random' => wfRandom(), 'page_touched' => $dbw->timestamp(), 'page_latest' => 0, 'page_len' => 0), __METHOD__);
     $newid = $dbw->insertId();
     $this->mTitle->resetArticleId($newid);
     wfProfileOut(__METHOD__);
     return $newid;
 }
Example #11
0
 public function run($resultPageSet = null)
 {
     $params = $this->extractRequestParams();
     $result = $this->getResult();
     $this->pageIDs = array();
     $this->prepareQuery(wfRandom(), $params['limit'], $params['namespace'], $resultPageSet, $params['redirect']);
     $count = $this->runQuery($resultPageSet);
     if ($count < $params['limit']) {
         /* We got too few pages, we probably picked a high value
          * for page_random. We'll just take the lowest ones, see
          * also the comment in Title::getRandomTitle()
          */
         $this->prepareQuery(0, $params['limit'] - $count, $params['namespace'], $resultPageSet, $params['redirect']);
         $this->runQuery($resultPageSet);
     }
     if (is_null($resultPageSet)) {
         $result->setIndexedTagName_internal(array('query', $this->getModuleName()), 'page');
     }
 }
Example #12
0
 /**
  * Select a random image from the database
  *
  * @return Title
  */
 protected function pickFromDatabase()
 {
     wfProfileIn(__METHOD__);
     $dbr = wfGetDB(DB_SLAVE);
     list($table, $conds, $opts) = $this->getExtraSelectOptions($dbr);
     $res = $dbr->select($table, array('page_namespace', 'page_title'), array('page_namespace' => NS_IMAGE, 'page_is_redirect' => 0, 'page_random > ' . $dbr->addQuotes(wfRandom())) + $conds, __METHOD__, array('ORDER BY' => 'page_random', 'LIMIT' => 1) + $opts);
     wfProfileOut(__METHOD__);
     if ($dbr->numRows($res) > 0) {
         $row = $dbr->fetchObject($res);
         $dbr->freeResult($res);
         return Title::makeTitleSafe($row->page_namespace, $row->page_title);
     }
     return null;
 }
	/**
	 * Gets a random poll ID from the database.
	 * The poll ID will be the ID of a poll to which the user hasn't answered
	 * yet.
	 *
	 * @param $user_name Mixed: current user's username
	 * @return Integer: random poll ID number
	 */
	public function getRandomPollID( $user_name ) {
		$dbr = wfGetDB( DB_MASTER );
		$poll_page_id = 0;
		$use_index = $dbr->useIndexClause( 'poll_random' );
		$randstr = wfRandom();
		$sql = "SELECT poll_page_id FROM {$dbr->tableName( 'poll_question' )} {$use_index}
			INNER JOIN {$dbr->tableName( 'page' )} ON page_id=poll_page_id WHERE poll_id NOT IN
				(SELECT pv_poll_id FROM {$dbr->tableName( 'poll_user_vote' )} WHERE pv_user_name = '" . $dbr->strencode( $user_name ) . "')
				AND poll_status=1 AND poll_random>$randstr ORDER BY poll_random LIMIT 0,1";
		$res = $dbr->query( $sql, __METHOD__ );
		$row = $dbr->fetchObject( $res );
		// random fallback
		if( !$row ) {
			$sql = "SELECT poll_page_id FROM {$dbr->tableName( 'poll_question' )} {$use_index}
				INNER JOIN {$dbr->tableName( 'page' )} ON page_id=poll_page_id WHERE poll_id NOT IN
					(SELECT pv_poll_id FROM {$dbr->tableName( 'poll_user_vote' )} WHERE pv_user_name = '" . $dbr->strencode( $user_name ) . "')
					AND poll_status=1 AND poll_random<$randstr ORDER BY poll_random LIMIT 0,1";
			wfDebugLog( 'PollNY', $sql );
			$res = $dbr->query( $sql, __METHOD__ );
			$row = $dbr->fetchObject( $res );
		}
		if( $row ) {
			$poll_page_id = $row->poll_page_id;
		}

		return $poll_page_id;
	}
Example #14
0
function wfGetSuggestedTitles($t)
{
    global $wgUser, $wgMemc;
    $html = "";
    if (!$t) {
        return $html;
    }
    // use memcached to store results
    $key = wfGetSuggTitlesMemcKey($t->getArticleID());
    $result = $wgMemc->get($key);
    if ($result) {
        return $result;
    }
    wfProfileIn(__METHOD__);
    $dbr = wfGetDB(DB_SLAVE);
    $group = date("W") % 5;
    $res = $dbr->select('suggested_links', array('sl_sugg'), array('sl_page' => $t->getArticleID()), array('ORDER BY' => 'sl_sort'), __METHOD__);
    $ids = array();
    while ($row = $dbr->fetchObject($res)) {
        $ids[] = $row->sl_sugg;
    }
    $randStr = wfRandom();
    if (sizeof($ids) == 0) {
        $top = wfGetTopCategory($t);
        if ($top) {
            $sql = "SELECT st_title FROM suggested_titles\n\t\t\t\tWHERE st_used = 0 and st_patrolled = 1 \n\t\t\t\t\tand st_group = {$group}\n\t\t\t\t\tand st_category = " . $dbr->addQuotes($top->getText()) . " \n\t\t\t\t\tand st_random > {$randStr} limit 5";
            $res = $dbr->query($sql, __METHOD__);
        }
    } else {
        $sql = "(" . implode(", ", $ids) . ")";
        $sql = "SELECT st_title FROM suggested_titles\n\t\t\tWHERE st_used = 0 and st_patrolled = 1 \n\t\t\t\tand st_group = {$group} and st_id\n\t\t\t\tin {$sql} limit 5";
        $res = $dbr->query($sql, __METHOD__);
    }
    if ($dbr->numRows($res) == 0) {
        $top = wfGetTopCategory($t);
        if ($top) {
            $sql = "SELECT st_title FROM suggested_titles\n\t\t\t\tWHERE st_used = 0 and st_patrolled = 1 \n\t\t\t\t\tand st_group = {$group}\n\t\t\t\t\tand st_category = " . $dbr->addQuotes($top->getText()) . "\n\t\t\t\t\tand st_random > {$randStr} limit 5";
            $res = $dbr->query($sql, __METHOD__);
        }
    }
    while ($row = $dbr->fetchObject($res)) {
        $title = Title::newFromText($row->st_title);
        if (!$title) {
            continue;
        }
        $sp = SpecialPage::getTitleFor('CreatePage', $title->getText());
        $html .= "<li><a onclick='clickshare(46);' href='{$sp->getLocalUrl()}' class='new'>" . wfMsg('howto', $title->getText()) . "</a></li>\n";
    }
    if ($html != "") {
        $html = "<h2>" . wfMsg('suggested_titles_section') . "</h2><div id='suggested_titles'>" . wfMsg('suggested_titles_section_description') . "<br/><br/><ul id='gatSuggestedTitle'>{$html}</ul></div>";
    }
    $wgMemc->set($key, $html);
    wfProfileOut(__METHOD__);
    return $html;
}
Example #15
0
 /**
  * Generate search form version 2
  */
 public function getSearchForm2()
 {
     // Use button label fallbacks
     if (!$this->mButtonLabel) {
         $this->mButtonLabel = wfMessage('inputbox-tryexact')->text();
     }
     if ($this->mID !== '') {
         $unescapedID = $this->mID;
     } else {
         // The label element needs a unique id, use
         // random number to avoid multiple input boxes
         // having conflicts.
         $unescapedID = wfRandom();
     }
     $id = Sanitizer::escapeId($unescapedID, 'noninitial');
     $htmlLabel = '';
     if (isset($this->mLabelText) && strlen(trim($this->mLabelText))) {
         $this->mLabelText = $this->mParser->recursiveTagParse($this->mLabelText);
         $htmlLabel = Xml::openElement('label', array('for' => 'bodySearchInput' . $id));
         $htmlLabel .= $this->mLabelText;
         $htmlLabel .= Xml::closeElement('label');
     }
     $htmlOut = Xml::openElement('form', array('name' => 'bodySearch' . $id, 'id' => 'bodySearch' . $id, 'class' => 'bodySearch' . ($this->mInline ? ' mw-inputbox-inline' : ''), 'action' => SpecialPage::getTitleFor('Search')->getLocalUrl()));
     $htmlOut .= Xml::openElement('div', array('class' => 'bodySearchWrap' . ($this->mInline ? ' mw-inputbox-inline' : ''), 'style' => $this->bgColorStyle()));
     $htmlOut .= $htmlLabel;
     $htmlOut .= Xml::element('input', array('type' => $this->mHidden ? 'hidden' : 'text', 'name' => 'search', 'size' => $this->mWidth, 'id' => 'bodySearchInput' . $id, 'dir' => $this->mDir));
     $htmlOut .= Xml::element('input', array('type' => 'submit', 'name' => 'go', 'value' => $this->mButtonLabel, 'class' => 'bodySearchBtnGo'));
     // Better testing needed here!
     if (!empty($this->mFullTextButton)) {
         $htmlOut .= Xml::element('input', array('type' => 'submit', 'name' => 'fulltext', 'class' => 'bodySearchBtnSearch', 'value' => $this->mSearchButtonLabel));
     }
     $htmlOut .= Xml::closeElement('div');
     $htmlOut .= Xml::closeElement('form');
     // Return HTML
     return $htmlOut;
 }
Example #16
0
 function getRelatedArticlesBox($e, $isBoxShape = false)
 {
     global $wgTitle, $wgContLang, $wgRequest, $wgMemc;
     if (!$wgTitle || $wgTitle->getNamespace() != NS_MAIN || $wgTitle->getFullText() == wfMessage('mainpage')->text() || $wgRequest->getVal('action') != '') {
         return '';
     }
     $cachekey = wfMemcKey('relarticles_box', intval($isBoxShape), $wgTitle->getArticleID());
     $val = $wgMemc->get($cachekey);
     if ($val) {
         return $val;
     }
     $cats = Categoryhelper::getCurrentParentCategories();
     $cat = '';
     if (is_array($cats) && sizeof($cats) > 0) {
         $keys = array_keys($cats);
         $templates = wfMessage('categories_to_ignore')->inContentLanguage()->text();
         $templates = explode("\n", $templates);
         $templates = str_replace("http://www.wikihow.com/Category:", "", $templates);
         $templates = array_flip($templates);
         // make the array associative.
         for ($i = 0; $i < sizeof($keys); $i++) {
             $t = Title::newFromText($keys[$i]);
             if (isset($templates[urldecode($t->getPartialURL())])) {
                 continue;
             } else {
                 $cat = $t->getDBKey();
                 break;
             }
         }
     }
     // Populate related articles box with other articles in the category,
     // displaying the featured articles first
     $result = "";
     if (!empty($cat)) {
         $dbr = wfGetDB(DB_SLAVE);
         $num = intval(wfMessage('num_related_articles_to_display')->inContentLanguage()->text());
         $res = $dbr->select(array('categorylinks', 'page'), array('cl_from', 'page_is_featured, page_title'), array('cl_from = page_id', 'cl_to' => $cat, 'page_namespace' => 0, 'page_is_redirect' => 0, '(page_is_featured = 1 OR page_random > ' . wfRandom() . ')'), __METHOD__, array('ORDER BY' => 'page_is_featured DESC'));
         if ($isBoxShape) {
             $result .= '<div class="related_square_row">';
         }
         $count = 0;
         foreach ($res as $row) {
             if ($count >= $num) {
                 break;
             }
             if ($row->cl_from == $wgTitle->getArticleID()) {
                 continue;
             }
             $t = Title::newFromDBkey($row->page_title);
             if (!$t || $this->needsFurtherEditing($t)) {
                 continue;
             }
             if ($isBoxShape) {
                 //exit if there's a word that will be too long
                 $word_array = explode(' ', $t->getText());
                 foreach ($word_array as $word) {
                     if (strlen($word) > 7) {
                         continue;
                     }
                 }
                 $data = self::featuredArticlesAttrs($t, $t->getFullText(), 200, 162);
                 $result .= $this->relatedArticlesBox($data, $num_cols);
                 if ($count == 1) {
                     $result .= '</div><div class="related_square_row">';
                 }
             } else {
                 //$data = self::featuredArticlesAttrs($t, $t->getFullText());
                 $result .= self::getArticleThumb($t, 127, 140);
             }
             $count++;
         }
         if ($isBoxShape) {
             $result .= '</div>';
         }
         if (!empty($result)) {
             if ($isBoxShape) {
                 $result = "<div id='related_squares'>{$result}\n</div>";
             } else {
                 $result = "<h3>" . wfMessage('relatedarticles')->text() . "</h3>{$result}<div class='clearall'></div>\n";
             }
         }
     }
     $wgMemc->set($cachekey, $result);
     return $result;
 }
Example #17
0
 function buildSQL()
 {
     global $wgUser;
     $dbr =& wfGetDB(DB_SLAVE);
     $sPageTable = $dbr->tableName('page');
     $categorylinks = $dbr->tableName('categorylinks');
     $sSqlSelectFrom = "SELECT distinct(page_id),page_namespace,page_title, page_counter,UNIX_TIMESTAMP(page_touched),page_id, IFNULL(comment_count,0) as comment_count, IFNULL(vote_count,0) as vote_count,  IFNULL(vote_avg,0) as vote_avg ";
     if ($this->Order == 'EDITS') {
         $sSqlSelectFrom .= ",(select count(*) from {$dbr->tableName('revision')} where page_id=rev_page ";
         $sSqlSelectFrom .= ") as Num_Edits ";
     }
     if ($this->ShowUser == 1) {
         $WhereVote = " and username = '******' ";
         $WhereComment = " and Comment_Username = '******' ";
     }
     if ($this->Order == 'VOTEDON') {
         $sSqlSelectFrom .= " ,(select vote_date from Vote WHERE vote_page_id = page_id " . $WhereVote . " order BY vote_date DESC limit 1) as LastDate ";
     }
     if ($this->Order == 'COMMENTEDON') {
         $sSqlSelectFrom .= " ,(select Comment_date from Comments WHERE Comment_page_id = page_id " . $WhereComment . " order BY Comment_date DESC limit 1) as LastDate ";
     }
     $sSqlSelectFrom .= "FROM {$sPageTable}";
     if ($this->ShowPublished == 1) {
         $sSqlSelectFrom .= " INNER JOIN published_page  ";
         $sSqlSelectFrom .= " ON page_id = published_page_id  ";
     }
     if (count($this->Categories) > 0) {
         $sSqlSelectFrom .= " INNER JOIN {$categorylinks} AS c";
         $sSqlSelectFrom .= ' ON page_id = c.cl_from';
     }
     if ($this->ShowPublished == -1) {
         $sSqlSelectFrom .= " LEFT JOIN published_page ";
         $sSqlSelectFrom .= ' ON page_id = published_page_id and published_type= ' . $this->Level . ' ';
     }
     $sSqlSelectFrom .= ' LEFT JOIN page_stats ON page_id=ps_page_id ';
     //BUILD WHERE CLAUSE
     $sSqlWhere = " WHERE 1=1";
     $sCtgSQL = "";
     if (count($this->Categories) > 0) {
         $sSqlWhere .= ' AND UPPER(c.cl_to) in (';
         for ($i = 0; $i < count($this->Categories); $i++) {
             if ($i > 0) {
                 $sCtgSQL .= ",";
             }
             $sCtgSQL .= strtoupper($dbr->addQuotes($this->Categories[$i]->getDbKey()));
         }
         $sSqlWhere .= $sCtgSQL . ')';
     }
     if ($this->ShowPublished == 1) {
         $sSqlWhere .= " AND published_type=" . $this->Level . " ";
     }
     if ($this->ShowPublished == -1) {
         $sSqlWhere .= " AND ( published_page_id IS NULL  ) ";
     }
     if ($this->random == 1) {
         $randstr = wfRandom();
         $sSqlWhere .= " AND page_random>{$randstr} ";
     }
     if ($this->ratingMin > 0) {
         $sSqlWhere .= " AND vote_count >= " . $this->ratingMin;
     }
     // Only Show Main Pages in lists
     $sSqlWhere .= " AND page_namespace in ( " . NS_MAIN . "," . NS_USER . "," . NS_IMAGE . ")";
     // BUILD ORDER BY CLAUSE
     $sSqlOrder = " ORDER BY ";
     if ($this->Order == 'LASTEDIT') {
         $sSqlOrder .= 'page_touched ';
     } else {
         if ($this->Order == 'PAGEVIEWS') {
             $sSqlOrder .= 'page_counter ';
         } else {
             if ($this->Order == 'VOTES') {
                 $sSqlOrder .= 'vote_count ';
             } else {
                 if ($this->Order == 'VOTE AVERAGE') {
                     $sSqlOrder .= 'vote_avg ';
                 } else {
                     if ($this->Order == 'COMMENTS') {
                         $sSqlOrder .= 'comment_count ';
                     } else {
                         if ($this->Order == 'NEW') {
                             $sSqlOrder .= 'page_id ';
                         } else {
                             if ($this->Order == 'EDITS') {
                                 $sSqlOrder .= 'Num_Edits ';
                             } else {
                                 if ($this->Order == 'PUBLISHEDDATE' && $this->ShowPublished == 1) {
                                     $sSqlOrder .= 'published_date ';
                                 } else {
                                     if ($this->Order == 'VOTEDON' || $this->Order == 'COMMENTEDON') {
                                         $sSqlOrder .= 'LastDate ';
                                     } else {
                                         if ($this->random == 1) {
                                             $sSqlOrder .= ' page_random ';
                                             $this->SortBy = 'ASCENDING';
                                         } else {
                                             $sSqlOrder .= 'page_title ';
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     if ($this->SortBy == 'ASCENDING') {
         $sSqlOrder .= 'ASC';
     } else {
         $sSqlOrder .= 'DESC';
     }
     // BUILD LIMIT RECORDS RETURNED
     $sSqlLimit = ' LIMIT ' . ($this->PageNo - 1) * ($this->ShowCount - 1) . ',' . $this->ShowCount;
     if ($this->Order == 'VOTEDON' || $this->Order == 'COMMENTEDON') {
         $sSqlWhere = " WHERE page_id IN ( " . $this->getPageIDs() . ")";
         $sSqlLimit = "";
     }
     return $sSqlSelectFrom . $sSqlWhere . $sSqlOrder . $sSqlLimit;
 }
Example #18
0
 /**
  * Move page to non-existing title.
  * @param Title &$nt the new Title
  * @private
  */
 function moveToNewTitle(&$nt, $reason = '')
 {
     global $wgUseSquid;
     $fname = 'MovePageForm::moveToNewTitle';
     $comment = wfMsgForContent('1movedto2', $this->getPrefixedText(), $nt->getPrefixedText());
     if ($reason) {
         $comment .= ": {$reason}";
     }
     $newid = $nt->getArticleID();
     $oldid = $this->getArticleID();
     $dbw =& wfGetDB(DB_MASTER);
     $now = $dbw->timestamp();
     $rand = wfRandom();
     $linkCache =& LinkCache::singleton();
     # Save a null revision in the page's history notifying of the move
     $nullRevision = Revision::newNullRevision($dbw, $oldid, $comment, true);
     $nullRevId = $nullRevision->insertOn($dbw);
     # Rename cur entry
     $dbw->update('page', array('page_touched' => $now, 'page_namespace' => $nt->getNamespace(), 'page_title' => $nt->getDBkey(), 'page_latest' => $nullRevId), array('page_id' => $oldid), $fname);
     $linkCache->clearLink($nt->getPrefixedDBkey());
     # Insert redirect
     $mwRedir = MagicWord::get(MAG_REDIRECT);
     $redirectText = $mwRedir->getSynonym(0) . ' [[' . $nt->getPrefixedText() . "]]\n";
     $redirectArticle = new Article($this);
     $newid = $redirectArticle->insertOn($dbw);
     $redirectRevision = new Revision(array('page' => $newid, 'comment' => $comment, 'text' => $redirectText));
     $revid = $redirectRevision->insertOn($dbw);
     $redirectArticle->updateRevisionOn($dbw, $redirectRevision, 0);
     $linkCache->clearLink($this->getPrefixedDBkey());
     # Log the move
     $log = new LogPage('move');
     $log->addEntry('move', $this, $reason, array(1 => $nt->getPrefixedText()));
     # Purge caches as per article creation
     Article::onArticleCreate($nt);
     # Record the just-created redirect's linking to the page
     $dbw->insert('pagelinks', array('pl_from' => $newid, 'pl_namespace' => $nt->getNamespace(), 'pl_title' => $nt->getDBkey()), $fname);
     # Purge old title from squid
     # The new title, and links to the new title, are purged in Article::onArticleCreate()
     $this->purgeSquid();
 }
	function createQuizGame() {
		global $wgRequest, $wgUser, $wgMemc, $wgQuizLogs;

		$key = $wgRequest->getText( 'key' );
		$chain = $wgRequest->getText( 'chain' );

		$max_answers = 8;

		if( $key != md5( $this->SALT . $chain ) ) {
			header( 'Location: ' . $this->getTitle()->getFullURL() );
			return;
		}

		$question = $wgRequest->getText( 'quizgame-question' );
		$imageName = $wgRequest->getText( 'quizGamePictureName' );

		// Add quiz question
		$dbw = wfGetDB( DB_MASTER );
		$dbw->insert(
			'quizgame_questions',
			array(
				'q_user_id' => $wgUser->getID(),
				'q_user_name' => $wgUser->getName(),
				'q_text' => strip_tags( $question ), // make sure nobody inserts malicious code
				'q_picture' => $imageName,
				'q_date' => date( 'Y-m-d H:i:s' ),
				'q_random' => wfRandom()
			),
			__METHOD__
		);
		$questionId = $dbw->insertId();

		// Add Quiz Choices
		for( $x = 1; $x <= $max_answers; $x++ ) {
			if( $wgRequest->getVal( "quizgame-answer-{$x}" ) ) {
				if( $wgRequest->getVal( "quizgame-isright-{$x}" ) == 'on' ) {
					$is_correct = 1;
				} else {
					$is_correct = 0;
				}
				$dbw->insert(
					'quizgame_choice',
					array(
						'choice_q_id' => $questionId,
						'choice_text' => strip_tags( $wgRequest->getVal( "quizgame-answer-{$x}" ) ), // make sure nobody inserts malicious code
						'choice_order' => $x,
						'choice_is_correct' => $is_correct
					),
					__METHOD__
				);
				$dbw->commit();
			}
		}
		$stats = new UserStatsTrack( $wgUser->getID(), $wgUser->getName() );
		$stats->incStatField( 'quiz_created' );

		// Add a log entry if quiz logging is enabled
		if( $wgQuizLogs ) {
			$message = wfMsgForContent(
				'quiz-questions-log-create-text',
				"Special:QuizGameHome/{$questionId}"
			);
			$log = new LogPage( 'quiz' );
			$log->addEntry( 'create', $wgUser->getUserPage(), $message );
		}

		// Delete memcached key
		$key = wfMemcKey( 'user', 'profile', 'quiz', $wgUser->getID() );
		$wgMemc->delete( $key );

		// Redirect the user
		header( 'Location: ' . $this->getTitle()->getFullURL( "questionGameAction=renderPermalink&permalinkID={$questionId}" ) );
	}
Example #20
0
 /**
  * @param ApiPageSet|null $resultPageSet
  */
 public function run($resultPageSet = null)
 {
     $params = $this->extractRequestParams();
     // Since 'filterredir" will always be set in $params, we have to dig
     // into the WebRequest to see if it was actually passed.
     $request = $this->getMain()->getRequest();
     if ($request->getCheck($this->encodeParamName('filterredir'))) {
         $this->requireMaxOneParameter($params, 'filterredir', 'redirect');
     }
     if (isset($params['continue'])) {
         $cont = explode('|', $params['continue']);
         $this->dieContinueUsageIf(count($cont) != 4);
         $rand = $cont[0];
         $start = $cont[1];
         $startId = (int) $cont[2];
         $end = $cont[3] ? $rand : null;
         $this->dieContinueUsageIf(!preg_match('/^0\\.\\d+$/', $rand));
         $this->dieContinueUsageIf(!preg_match('/^0\\.\\d+$/', $start));
         $this->dieContinueUsageIf($cont[2] !== (string) $startId);
         $this->dieContinueUsageIf($cont[3] !== '0' && $cont[3] !== '1');
     } else {
         $rand = wfRandom();
         $start = $rand;
         $startId = null;
         $end = null;
     }
     list($left, $continue) = $this->runQuery($resultPageSet, $params['limit'], $start, $startId, $end);
     if ($end === null && $continue === null) {
         // Wrap around. We do this even if $left === 0 for continuation
         // (saving a DB query in this rare case probably isn't worth the
         // added code complexity it would require).
         $end = $rand;
         list($left, $continue) = $this->runQuery($resultPageSet, $left, null, null, $end);
     }
     if ($continue !== null) {
         $endFlag = $end === null ? 0 : 1;
         $this->setContinueEnumParameter('continue', "{$rand}|{$continue}|{$endFlag}");
     }
     if (is_null($resultPageSet)) {
         $this->getResult()->addIndexedTagName(array('query', $this->getModuleName()), 'page');
     }
 }
 /**
  * Choose a random title.
  * @return Title|null Title object (or null if nothing to choose from)
  */
 public function getRandomTitle()
 {
     // Convert to float, since we do math with the random number.
     $rand = (double) wfRandom();
     $title = null;
     // Given that timestamps are rather unevenly distributed, we also
     // use an offset between 0 and 30 to make any biases less noticeable.
     $offset = mt_rand(0, $this->maxOffset);
     if (mt_rand(0, 1)) {
         $up = true;
     } else {
         $up = false;
     }
     $row = $this->selectRandomPageFromDB($rand, $offset, $up);
     // Try again without the timestamp offset (wrap around the end)
     if (!$row) {
         $row = $this->selectRandomPageFromDB(false, $offset, $up);
     }
     // Maybe the category is really small and offset too high
     if (!$row) {
         $row = $this->selectRandomPageFromDB($rand, 0, $up);
     }
     // Just get the first entry.
     if (!$row) {
         $row = $this->selectRandomPageFromDB(false, 0, true);
     }
     if ($row) {
         return Title::makeTitle($row->page_namespace, $row->page_title);
     }
     return null;
 }
Example #22
0
 /**
  * @covers ::wfRandom
  */
 public function testRandom()
 {
     $this->assertFalse(wfRandom() == wfRandom());
 }
Example #23
0
 /**
  * @param $db DatabaseBase
  * @param $pageId int
  * @param $title Title
  * @return Article
  */
 function prepareArticle($db, $pageId, $title)
 {
     $fname = 'OAIUpdateRecord::prepareArticle';
     $article = new Article($title);
     $foundId = $article->getId();
     if ($foundId == $pageId) {
         return $article;
     }
     if ($foundId != 0) {
         $this->hideConflictingPage($db, $foundId, $title);
     }
     // Check to see if the page exists under a different title
     $foundTitle = Title::newFromId($pageId);
     if ($foundTitle) {
         // Rename it...
         echo "RENAMING page record\n";
         $db->update('page', array('page_namespace' => $title->getNamespace(), 'page_title' => $title->getDBkey()), array('page_id' => $pageId), $fname);
     } else {
         // FIXME: prefer to use Article::insertOn here, but it doesn't provide
         // currently for overriding the page ID.
         echo "INSERTING page record\n";
         $db->insert('page', array('page_id' => $pageId, 'page_namespace' => $title->getNamespace(), 'page_title' => $title->getDBkey(), 'page_counter' => 0, 'page_restrictions' => '', 'page_is_redirect' => 0, 'page_is_new' => 1, 'page_random' => wfRandom(), 'page_touched' => $db->timestamp(), 'page_latest' => 0, 'page_len' => 0), $fname);
     }
     $title->resetArticleID(-1);
     return new Article($title);
 }
Example #24
0
 /**
  * Insert a new empty page record for this article.
  * This *must* be followed up by creating a revision
  * and running $this->updateRevisionOn( ... );
  * or else the record will be left in a funky state.
  * Best if all done inside a transaction.
  *
  * @param IDatabase $dbw
  * @param int|null $pageId Custom page ID that will be used for the insert statement
  *
  * @return bool|int The newly created page_id key; false if the row was not
  *   inserted, e.g. because the title already existed or because the specified
  *   page ID is already in use.
  */
 public function insertOn($dbw, $pageId = null)
 {
     $pageIdForInsert = $pageId ?: $dbw->nextSequenceValue('page_page_id_seq');
     $dbw->insert('page', ['page_id' => $pageIdForInsert, 'page_namespace' => $this->mTitle->getNamespace(), 'page_title' => $this->mTitle->getDBkey(), 'page_restrictions' => '', 'page_is_redirect' => 0, 'page_is_new' => 1, 'page_random' => wfRandom(), 'page_touched' => $dbw->timestamp(), 'page_latest' => 0, 'page_len' => 0], __METHOD__, 'IGNORE');
     if ($dbw->affectedRows() > 0) {
         $newid = $pageId ?: $dbw->insertId();
         $this->mId = $newid;
         $this->mTitle->resetArticleID($newid);
         return $newid;
     } else {
         return false;
         // nothing changed
     }
 }
Example #25
0
 function testRandom()
 {
     # This could hypothetically fail, but it shouldn't ;)
     $this->assertFalse(wfRandom() == wfRandom());
 }
 private function getPagesByCategory()
 {
     global $wgDBname;
     #--- blank variables
     $category = $order = null;
     #--- initial parameters (dbname, limit, offset ...)
     extract($this->getInitialParams());
     #--- request parameters ()
     extract($this->extractRequestParams());
     #---
     $this->initCacheKey($lcache_key, __METHOD__);
     try {
         #--- database instance
         $db =& $this->getDB();
         $db->selectDB(!defined(WIKIA_API_QUERY_DBNAME) ? WIKIA_API_QUERY_DBNAME : $wgDBname);
         if (is_null($db)) {
             throw new WikiaApiQueryError(0);
         }
         #--- check categories
         $cats = explode('|', $category);
         $encodedCats = array();
         $memcKeyCats = "";
         foreach ($cats as $cat) {
             $categoryTitle = Title::newFromText($cat);
             if (is_object($categoryTitle)) {
                 $encodedCats[] = $db->strencode($categoryTitle->getDbKey());
                 $memcKeyCats .= str_replace(" ", "_", $categoryTitle->getDbKey());
             }
         }
         if (empty($encodedCats)) {
             throw new WikiaApiQueryError(1, "Missing category");
         }
         $this->setCacheKey($lcache_key, 'CCX', $memcKeyCats);
         # check order by to use proper table from DB
         $orderCache = 0;
         if (!empty($order)) {
             switch ($order) {
                 case "edit":
                     $order_field = "page.page_touched DESC";
                     $orderCache = 1;
                     break;
                 case "random":
                     $orderCache = wfRandom();
                     $this->addWhere("page_random >= " . $orderCache);
                     $order_field = "page.page_random";
                     break;
                 default:
                     $order_field = "page.page_id DESC";
                     break;
             }
         } else {
             if (count($encodedCats) > 1) {
                 $order_field = "page.page_id DESC";
                 #"categorylinks.cl_to, categorylinks.cl_from DESC";
                 $orderCache = 3;
             } else {
                 $order_field = "page.page_id DESC";
                 $orderCache = 4;
             }
         }
         $this->setCacheKey($lcache_key, 'ORD', $orderCache);
         #--- limit
         if (!empty($limit)) {
             if (!$this->isInt($limit)) {
                 throw new WikiaApiQueryError(1);
             }
             $this->setCacheKey($lcache_key, 'L', $limit);
         }
         if (!empty($offset)) {
             if (!$this->isInt($offset)) {
                 throw new WikiaApiQueryError(1);
             }
             $this->setCacheKey($lcache_key, 'LO', $offset);
         }
         # if user categorylinks in query
         sort($encodedCats);
         $data = array();
         // check data from cache ...
         $cached = "";
         #$this->getDataFromCache($lcache_key);
         if (!is_array($cached)) {
             foreach ($encodedCats as $id => $category) {
                 #---
                 $pages = $this->getCategoryPages($db, $category, $limit);
                 #--- no pages
                 if (empty($pages)) {
                     continue;
                 }
                 $this->resetQueryParams();
                 # build main query on page table
                 $this->addTables(array("page"));
                 $this->addFields(array('page_id', 'page_namespace', 'page_title', 'page_touched', 'page_random'));
                 $this->addWhere("page_id in ('" . implode("','", $pages) . "')");
                 $this->addWhere("page_is_redirect = 0");
                 #-- limit;
                 $this->addOption("LIMIT", $limit);
                 $this->addOption("OFFSET", $offset);
                 $this->addOption("ORDER BY", "{$order_field}");
                 #---
                 $res = $this->select(__METHOD__);
                 #---
                 while ($row = $db->fetchObject($res)) {
                     $data[$row->page_id] = array("id" => $row->page_id, "namespace" => $row->page_namespace, "title" => $row->page_title, "url" => htmlspecialchars(Title::makeTitle($row->page_namespace, $row->page_title)->getFullURL()), "category" => $category);
                     ApiResult::setContent($data[$row->page_id], $row->page_title);
                 }
                 $db->freeResult($res);
                 if (count($data) >= $limit) {
                     break;
                 }
             }
             #--- set in memc
             $this->saveCacheData($lcache_key, $data, $ctime);
         } else {
             // ... cached
             $data = $cached;
         }
     } catch (WikiaApiQueryError $e) {
         // getText();
     } catch (DBQueryError $e) {
         $e = new WikiaApiQueryError(0, 'Query error: ' . $e->getText());
     } catch (DBConnectionError $e) {
         $e = new WikiaApiQueryError(0, 'DB connection error: ' . $e->getText());
     } catch (DBError $e) {
         $e = new WikiaApiQueryError(0, 'Error in database: ' . $e->getLogMessage());
     }
     // is exception
     if (isset($e)) {
         $data = $e->getText();
         $this->getResult()->setIndexedTagName($data, 'fault');
     } else {
         $this->getResult()->setIndexedTagName($data, 'item');
     }
     $this->getResult()->addValue('query', $this->getModuleName(), $data);
 }
Example #27
0
 function execute($par)
 {
     global $wgOut, $wgRequest, $wgUser, $wgTitle, $wgLanguageCode, $wgHooks;
     require_once 'Leaderboard.body.php';
     if ($wgLanguageCode != 'en') {
         $wgOut->errorpage('nosuchspecialpage', 'nospecialpagetext');
         return;
     }
     $map = SuggestCategories::getCatMap(true);
     $cats = SuggestCategories::getSubscribedCats();
     $dbr = wfGetDB(DB_SLAVE);
     wfLoadExtensionMessages('RecommendedArticles');
     $wgOut->setRobotPolicy('noindex,nofollow');
     $wgOut->setHTMLTitle('Manage Suggested Topics - wikiHow');
     $target = isset($par) ? $par : $wgRequest->getVal('target');
     if ($target == 'TopRow') {
         $wgOut->setArticleBodyOnly(true);
         $wgOut->addHTML($this->getTopLevelSuggestions($map, $cats));
         return;
     }
     $wgOut->addHTML('<style type="text/css" media="all">/*<![CDATA[*/ @import "' . wfGetPad('/extensions/min/f/extensions/wikihow/suggestedtopics.css?rev=') . WH_SITEREV . '"; /*]]>*/</style>');
     $wgOut->addScript('<script type="text/javascript" src="' . wfGetPad('/extensions/min/f/extensions/wikihow/suggestedtopics.js?rev=') . WH_SITEREV . '"></script>');
     ListRequestedTopics::setActiveWidget();
     ListRequestedTopics::setTopAuthorWidget();
     ListRequestedTopics::getNewArticlesWidget();
     $wgHooks["pageTabs"][] = array("wfRequestedTopicsTabs");
     //heading with link
     $request = '<a href="/Special:RequestTopic" class="edit">' . wfMsg('requesttopic') . '</a>';
     $heading = $request . '<h2>' . wfMsg('suggestedarticles_header') . '</h2>';
     $wgOut->addHTML($heading);
     $suggestions = "";
     if (count($cats) > 0) {
         foreach ($cats as $key) {
             $cat = $map[$key];
             $suggestionsArray = array();
             // grab some suggestions
             $randstr = wfRandom();
             $headerDone = false;
             $suggCount = 0;
             // grab 2 suggested articles that are NOT by ANON
             $resUser = $dbr->select('suggested_titles', array('st_title', 'st_user', 'st_user_text'), array('st_category' => $cat, 'st_used=0', "st_user > 0"), __METHOD__, array("ORDER BY" => "st_random", "LIMIT" => 2));
             foreach ($resUser as $userRow) {
                 $randSpot = mt_rand(0, 4);
                 while (!empty($suggestionsArray[$randSpot])) {
                     $randSpot = mt_rand(0, 4);
                 }
                 $suggestionsArray[$randSpot]->title = $userRow->st_title;
                 $suggestionsArray[$randSpot]->user = $userRow->st_user;
                 $suggCount++;
             }
             $res = $dbr->select('suggested_titles', array('st_title', 'st_user', 'st_user_text'), array('st_category' => $cat, 'st_used' => 0, 'st_traffic_volume' => 2, "st_random >= {$randstr}"), __METHOD__, array("ORDER BY" => "st_random", "LIMIT" => 5));
             if ($dbr->numRows($res) > 0) {
                 foreach ($res as $row) {
                     if ($suggCount >= 5) {
                         break;
                     }
                     $randSpot = mt_rand(0, 4);
                     while (!empty($suggestionsArray[$randSpot])) {
                         $randSpot = mt_rand(0, 4);
                     }
                     $suggestionsArray[$randSpot]->title = $row->st_title;
                     $suggestionsArray[$randSpot]->user = $row->st_user;
                     $suggCount++;
                 }
             }
             if ($cat != 'Other') {
                 $cat_class = 'cat_' . strtolower(str_replace(' ', '', $cat));
                 $cat_class = preg_replace('/&/', 'and', $cat_class);
                 $cat_icon = '<div class="cat_icon ' . $cat_class . '"></div>';
             } else {
                 $cat_icon = '';
             }
             if ($suggCount > 0) {
                 $suggestions .= "<table class='suggested_titles_list wh_block'>";
                 $suggestions .= "<tr class='st_top_row'><th class='st_icon'>{$cat_icon}</th><th class='st_title'><strong>{$cat}</strong></th><th>Requested By</th></tr>";
                 require_once 'EditPageWrapper.php';
                 foreach ($suggestionsArray as $suggestion) {
                     if (!empty($suggestionsArray)) {
                         $t = Title::newFromText(EditPageWrapper::formatTitle($suggestion->title));
                         if ($suggestion->user > 0) {
                             $u = User::newFromId($suggestion->user);
                             $u = "<a href='{$u->getUserPage()->getFullURL()}'>{$u->getName()}</a>";
                         } else {
                             $u = "Anonymous";
                         }
                         $suggestions .= "<tr><td class='st_write'><a href='/Special:CreatePage/{$t->getPartialURL()}'>Write</td><td class='st_title'>{$t->getText()}</td><td class='st_requestor'>{$u}</td></tr>";
                     }
                 }
                 $suggestions .= "</table>";
             }
         }
     }
     if ($wgRequest->getInt('surprise') == 1 || $suggestions == "") {
         $wgOut->addHTML("<div id='top_suggestions'>" . $this->getTopLevelSuggestions($map, $cats) . "</div>");
     }
     $wgOut->addHTML("<br class='clearall' /><div id='suggested_surprise_big'><a href='/Special:RecommendedArticles?surprise=1' class='button secondary'>" . wfMsg('suggested_list_button_surprise') . "</a></div><br class='clearall' />");
     if (sizeof($cats) == 0) {
         $wgOut->addHTML(wfMsg('suggested_nocats'));
         $wgOut->addHTML("<a href='#' id='choose_cats'>Choose which categories to display</a>");
         return;
     }
     if ($wgUser->getID() > 0) {
         $wgOut->addHTML($suggestions);
         $wgOut->addHTML("<a href='#' id='choose_cats'>Choose which categories to display</a>");
     } else {
         $rt = $wgTitle->getPrefixedURL();
         $q = "returnto={$rt}";
         $wgOut->addHTML(wfMsg('recommend_anon', $q));
     }
 }
Example #28
0
	/**
	 * Insert a new empty page record for this article.
	 * This *must* be followed up by creating a revision
	 * and running $this->updateRevisionOn( ... );
	 * or else the record will be left in a funky state.
	 * Best if all done inside a transaction.
	 *
	 * @param $dbw DatabaseBase
	 * @return int The newly created page_id key, or false if the title already existed
	 */
	public function insertOn( $dbw ) {
		wfProfileIn( __METHOD__ );

		$page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
		$dbw->insert( 'page', array(
			'page_id'           => $page_id,
			'page_namespace'    => $this->mTitle->getNamespace(),
			'page_title'        => $this->mTitle->getDBkey(),
			'page_counter'      => 0,
			'page_restrictions' => '',
			'page_is_redirect'  => 0, // Will set this shortly...
			'page_is_new'       => 1,
			'page_random'       => wfRandom(),
			'page_touched'      => $dbw->timestamp(),
			'page_latest'       => 0, // Fill this in shortly...
			'page_len'          => 0, // Fill this in shortly...
		), __METHOD__, 'IGNORE' );

		$affected = $dbw->affectedRows();

		if ( $affected ) {
			$newid = $dbw->insertId();
			$this->mId = $newid;
			$this->mTitle->resetArticleID( $newid );
		}
		wfProfileOut( __METHOD__ );

		return $affected ? $newid : false;
	}
Example #29
0
 /**
  * Selects a random title.  Observes user's category filter.
  * @return Title the title object result
  */
 public static function getRandomTitle()
 {
     global $wgUser;
     $fname = __METHOD__;
     wfProfileIn($fname);
     $NUM_TRIES = 5;
     $filterSql = $wgUser->getCatFilter('pr_catinfo', true);
     $dbr = wfGetDB(DB_SLAVE);
     for ($i = 0; $i < $NUM_TRIES; $i++) {
         $randstr = wfRandom();
         $sql = "SELECT pr_title\n\t\t\t\tFROM page_randomizer\n\t\t\t\tWHERE pr_random >= {$randstr}\n\t\t\t\t{$filterSql}\n\t\t\t\tORDER BY pr_random";
         $sql = $dbr->limitResult($sql, 1, 0);
         $res = $dbr->query($sql, $fname);
         $row = $dbr->fetchObject($res);
         $title = Title::newFromDBkey($row->pr_title);
         if ($title && $title->exists()) {
             break;
         }
     }
     wfProfileOut($fname);
     return $title;
 }