/**
  * Execute special page.  Only available to wikihow staff.
  */
 function execute()
 {
     global $wgRequest, $wgOut, $wgUser, $wgLang;
     # don't stop execution
     set_time_limit(0);
     print "querying database...<br>\n";
     $dbr = wfGetDB(DB_SLAVE);
     $titles = array();
     $sql = 'SELECT page_title FROM page WHERE page_namespace=' . NS_MAIN . ' AND page_is_redirect=0';
     $res = $dbr->query($sql);
     while ($obj = $res->fetchObject()) {
         $titles[] = Title::newFromDBkey($obj->page_title);
     }
     $wgOut->clearHTML();
     $file = '/tmp/out.csv';
     print "writing output to {$file}...<br>\n";
     $fp = fopen($file, 'w');
     fputs($fp, "url,new,new-format,old\n");
     foreach ($titles as $title) {
         $tt = TitleTests::newFromTitle($title);
         if (!$tt) {
             continue;
         }
         list($new, $format) = $tt->getTitle();
         list($old, ) = $tt->getOldTitle();
         $url = 'http://www.wikihow.com/' . $title->getPartialURL();
         $out = array($url, $new, $format, $old);
         fputcsv($fp, $out);
     }
     fclose($fp);
     print "done.<br>\n";
     exit;
 }
 /**
  * Show the special page
  *
  * @param $params Mixed: parameter(s) passed to the page or null
  */
 public function execute($params)
 {
     global $wgOut, $wgUser;
     // Check permissions
     if (!in_array('staff', $wgUser->getEffectiveGroups())) {
         throw new ErrorPageError('error', 'badaccess');
     }
     // Show a message if the database is in read-only mode
     if (wfReadOnly()) {
         $wgOut->readOnlyPage();
         return;
     }
     // If user is blocked, they don't need to access this page
     if ($wgUser->isBlocked()) {
         $wgOut->blockedPage();
         return;
     }
     $dbw = wfGetDB(DB_MASTER);
     $res = $dbw->select('page', array('page_title'), array('page_namespace' => NS_USER), __METHOD__);
     $count = 0;
     // To avoid an annoying PHP notice
     foreach ($res as $row) {
         $user_name_title = Title::newFromDBkey($row->page_title);
         $user_name = $user_name_title->getText();
         $user_id = User::idFromName($user_name);
         if ($user_id > 0) {
             $s = $dbw->selectRow('user_profile', array('up_user_id'), array('up_user_id' => $user_id), __METHOD__);
             if ($s === false) {
                 $dbw->insert('user_profile', array('up_user_id' => $user_id, 'up_type' => 0), __METHOD__);
                 $count++;
             }
         }
     }
     $wgOut->addHTML(wfMsgExt('populate-user-profile-done', 'parsemag', $count));
 }
 /**
  * Adds users to watchlist if:
  * - User is watching parent page
  * - User has 'watchlistsubpages' turned on
  *
  * @param $watchers array of user ID
  * @param $title Title object
  * @param $editor User object
  * @param $notificationTimeoutSql string timeout to the watchlist
  *
  * @author Jakub Kurcek <*****@*****.**>
  */
 public static function NotifyOnSubPageChange($watchers, $title, $editor, $notificationTimeoutSql)
 {
     wfProfileIn(__METHOD__);
     // Gets parent data
     $arrTitle = explode('/', $title->getDBkey());
     if (empty($arrTitle)) {
         wfProfileOut(__METHOD__);
         return true;
     }
     // make Title
     $t = reset($arrTitle);
     $newTitle = Title::newFromDBkey($t);
     if (!$newTitle instanceof Title) {
         return true;
     }
     $dbw = wfGetDB(DB_MASTER);
     /** @var $dbw Database */
     $res = $dbw->select(array('watchlist'), array('wl_user'), array('wl_title' => $newTitle->getDBkey(), 'wl_namespace' => $newTitle->getNamespace(), 'wl_user != ' . intval($editor->getID()), $notificationTimeoutSql), __METHOD__);
     // Gets user settings
     $parentpageWatchers = array();
     while ($row = $dbw->fetchObject($res)) {
         $userId = intval($row->wl_user);
         $tmpUser = User::newFromId($userId);
         if ($tmpUser->getBoolOption(self::PREFERENCES_ENTRY)) {
             $parentpageWatchers[] = $userId;
         }
         unset($tmpUser);
     }
     // Updates parent watchlist timestamp for $parentOnlyWatchers.
     $parentOnlyWatchers = array_diff($parentpageWatchers, $watchers);
     $wl = WatchedItem::fromUserTitle($editor, $newTitle);
     $wl->updateWatch($parentOnlyWatchers);
     wfProfileOut(__METHOD__);
     return true;
 }
Example #4
0
 /**
  * Add meta descriptions for all pages on site.  Convert all to the
  * given style.
  *
  * Commenting out this function because it's dangerous.  It could delete
  * all user-generated descriptions from the table.
  *
  */
 public static function reprocessAllArticles($style)
 {
     // pull all pages from DB
     $dbw = wfGetDB(DB_MASTER);
     $rows = $dbw->select('page', 'page_title', array('page_is_redirect' => 0, 'page_namespace' => NS_MAIN), __METHOD__);
     //array('LIMIT' => 100));
     $pages = array();
     foreach ($rows as $obj) {
         $pages[] = $obj->page_title;
     }
     // delete all existing meta descriptions not of the chosen style
     //$dbw->delete('article_meta_info', '*', __METHOD__);
     //$dbw->update('article_meta_info',
     //  array('ami_desc_style = ' . $style,
     //      "ami_desc = ''"),
     //  array('ami_desc_style <> ' . $style),
     //  __METHOD__);
     // process all pages, adding then chosen style description to them
     foreach ($pages as $page) {
         $title = Title::newFromDBkey($page);
         if ($title) {
             $ami = new ArticleMetaInfo($title, true);
             $ami->refreshMetaData($style);
             if (@$count++ % 10000 == 0 && $count > 0) {
                 print date('r') . " done {$count}\n";
             }
             sleep(2);
             // roll out slowly to prevent overwhelming servers with new image requests
         } else {
             print "title not found: {$page}\n";
         }
     }
 }
Example #5
0
function wfSajaxSearch($term)
{
    global $wgContLang, $wgOut;
    $limit = 16;
    $l = new Linker();
    $term = str_replace(' ', '_', $wgContLang->ucfirst($wgContLang->checkTitleEncoding($wgContLang->recodeInput(js_unescape($term)))));
    if (strlen(str_replace('_', '', $term)) < 3) {
        return;
    }
    $db =& wfGetDB(DB_SLAVE);
    $res = $db->select('page', 'page_title', array('page_namespace' => 0, "page_title LIKE '" . $db->strencode($term) . "%'"), "wfSajaxSearch", array('LIMIT' => $limit + 1));
    $r = "";
    $i = 0;
    while (($row = $db->fetchObject($res)) && ++$i <= $limit) {
        $nt = Title::newFromDBkey($row->page_title);
        $r .= '<li>' . $l->makeKnownLinkObj($nt) . "</li>\n";
    }
    if ($i > $limit) {
        $more = '<i>' . $l->makeKnownLink($wgContLang->specialPage("Allpages"), wfMsg('moredotdotdot'), "namespace=0&from=" . wfUrlEncode($term)) . '</i>';
    } else {
        $more = '';
    }
    $subtitlemsg = Title::newFromText($term) ? 'searchsubtitle' : 'searchsubtitleinvalid';
    $subtitle = $wgOut->parse(wfMsg($subtitlemsg, wfEscapeWikiText($term)));
    #FIXME: parser is missing mTitle !
    $term = htmlspecialchars($term);
    $html = '<div style="float:right; border:solid 1px black;background:gainsboro;padding:2px;"><a onclick="Searching_Hide_Results();">' . wfMsg('hideresults') . '</a></div>' . '<h1 class="firstHeading">' . wfMsg('search') . '</h1><div id="contentSub">' . $subtitle . '</div><ul><li>' . $l->makeKnownLink($wgContLang->specialPage('Search'), wfMsg('searchcontaining', $term), "search={$term}&fulltext=Search") . '</li><li>' . $l->makeKnownLink($wgContLang->specialPage('Search'), wfMsg('searchnamed', $term), "search={$term}&go=Go") . "</li></ul><h2>" . wfMsg('articletitles', $term) . "</h2>" . '<ul>' . $r . '</ul>' . $more;
    $response = new AjaxResponse($html);
    $response->setCacheDuration(30 * 60);
    return $response;
}
Example #6
0
 /**
  * Check to see if an image was already uploaded for wikiphoto
  */
 public static function checkDupImage($filename)
 {
     $dbr = self::getDB('read');
     $contents = @file_get_contents($filename);
     if ($contents) {
         $sha1 = sha1($contents);
         $db_title = $dbr->selectField('images_sha1', 'is_page_title', array('is_sha1' => $sha1), __METHOD__);
         if ($db_title) {
             $title = Title::newFromDBkey('Image:' . $db_title);
             if ($title && $title->exists()) {
                 $file = wfFindFile($title);
                 if ($file) {
                     $path = $file->getPath();
                     if ($path && @file_exists($path)) {
                         $contents = @file_get_contents($path);
                         if ($contents) {
                             $sha1_orig = sha1($contents);
                             if ($sha1_orig == $sha1) {
                                 return $title->getText();
                             }
                         }
                     }
                 }
             }
         }
     }
     return '';
 }
 public static function getSelection($maxUrls, $minImages)
 {
     $output = array();
     $dbr = wfGetDB(DB_SLAVE);
     $sql = 'SELECT pr_title FROM page_randomizer';
     $rows = parent::loadRows($dbr, $sql, '', __METHOD__);
     shuffle($rows);
     foreach ($rows as $row) {
         $wikitext = '';
         $steps = '';
         $titleDBkey = $row['pr_title'];
         $title = Title::newFromDBkey($titleDBkey);
         if ($title) {
             $wikitext = parent::getWikitext($dbr, $title);
         }
         if ($wikitext) {
             list($steps, ) = Wikitext::getStepsSection($wikitext);
         }
         if ($steps) {
             $images = parent::getNumStepsImages($steps);
             if ($images >= $minImages) {
                 $output[] = $title->getPartialURL();
                 if (count($output) >= $maxUrls) {
                     break;
                 }
             }
         }
     }
     return $output;
 }
function addAll404Redirects()
{
    $rows = DatabaseHelper::batchSelect('page', array('page_title', 'page_id'), array('page_namespace' => NS_MAIN, 'page_is_redirect' => 0), __METHOD__);
    foreach ($rows as $row) {
        $title = Title::newFromDBkey($row->page_title);
        if ($title) {
            Misc::modify404Redirect($row->page_id, $title);
        }
    }
}
Example #9
0
 function setUser2($username)
 {
     $title1 = Title::newFromDBkey($username);
     $this->challenge_username2 = $title1->getText();
     $dbr =& wfGetDB(DB_SLAVE);
     $s = $dbr->selectRow('user', array('user_id'), array('user_name' => $this->challenge_username2), $fname);
     if ($s === false) {
         $this->challenge_user_id_2 = 0;
     } else {
         $this->challenge_user_id_2 = $s->user_id;
     }
 }
	/**
	 * Constructor
	 *
	 * @param $username String: username (usually $wgUser's username)
	 * @param $filter String: passed to setFilter(); can be either 'user',
	 *                        'friends', 'foes' or 'all', depending on what
	 *                        kind of information is wanted
	 * @param $item_max Integer: maximum amount of items to display in the feed
	 */
	public function __construct( $username, $filter, $item_max ) {
		if ( $username ) {
			$title1 = Title::newFromDBkey( $username );
			$this->user_name = $title1->getText();
			$this->user_id = User::idFromName( $this->user_name );
		}
		$this->setFilter( $filter );
		$this->item_max = $item_max;
		$this->now = time();
		$this->three_days_ago = $this->now - ( 60 * 60 * 24 * 3 );
		$this->items_grouped = array();
	}
Example #11
0
 private static function searchHTML($terms)
 {
     $html = '';
     $html .= '<style>tr:nth-child(even) {background: #EEE}</style>';
     $html .= '<table>';
     $dbr = wfGetDB(DB_SLAVE);
     $terms = trim(strip_tags($terms));
     $terms = '%' . join('%', preg_split('@\\s+@', $terms)) . '%';
     $res = $dbr->select('page', array('page_title', 'page_is_redirect', 'page_id'), array('page_namespace' => NS_MAIN, 'LOWER(page_title) LIKE ' . $dbr->addQuotes($terms)), __METHOD__);
     foreach ($res as $row) {
         $id = $row->page_id;
         $title = Title::newFromDBkey($row->page_title);
         $html .= "<tr id='row_{$id}'>";
         $html .= '<td><a href="' . htmlspecialchars($title->getFullURL('redirect=no')) . '" target="_new">' . htmlspecialchars($title->getText()) . '</a>' . ($row->page_is_redirect ? ' <i>redirect</i>' : '') . '</td>';
         $html .= '<td><a href="#" class="delete" id="rm_' . $id . '">delete</a></td>';
         $html .= "</tr>\n";
     }
     $html .= "</table>";
     return $html;
 }
    /**
     * Compute the latest good revisions table for all articles.
     */
    public static function computeLatestAll()
    {
        $dbw = wfGetDB(DB_MASTER);
        $one_week_ago = wfTimestamp(TS_MW, time() - 7 * 24 * 60 * 60);
        $corrected = array();
        $updateRevFunc = function ($page_id, $page_title, $rev_id) {
            $title = Title::newFromDBkey($page_title);
            $goodRev = GoodRevision::newFromTitle($title, $page_id);
            if ($goodRev) {
                return $goodRev->updateRev($rev_id, true);
            } else {
                return false;
            }
        };
        // Clear from good_revision table all the deleted articles,
        // articles moved to other namespaces and articles
        // turned into redirects.
        $sql = 'DELETE good_revision FROM good_revision
				LEFT JOIN page ON gr_page = page_id
				WHERE page_is_redirect <> 0 OR
					page_namespace <> 0 OR
					page_title IS NULL';
        $dbw->query($sql, __METHOD__);
        $count = $dbw->affectedRows();
        print __METHOD__ . ": removed " . $dbw->affectedRows() . " non-article rows from good_revision table\n";
        // List all articles patrolled over the last week and
        // compute good_rev on them
        $sql = 'SELECT page_title, page_id, MAX(rc_id) AS rc_id
				FROM page, recentchanges 
				WHERE page_id = rc_cur_id AND
					page_namespace = 0 AND
					page_is_redirect = 0 AND
					rc_patrolled = 1 AND
					page_touched >= ' . $dbw->addQuotes($one_week_ago) . '
				GROUP BY rc_cur_id';
        $patrolled = array();
        $res = $dbw->query($sql, __METHOD__);
        foreach ($res as $obj) {
            $patrolled[$obj->page_id] = (array) $obj;
        }
        // Store recently patrolled articles with their patrolled revision
        foreach ($patrolled as $row) {
            $rev_id = GoodRevision::getRevFromRC($row['page_id'], $row['rc_id']);
            $updated = $updateRevFunc($row['page_id'], $row['page_title'], $rev_id);
            if ($updated) {
                $corrected[] = $row['page_id'];
            }
        }
        $count = count($corrected);
        print __METHOD__ . ": updated {$count} recently patrolled articles in good_revision table\n";
        // List all articles that haven't been touched in the last week
        // and correct their good revision if need
        $sql = 'SELECT page_title, page_id, page_latest
				FROM page
				WHERE page_namespace = 0 AND
					page_is_redirect = 0 AND
					page_touched < ' . $dbw->addQuotes($one_week_ago);
        $rows = array();
        $res = $dbw->query($sql, __METHOD__);
        foreach ($res as $obj) {
            $rows[] = (array) $obj;
        }
        // Store latest revision of all articles not edited in the last week
        foreach ($rows as $row) {
            if (!isset($patrolled[$row['page_id']])) {
                $updated = $updateRevFunc($row['page_id'], $row['page_title'], $row['page_latest']);
                if ($updated) {
                    $corrected[] = $row['page_id'];
                }
            }
        }
        print __METHOD__ . ": updated " . (count($corrected) - $count) . " older articles in good_revision table\n";
        // Call out to DailyEdits to let Titus and others know what should be recomputed
        foreach ($corrected as $aid) {
            DailyEdits::onGoodRevisionFixed($aid);
        }
    }
	/**
	 * Show the special page
	 *
	 * @param $params Mixed: parameter(s) passed to the page or null
	 */
	public function execute( $params ) {
		global $wgUser, $wgOut, $wgRequest, $wgUserRelationshipScripts;

		// Can't use $this->setHeaders(); here because then it'll set the page
		// title to <removerelationship> and we don't want that, we'll be
		// messing with the page title later on in the code
		$wgOut->setArticleRelated( false );
		$wgOut->setRobotPolicy( 'noindex,nofollow' );

		$wgOut->addExtensionStyle( $wgUserRelationshipScripts . '/UserRelationship.css' );

		$usertitle = Title::newFromDBkey( $wgRequest->getVal( 'user' ) );
		if ( !$usertitle ) {
			$wgOut->setPageTitle( wfMsgHtml( 'ur-error-title' ) );
			$wgOut->addWikiText( wfMsgNoTrans( 'ur-add-no-user' ) );
			return false;
		}

		$this->user_name_to = $usertitle->getText();
		$this->user_id_to = User::idFromName( $this->user_name_to );
		$this->relationship_type = UserRelationship::getUserRelationshipByID(
			$this->user_id_to,
			$wgUser->getID()
		);

		if ( $this->relationship_type == 1 ) {
			$confirmTitle = wfMsg( 'ur-remove-relationship-title-confirm-friend', $this->user_name_to );
			$confirmMsg = wfMsg( 'ur-remove-relationship-message-confirm-friend', $this->user_name_to );
			$error = wfMsg( 'ur-remove-error-not-loggedin-friend' );
			$pending = wfMsg( 'ur-remove-error-message-pending-friend-request', $this->user_name_to );
		} else {
			$confirmTitle = wfMsg( 'ur-remove-relationship-title-confirm-foe', $this->user_name_to );
			$confirmMsg = wfMsg( 'ur-remove-relationship-message-confirm-foe', $this->user_name_to );
			$error = wfMsg( 'ur-remove-error-not-loggedin-foe' );
			$pending = wfMsg( 'ur-remove-error-message-pending-foe-request', $this->user_name_to );
		}

		$out = '';
		if ( $wgUser->getID() == $this->user_id_to ) {
			$wgOut->setPageTitle( wfMsg( 'ur-error-title' ) );
			$out .= '<div class="relationship-error-message">' .
				wfMsg( 'ur-remove-error-message-remove-yourself' ) .
			'</div>
			<div>
				<input type="button" class="site-button" value="' . wfMsg( 'ur-main-page' ) . '" size="20" onclick=\'window.location="index.php?title=' . wfMsgForContent( 'mainpage' ) . '"\' />';
			if ( $wgUser->isLoggedIn() ) {
				$out .= '<input type="button" class="site-button" value="' . wfMsg( 'ur-your-profile' ) . '" size="20" onclick=\'window.location="' . $wgUser->getUserPage()->escapeFullURL() . '"\' />';
			}
			$out .= '</div>';

			$wgOut->addHTML( $out );
		} elseif ( $this->relationship_type == false ) {
			$wgOut->setPageTitle( wfMsg( 'ur-error-title' ) );
			$out .= '<div class="relationship-error-message">' .
				wfMsg( 'ur-remove-error-message-no-relationship', $this->user_name_to ) .
			'</div>
			<div>
				<input type="button" class="site-button" value="' . wfMsg( 'ur-main-page' ) . '" size="20" onclick=\'window.location="index.php?title="' . wfMsgForContent( 'mainpage' ) . '"\' />';
			if ( $wgUser->isLoggedIn() ) {
				$out .= '<input type="button" class="site-button" value="' . wfMsg( 'ur-your-profile' ) . '" size="20" onclick=\'window.location="' . $wgUser->getUserPage()->escapeFullURL() . '"\' />';
			}
			$out .= '</div>';

			$wgOut->addHTML( $out );
		} elseif ( UserRelationship::userHasRequestByID( $this->user_id_to, $wgUser->getID() ) == true ) {
			$wgOut->setPageTitle( wfMsg( 'ur-error-title' ) );
			$out .= '<div class="relationship-error-message">' .
				$pending .
				'</div>
			<div>
				<input type="button" class="site-button" value="' . wfMsg( 'ur-main-page' ) . '" size="20" onclick=\'window.location="index.php?title="' . wfMsgForContent( 'mainpage' ) . '"\' />';
			if ( $wgUser->isLoggedIn() ) {
				$out .= '<input type="button" class="site-button" value="' . wfMsg( 'ur-your-profile' ) . '" size="20" onclick=\'window.location="' . $wgUser->getUserPage()->escapeFullURL() . '"\' />';
			}
			$out .= '</div>';

			$wgOut->addHTML( $out );
		} elseif ( $wgUser->getID() == 0 ) {
			$wgOut->setPageTitle( wfMsg( 'ur-error-title' ) );
			$out .= '<div class="relationship-error-message">' .
				$error .
			'</div>
			<div>
				<input type="button" class="site-button" value="' . wfMsg( 'ur-main-page' ) . '" size="20" onclick=\'window.location="index.php?title="' . wfMsgForContent( 'mainpage' ) . '"\' />';
			if ( $wgUser->isLoggedIn() ) {
				$out .= '<input type="button" class="site-button" value="' . wfMsg( 'ur-your-profile' ) . '" size="20" onclick=\'window.location="' . $wgUser->getUserPage()->escapeFullURL() . '"\' />';
			}
			$out .= '</div>';

			$wgOut->addHTML( $out );
		} else {
			$rel = new UserRelationship( $wgUser->getName() );
	 		if ( $wgRequest->wasPosted() && $_SESSION['alreadysubmitted'] == false ) {
				$_SESSION['alreadysubmitted'] = true;
				$rel->removeRelationshipByUserID(
					$this->user_id_to,
					$wgUser->getID()
				);
				$rel->sendRelationshipRemoveEmail(
					$this->user_id_to,
					$wgUser->getName(),
					$this->relationship_type
				);
				$avatar = new wAvatar( $this->user_id_to, 'l' );

				$wgOut->setPageTitle( $confirmTitle );

				$out .= "<div class=\"relationship-action\">
					{$avatar->getAvatarURL()}" .
					$confirmMsg .
					"<div class=\"relationship-buttons\">
						<input type=\"button\" class=\"site-button\" value=\"" . wfMsg( 'ur-main-page' ) . "\" size=\"20\" onclick=\"window.location='index.php?title=" . wfMsgForContent( 'mainpage' ) . "'\"/>
						<input type=\"button\" class=\"site-button\" value=\"" . wfMsg( 'ur-your-profile' ) . "\" size=\"20\" onclick=\"window.location='" . $wgUser->getUserPage()->escapeFullURL() . "'\"/>
					</div>
					<div class=\"cleared\"></div>
					</div>";

				$wgOut->addHTML( $out );
			} else {
				$_SESSION['alreadysubmitted'] = false;
				$wgOut->addHTML( $this->displayForm() );
			}

		}
	}
Example #14
0
 /**
  * Try to find an SMWDataItem that the given SMWExpElement might
  * represent. Returns null if this attempt failed.
  *
  * @param SMWExpElement $expElement
  * @return SMWDataItem or null
  */
 public static function findDataItemForExpElement(SMWExpElement $expElement)
 {
     global $wgContLang;
     $dataItem = null;
     if ($expElement instanceof SMWExpResource) {
         $uri = $expElement->getUri();
         $wikiNamespace = self::getNamespaceUri('wiki');
         if (strpos($uri, $wikiNamespace) === 0) {
             $localName = substr($uri, strlen($wikiNamespace));
             $dbKey = urldecode(self::decodeURI($localName));
             $parts = explode('-23', $dbKey, 2);
             if (count($parts) == 2) {
                 $subobjectname = $parts[1];
             } else {
                 $subobjectname = '';
             }
             $parts = explode(':', $dbKey, 2);
             if (count($parts) == 1) {
                 $dataItem = new SMWDIWikiPage($dbKey, NS_MAIN, '', $subobjectname);
             } else {
                 // try the by far most common cases directly before using Title
                 $namespaceName = str_replace('_', ' ', $parts[0]);
                 $namespaceId = -1;
                 foreach (array(SMW_NS_PROPERTY, NS_CATEGORY, NS_USER, NS_HELP) as $nsId) {
                     if ($namespaceName == $wgContLang->getNsText($nsId)) {
                         $namespaceId = $nsId;
                         break;
                     }
                 }
                 if ($namespaceId != -1) {
                     $dataItem = new SMWDIWikiPage($parts[1], $namespaceId, '', $subobjectname);
                 } else {
                     $title = Title::newFromDBkey($dbKey);
                     if (!is_null($title)) {
                         $dataItem = new SMWDIWikiPage($title->getDBkey(), $title->getNamespace(), $title->getInterwiki(), $subobjectname);
                     }
                 }
             }
         }
         // else: not in wiki namespace -- TODO: this could be an imported URI
     } else {
         // TODO (currently not needed, but will be useful for displaying external SPARQL results)
     }
     return $dataItem;
 }
Example #15
0
 public static function toggle($pagename)
 {
     global $wgUser;
     $title = Title::newFromDBkey($pagename);
     if (!$title) {
         return self::returnMsg(self::TITLE_INVALID, $protectState);
     }
     $aid = $title->getArticleID();
     // title must exist!
     if ($aid == 0) {
         return self::returnMsg(self::TITLE_INVALID, $protectState);
     }
     // user must have the required clearance
     if (!$wgUser->isAllowed('protect')) {
         return self::returnMsg(self::USER_INSUFFICIENT_RIGHT, $protectState);
     }
     $protectState = $title->isProtected('edit');
     // format the restriction
     //  whilst inverting the state...
     $group = $protectState ? '' : 'sysop';
     $restriction = array('edit' => $group);
     // update!
     $article = new Article($title);
     $code = $article->updateRestrictions($restriction);
     $msg = $code ? self::SUCCESS : self::FAILURE;
     // update protection status
     $protectState = $code ? !$protectState : $protectState;
     return self::returnMsg($msg, $protectState);
 }
 /**
  * Modify $this->internals and $colours according to language variant linking rules
  */
 protected function doVariants(&$colours)
 {
     global $wgContLang;
     $linkBatch = new LinkBatch();
     $variantMap = array();
     // maps $pdbkey_Variant => $keys (of link holders)
     $output = $this->parent->getOutput();
     $linkCache = LinkCache::singleton();
     $threshold = $this->parent->getOptions()->getStubThreshold();
     $titlesToBeConverted = '';
     $titlesAttrs = array();
     // Concatenate titles to a single string, thus we only need auto convert the
     // single string to all variants. This would improve parser's performance
     // significantly.
     foreach ($this->internals as $ns => $entries) {
         foreach ($entries as $index => $entry) {
             $pdbk = $entry['pdbk'];
             // we only deal with new links (in its first query)
             if (!isset($colours[$pdbk]) || $colours[$pdbk] === 'new') {
                 $title = $entry['title'];
                 $titleText = $title->getText();
                 $titlesAttrs[] = array('ns' => $ns, 'key' => "{$ns}:{$index}", 'titleText' => $titleText);
                 // separate titles with \0 because it would never appears
                 // in a valid title
                 $titlesToBeConverted .= $titleText . "";
             }
         }
     }
     // Now do the conversion and explode string to text of titles
     $titlesAllVariants = $wgContLang->autoConvertToAllVariants(rtrim($titlesToBeConverted, ""));
     $allVariantsName = array_keys($titlesAllVariants);
     foreach ($titlesAllVariants as &$titlesVariant) {
         $titlesVariant = explode("", $titlesVariant);
     }
     $l = count($titlesAttrs);
     // Then add variants of links to link batch
     for ($i = 0; $i < $l; $i++) {
         foreach ($allVariantsName as $variantName) {
             $textVariant = $titlesAllVariants[$variantName][$i];
             if ($textVariant != $titlesAttrs[$i]['titleText']) {
                 $variantTitle = Title::makeTitle($titlesAttrs[$i]['ns'], $textVariant);
                 if (is_null($variantTitle)) {
                     continue;
                 }
                 $linkBatch->addObj($variantTitle);
                 $variantMap[$variantTitle->getPrefixedDBkey()][] = $titlesAttrs[$i]['key'];
             }
         }
     }
     // process categories, check if a category exists in some variant
     $categoryMap = array();
     // maps $category_variant => $category (dbkeys)
     $varCategories = array();
     // category replacements oldDBkey => newDBkey
     foreach ($output->getCategoryLinks() as $category) {
         $variants = $wgContLang->autoConvertToAllVariants($category);
         foreach ($variants as $variant) {
             if ($variant != $category) {
                 $variantTitle = Title::newFromDBkey(Title::makeName(NS_CATEGORY, $variant));
                 if (is_null($variantTitle)) {
                     continue;
                 }
                 $linkBatch->addObj($variantTitle);
                 $categoryMap[$variant] = $category;
             }
         }
     }
     if (!$linkBatch->isEmpty()) {
         // construct query
         $dbr = wfGetDB(DB_SLAVE);
         $varRes = $dbr->select('page', array('page_id', 'page_namespace', 'page_title', 'page_is_redirect', 'page_len', 'page_latest'), $linkBatch->constructSet('page', $dbr), __METHOD__);
         $linkcolour_ids = array();
         // for each found variants, figure out link holders and replace
         foreach ($varRes as $s) {
             $variantTitle = Title::makeTitle($s->page_namespace, $s->page_title);
             $varPdbk = $variantTitle->getPrefixedDBkey();
             $vardbk = $variantTitle->getDBkey();
             $holderKeys = array();
             if (isset($variantMap[$varPdbk])) {
                 $holderKeys = $variantMap[$varPdbk];
                 $linkCache->addGoodLinkObjFromRow($variantTitle, $s);
                 $output->addLink($variantTitle, $s->page_id);
             }
             // loop over link holders
             foreach ($holderKeys as $key) {
                 list($ns, $index) = explode(':', $key, 2);
                 $entry =& $this->internals[$ns][$index];
                 $pdbk = $entry['pdbk'];
                 if (!isset($colours[$pdbk]) || $colours[$pdbk] === 'new') {
                     // found link in some of the variants, replace the link holder data
                     $entry['title'] = $variantTitle;
                     $entry['pdbk'] = $varPdbk;
                     // set pdbk and colour
                     # @todo FIXME: Convoluted data flow
                     # The redirect status and length is passed to getLinkColour via the LinkCache
                     # Use formal parameters instead
                     $colours[$varPdbk] = Linker::getLinkColour($variantTitle, $threshold);
                     $linkcolour_ids[$s->page_id] = $pdbk;
                 }
             }
             // check if the object is a variant of a category
             if (isset($categoryMap[$vardbk])) {
                 $oldkey = $categoryMap[$vardbk];
                 if ($oldkey != $vardbk) {
                     $varCategories[$oldkey] = $vardbk;
                 }
             }
         }
         wfRunHooks('GetLinkColours', array($linkcolour_ids, &$colours));
         // rebuild the categories in original order (if there are replacements)
         if (count($varCategories) > 0) {
             $newCats = array();
             $originalCats = $output->getCategories();
             foreach ($originalCats as $cat => $sortkey) {
                 // make the replacement
                 if (array_key_exists($cat, $varCategories)) {
                     $newCats[$varCategories[$cat]] = $sortkey;
                 } else {
                     $newCats[$cat] = $sortkey;
                 }
             }
             $output->setCategoryLinks($newCats);
         }
     }
 }
 /**
  * @param $article WikiPage
  * @param bool $wgUser
  * @param bool $reason
  * @param bool $error
  * @return bool
  */
 public static function onArticleDelete(&$article, &$wgUser = false, &$reason = false, &$error = false)
 {
     $id = $article->mTitle->getArticleID();
     $dbr = wfGetDB(DB_SLAVE);
     if ((int) $id > 0) {
         $res = $dbr->select(array('imagelinks'), array('il_to'), array('il_from=' . $id), __METHOD__);
         while ($s = $res->fetchObject()) {
             $title = Title::newFromDBkey($s->il_to);
             if (!empty($title)) {
                 $mq = new self($title);
                 $mq->unsetCache();
             }
         }
     }
     return true;
 }
//
// List all articles on that site that have a short (or non-existent) intro
// section. All wikitext is stripped, so images aren't included in this
// output.
//
require_once "commandLine.inc";
$dbr = wfGetDB(DB_SLAVE);
$sql = "SELECT page_title, page_id FROM page WHERE page_is_redirect=0 AND page_namespace=" . NS_MAIN;
$res = $dbr->query($sql, __FILE__);
$fp = fopen('short-intros.csv', 'w');
if (!$fp) {
    die("could not open file for write\n");
}
fputcsv($fp, array('page_id', 'URL', 'has_template', 'intro_length', 'intro'));
foreach ($res as $row) {
    $title = Title::newFromDBkey($row->page_title);
    if (!$title) {
        print "Can't make title out of {$row->page_title}\n";
        continue;
    }
    $rev = Revision::newFromTitle($title);
    $wikitext = $rev->getText();
    $intro = Article::getSection($wikitext, 0);
    $flat = Wikitext::flatten($intro);
    $flat = trim($flat);
    $len = mb_strlen($flat);
    if ($len < 50) {
        // check whether it has either the {{intro or {{introduction template
        $hasTemplate = strpos(strtolower($intro), '{{intro') !== false;
        $fields = array($row->page_id, 'http://www.wikihow.com/' . $title->getPartialURL(), $hasTemplate ? 'y' : 'n', $len, $flat);
        fputcsv($fp, $fields);
/**
 * Track new user registrations to the user_register_track database table if
 * $wgRegisterTrack is set to true.
 *
 * @param $user Object: the User object representing the newly-created user
 * @return Boolean: true
 */
function fnRegisterTrack($user)
{
    global $wgRequest, $wgRegisterTrack, $wgMemc;
    if ($wgRegisterTrack) {
        $wgMemc->delete(wfMemcKey('users', 'new', '1'));
        // How the user registered (via email from friend, just on the site etc.)?
        $from = $wgRequest->getInt('from');
        if (!$from) {
            $from = 0;
        }
        // Track if the user clicked on email from friend
        $user_id_referral = 0;
        $user_name_referral = '';
        $referral_user = $wgRequest->getVal('referral');
        if ($referral_user) {
            $user_registering_title = Title::makeTitle(NS_USER, $user->getName());
            $user_title = Title::newFromDBkey($referral_user);
            $user_id_referral = User::idFromName($user_title->getText());
            if ($user_id_referral) {
                $user_name_referral = $user_title->getText();
            }
            $stats = new UserStatsTrack($user_id_referral, $user_title->getText());
            $stats->incStatField('referral_complete');
            if (class_exists('UserSystemMessage')) {
                $m = new UserSystemMessage();
                // Nees to be forContent because addMessage adds this into a
                // database table - we don't want to display Japanese text
                // to English users
                $message = wfMsgForContent('login-reg-recruited', $user_registering_title->getFullURL(), $user->getName());
                $m->addMessage($user_title->getText(), 1, $message);
            }
        }
        // Track registration
        $dbw = wfGetDB(DB_MASTER);
        $dbw->insert('user_register_track', array('ur_user_id' => $user->getID(), 'ur_user_name' => $user->getName(), 'ur_user_id_referral' => $user_id_referral, 'ur_user_name_referral' => $user_name_referral, 'ur_from' => $from, 'ur_date' => date('Y-m-d H:i:s')), __METHOD__);
        $dbw->commit();
        // Just in case...
    }
    return true;
}
Example #20
0
/**
 * Called for AJAX watch/unwatch requests.
 * @param $pagename Prefixed title string for page to watch/unwatch
 * @param $watch String 'w' to watch, 'u' to unwatch
 * @return String '<w#>' or '<u#>' on successful watch or unwatch,
 *   respectively, followed by an HTML message to display in the alert box; or
 *   '<err#>' on error
 */
function wfAjaxWatch($pagename = "", $watch = "")
{
    if (wfReadOnly()) {
        // redirect to action=(un)watch, which will display the database lock
        // message
        return '<err#>';
    }
    if ('w' !== $watch && 'u' !== $watch) {
        return '<err#>';
    }
    $watch = 'w' === $watch;
    $title = Title::newFromDBkey($pagename);
    if (!$title) {
        // Invalid title
        return '<err#>';
    }
    $article = new Article($title);
    $watching = $title->userIsWatching();
    if ($watch) {
        if (!$watching) {
            $dbw = wfGetDB(DB_MASTER);
            $dbw->begin();
            $ok = $article->doWatch();
            $dbw->commit();
        }
    } else {
        if ($watching) {
            $dbw = wfGetDB(DB_MASTER);
            $dbw->begin();
            $ok = $article->doUnwatch();
            $dbw->commit();
        }
    }
    // Something stopped the change
    if (isset($ok) && !$ok) {
        return '<err#>';
    }
    if ($watch) {
        return '<w#>' . wfMsgExt('addedwatchtext', array('parse'), $title->getPrefixedText());
    } else {
        return '<u#>' . wfMsgExt('removedwatchtext', array('parse'), $title->getPrefixedText());
    }
}
	/* private */ function __construct( $username ) {
		$title1 = Title::newFromDBkey( $username );
		$this->user_name = $title1->getText();
		$this->user_id = User::idFromName( $this->user_name );
	}
 /**
  * purge cache for connected articles
  *
  * @access public
  * @author Krzysztof Krzyżaniak <*****@*****.**>
  *
  */
 public function invalidateCacheConnected(BlogArticle $article)
 {
     $title = $article->getTitle();
     $title->invalidateCache();
     /**
      * this should be subpage, invalidate page as well
      */
     list($page, $subpage) = explode("/", $title->getDBkey());
     $title = Title::newFromDBkey($page);
     $title->invalidateCache();
     $article->clearBlogListing();
 }
Example #23
0
function getDocData($row, $dbr, $printIntro = false)
{
    $page_id = $row->page_id;
    $page_counter = $row->page_counter;
    $title = Title::newFromDBkey($row->page_title);
    if (!$title || !$title->exists()) {
        decho("unknown title for id", $page_id, false);
        return "";
    }
    $wikitext = Wikitext::getWikitext($dbr, $title);
    $intro = Wikitext::getIntro($wikitext);
    //$intro = str_replace("{{toc}}", "", $intro);
    $intro = preg_replace('#\\{\\{.*?\\}\\}#s', '', $intro);
    $intro = trim(preg_replace('#\\[\\[.*?\\]\\]#s', '', $intro));
    $intro = preg_replace('/\\s+/', ' ', trim($intro));
    $intro = str_replace('<br>', '', $intro);
    //if (contains($intro, "Here's how:")) {
    if (stripos($intro, "here's how") !== FALSE || ":" == substr($intro, -1)) {
        //check the number of monthly page views...
        $data = getTitusData($row->page_id);
        if ($data->titus) {
            $ti30 = $data->titus->ti_30day_views;
        }
        if ($ti30 >= 5000 && $ti30 <= 6000) {
            echo $ti30 . " http://www.wikihow.com/" . $row->page_title . " ";
            if ($printIntro) {
                echo $intro;
            }
            echo "\n";
        }
    }
    //echo $page_counter ." http://www.wikihow.com/".$row->page_title." ,> ".$intro."\n";
    //echo "http://www.wikihow.com/".$row->page_title." ,> ".$intro."\n";
    return $intro;
}
	/**
	 * Show the special page
	 *
	 * @param $params Mixed: parameter(s) passed to the page or null
	 */
	public function execute( $params ) {
		global $wgUser, $wgOut, $wgRequest, $wgUserRelationshipScripts;

		// Can't use $this->setHeaders(); here because then it'll set the page
		// title to <removerelationship> and we don't want that, we'll be
		// messing with the page title later on in the code
		$wgOut->setArticleRelated( false );
		$wgOut->setRobotPolicy( 'noindex,nofollow' );

		$wgOut->addExtensionStyle( $wgUserRelationshipScripts . '/UserRelationship.css' );

		$userTitle = Title::newFromDBkey( $wgRequest->getVal( 'user' ) );

		if ( !$userTitle ) {
			$wgOut->setPageTitle( wfMsgHtml( 'ur-error-title' ) );
			$wgOut->addWikiText( wfMsgNoTrans( 'ur-add-no-user' ) );
			return false;
		}

		$user = Title::makeTitle( NS_USER, $userTitle->getText() );

		$this->user_name_to = $userTitle->getText();
		$this->user_id_to = User::idFromName( $this->user_name_to );
		$this->relationship_type = $wgRequest->getInt( 'rel_type' );
		if ( !$this->relationship_type || !is_numeric( $this->relationship_type ) ) {
			$this->relationship_type = 1;
		}
		$hasRelationship = UserRelationship::getUserRelationshipByID(
			$this->user_id_to,
			$wgUser->getID()
		);

		if ( ( $wgUser->getID() == $this->user_id_to ) && ( $wgUser->getID() != 0 ) ) {
			$wgOut->setPageTitle( wfMsg( 'ur-error-title' ) );
			$out .= '<div class="relationship-error-message">' .
				wfMsg( 'ur-add-error-message-yourself' ) .
			'</div>
			<div>
				<input type="button" class="site-button" value="' . wfMsg( 'ur-main-page' ) . '" size="20" onclick=\'window.location="index.php?title="' . wfMsgForContent( 'mainpage' ) . '"\' />';
			if ( $wgUser->isLoggedIn() ) {
				$out .= '<input type="button" class="site-button" value="' . wfMsg( 'ur-your-profile' ) . '" size="20" onclick=\'window.location="' . $wgUser->getUserPage()->escapeFullURL() . '"\' />';
			}
			$out .= '</div>';

			$wgOut->addHTML( $out );

		} elseif ( $wgUser->isBlocked() ) {
			$wgOut->setPageTitle( wfMsg( 'ur-error-title' ) );
			$out .= '<div class="relationship-error-message">' .
				wfMsg( 'ur-add-error-message-blocked' ) .
			'</div>
			<div>
				<input type="button" class="site-button" value="' . wfMsg( 'ur-main-page' ) . '" size="20" onclick=\'window.location="index.php?title="' . wfMsgForContent( 'mainpage' ) . '"\' />';
			if ( $wgUser->isLoggedIn() ) {
				$out .= '<input type="button" class="site-button" value="' . wfMsg( 'ur-your-profile' ) . '" size="20" onclick=\'window.location="' . $wgUser->getUserPage()->escapeFullURL() . '"\' />';
			}
			$out .= '</div>';

			$wgOut->addHTML( $out );

		} elseif ( $this->user_id_to == 0 ) {
			$wgOut->setPageTitle( wfMsg( 'ur-error-title' ) );
			$out .= '<div class="relationship-error-message">' .
				wfMsg( 'ur-add-error-message-no-user' ) .
			'</div>
			<div>
				<input type="button" class="site-button" value="' . wfMsg( 'ur-main-page' ) . '" size="20" onclick=\'window.location="index.php?title="' . wfMsgForContent( 'mainpage' ) . '"\' />';
			if ( $wgUser->isLoggedIn() ) {
				$out .= '<input type="button" class="site-button" value="' . wfMsg( 'ur-your-profile' ) . '" size="20" onclick=\'window.location="' . $wgUser->getUserPage()->escapeFullURL() . '"\' />';
			}
			$out .= '</div>';

			$wgOut->addHTML( $out );

		} elseif ( $hasRelationship >= 1 ) {

			if ( $hasRelationship == 1 ) {
				$error = wfMsg( 'ur-add-error-message-existing-relationship-friend', $this->user_name_to );
			} else {
				$error = wfMsg( 'ur-add-error-message-existing-relationship-foe', $this->user_name_to );
			}

			$avatar = new wAvatar( $this->user_id_to, 'l' );

			$out = '';
			$wgOut->setPageTitle( wfMsg( 'ur-error-title' ) );

			$out .= "<div class=\"relationship-action\">
				{$avatar->getAvatarURL()}
				" . $error . "
				<div class=\"relationship-buttons\">
					<input type=\"button\" class=\"site-button\" value=\"" . wfMsg( 'ur-main-page' ) . "\" size=\"20\" onclick=\"window.location='index.php?title=" . wfMsgForContent( 'mainpage' ) . "'\"/>
					<input type=\"button\" class=\"site-button\" value=\"" . wfMsg( 'ur-your-profile' ) . "\" size=\"20\" onclick=\"window.location='" . $wgUser->getUserPage()->escapeFullURL() . "'\"/>
				</div>
				<div class=\"cleared\"></div>
			</div>";

			$wgOut->addHTML( $out );

		} elseif ( UserRelationship::userHasRequestByID( $this->user_id_to, $wgUser->getID() ) == true ) {

			if ( $this->relationship_type == 1 ) {
				$error = wfMsg( 'ur-add-error-message-pending-friend-request', $this->user_name_to );
			} else {
				$error = wfMsg( 'ur-add-error-message-pending-foe-request', $this->user_name_to );
			}

			$avatar = new wAvatar( $this->user_id_to, 'l' );

			$out = '';
			$wgOut->setPageTitle( wfMsg( 'ur-add-error-message-pending-request-title' ) );
			$out .= "<div class=\"relationship-action\">
				{$avatar->getAvatarURL()}
				" . $error . "
				<div class=\"relationship-buttons\">
					<input type=\"button\" class=\"site-button\" value=\"" . wfMsg( 'ur-main-page' ) . "\" size=\"20\" onclick=\"window.location='index.php?title=" . wfMsgForContent( 'mainpage' ) . "'\"/>
					<input type=\"button\" class=\"site-button\" value=\"" . wfMsg( 'ur-your-profile' ) . "\" size=\"20\" onclick=\"window.location='" . $wgUser->getUserPage()->escapeFullURL() . "'\"/>
				</div>
				<div class=\"cleared\"></div>
			</div>";

			$wgOut->addHTML( $out );
		} elseif ( UserRelationship::userHasRequestByID( $wgUser->getID(), $this->user_id_to ) == true ) {
			$relationship_request = SpecialPage::getTitleFor( 'ViewRelationshipRequests' );
			$wgOut->redirect( $relationship_request->getFullURL() );
		} elseif ( $wgUser->getID() == 0 ) {
			$login_link = SpecialPage::getTitleFor( 'Userlogin' );

			if ( $this->relationship_type == 1 ) {
				$error = wfMsg( 'ur-add-error-message-not-loggedin-friend' );
			} else {
				$error = wfMsg( 'ur-add-error-message-not-loggedin-foe' );
			}

			$out = '';
			$wgOut->setPageTitle( wfMsg( 'ur-error-title' ) );
			$out .= '<div class="relationship-error-message">'
				. $error .
			'</div>
			<div>
				<input type="button" class="site-button" value="' . wfMsg( 'ur-main-page' ) . '" size="20" onclick=\'window.location="index.php?title="' . wfMsgForContent( 'mainpage' ) . '"\' />
				<input type="button" class="site-button" value="' . wfMsg( 'ur-login' ) . '" size="20" onclick="window.location=\'' . $login_link->escapeFullURL() . '\'" />';
			$out .= '</div>';

			$wgOut->addHTML( $out );
		} else {
			$rel = new UserRelationship( $wgUser->getName() );

			if ( $wgRequest->wasPosted() && $_SESSION['alreadysubmitted'] == false ) {
				$_SESSION['alreadysubmitted'] = true;
				$rel = $rel->addRelationshipRequest( $this->user_name_to, $this->relationship_type, $wgRequest->getVal( 'message' ) );

				$avatar = new wAvatar( $this->user_id_to, 'l' );

				$out = '';

				if ( $this->relationship_type == 1 ) {
					$wgOut->setPageTitle( wfMsg( 'ur-add-sent-title-friend', $this->user_name_to ) );
					$sent = wfMsg( 'ur-add-sent-message-friend', $this->user_name_to );
				} else {
					$wgOut->setPageTitle( wfMsg( 'ur-add-sent-title-foe', $this->user_name_to ) );
					$sent = wfMsg( 'ur-add-sent-message-foe', $this->user_name_to );
				}

				$out .= "<div class=\"relationship-action\">
					{$avatar->getAvatarURL()}
					" . $sent . "
					<div class=\"relationship-buttons\">
						<input type=\"button\" class=\"site-button\" value=\"" . wfMsg( 'ur-main-page' ) . "\" size=\"20\" onclick=\"window.location='index.php?title=" . wfMsgForContent( 'mainpage' ) . "'\"/>
						<input type=\"button\" class=\"site-button\" value=\"" . wfMsg( 'ur-your-profile' ) . "\" size=\"20\" onclick=\"window.location='" . $wgUser->getUserPage()->escapeFullURL() . "'\"/>
					</div>
					<div class=\"cleared\"></div>
				</div>";

				$wgOut->addHTML( $out );
			} else {
				$_SESSION['alreadysubmitted'] = false;
				$wgOut->addHTML( $this->displayForm() );
			}
		}
	}
Example #25
0
 /**
  * The inverse of titleToKey()
  * @deprecated since 1.24, unused and probably never needed
  * @param string $key Page title with underscores
  * @return string Page title with spaces
  */
 public function keyToTitle($key)
 {
     wfDeprecated(__METHOD__, '1.24');
     // Don't throw an error if we got an empty string
     if (trim($key) == '') {
         return '';
     }
     $t = Title::newFromDBkey($key);
     // This really shouldn't happen but we gotta check anyway
     if (!$t) {
         $this->dieUsageMsg(array('invalidtitle', $key));
     }
     return $t->getPrefixedText();
 }
Example #26
0
 public function vote($vote)
 {
     global $wgMemc, $wgUser;
     $db = wfGetDB(DB_MASTER);
     $vote = intval($vote);
     // pull all data for this page from the hillary_page
     $posVotes = 0;
     $negVotes = 0;
     $ownVote = false;
     $res = $db->select('hillary_votes', array('hv_vote', 'hv_userid'), array('hv_pageid' => $this->pageid), __METHOD__);
     foreach ($res as $row) {
         // don't count a user's own votes so that the counts are accurate
         if ($row->hv_userid == $this->userid) {
             // do nothing and exit if their vote hasn't changed
             if ($row->hv_vote == $vote) {
                 return true;
             }
             $ownVote = true;
         } else {
             if ($row->hv_vote > 0) {
                 $posVotes++;
             }
             if ($row->hv_vote < 0) {
                 $negVotes++;
             }
         }
     }
     // Add new vote vs changing their existing vote
     if (!$ownVote) {
         $row = array('hv_pageid' => $this->pageid, 'hv_userid' => $this->userid, 'hv_vote' => $vote);
         $db->insert('hillary_votes', $row, __METHOD__);
     } else {
         // just update the vote if it's a re-vote
         $db->update('hillary_votes', array('hv_vote' => $vote), array('hv_pageid' => $this->pageid, 'hv_userid' => $this->userid), __METHOD__);
     }
     if ($vote > 0) {
         $posVotes++;
     }
     if ($vote < 0) {
         $negVotes++;
     }
     // if there are greater than n votes for keep or delete, we
     // take an action
     $enoughPos = !$page->hp_action && $posVotes >= self::VOTE_THRESHOLD;
     $enoughNeg = !$page->hp_action && $negVotes >= self::VOTE_THRESHOLD;
     $oldAction = $db->selectField('hillary_pages', array('hp_action'), array('hp_pageid' => $this->pageid), __METHOD__);
     $action = $oldAction;
     if (!$oldAction) {
         if ($enoughPos) {
             $action = 'keep';
         } elseif ($enoughNeg) {
             $action = 'stub';
         }
     }
     // update hillary_pages
     $db->update('hillary_pages', array('hp_pos_votes' => $posVotes, 'hp_neg_votes' => $negVotes, 'hp_last_voted = CURRENT_TIMESTAMP', 'hp_action' => $action), array('hp_pageid' => $this->pageid), __METHOD__);
     // do an action if we've received enough votes
     if ($action && !$oldAction) {
         $details = $db->selectRow('page', array('page_title', 'page_counter'), array('page_namespace' => NS_MAIN, 'page_id' => $this->pageid), __METHOD__);
         if ($details) {
             $title = Title::newFromDBkey($details->page_title);
             $views = $details->page_counter;
         } else {
             $title = null;
         }
         if ($title) {
             // Anons can't log in the MW logging infrastructure, so we
             // use the AnonLogBot
             $oldUser = null;
             if (!$wgUser || $wgUser->isAnon()) {
                 $oldUser = $wgUser;
                 $wgUser = User::newFromName('AnonLogBot');
             }
             // Log action to Mediawiki logging system
             $titleStr = $title->getText();
             $viewsStr = number_format($views);
             $verb = $action == 'keep' ? 'kept' : 'stubbed';
             $posStr = $posVotes == 1 ? '1 person' : "{$posVotes} people";
             $negStr = $negVotes == 1 ? '1 person' : "{$negVotes} people";
             $msg = "[[{$titleStr}]] has been {$verb}. {$negStr} voted for the stubbing. {$posStr} voted keeping as is. It had {$viewsStr} views at the time of this action.";
             $log = new LogPage('hillary', false);
             $log->addEntry($action, $title, $msg);
             // Add the stub template to wikitext
             if ($action == 'stub') {
                 $revision = Revision::newFromTitle($title);
                 $article = new Article($title);
                 if ($revision && $article) {
                     $text = $revision->getText();
                     if (!preg_match('@\\{\\{Stub@i', $text)) {
                         $text = "{{Stub}}\n" . $text;
                         $article->doEdit($text, "Marking article with stub template after the votes went that way");
                     }
                 }
             }
             // If anon right now, make it so that further actions are not
             // under Bot account
             if ($oldUser) {
                 $wgUser = $oldUser;
             }
         }
         // Run a hook
         wfRunHooks('HillaryAfterAction', array(&$this, $action));
     }
     // Fix memcache objects
     $cacheKey = wfMemcKey(self::USER_VOTES_KEY, $this->userid);
     $pages = $wgMemc->get($cacheKey);
     if (is_array($pages)) {
         $this->userVotes = null;
         $pages[$this->pageid] = $vote;
         $wgMemc->set($cacheKey, $pages, self::USER_VOTES_CACHE_EXPIRY);
     }
     if ($action) {
         $cacheKey = wfMemcKey(self::PAGES_KEY);
         $bundle = $wgMemc->get($cacheKey);
         if (is_array($bundle)) {
             foreach ($bundle as $i => $pageid) {
                 if ($this->pageid == $pageid) {
                     unset($bundle[$i]);
                     $wgMemc->set($cacheKey, $bundle, self::PAGE_CACHE_EXPIRY);
                     break;
                 }
             }
         }
     }
     return true;
 }
Example #27
0
function main($out_csv)
{
    $dbr = wfGetDB(DB_SLAVE);
    # List all articles in main namespace who redirect elsewhere
    $articles = array();
    $batch_size = 500;
    $page = 0;
    while (true) {
        $offset = $page++ * $batch_size;
        $res = $dbr->query('SELECT page_title FROM page WHERE page_namespace=' . NS_MAIN . ' AND page_is_redirect=1 LIMIT ' . $offset . ',' . $batch_size);
        $count = 0;
        foreach ($res as $row) {
            $count++;
            $articles[] = array('title' => $row->page_title);
        }
        if ($count < $batch_size) {
            break;
        }
    }
    print "number of redirects found: " . sizeof($articles) . "\n";
    # Get the extra redirect info, write the line to $out_csv
    $bad_records = 0;
    $fp = fopen($out_csv, 'w');
    $count = 0;
    foreach ($articles as $article) {
        $count++;
        $redir_title = $article['title'];
        $title = Title::newFromDBkey($redir_title);
        if (!$title) {
            $bad_records++;
            continue;
        }
        $rev = Revision::newFromTitle($title);
        if (!$rev) {
            $bad_records++;
            continue;
        }
        # Parse title of article to which to redirect
        $body = $rev->getText();
        if (preg_match('@^\\s*#REDIRECT[: *]*\\[\\[(.*)\\]\\]@i', $body, $matches)) {
            $redir_dest = $matches[1];
            $title_dest = Title::newFromText($redir_dest);
            if (!$title_dest) {
                $bad_records++;
                continue;
            }
            # Search for inbound links
            $fields = array('page_title');
            $conds = array('page_id=pl_from', 'pl_title' => $redir_title, 'pl_namespace' => NS_MAIN, 'page_namespace' => NS_MAIN);
            $options = array('STRAIGHT_JOIN', 'LIMIT' => 6);
            $res = $dbr->select(array('pagelinks', 'page'), $fields, $conds, __METHOD__, $options);
            $links = array();
            while ($row = $dbr->fetchRow($res)) {
                $link = Title::newFromDBkey($row['page_title']);
                if (!$link) {
                    print "err: bad link title: {$row['page_title']}\n";
                    continue;
                }
                $links[] = $link->getText();
            }
            # collate results, print in CSV format
            $inbound_links = $links ? join(', ', $links) : '';
            $line = array('', $title->getText(), $title_dest->getText(), $inbound_links);
            fputcsv($fp, $line);
        } else {
            print "err: bad match: {$redir_title}, text:{$body}\n";
            $bad_records++;
        }
        if ($count % 1000 == 0) {
            print "processed {$count} ...\n";
        }
    }
    fclose($fp);
    print "num bad records: {$bad_records}\n";
}
Example #28
0
 /**
  * Replace <!--LINK--> link placeholders with actual links, in the buffer
  * Placeholders created in Skin::makeLinkObj()
  * Returns an array of link CSS classes, indexed by PDBK.
  * $options is a bit field, RLH_FOR_UPDATE to select for update
  */
 function replaceLinkHolders(&$text, $options = 0)
 {
     global $wgUser;
     global $wgContLang;
     $fname = 'Parser::replaceLinkHolders';
     wfProfileIn($fname);
     $pdbks = array();
     $colours = array();
     $linkcolour_ids = array();
     $sk = $this->mOptions->getSkin();
     $linkCache =& LinkCache::singleton();
     if (!empty($this->mLinkHolders['namespaces'])) {
         wfProfileIn($fname . '-check');
         $dbr = wfGetDB(DB_SLAVE);
         $page = $dbr->tableName('page');
         $threshold = $wgUser->getOption('stubthreshold');
         # Sort by namespace
         asort($this->mLinkHolders['namespaces']);
         # Generate query
         $query = false;
         $current = null;
         foreach ($this->mLinkHolders['namespaces'] as $key => $ns) {
             # Make title object
             $title = $this->mLinkHolders['titles'][$key];
             # Skip invalid entries.
             # Result will be ugly, but prevents crash.
             if (is_null($title)) {
                 continue;
             }
             $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
             # Check if it's a static known link, e.g. interwiki
             if ($title->isAlwaysKnown()) {
                 $colours[$pdbk] = '';
             } elseif (($id = $linkCache->getGoodLinkID($pdbk)) != 0) {
                 $colours[$pdbk] = '';
                 $this->mOutput->addLink($title, $id);
             } elseif ($linkCache->isBadLink($pdbk)) {
                 $colours[$pdbk] = 'new';
             } elseif ($title->getNamespace() == NS_SPECIAL && !SpecialPage::exists($pdbk)) {
                 $colours[$pdbk] = 'new';
             } else {
                 # Not in the link cache, add it to the query
                 if (!isset($current)) {
                     $current = $ns;
                     $query = "SELECT page_id, page_namespace, page_title, page_is_redirect";
                     if ($threshold > 0) {
                         $query .= ', page_len';
                     }
                     $query .= " FROM {$page} WHERE (page_namespace={$ns} AND page_title IN(";
                 } elseif ($current != $ns) {
                     $current = $ns;
                     $query .= ")) OR (page_namespace={$ns} AND page_title IN(";
                 } else {
                     $query .= ', ';
                 }
                 $query .= $dbr->addQuotes($this->mLinkHolders['dbkeys'][$key]);
             }
         }
         if ($query) {
             $query .= '))';
             if ($options & RLH_FOR_UPDATE) {
                 $query .= ' FOR UPDATE';
             }
             $res = $dbr->query($query, $fname);
             # Fetch data and form into an associative array
             # non-existent = broken
             while ($s = $dbr->fetchObject($res)) {
                 $title = Title::makeTitle($s->page_namespace, $s->page_title);
                 $pdbk = $title->getPrefixedDBkey();
                 $linkCache->addGoodLinkObj($s->page_id, $title);
                 $this->mOutput->addLink($title, $s->page_id);
                 $colours[$pdbk] = $sk->getLinkColour($s, $threshold);
                 //add id to the extension todolist
                 $linkcolour_ids[$s->page_id] = $pdbk;
             }
             //pass an array of page_ids to an extension
             wfRunHooks('GetLinkColours', array($linkcolour_ids, &$colours));
         }
         wfProfileOut($fname . '-check');
         # Do a second query for different language variants of links and categories
         if ($wgContLang->hasVariants()) {
             $linkBatch = new LinkBatch();
             $variantMap = array();
             // maps $pdbkey_Variant => $keys (of link holders)
             $categoryMap = array();
             // maps $category_variant => $category (dbkeys)
             $varCategories = array();
             // category replacements oldDBkey => newDBkey
             $categories = $this->mOutput->getCategoryLinks();
             // Add variants of links to link batch
             foreach ($this->mLinkHolders['namespaces'] as $key => $ns) {
                 $title = $this->mLinkHolders['titles'][$key];
                 if (is_null($title)) {
                     continue;
                 }
                 $pdbk = $title->getPrefixedDBkey();
                 $titleText = $title->getText();
                 // generate all variants of the link title text
                 $allTextVariants = $wgContLang->convertLinkToAllVariants($titleText);
                 // if link was not found (in first query), add all variants to query
                 if (!isset($colours[$pdbk])) {
                     foreach ($allTextVariants as $textVariant) {
                         if ($textVariant != $titleText) {
                             $variantTitle = Title::makeTitle($ns, $textVariant);
                             if (is_null($variantTitle)) {
                                 continue;
                             }
                             $linkBatch->addObj($variantTitle);
                             $variantMap[$variantTitle->getPrefixedDBkey()][] = $key;
                         }
                     }
                 }
             }
             // process categories, check if a category exists in some variant
             foreach ($categories as $category) {
                 $variants = $wgContLang->convertLinkToAllVariants($category);
                 foreach ($variants as $variant) {
                     if ($variant != $category) {
                         $variantTitle = Title::newFromDBkey(Title::makeName(NS_CATEGORY, $variant));
                         if (is_null($variantTitle)) {
                             continue;
                         }
                         $linkBatch->addObj($variantTitle);
                         $categoryMap[$variant] = $category;
                     }
                 }
             }
             if (!$linkBatch->isEmpty()) {
                 // construct query
                 $titleClause = $linkBatch->constructSet('page', $dbr);
                 $variantQuery = "SELECT page_id, page_namespace, page_title, page_is_redirect";
                 if ($threshold > 0) {
                     $variantQuery .= ', page_len';
                 }
                 $variantQuery .= " FROM {$page} WHERE {$titleClause}";
                 if ($options & RLH_FOR_UPDATE) {
                     $variantQuery .= ' FOR UPDATE';
                 }
                 $varRes = $dbr->query($variantQuery, $fname);
                 // for each found variants, figure out link holders and replace
                 while ($s = $dbr->fetchObject($varRes)) {
                     $variantTitle = Title::makeTitle($s->page_namespace, $s->page_title);
                     $varPdbk = $variantTitle->getPrefixedDBkey();
                     $vardbk = $variantTitle->getDBkey();
                     $holderKeys = array();
                     if (isset($variantMap[$varPdbk])) {
                         $holderKeys = $variantMap[$varPdbk];
                         $linkCache->addGoodLinkObj($s->page_id, $variantTitle);
                         $this->mOutput->addLink($variantTitle, $s->page_id);
                     }
                     // loop over link holders
                     foreach ($holderKeys as $key) {
                         $title = $this->mLinkHolders['titles'][$key];
                         if (is_null($title)) {
                             continue;
                         }
                         $pdbk = $title->getPrefixedDBkey();
                         if (!isset($colours[$pdbk])) {
                             // found link in some of the variants, replace the link holder data
                             $this->mLinkHolders['titles'][$key] = $variantTitle;
                             $this->mLinkHolders['dbkeys'][$key] = $variantTitle->getDBkey();
                             // set pdbk and colour
                             $pdbks[$key] = $varPdbk;
                             $colours[$varPdbk] = $sk->getLinkColour($s, $threshold);
                             $linkcolour_ids[$s->page_id] = $pdbk;
                         }
                         wfRunHooks('GetLinkColours', array($linkcolour_ids, &$colours));
                     }
                     // check if the object is a variant of a category
                     if (isset($categoryMap[$vardbk])) {
                         $oldkey = $categoryMap[$vardbk];
                         if ($oldkey != $vardbk) {
                             $varCategories[$oldkey] = $vardbk;
                         }
                     }
                 }
                 // rebuild the categories in original order (if there are replacements)
                 if (count($varCategories) > 0) {
                     $newCats = array();
                     $originalCats = $this->mOutput->getCategories();
                     foreach ($originalCats as $cat => $sortkey) {
                         // make the replacement
                         if (array_key_exists($cat, $varCategories)) {
                             $newCats[$varCategories[$cat]] = $sortkey;
                         } else {
                             $newCats[$cat] = $sortkey;
                         }
                     }
                     $this->mOutput->setCategoryLinks($newCats);
                 }
             }
         }
         # Construct search and replace arrays
         wfProfileIn($fname . '-construct');
         $replacePairs = array();
         foreach ($this->mLinkHolders['namespaces'] as $key => $ns) {
             $pdbk = $pdbks[$key];
             $searchkey = "<!--LINK {$key}-->";
             $title = $this->mLinkHolders['titles'][$key];
             if (!isset($colours[$pdbk]) || $colours[$pdbk] == 'new') {
                 $linkCache->addBadLinkObj($title);
                 $colours[$pdbk] = 'new';
                 $this->mOutput->addLink($title, 0);
                 $replacePairs[$searchkey] = $sk->makeBrokenLinkObj($title, $this->mLinkHolders['texts'][$key], $this->mLinkHolders['queries'][$key]);
             } else {
                 $replacePairs[$searchkey] = $sk->makeColouredLinkObj($title, $colours[$pdbk], $this->mLinkHolders['texts'][$key], $this->mLinkHolders['queries'][$key]);
             }
         }
         $replacer = new HashtableReplacer($replacePairs, 1);
         wfProfileOut($fname . '-construct');
         # Do the thing
         wfProfileIn($fname . '-replace');
         $text = preg_replace_callback('/(<!--LINK .*?-->)/', $replacer->cb(), $text);
         wfProfileOut($fname . '-replace');
     }
     # Now process interwiki link holders
     # This is quite a bit simpler than internal links
     if (!empty($this->mInterwikiLinkHolders['texts'])) {
         wfProfileIn($fname . '-interwiki');
         # Make interwiki link HTML
         $replacePairs = array();
         foreach ($this->mInterwikiLinkHolders['texts'] as $key => $link) {
             $title = $this->mInterwikiLinkHolders['titles'][$key];
             $replacePairs[$key] = $sk->makeLinkObj($title, $link);
         }
         $replacer = new HashtableReplacer($replacePairs, 1);
         $text = preg_replace_callback('/<!--IWLINK (.*?)-->/', $replacer->cb(), $text);
         wfProfileOut($fname . '-interwiki');
     }
     wfProfileOut($fname);
     return $colours;
 }
Example #29
0
 /**
  * Add a title to the link cache, return the page_id or zero if non-existent
  *
  * @param string $title Title to add
  * @return int Page ID or zero
  */
 public function addLink($title)
 {
     $nt = Title::newFromDBkey($title);
     if (!$nt) {
         return 0;
     }
     return $this->addLinkObj($nt);
 }
Example #30
0
 /**
  * Post process request uses globals and mediaWiki configuration to
  * validate classes and generate request key
  */
 function postProcRequestVars()
 {
     global $wgContLanguageCode, $wgResourceLoaderNamedPaths, $wgStyleVersion;
     // Set debug flag
     if (isset($_GET['debug']) && $_GET['debug'] == 'true' || isset($wgEnableScriptDebug) && $wgEnableScriptDebug == true) {
         $this->debug = true;
     }
     // Set the urid. Be sure to escape it as it goes into our JS output.
     if (isset($_GET['urid']) && $_GET['urid'] != '') {
         $this->urid = htmlspecialchars($_GET['urid']);
     } else {
         // Just give it the current style sheet ID:
         // NOTE: read the svn version number
         $this->urid = $wgStyleVersion;
     }
     // Get the language code (if not provided use the "default" language
     if (isset($_GET['uselang']) && $_GET['uselang'] != '') {
         // Strip any non alphaNumeric or dash characters from the language code:
         $this->langCode = preg_replace("/[^A-Za-z\\-_]/", '', $_GET['uselang']);
     } else {
         //set English as default
         $this->langCode = 'en';
     }
     $this->langCode = self::checkForCommonsLanguageFormHack($this->langCode);
     $reqClassList = false;
     if (isset($_GET['class']) && $_GET['class'] != '') {
         $reqClassList = explode(',', $_GET['class']);
         self::$rawClassList = $_GET['class'];
     }
     // Check for the requested classes
     if ($reqClassList) {
         // sanitize the Resource list and populate namedFileList
         foreach ($reqClassList as $reqClass) {
             if (trim($reqClass) != '') {
                 if (substr($reqClass, 0, 3) == 'WT:') {
                     $doAddWT = false;
                     // Check for special case '-' resource for user-generated JS
                     if (substr($reqClass, 3, 1) == '-') {
                         $doAddWT = true;
                     } else {
                         if (strtolower(substr($reqClass, -3)) == '.js') {
                             //make sure its a valid wikipage before doing processing
                             $t = Title::newFromDBkey(substr($reqClass, 3));
                             if ($t->exists() && ($t->getNamespace() == NS_MEDIAWIKI || $t->getNamespace() == NS_USER)) {
                                 $doAddWT = true;
                             }
                         }
                     }
                     if ($doAddWT) {
                         $this->namedFileList[$reqClass] = true;
                         $this->requestKey .= $reqClass;
                         $this->jsvarurl = true;
                     }
                     continue;
                 }
                 $reqClass = preg_replace("/[^A-Za-z0-9_\\-\\.]/", '', $reqClass);
                 $filePath = self::getPathFromClass($reqClass);
                 if (!$filePath) {
                     $this->errorMsg .= 'Requested class: ' . xml::escapeJsString($reqClass) . ' not found' . "\n";
                 } else {
                     $this->namedFileList[$reqClass] = $filePath;
                     $this->requestKey .= $reqClass;
                 }
             }
         }
     }
     // Add the language code to the requestKey:
     $this->requestKey .= '_' . $wgContLanguageCode;
     // Add the unique rid
     $this->requestKey .= $this->urid;
 }