Example #1
0
 static function listArticles($includeDatesAndFullURLs, $touchedSince)
 {
     $PAGE_SIZE = 2000;
     $dbr = wfGetDB(DB_SLAVE);
     for ($page = 0;; $page++) {
         $offset = $PAGE_SIZE * $page;
         if ($touchedSince) {
             $sql = "SELECT page_id, page_title, page_touched FROM page, recentchanges WHERE page_id = rc_cur_id AND page_namespace = 0 AND page_is_redirect = 0 AND rc_timestamp >= '{$touchedSince}' AND rc_minor = 0 GROUP BY page_id ORDER BY page_touched DESC LIMIT {$offset},{$PAGE_SIZE}";
         } else {
             $sql = "SELECT page_id, page_title, page_touched FROM page WHERE page_namespace = " . NS_MAIN . " AND page_is_redirect = 0 ORDER BY page_touched DESC LIMIT {$offset},{$PAGE_SIZE}";
         }
         $res = $dbr->query($sql, __FILE__);
         if (!$res->numRows()) {
             break;
         }
         foreach ($res as $row) {
             $title = Title::newFromDBKey($row->page_title);
             if (!$title) {
                 continue;
             }
             if (class_exists('RobotPolicy')) {
                 $indexed = RobotPolicy::isIndexable($title);
                 if (!$indexed) {
                     continue;
                 }
             }
             if ($includeDatesAndFullURLs) {
                 $line = $title->getFullUrl() . ' lastmod=' . self::iso8601_date($row->page_touched);
             } else {
                 $line = $row->page_id . ' ' . $title->getDBkey();
             }
             print "{$line}\n";
         }
     }
 }
 static function listArticles()
 {
     $PAGE_SIZE = 2000;
     $dbr = wfGetDB(DB_SLAVE);
     $titles = array();
     for ($page = 0;; $page++) {
         $offset = $PAGE_SIZE * $page;
         $sql = "SELECT page_id, page_title, page_touched FROM page WHERE page_namespace = " . NS_MAIN . " AND page_is_redirect = 0 ORDER BY page_touched DESC LIMIT {$offset},{$PAGE_SIZE}";
         $res = $dbr->query($sql, __FILE__);
         if (!$res->numRows()) {
             break;
         }
         foreach ($res as $row) {
             $title = Title::newFromDBKey($row->page_title);
             if (!$title) {
                 continue;
             }
             $text = $title->getText();
             $crc = crc32($text);
             $titles[] = array('uri' => $title->getFullUrl(), 'percent' => $crc % 100);
         }
     }
     usort($titles, function ($i, $j) {
         if ($i['percent'] == $j['percent']) {
             return strcasecmp($i['uri'], $j['uri']);
         } elseif ($i['percent'] < $j['percent']) {
             return -1;
         } else {
             return 1;
         }
     });
     foreach ($titles as $title) {
         print $title['uri'] . "\n";
     }
 }
Example #3
0
 function execute($par)
 {
     global $wgRequest, $wgOut, $wgUser;
     $target = isset($par) ? $par : $wgRequest->getVal('target');
     $createdate = $wgRequest->getVal('createdate');
     if (!in_array('sysop', $wgUser->getGroups())) {
         $wgOut->showErrorPage('nosuchspecialpage', 'nospecialpagetext');
         return;
     }
     // get the averages
     $dbr = wfGetDB(DB_SLAVE);
     $row = $dbr->selectRow('google_indexed', array('avg(gi_indexed) as A', 'count(*) as C'), array('gi_times_checked > 0'));
     $wgOut->addHTML("Number of pages checked: {$row->C} <br/>Average of those indexed: " . number_format($row->A * 100, 2) . "%<br/>");
     $left = $dbr->selectField('google_indexed', array('count(*) as C'), array('gi_times_checked' => 0));
     $wgOut->addHTML("Pages which have not been checked: " . number_format($left, 0, "", ",") . "<br/><br/>");
     // do we have a target ?
     if ($createdate && $target) {
         $sql = "select page_title, gl_err, gl_page, gl_pos, substr(gi_page_created, 1, 8) as createdate\n                    from google_indexed_log left join google_indexed on gi_page=gl_page left join page on page_id=gl_page\n\t\t\t\t\twhere substr(gi_page_created, 1, 8)='{$createdate}' and substr(gl_checked, 1, 8) = '{$target}';";
         $res = $dbr->query($sql);
         $f = preg_replace("@([0-9]{4})([0-9]{2})([0-9]{2})@", "\$1-\$2-\$3", $target);
         $c = preg_replace("@([0-9]{4})([0-9]{2})([0-9]{2})@", "\$1-\$2-\$3", $createdate);
         $wgOut->addHTML("<h2>Detailed report for the {$f} check for pages created on {$c}</h2>\n\t\t\t\t\t<table width='80%' align='center'>\n\t\t\t\t\t<tr><td>Article</td><td>Indexed?</td><td>Error?</td><td>Check</td></tr>\n\t\t\t\t");
         while ($row = $dbr->fetchObject($res)) {
             $t = Title::newFromDBKey($row->page_title);
             $query = $t->getText() . " site:wikihow.com";
             $url = "http://www.google.com/search?q=" . urlencode($query) . "&num=100";
             $wgOut->addHTML("<tr><td><a href='{$t->getFullURL()}'>{$t->getText()}</td><td>{$row->gl_pos}</td><td>{$row->gl_err}</td><td><a href='{$url}' target='new'>Link</a></td></tr>");
         }
         $wgOut->addHTML("</table>");
     } else {
         if ($target) {
             $sql = "select substr(gi_page_created, 1, 8) as D, count(*) as C, avg(gl_pos)  as A\n                    from google_indexed_log left join google_indexed on gi_page=gl_page                     \n\t\t\t\t\twhere gl_err = 0 group by D order by D desc;";
             $f = preg_replace("@([0-9]{4})([0-9]{2})([0-9]{2})@", "\$1-\$2-\$3", $target);
             $wgOut->addHTML("<h2>Report for the {$f} check</h2>\n\t\t\t\t\t<table width='80%' align='center'><tr><td>Page creation date</td><td># of pages checked</td><td>Average indexed</td></tr>");
             $res = $dbr->query($sql);
             while ($row = $dbr->fetchObject($res)) {
                 $avg = number_format($row->A * 100, 2);
                 $count = number_format($row->C, 0, "", ",");
                 $f = preg_replace("@([0-9]{4})([0-9]{2})([0-9]{2})@", "\$1-\$2-\$3", $row->D);
                 $wgOut->addHTML("<tr><td><a href='/Special:CheckG/{$target}?createdate={$row->D}'>{$f}</a></td><td>{$count}</td><td>{$avg}%</td></tr>");
             }
             $wgOut->addHTML("</table>");
             $errs = $dbr->selectField("google_indexed_log", array("count(*)"), array("gl_checked like '{$target}%'", "gl_err" => 1));
             $wgOut->addHTML("<br/><br/>Number of errors occurred in this check: {$errs}<br/>");
         }
     }
     // list the individual reports we ran
     $wgOut->addHTML("<br/><br/><h2>Individual reports</h2><ul>");
     $sql = "select substr(gl_checked, 1, 8) as D from google_indexed_log group by D order by D desc;";
     $res = $dbr->query($sql);
     while ($row = $dbr->fetchObject($res)) {
         $f = preg_replace("@([0-9]{4})([0-9]{2})([0-9]{2})@", "\$1-\$2-\$3", $row->D);
         if ($target == $row->D) {
             $wgOut->addHTML("<li>{$f} (you are looking at it)</li>\n");
         } else {
             $wgOut->addHTML("<li><a href='/Special:CheckG/{$row->D}'>{$f}</a></li>\n");
         }
     }
     $wgOut->addHTML("</ul>");
 }
Example #4
0
 /**
  * Executes special page rendering and data processing
  *
  * @param $sub Mixed: MediaWiki supplied sub-page path
  * @throws PermissionsError
  */
 public function execute($sub)
 {
     $out = $this->getOutput();
     $user = $this->getUser();
     $request = $this->getRequest();
     // Begin output
     $this->setHeaders();
     // Make sure the user is logged in
     if (!$user->isLoggedIn()) {
         throw new PermissionsError('read');
     }
     // Handle discarding
     $draft = Draft::newFromID($request->getIntOrNull('discard'));
     if ($draft->exists()) {
         // Discard draft
         $draft->discard();
         // Redirect to the article editor or view if returnto was set
         $section = $request->getIntOrNull('section');
         $urlSection = $section !== null ? "&section={$section}" : '';
         switch ($request->getText('returnto')) {
             case 'edit':
                 $title = Title::newFromDBKey($draft->getTitle());
                 $out->redirect(wfExpandURL($title->getEditURL() . $urlSection));
                 break;
             case 'view':
                 $title = Title::newFromDBKey($draft->getTitle());
                 $out->redirect(wfExpandURL($title->getFullURL() . $urlSection));
                 break;
         }
     }
     // Show list of drafts, or a message that there are none
     if (Drafts::display() == 0) {
         $out->addWikiMsg('drafts-view-nonesaved');
     }
 }
function newSearchKeyRow($dbr, $row)
{
    $t = Title::newFromDBKey($row->page_title);
    if (!$t) {
        print "Got null title for {$row->page_title}\n";
        return null;
    }
    $search_key = generateSearchKey($t->getText());
    $featured = intval($row->tl_from != null);
    return array('tsk_title' => $row->page_title, 'tsk_namespace' => NS_MAIN, 'tsk_key' => $search_key, 'tsk_wasfeatured' => $featured);
}
Example #6
0
function fnWatchHeldPage($user)
{
    global $wgOut, $wgCookiePrefix, $wgCookieDomain, $wgCookieSecure;
    $watch_page = isset($_COOKIE["{$wgCookiePrefix}wsWatchHold"]) ? $_COOKIE["{$wgCookiePrefix}wsWatchHold"] : '';
    //user had clicked to watch page
    if (isset($watch_page) && $watch_page != "") {
        $watched_title = Title::newFromDBKey($watch_page);
        $user->addWatch($watched_title);
        setCookie("{$wgCookiePrefix}wsWatchHold", '', time() - 86400, '/', $wgCookieDomain, $wgCookieSecure);
        $wgOut->redirect($watched_title->getFullURL());
    }
}
 /**
  * On preg_replace_callback
  * Found a match of [[Fan:]], so get parameters and construct <fan> hook
  *
  * @param $matches Array
  * @return String: HTML
  */
 public static function renderFanBoxTag($matches)
 {
     $name = $matches[2];
     $params = explode('|', $name);
     $fan_name = $params[0];
     $fan_name = Title::newFromDBKey($fan_name);
     if (!is_object($fan_name)) {
         return '';
     }
     $fan = FanBox::newFromName($fan_name->getText());
     if ($fan->exists()) {
         $output = "<fan name=\"{$fan->getName()}\"></fan>";
         return $output;
     }
     return $matches[0];
 }
function wfSpamDiffLink( $title ) {
	global $wgUser, $wgRequest, $wgSpamBlacklistArticle;
	$sk = $wgUser->getSkin();
	$sb = Title::newFromDBKey( $wgSpamBlacklistArticle );
	if ( !$sb->userCan( 'edit' ) ) {
		return '';
	}
	$link = '[' . $sk->makeKnownLinkObj( SpecialPage::getTitleFor( 'SpamDiffTool' ),
		wfMsg( 'spamdifftool_spam_link_text' ),
		'target=' . $title->getPrefixedURL().
		'&oldid2=' . $wgRequest->getVal( 'oldid' ) .
		'&rcid='. $wgRequest->getVal( 'rcid' ) .
		'&diff2='. $wgRequest->getVal( 'diff' )  .
		'&returnto=' . urlencode( $_SERVER['QUERY_STRING'] )
		) .
		']';

	return $link;
}
Example #9
0
function wfSpecialRevisionReel($par)
{
    global $wgOut, $wgParser, $wgRequest, $wgLang, $wgUser;
    $fname = "wfRevisionReel";
    if ($wgUser->getId() == 0) {
        $wgOut->showErrorPage('revisionreel', 'revisionreel_loggedin');
        return;
    }
    if ($wgRequest->getVal('rev', null)) {
        $wgOut->setArticleBodyOnly(true);
        $r = Revision::newFromId($wgRequest->getVal('rev'));
        $title = Title::newFromDBKey($wgRequest->getVal('target'));
        $output = $wgParser->parse($r->getText(), $title, new ParserOptions());
        $wgOut->addHTML($output->getText());
        return;
    }
    // landing page
    if ($wgRequest->getVal('target', null)) {
        $title = Title::newFromDBKey($wgRequest->getVal('target'));
        if ($title->getText() == wfMsg('mainpage')) {
            $wgOut->setPageTitle('Now Playing: ' . wfMsg('mainpage'));
        } else {
            $wgOut->setPageTitle('Now Playing: ' . wfMsg('howto', $title->getText()));
        }
        $dbr =& wfGetDB(DB_SLAVE);
        $res = $dbr->select('revision', array('rev_id', 'rev_timestamp'), array('rev_page=' . $title->getArticleID()), array('ORDER BY' => 'rev_id'));
        $revs = array();
        $rev_timestamps = array();
        while ($row = $dbr->fetchObject($res)) {
            $revs[] = $row->rev_id;
            $rev_timestamps[] = "'" . $wgLang->timeanddate(wfTimestamp(TS_MW, $row->rev_timestamp), true) . "'";
            //$rev_timestamps[] = "'" .  wfTimestamp( TS_MW, $row->rev_timestamp ) . "'";
        }
        $dbr->freeResult($res);
        $revisions = implode(',', $revs);
        $timestamps = implode(',', $rev_timestamps);
        $size = sizeof($revs);
        $wgOut->addHTML("\n\t\n<script type='text/javascript'>\n\n\t\tvar index = 0;\n\t\tvar stop = 0;\n\t\tvar size = {$size};\n\t\tvar revisions = new Array({$revisions});\n\t\tvar timestamps = new Array({$timestamps});\n\t\tvar requester = null;\n\t\tfunction showRevision() {\n\t\t\tvar box = document.getElementById('output_html');\n\t\t\tif ( requester.readyState == 4) {\n        \t\tif ( requester.status == 200) {\n\t\t\t\t\tbox.innerHTML = requester.responseText;\n\t\t\t\t\trevision_date = document.getElementById('revision_date');\n\t\t\t\t\trevision_date.innerHTML = timestamps[index] + ' Revision #' + (index + 1) + ' of ' + size;\n\t\t\t\t\tindex++;\n\t\t\t\t\tif (index != size)\n\t\t\t\t\t\tsetTimeout(\"showReel()\", 3000);\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\t\n\t\tfunction showReel() {\n\t\t\tif (stop == 1) return;\n    \t\ttry {\n        \t\trequester = new XMLHttpRequest();\n    \t\t} catch (error) {\n        \t\ttry {\n          \t \t\t requester = new ActiveXObject('Microsoft.XMLHTTP');\n        \t\t} catch (error) {\n\t\t\t\t\talert(error);\n           \t \t\treturn false;\n        \t\t}\n\t\t\t}\n\t\t\turl = location.href + '&rev=' + revisions[index];\n\t\t\trequester.onreadystatechange = showRevision;\n\t\t\trequester.open('GET', url);\n           \trequester.send(null);\n\t\t}\t\n\t\tsetTimeout(\"showReel()\", 1000);\n</script>\n\t\t<div style='border: 1px solid #ccc; padding: 5px;'>\n\t\t\t<input type='button' value='Stop!' onclick='stop = 1; this.value=\"Stopped.\";'>\n\t\t\t<input type='button' value='Go back 5' onclick='if (index > 5) index =- 5; else index = 0;'>\n\t\t\t<input type='button' value='Go forward 5' onclick='index += 5'>\n<span id='revision_date' style='margin-left:20px; font-weight: bold;'> </span>\n\t\t</div>\n\n\t\t\t<br/>\n\t\t\t<div id='output_html' style='margin-top: 20px;'>\n\t\t\t\tGenerating slideshow....\n\t\t\t</div>\n\t\t");
        return;
    }
}
Example #10
0
 /**
  * Executes special page rendering and data processing
  *
  * @param $sub Mixed: MediaWiki supplied sub-page path
  */
 public function execute($sub)
 {
     global $wgRequest, $wgOut, $wgUser;
     // Begin output
     $this->setHeaders();
     // Make sure the user is logged in
     if (!$wgUser->isLoggedIn()) {
         // If not, let them know they need to
         $wgOut->loginToUse();
         // Continue
         return true;
     }
     // Handle discarding
     $draft = Draft::newFromID($wgRequest->getIntOrNull('discard'));
     if ($draft->exists()) {
         // Discard draft
         $draft->discard();
         // Redirect to the article editor or view if returnto was set
         $section = $wgRequest->getIntOrNull('section');
         $urlSection = $section !== null ? "&section={$section}" : '';
         switch ($wgRequest->getText('returnto')) {
             case 'edit':
                 $title = Title::newFromDBKey($draft->getTitle());
                 $wgOut->redirect(wfExpandURL($title->getEditURL() . $urlSection));
                 break;
             case 'view':
                 $title = Title::newFromDBKey($draft->getTitle());
                 $wgOut->redirect(wfExpandURL($title->getFullURL() . $urlSection));
                 break;
         }
     }
     // Show list of drafts, or a message that there are none
     if (Drafts::display() == 0) {
         $wgOut->addHTML(wfMsgHTML('drafts-view-nonesaved'));
     }
 }
Example #11
0
function wfSpecialListFeed($par)
{
    global $wgUser, $wgOut;
    $fname = "wfSpecialListFeed";
    $sk = $wgUser->getSkin();
    $feeds = FeaturedArticles::getFeaturedArticles(11);
    $wgOut->addHTML("<ul>");
    foreach ($feeds as $item) {
        $feed = $item[0];
        $x = str_replace("http://wiki.ehow.com/", "", $feed);
        $x = str_replace("http://www.wikihow.com/", "", $feed);
        $t = Title::newFromDBKey($x);
        $summary = "";
        $a = null;
        if ($t->getArticleID() > 0) {
            $a = new Article(&$t);
            $summary = Article::getSection($a->getContent(false), 0);
            $summary = ereg_replace("<.*>", "", $summary);
            $summary = ereg_replace("\\[\\[.*\\]\\]", "", $summary);
            $summary = ereg_replace("\\{\\{.*\\}\\}", "", $summary);
            $summary = trim($summary);
            $tags = getTechnoratiTags($a->getContent(false));
        }
        $wgOut->addHTML("<div style='width:400px; border: 1px #ccc solid; margin-bottom:20px; padding: 10px; '>");
        $wgOut->addHTML("<img height=16 src='http://wiki.ehow.com/skins/common/images/check.jpg'><a href='{$feed}'>How to " . $t->getText() . "</a><br/><br/>");
        $wgOut->addHTML($summary);
        $wgOut->addHTML("<br/><a href='{$feed}'><i>Read more...</i></a><br/><br/><font size=-2>Posted " . $item[1] . " - (<a href='{$feed}'>Permalink</a>)");
        if ($tags != null) {
            $wgOut->addHTML(" (Technorati Tags: " . trim($tags) . ")");
        }
        $wgOut->addHTML("</font>");
        $wgOut->addHTML("</div>");
    }
    $wgOut->addHTML("</ul>");
    $wgOut->addHTML('<script type="text/javascript" src="http://embed.technorati.com/embed/unj3heqw9.js"></script>');
}
	function execute( $par ) {
		global $wgUser, $wgOut, $wgLang, $wgMemc, $wgDBname;
		global $wgRequest, $wgSitename, $wgLanguageCode;
		global $wgFilterCallback, $wgWhitelistEdit;

		//echo "topic: " . $wgRequest->getVal("topic_name") . "<br />";
		//echo "title: " . $wgRequest->getVal("title") . "<br />";
		//echo "comment: " . $wgRequest->getVal("comment_text") . "<br />";
		//echo "new_topic id " . $wgRequest->getVal("new_topic") . "<br />";

		if ( wfReadOnly() ) {
			$wgOut->readOnlyPage();
			return;
		}

		$t = Title::newFromDBKey( $wgRequest->getVal( 'target' ) );

		if ( $t == null ) {
			$wgOut->showErrorPage( 'postcomment', 'postcomment_invalidrequest' );
			return;
		}

		$errors = $t->getUserPermissionsErrors( 'edit', $wgUser );
		if ( count( $errors ) ) {
			$wgOut->showPermissionsErrorPage( $errors, 'edit' );
			return;
		}

		if ( $wgUser->pingLimiter() ) {
			$wgOut->rateLimited();
			return;
		}

		$article = new Article( $t );
		$update = $article->exists();

		$comment = $wgRequest->getVal( 'comment_text' );
		$topic = $wgRequest->getVal( 'topic_name' );

		if ( trim( $comment ) == '' ) {
			$wgOut->showErrorPage( 'postcomment', 'postcomment_nopostingtoadd' );
			return;
		}

		$user = $wgUser->getName();
		$real_name = $wgUser->getRealName();
		if ( $real_name == '' ) {
			$real_name = $user;
		}
		$dateStr = $wgLang->timeanddate( wfTimestampNow() );

		$formattedComment = "
	<div id=\"discussion_entry\"><table width=\"100%\">
		<tr><td width=\"50%\" valign=\"top\" class=\"discussion_entry_user\">" .
			wfMsgExt( 'postcomment-userwrote', array( 'parsemag' ), $user, $real_name ) . "
</td><td align=\"right\" width=\"50%\" class=\"discussion_entry_date\">" . wfMsg( 'postcomment_on', $dateStr ) . "<br />
	</td></tr><tr>
<td colspan=2 class=\"discussion_entry_comment\">
	$comment</td></tr>
	<tr><td colspan=\"2\" class=\"discussion_entry_date\" padding=5>[[User_talk:$user#post|" . wfMsg('postcomment_replyto', $real_name) . "]]</td></tr>
	</table></div>
";

		$text = '';

		if ( $update ) {
			$r = Revision::newFromTitle( $t );
			$text = $r->getText();
		}

		$text .= "\n\n$formattedComment\n\n";

		$tmp = "";
		if ( $wgFilterCallback && $wgFilterCallback( $t, $text, $tmp) ) {
			# Error messages or other handling should be performed by the filter function
			return;
		}

		$article->doEdit( $text, '' );
	}
Example #13
0
 function execute($par)
 {
     global $wgUser, $wgOut, $wgLang, $wgTitle, $wgMemc, $wgDBname, $wgScriptPath;
     global $wgRequest, $wgSitename, $wgLanguageCode;
     global $wgScript;
     $fname = "wfSpecialEmailLink";
     if ($wgRequest->getVal('fromajax')) {
         $wgOut->setArticleBodyOnly(true);
     }
     $this->setHeaders();
     $me = Title::makeTitle(NS_SPECIAL, "EmailLink");
     $action = $me->getFullURL();
     $fc = new FancyCaptcha();
     $pass_captcha = true;
     $name = $from = $r1 = $r2 = $r3 = $m = "";
     if ($wgRequest->wasPosted()) {
         $pass_captcha = $fc->passCaptcha();
         $email = $wgRequest->getVal("email");
         $name = $wgRequest->getVal("name");
         $recipient1 = $wgRequest->getVal('recipient1');
         $recipient2 = $wgRequest->getVal('recipient2');
         $recipient3 = $wgRequest->getVal('recipient3');
         if (preg_match("@kittens683\\@aol.com@", $recipient1) || preg_match("@kittens683\\@aol.com@", $recipient2) || preg_match("@kittens683\\@aol.com@", $recipient3)) {
             return;
         }
         $message = $wgRequest->getVal('message');
     }
     if (!$wgRequest->wasPosted() || !$pass_captcha) {
         if ($wgUser->getID() > 0 && !$wgUser->canSendEmail()) {
             $userEmail = $wgUser->getEmail();
             // If there is no verification time stamp and no email on record, show initial message to have a user input a valid email address
             if (empty($userEmail)) {
                 wfDebug("User can't send.\n");
                 $wgOut->errorpage("mailnologin", "mailnologintext");
             } else {
                 // When user does have an email on record, but has not verified it yet
                 wfDebug("User can't send without verification.\n");
                 $wgOut->errorpage("mailnologin", "mailnotverified");
             }
             return;
         }
         $titleKey = isset($par) ? $par : $wgRequest->getVal('target');
         if ($titleKey == "") {
             $wgOut->addHTML("<br/></br><font color=red>" . wfMsg('error-no-title') . "</font>");
             return;
         }
         $titleObj = Title::newFromURL($titleKey);
         if (!$titleObj) {
             $titleObj = Title::newFromURL(urldecode($titleKey));
         }
         if (!$titleObj || $titleObj->getArticleID() < 0) {
             $wgOut->addHTML("<br/></br><font color=red>" . wfMsg('error-article-not-found') . "</font>");
             return;
         } else {
             $titleKey = $titleObj->getDBKey();
         }
         $articleObj = new Article($titleObj);
         $subject = $titleObj->getText();
         $titleText = $titleObj->getText();
         if (WikihowArticleEditor::articleIsWikiHow($articleObj)) {
             $subject = wfMsg('howto', $subject);
             $titleText = wfMsg('howto', $titleText);
         }
         $subject = wfMsg('wikihow-article-subject', $subject);
         if ($titleObj->getText() == wfMsg('mainpage')) {
             $subject = wfMsg('wikihow-article-subject-main-page');
         }
         // add the form HTML
         $article_title = wfMsg('article') . ":";
         if ($titleObj->getNamespace() == NS_ARTICLE_REQUEST) {
             $wgOut->addHTML("<br/><br/>" . wfMsg('know-someone-answer-topic-request'));
             $article_title = wfMsg('topic-requested') . ":";
         }
         if ($titleObj->getNamespace() != NS_MAIN && $titleObj->getNamespace() != NS_ARTICLE_REQUEST && $titleObj->getNamespace() != NS_PROJECT) {
             $wgOut->errorPage('emaillink', 'emaillink_invalidpage');
             return;
         }
         if ($titleObj->getText() == "Books For Africa") {
             $message = wfMsg('friend-sends-article-email-africa-body');
         }
         $titleKey = urlencode($titleKey);
         $token = $this->getToken1();
         $wgOut->addHTML("\n<link type='text/css' rel='stylesheet' href='" . wfGetPad('/extensions/wikihow/common/jquery-ui-themes/jquery-ui.css?rev=' . WH_SITEREV) . "' />\n<form id=\"emaillink\" method=\"post\" action=\"{$action}\">\n<input type=\"hidden\" name=\"target\" value=\"{$titleKey}\">\n<input type=\"hidden\" name=\"token\" value=\"{$token}\">\n<table border=\"0\">\n<tr>\n<td valign=\"top\" colspan=\"1\" class='mw-label'>{$article_title}</td>\n<td valign=\"top\" colspan=\"2\">{$titleText}</td>\n</tr>\n");
         if ($wgUser->getID() <= 0) {
             $wgOut->addHTML("\n<tr>\n<td valign=\"top\" colspan=\"1\" class='mw-label'>" . wfMsg('your-name') . ":</td>\n<td valign=\"top\" colspan=\"2\"><input type=text size=\"40\" name=\"name\" value=\"{$name}\" class='input_med'></td>\n</tr>\n<tr>\n<td valign=\"top\" colspan=\"1\" class='mw-label'>" . wfMsg('your-email') . ":</td>\n<td valign=\"top\" colspan=\"2\"><input type=text size=\"40\" name=\"email\" value=\"{$email}\" class='input_med'></td>\n</tr>");
         }
         $wgOut->addHTML("\n<tr>\n<td valign=\"top\" width=\"300px\" colspan=\"1\" rowspan='3' class='mw-label'>" . wfMsg('recipient-emails') . ":</td>\n<td valign=\"top\" colspan=\"2\"><input type=text size=\"40\" name=\"recipient1\" value=\"{$recipient1}\" class='input_med'></td>\n</tr>\n<tr>\n<td valign=\"top\" colspan=\"2\"><input type=text size=\"40\" name=\"recipient2\" value=\"{$recipient2}\" class='input_med'></td>\n</tr>\n<tr>\n<td valign=\"top\" colspan=\"2\"><input type=text size=\"40\" name=\"recipient3\" value=\"{$recipient3}\" class='input_med'></td>\n</tr>\n<!--<tr>\n<td valign=\"top\" colspan=\"1\">" . wfMsg('emailsubject') . ":</td>\n<td valign=\"top\" colspan=\"2\"><input type=text size=\"40\" name=\"subject\" value=\"{$subject}\" class='input_med'></td>\n</tr>-->\n<tr>\n<td colspan=\"1\" valign=\"top\" class='mw-label'>" . wfMsg('emailmessage') . ":</td>\n<td colspan=\"2\"><TEXTAREA rows=\"5\" cols=\"55\" name=\"message\">{$message}</TEXTAREA></td>\n</tr>\n<tr>\n<TD>&nbsp;</TD>\n<TD colspan=\"2\"><br/>\n" . wfMsgWikiHTML('emaillink_captcha') . "\n" . ($pass_captcha ? "" : "<br><br/><font color='red'>Sorry, that phrase was incorrect, try again.</font><br/><br/>") . "\n" . $fc->getForm('') . "\n</TD>\n</tr>\n<tr>\n<TD>&nbsp;</TD>\n<TD colspan=\"2\"><br/>\n<input type='submit' name=\"wpEmaiLinkSubmit\" value=\"" . wfMsg('submit') . "\" class=\"button primary\" />\n</td>\n</tr>\n<tr>\n<TD colspan=\"3\">\n<br/><br/>\n" . wfMsg('share-message-three-friends') . "\n</TD>\n</TR>\n\n");
         // do this if the user isn't logged in
         $wgOut->addHTML("</table> </form>");
     } else {
         if ($wgUser->pingLimiter('emailfriend')) {
             $wgOut->rateLimited();
             wfProfileOut("{$fname}-checks");
             wfProfileOut($fname);
             return false;
         }
         $usertoken = $wgRequest->getVal('token');
         $token1 = $this->getToken1();
         $token2 = $this->getToken2();
         if ($usertoken != $token1 && $usertoken != $token2) {
             $this->reject();
             echo "token {$usertoken} {$token1} {$token2}\n";
             exit;
             return;
         }
         // check referrer
         $good_referer = Title::makeTitle(NS_SPECIAL, "EmailLink")->getFullURL();
         $referer = $_SERVER["HTTP_REFERER"];
         if (strpos($refer, $good_referer) != 0) {
             $this->reject();
             echo "referrer bad\n";
             exit;
         }
         // this is a post, accept the POST data and create the Request article
         $recipient1 = $_POST['recipient1'];
         $recipient2 = $_POST['recipient2'];
         $recipient3 = $_POST['recipient3'];
         $titleKey = $_POST['target'];
         $message = $_POST['message'];
         if ($titleKey == "Books-For-Africa") {
             $titleKey = "wikiHow:" . $titleKey;
         }
         $titleKey = urldecode($titleKey);
         $titleObj = Title::newFromDBKey($titleKey);
         if ($titleObj->getArticleID() <= 0) {
             $this->reject();
             echo "no article id\n";
             exit;
         }
         $dbkey = $titleObj->getDBKey();
         $articleObj = new Article($titleObj);
         $subject = $titleObj->getText();
         $how_to = $subject;
         if (WikihowArticleEditor::articleIsWikiHow($articleObj)) {
             $subject = wfMsg("howto", $subject);
         }
         $how_to = $subject;
         if ($titleObj->getNamespace() == NS_ARTICLE_REQUEST) {
             $subject = wfMsg('subject-requested-howto') . ": " . wfMsg("howto", $subject);
         } else {
             if ($titleObj->getNamespace() == NS_PROJECT) {
                 $subject = wfMsg('friend-sends-article-email-africa-subject');
             } else {
                 $subject = wfMsg('wikihow-article-subject', $subject);
             }
         }
         if ($titleObj->getNamespace() != NS_MAIN && $titleObj->getNamespace() != NS_ARTICLE_REQUEST && $titleObj->getNamespace() != NS_PROJECT) {
             $wgOut->errorPage('emaillink', 'emaillink_invalidpage');
             return;
         }
         // for the body of the email
         $titleText = $titleObj->getText();
         if ($titleText != wfMsg('mainpage')) {
             $summary = Article::getSection($articleObj->getContent(true), 0);
             // trip out all MW and HTML tags
             $summary = ereg_replace("<.*>", "", $summary);
             $summary = ereg_replace("\\[\\[.*\\]\\]", "", $summary);
             $summary = ereg_replace("\\{\\{.*\\}\\}", "", $summary);
         }
         $url = $titleObj->getFullURL();
         $from_name = "";
         $validEmail = "";
         if ($wgUser->getID() > 0) {
             $from_name = $wgUser->getName();
             $real_name = $wgUser->getRealName();
             if ($real_name != "") {
                 $from_name = $real_name;
             }
             $email = $wgUser->getEmail();
             if ($email != "") {
                 $validEmail = $email;
                 $from_name .= "<{$email}>";
             } else {
                 $from_name .= "<*****@*****.**>";
             }
         } else {
             $email = $wgRequest->getVal("email");
             $name = $wgRequest->getVal("name");
             if ($email == "") {
                 $email = "*****@*****.**";
             } else {
                 $validEmail = $email;
             }
             $from_name = "{$name} <{$email}>";
         }
         if (strpos($email, "\n") !== false || strpos($recipient1, "\n") !== false || strpos($recipient2, "\n") !== false || strpos($recipient3, "\n") !== false || strpos($title, "\n") !== false) {
             echo "reciep\n";
             exit;
             $this->reject();
             return;
         }
         $r_array = array();
         $num_recipients = 0;
         if ($recipient1 != "") {
             $num_recipients++;
             $x = split(";", $recipient1);
             $r_array[] = $x[0];
         }
         if ($recipient2 != "") {
             $num_recipients++;
             $x = split(";", $recipient2);
             $r_array[] = $x[0];
         }
         if ($recipient3 != "") {
             $num_recipients++;
             $x = split(";", $recipient3);
             $r_array[] = $x[0];
         }
         if ($titleObj->getNamespace() == NS_PROJECT) {
             $r_array[] = '*****@*****.**';
         }
         if ($validEmail != "" && !in_array($validEmail, $r_array)) {
             $num_recipients++;
             $r_array[] = $validEmail;
         }
         if ($titleObj->getNamespace() == NS_ARTICLE_REQUEST) {
             $body = "{$message}\n\n----------------\n\n\t" . wfMsg('article-request-email', $how_to, "http://www.wikihow.com/index.php?title2={$dbkey}&action=easy&requested={$dbkey}", "http://www.wikihow.com/Request:{$dbkey}", "http://www.wikihow.com/" . wfMsg('writers-guide-url'), "http://www.wikihow.com/" . wfMsg('about-wikihow-url') . "");
         } else {
             if ($titleObj->getText() == wfMsg('mainpage')) {
                 $body = "{$message}\n\n----------------\n\n\t" . wfMsg('friend-sends-article-email-main-page') . "\n\n\t";
             } else {
                 if ($titleObj->getNamespace() == NS_PROJECT) {
                     $body = "{$message}";
                 } else {
                     $body = "{$message}\n\n----------------\n\n" . wfMsg('friend-sends-article-email', $how_to, $summary, $url) . "\n\n\t";
                 }
             }
         }
         $from = new MailAddress($email);
         foreach ($r_array as $address) {
             $address = preg_replace("@,.*@", "", $address);
             $to = new MailAddress($address);
             $sbody = $body;
             if ($address == $validEmail) {
                 $sbody = wfMsg('copy-email-from-yourself') . "\n\n" . $sbody;
             }
             if (!userMailer($to, $from, $subject, $sbody, false)) {
                 //echo "got an en error\n";
             }
         }
         SiteStatsUpdate::addLinksEmailed($num_recipients);
         $this->thanks();
     }
 }
 function writeOutput($par)
 {
     global $wgLang, $wgMemc, $wgDBname, $wgUser;
     global $wgSitename, $wgLanguageCode;
     global $wgFeedClasses, $wgFilterCallback, $wgWhitelistEdit, $wgParser;
     $this->getOutput()->setRobotpolicy("noindex,nofollow");
     $target = !empty($par) ? $par : $this->getRequest()->getVal("target");
     $t = Title::newFromDBKey($target);
     $update = true;
     if (!$t || !$t->userCan('edit')) {
         return;
     }
     if (!$this->getUser()->isAllowed('edit')) {
         return;
     }
     $article = new Article($t);
     $user = $this->getUser()->getName();
     $real_name = User::whoIsReal($this->getUser()->getID());
     if ($real_name == "") {
         $real_name = $user;
     }
     $dateStr = $wgLang->timeanddate(wfTimestampNow());
     $comment = $this->getRequest()->getVal("comment_text");
     foreach ($this->getRequest()->getValues() as $key => $value) {
         if (strpos($key, "comment_text") === 0) {
             $comment = $value;
             break;
         }
     }
     $topic = $this->getRequest()->getVal("topic_name");
     //echo "$dateStr<br/>";
     // remove leading space, tends to be a problem with a lot of talk page comments as it breaks the
     // HTML on the page
     $comment = preg_replace('/\\n[ ]*/', "\n", trim($comment));
     // Check to see if the user is also getting a thumbs up. If so, append the thumbs message and give a thumbs up
     if ($this->getRequest()->getVal('thumb')) {
         $comment .= "\n\n" . wfMsg('qn_thumbs_up');
         $userName = explode(":", $this->getRequest()->getVal('target'));
         ThumbsUp::quickNoteThumb($this->getRequest()->getVal('revold'), $this->getRequest()->getVal('revnew'), $this->getRequest()->getVal('pageid'), $userName[1]);
     }
     $formattedComment = wfMsg('postcomment_formatted_comment', $dateStr, $user, $real_name, $comment);
     if ($this->getRequest()->getVal('fromajax') == 'true') {
         $this->getOutput()->setArticleBodyOnly(true);
     }
     $text = "";
     $r = Revision::newFromTitle($t);
     if ($r) {
         $text = $r->getText();
     }
     $text .= "\n\n{$formattedComment}\n\n";
     $this->getOutput()->setStatusCode(409);
     //echo "updating with text:<br/> $text";
     //exit;
     $tmp = "";
     if ($this->getUser()->isBlocked()) {
         $this->getOutput()->blockedPage();
         return;
     }
     if (!$this->getUser()->getID() && $wgWhitelistEdit) {
         $this->userNotLoggedInPage();
         return;
     }
     if (wfReadOnly()) {
         $this->getOutput()->readOnlyPage();
         return;
     }
     if ($target == "Spam-Blacklist") {
         $this->getOutput()->readOnlyPage();
         return;
     }
     if ($this->getUser()->pingLimiter()) {
         $this->getOutput()->rateLimited();
         return;
     }
     $editPage = new EditPage($article);
     $contentModel = $t->getContentModel();
     $handler = ContentHandler::getForModelID($contentModel);
     $contentFormat = $handler->getDefaultFormat();
     $content = ContentHandler::makeContent($text, $t, $contentModel, $contentFormat);
     $status = Status::newGood();
     if (!wfRunHooks('EditFilterMergedContent', array($this->getContext(), $content, &$status, '', $wgUser, false))) {
         return;
     }
     if (!$status->isGood()) {
         $errors = $status->getErrorsArray(true);
         foreach ($errors as $error) {
             if (is_array($error)) {
                 $error = count($error) ? $error[0] : '';
             }
             if (preg_match('@^spamprotection@', $error)) {
                 $message = 'Error: found spam link';
                 $this->getOutput()->addHTML($message);
                 return;
             }
         }
         $message = 'EditFilterMergedContent returned an error -- cannot post comment';
         return;
     }
     $matches = array();
     $preg = "/http:\\/\\/[^] \n'\">]*/";
     $mod = str_ireplace('http://www.wikihow.com', '', $comment);
     preg_match_all($preg, $mod, $matches);
     if (sizeof($matches[0]) > 2) {
         $this->getOutput()->showErrorPage("postcomment", "postcomment_urls_limit");
         return;
     }
     if (trim(strip_tags($comment)) == "") {
         $this->getOutput()->showErrorPage("postcomment", "postcomment_nopostingtoadd");
         return;
     }
     if (!$t->userCan('edit')) {
         $this->getOutput()->showErrorPage("postcomment", "postcomment_discussionprotected");
         return;
     }
     $watch = false;
     if ($this->getUser()->getID() > 0) {
         $watch = $this->getUser()->isWatched($t);
     }
     $fc = new FancyCaptcha();
     $pass_captcha = $fc->passCaptcha();
     if (!$pass_captcha && $this->getUser()->getID() == 0) {
         $this->getOutput()->addHTML("Sorry, please enter the correct word. Click <a onclick='window.location.reload(true);'>here</a> to get a new one.<br/><br/>");
         return;
     }
     $article->doEdit($text, "");
     if ($this->getRequest()->getVal('jsonresponse') == 'true') {
         $this->revId = $article->getRevIdFetched();
     }
     // Notify users of usertalk updates
     if ($t->getNamespace() == NS_USER_TALK) {
         AuthorEmailNotification::notifyUserTalk($t->getArticleID(), $this->getUser()->getID(), $comment);
     }
     $this->getOutput()->setStatusCode(200);
     if ($this->getRequest()->getVal('fromajax') == 'true') {
         $this->getOutput()->redirect('');
         $this->getContext()->setTitle($t);
         $formattedComment = $wgParser->preSaveTransform($formattedComment, $t, $this->getUser(), new ParserOptions());
         $this->getOutput()->addHTML($this->getOutput()->parse("\n" . $formattedComment));
         return;
     }
 }
Example #15
0
    function execute($par)
    {
        global $wgRequest, $wgUser, $wgOut, $wgEmbedVideoServiceList;
        /* disabled this check, per Eliz and Jack.  added noindex meta tag.
        		if ( !in_array( 'importxml', $wgUser->getRights() ) ) {
        			$wgOut->showErrorPage( 'nosuchspecialpage', 'nospecialpagetext' );
        			return;
        		}
        		*/
        if (!$wgRequest->wasPosted()) {
            $wgOut->addMeta('robots', 'noindex');
            $wgOut->addHTML(<<<END
\t\t\t<form action='/Special:ExportXML' method='post' enctype="multipart/form-data" >
\t\t\tURLS to export: <textarea name='xml'></textarea>
\t\t\tWOI category mappings: <input type="file" name="uploadFile"> <br/>
\t\t\t<input type='submit'>
\t\t\t</form>
END
);
            return;
        }
        $dbr = wfGetDB(DB_SLAVE);
        $urls = split("\n", $wgRequest->getVal('xml'));
        $valid_sections = array("steps", "tips", "warnings", "things", "sources", "videos");
        $dom = new DOMDocument("1.0");
        $root = $dom->createElement("wikihowmedia");
        $dom->appendChild($root);
        // did we get a WOI category mapping sent to us?
        $woi_map = array();
        foreach ($_FILES as $f) {
            if (trim($f['tmp_name']) == "") {
                continue;
            }
            $text = preg_replace('@\\r@', "\n", file_get_contents($f['tmp_name']));
            $lines = split("\n", $text);
            foreach ($lines as $l) {
                $tokens = split(",", $l);
                $url = array_shift($tokens);
                $key = urldecode(preg_replace("@http://www.wikihow.com/@im", "", $url));
                if (preg_match("@index.php?@", $url)) {
                    $parts = parse_url($url);
                    $query = $parts['query'];
                    $params = array();
                    $tx = split("&", $query);
                    foreach ($tx as $v) {
                        $xx = split("=", $v);
                        if ($xx[0] == "title") {
                            $key = urldecode($xx[1]);
                            break;
                        }
                    }
                }
                if ($key == "") {
                    continue;
                }
                $woi_map[$key] = $tokens;
                $urls[] = $url;
            }
        }
        foreach ($urls as $url) {
            $origUrl = $url;
            if (trim($url) == "") {
                continue;
            }
            $url = trim($url);
            $url = str_replace("http://www.wikihow.com/", "", $url);
            $url = preg_replace('@^\\s*index\\.php\\?@', '', $url);
            $kv = split('&', $url);
            $urlParams = array();
            # decode URLs that look like this:
            #   http://www.wikihow.com/index.php?title=Sing&oldid=4956082
            foreach ($kv as $pair) {
                $a = split('=', $pair);
                if (count($a) < 2) {
                    $urlParams['title'] = $a[0];
                } else {
                    $urlParams[$a[0]] = $a[1];
                }
            }
            $t = Title::newFromDBKey(urldecode($urlParams['title']));
            if (!$t) {
                echo "Can't get title from {$origUrl}\n";
                continue;
            }
            $revid = !empty($urlParams['oldid']) ? $urlParams['oldid'] : '';
            $r = Revision::newFromTitle($t, $revid);
            if (!$r) {
                echo "Can't get revision from {$origUrl}\n";
                continue;
            }
            $text = $r->getText();
            $a = $dom->createElement("article");
            // title
            $x = $dom->createElement("title");
            // make sure the title is in the form "How to x y z"
            $title = $t->getText();
            if (!preg_match('@' . wfMsg('howto', '') . '@', $title)) {
                $title = wfMsg('howto', $title);
            }
            $x->appendChild($dom->createTextNode($title));
            $a->appendChild($x);
            // intro
            $content = $dom->createElement("content");
            $intro = Article::getSection($text, 0);
            $i = $dom->createElement("introduction");
            self::handleImages($intro, $dom, $i);
            $intro = self::cleanupText($intro);
            $n = $dom->createElement("text");
            $n->appendChild($dom->createTextNode($intro));
            $i->appendChild($n);
            $content->appendChild($i);
            # woi tags and categories
            if (isset($woi_map[$t->getDBKey()])) {
                $params = $woi_map[$t->getDBKey()];
                //tags
                $tags = array();
                for ($i = 2; $i < 4; $i++) {
                    if ($params[$i] != "None") {
                        $tags[] = $params[$i];
                    }
                }
                if (sizeof($tags) > 0) {
                    $xx = $dom->createElement("tags");
                    $xx->appendChild($dom->createTextNode(implode(",", $tags)));
                    $a->appendChild($xx);
                }
                $yy = $dom->createElement("categories");
                if ($params[0] != "None") {
                    $zz = $dom->createElement("category");
                    $zz->setAttribute("type", "mainmenu");
                    $zz->appendChild($dom->createTextNode($params[0]));
                    $yy->appendChild($zz);
                }
                if ($params[1] != "None") {
                    $zz = $dom->createElement("category");
                    $zz->setAttribute("type", "featured");
                    $zz->appendChild($dom->createTextNode($params[1]));
                    $yy->appendChild($zz);
                }
                $a->appendChild($yy);
            }
            $parts = preg_split("@(^==[^=]*==)@im", $text, 0, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
            $sources_element = null;
            while (sizeof($parts) > 0) {
                $x = trim(strtolower(str_replace('==', '', array_shift($parts))));
                // title
                $x = preg_replace("@[^a-z]@", "", $x);
                if ($x == "thingsyoullneed") {
                    $x = "things";
                }
                if ($x == "sourcesandcitations") {
                    $x = "sources";
                }
                if ($x == "video") {
                    $x = "videos";
                }
                if (!in_array($x, $valid_sections)) {
                    continue;
                }
                $section = $dom->createElement($x);
                if ($x == "sources") {
                    $sources_element = $section;
                }
                // process subsections
                $beef = array_shift($parts);
                if ($x == "steps") {
                    if (preg_match("@(^===[^=]*===)@im", $beef)) {
                        $subs = preg_split("@(^===[^=]*===)@im", $beef, 0, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
                        while (sizeof($subs) > 0) {
                            $y = array_shift($subs);
                            $sub = null;
                            if (preg_match("@(^===[^=]*===)@", $y)) {
                                // this is a subsection
                                $sub = $dom->createElement("subsection");
                                $x = str_replace("=", "", $y);
                                $tnode = $dom->createElement("title");
                                $ttext = self::cleanupText($x);
                                $tnode->appendChild($dom->createTextNode($ttext));
                                $sub->appendChild($tnode);
                                $body = array_shift($subs);
                                self::processListSection($dom, $sub, $body);
                                $section->appendChild($sub);
                            } else {
                                // this is not a subsection, it could be a set of steps preceeding  a subsection
                                $body = $y;
                                self::processListSection($dom, $section, $y);
                            }
                        }
                    } else {
                        self::processListSection($dom, $section, $beef);
                    }
                } else {
                    if ($x == "videos") {
                        // {{Video:...}} embeds can point to other videos, so
                        // we need a loop here
                        $title = $t->getText();
                        while (true) {
                            $vid_t = Title::makeTitle(NS_VIDEO, $title);
                            $vid_r = Revision::newFromTitle($vid_t);
                            if ($vid_r) {
                                $vid_text = $vid_r->getText();
                                $tokens = split("\\|", $vid_text);
                                if (preg_match('@^{{video:([^|}]*)@i', $tokens[0], $m)) {
                                    $title = $m[1];
                                    if (!empty($title)) {
                                        continue;
                                    }
                                } else {
                                    $provider = $tokens[1];
                                    $id = $tokens[2];
                                    // special hack for wonderhowto videos that
                                    // are actually youtube videos
                                    if ($provider == 'wonderhowto' && preg_match('@http://www.youtube.com/v/([^&/">]*)@', $vid_text, $m)) {
                                        $provider = 'youtube';
                                        $id = $m[1];
                                    }
                                    $found = false;
                                    foreach ($wgEmbedVideoServiceList as $service => $params) {
                                        if ($provider == $service) {
                                            $url = str_replace("\$1", $id, $params['url']);
                                            if ($url != "") {
                                                $vid = $dom->createElement("video");
                                                $vid->appendChild($dom->createTextNode($url));
                                                $section->appendChild($vid);
                                                $found = true;
                                                break;
                                            }
                                        }
                                    }
                                    if (!$found) {
                                        $text = htmlspecialchars_decode($vid_text);
                                        preg_match("@src&61;\"[^\"]*@", $text, $matches);
                                        if (sizeof($matches[0]) > 0) {
                                            $url = preg_replace("@.*\"@", "", $matches[0]);
                                            $vid = $dom->createElement("video");
                                            $vid->appendChild($dom->createTextNode($url));
                                            $section->appendChild($vid);
                                        }
                                    }
                                }
                            }
                            break;
                        }
                    } else {
                        self::processListSection($dom, $section, $beef, false, preg_replace("@s\$@", "", $x));
                    }
                }
                // append the section
                $content->appendChild($section);
            }
            // process references
            preg_match_all("@<ref[^>]*>.*</ref>@imU", $text, $matches);
            foreach ($matches[0] as $m) {
                if (!$sources_element) {
                    $sources_element = $dom->createElement("sources");
                }
                $m = preg_replace("@<[/]*ref[^>]*>@", "", $m);
                $e = $dom->createElement("source");
                $tx = $dom->createElement("text");
                $m = self::convertLinks($m);
                $m = self::cleanUpText($m, true);
                $tx->appendChild($dom->createTextNode($m));
                $e->appendChild($tx);
                $sources_element->appendChild($e);
                $content->appendChild($sources_element);
            }
            $a->appendChild($content);
            //attribution
            $attr = $dom->createElement("attribution");
            $num = $dom->createElement("numeditors");
            $users = array();
            $res = $dbr->select("revision", array("distinct(rev_user_text)"), array("rev_page" => $t->getArticleID(), "rev_user != 0"), "generate_xml.php", array("ORDER BY" => "rev_timestamp DESC"));
            $num->appendChild($dom->createTextNode($dbr->numRows($res)));
            $attr->appendChild($num);
            while ($row = $dbr->fetchObject($res)) {
                $u = User::newFromName($row->rev_user_text);
                $u->load();
                $name = $u->getRealName() != "" ? $u->getRealName() : $u->getName();
                $users[] = $name;
            }
            $names = $dom->createElement("names");
            $names_text = $dom->createElement("text");
            $names_text->appendChild($dom->createTextNode(implode(", ", $users)));
            $names->appendChild($names_text);
            $attr->appendChild($names);
            $a->appendChild($attr);
            $root->appendChild($a);
        }
        $wgOut->disable();
        header("Content-type: text/xml;");
        echo $dom->saveXML();
    }
Example #16
0
function UW_Layouts_checkActionIsLayout( $action, $article ) {
	global $wgOut, $wgDBprefix, $wgLayoutCategories, $wgLayoutUseCategoryPage,
		$wgNoLayoutOption, $wgContLang,
		$wgLayoutCategoryNSWhiteList;

	// not layout = do nothing
	if ( $action != "layout" )
		return true;

	/* if this page already exists, or
	 * is a discussion page, redirect
	 * to the regular edit page */
	if ( $article->fetchContent() !== false
	|| ( $article->mTitle->getNamespace() % 2 ) ) {
		$wgOut->redirect( $article->mTitle->getInternalUrl ( "action=edit" ) );
		return false;
	}

	// pluck out the bits that we need from mTitle
	$title = $article->mTitle->getPrefixedText();
	$url   = $article->mTitle->getInternalUrl();
	$name  = $article->mTitle->getPrefixedURL();
	$namespace = $article->mTitle->getNamespace();

	

	$wgOut->setPageTitle ( wfMsg ( "layouts_title" ) );

	/* fetch all articles/pages in the NS_LAYOUT namespace
	 * by directly querying the database. mediawiki doesn't
	 * provide any OO way of doing this :( */
	$db = wfGetDB( DB_MASTER );
	$layouts = $db->resultObject ( $db->query ( "select * from {$wgDBprefix}page where page_namespace=" . NS_LAYOUT . " order by page_title" ) );

	$wgOut->addHTML ( wfMsg ( "layouts_chooselayout", $title ) . "
		<form action='$url' method='get'>
			<input type='hidden' name='title' value='$name' />
			<input type='hidden' name='action' value='edit' />
	" );

	/* iterate the pages we found in the Layouts
	 * namespace, and list each one as an option
	 * as long as it is not restricted to specific
	 * namespaces */
	$default = true;
	while ( $result = $layouts->next() ) {
		// page info
		$title = Title::newFromURL ( $result->page_title )->getText();
		$revision = Revision::loadFromPageId ( $db, $result->page_id );
		$text = $revision->getText();
		$lines = explode ( "\n", $text );
		$namespaces = array();

		// add this layout to the choices by default
		$add = true;

		/* go through the layout text and see if it has an @namespace
		 * restriction, if so only add the layout as a choice if we find
		 * the namespace of this page in the layout text */
		foreach ( $lines as $line ) {
			if ( preg_match ( "/^@namespace(.+?)$/m", $line, $matches ) ) {
				$namespaces = explode ( " ", trim( $matches[1] ) );
				$add = in_array ( $wgContLang->getNsText ( $namespace ), $namespaces ) ||
					$namespace == NS_MAIN && in_array ( "Main", $namespaces );
			}
		}
		if ( $add ) {
			$checked = $default ? "checked='checked'" : "";
			$default = false;
			$fm_id = "layout-" . $result->page_id;
			$wgOut->addHTML( "
				<div>
					<input type='radio' name='layout' id='$fm_id' value='$title' $checked/>
					<label for='$fm_id'>$title</label>
				</div>
			" );
		}
	}

	/* include an option to create a page
	 * without any layout (before any are created,
	 * this will be the only option available) */
	if ( $wgNoLayoutOption ) {
		$wgOut->addHTML( "
			<div>
				<input type='radio' name='layout' id='layout-0' value='none' />
				<label for='layout-0'>" . wfMsg( 'layouts_nolayout' ) . "</label>
			</div>
		" );
	}
	$wgOut->addHTML( "<br />" );

	/* check to see if we are allowing categories on the layout page
	 * and if so then, either grab all the categories, or get them from
	 * the designated page (do this for pages in the whitelisted namespaces) */
	if ( $wgLayoutCategories && in_array( $namespace, $wgLayoutCategoryNSWhiteList ) ) {
		$categories = array();

		/* get the categories from the page if desired,
		 * otherwise grab them from the db */
		if ( $wgLayoutUseCategoryPage ) {
			$revision = Revision::newFromTitle( Title::newFromDBKey( wfMsgForContent( 'layouts-layoutcategorypage' ) ) );
			$results = $revision ? split( "\n", $revision->getText() ) : array();
			foreach ( $results as $result ) {
				if ( trim ( $result ) != '' )
					$categories[] = Title::newFromText( trim( $result ) )->getDBkey();
			}
		} else {
			// todo: implement this later...
		}

		// add radio buttons for the categories
		$default = true;
		$title = $article->mTitle->getPrefixedText();
		$wgOut->addHTML( "<div id='category-box'>" . wfMsg ( "layouts_choosecategory", $title ) );
		foreach ( $categories as $category ) {
			$checked = $default ? "checked='checked'" : "";
			$default = false;
			$fm_id = "category-$category";
			$caption = Title::newFromDBkey ( $category )->getText();
			$wgOut->addHTML( "
				<div>
					<input type='radio' name='category' id='$fm_id' value='$fm_id' $checked/>
					<label for='$fm_id'>$caption</label>
				</div>
			" );
		}
		$wgOut->addHTML ( "</div><br />" );
	}

	$wgOut->addHTML ( "<input type='submit' value='" . wfMsg( 'layouts_continue' ) . "' />" );
	$wgOut->addHTML ( "</form>" );

	return false;
}
    function execute($par)
    {
        global $wgUser, $wgOut, $wgLang, $wgTitle, $wgMemc, $wgDBname;
        global $wgRequest, $wgSitename, $wgLanguageCode, $IP;
        global $wgScript, $wgFilterCallback, $wgScriptPath;
        $this->setHeaders();
        require_once "{$IP}/extensions/wikihow/EditPageWrapper.php";
        require_once "{$IP}/includes/EditPage.php";
        $target = isset($par) ? $par : $wgRequest->getVal('target');
        if (!$target) {
            $wgOut->addHTML("No target specified. In order to thank a group of authors, a page must be provided.");
            return;
        }
        $title = Title::newFromDBKey($target);
        $me = Title::makeTitle(NS_SPECIAL, "ThankAuthors");
        if (!$wgRequest->getVal('token')) {
            $sk = $wgUser->getSkin();
            $talk_page = $title->getTalkPage();
            $token = $this->getToken1();
            $thanks_msg = wfMsg('thank-you-kudos', $title->getFullURL(), wfMsg('howto', $title->getText()));
            // add the form HTML
            $wgOut->addHTML(<<<EOHTML
\t\t\t\t<script type='text/javascript'>
\t\t\t\t\tfunction submitThanks () {
\t\t\t\t\t\tvar message = \$('#details').val();
\t\t\t\t\t\tif(message == "") {
\t\t\t\t\t\t\talert("Please enter a message.");
\t\t\t\t\t\t\treturn false;
\t\t\t\t\t\t}
\t\t\t\t\t\tvar url = '{$me->getFullURL()}?token=' + \$('#token')[0].value + '&target=' + \$('#target')[0].value + '&details=' + \$('#details')[0].value;
\t\t\t\t\t\tvar form = \$('#thanks_form');
\t\t\t\t\t\tform.html(\$('#thanks_response').html());
\t\t\t\t\t\t\$.get(url);
\t\t\t\t\t\treturn true;
\t\t\t\t\t}
\t\t\t\t</script>

\t\t\t\t<div id="thanks_response" style="display:none;">{$thanks_msg}</div>
\t\t\t\t<div id="thanks_form"><div class="section_text">
EOHTML
);
            $wgOut->addWikiText(wfMsg('enjoyed-reading-article', $title->getFullText(), $talk_page->getFullText()));
            $wgOut->addHTML("<input id=\"target\" type=\"hidden\" name=\"target\" value=\"{$target}\"/>\n\t\t\t\t<input id=\"token\" type=\"hidden\" name=\"{$token}\" value=\"{$token}\"/>\n\t\t\t\t");
            $wgOut->addHTML("<br />\n\t\t\t\t<textarea style='width:98%;' id=\"details\" rows=\"5\" cols=\"100\" name=\"details\"></textarea><br/>\n\t\t\t\t<br /><button onclick='submitThanks();' class='button primary'>" . wfMsg('submit') . "</button>\n\t\t\t\t</div></div>");
        } else {
            // this is a post, accept the POST data and create the
            // Request article
            wfLoadExtensionMessages('PostComment');
            $wgOut->setArticleBodyOnly(true);
            $user = $wgUser->getName();
            $real_name = User::whoIsReal($wgUser->getID());
            if ($real_name == "") {
                $real_name = $user;
            }
            $dateStr = $wgLang->timeanddate(wfTimestampNow());
            $comment = $wgRequest->getVal("details");
            $text = $title->getFullText();
            wfDebug("STA: got text...");
            // filter out links
            $preg = "/[^\\s]*\\.[a-z][a-z][a-z]?[a-z]?/i";
            $matches = array();
            if (preg_match($preg, $comment, $matches) > 0) {
                $wgOut->addHTML(wfMsg('no_urls_in_kudos', $matches[0]));
                return;
            }
            $comment = strip_tags($comment);
            $formattedComment = wfMsg('postcomment_formatted_thanks', $dateStr, $user, $real_name, $comment, $text);
            wfDebug("STA: comment {$formattedComment}\n");
            wfDebug("STA: Checking blocks...");
            $tmp = "";
            if ($wgUser->isBlocked()) {
                $this->blockedIPpage();
                return;
            }
            if (!$wgUser->getID() && $wgWhitelistEdit) {
                $this->userNotLoggedInPage();
                return;
            }
            if ($target == "Spam-Blacklist") {
                $wgOut->readOnlyPage();
                return;
            }
            wfDebug("STA: checking read only\n");
            if (wfReadOnly()) {
                $wgOut->readOnlyPage();
                return;
            }
            wfDebug("STA: checking rate limiter\n");
            if ($wgUser->pingLimiter('userkudos')) {
                $wgOut->rateLimited();
                return;
            }
            wfDebug("STA: checking blacklist\n");
            if ($wgFilterCallback && $wgFilterCallback($title, $comment, "")) {
                // Error messages or other handling should be
                // performed by the filter function
                return;
            }
            wfDebug("STA: checking tokens\n");
            $usertoken = $wgRequest->getVal('token');
            $token1 = $this->getToken1();
            $token2 = $this->getToken2();
            if ($usertoken != $token1 && $usertoken != $token2) {
                wfDebug("STA: User kudos token doesn't match user: {$usertoken} token1: {$token1} token2: {$token2}");
                return;
            }
            wfDebug("STA: going through contributors\n");
            $article = new Article($title);
            //$contributors = $article->getContributors(0, 0, true);
            $contributors = ArticleAuthors::getAuthors($article->getID());
            foreach ($contributors as $k => $v) {
                $u = User::newFromName($k);
                $id = $u->getID();
                //$id = $c->getID();
                //$u = $c;
                wfDebug("STA: going through contributors {$u} {$id}\n");
                if ($id == "0") {
                    continue;
                }
                // forget the anon users.
                //notify via the echo notification system
                if (class_exists('EchoEvent')) {
                    EchoEvent::create(array('type' => 'kudos', 'title' => $title, 'extra' => array('kudoed-user-id' => $id), 'agent' => $wgUser));
                }
                $t = Title::newFromText("User_kudos:" . $u);
                $a = new Article($t);
                $update = $t->getArticleID() > 0;
                $text = "";
                if ($update) {
                    $text = $a->getContent(true);
                    $text .= "\n\n" . $formattedComment;
                    if ($wgFilterCallback && $wgFilterCallback($t, $text, $text)) {
                        // Error messages or other handling should be
                        // performed by the filter function
                        return;
                    }
                }
                if ($update) {
                    $a->updateArticle($text, "", true, false, false, '', false);
                } else {
                    $a->insertNewArticle($text, "", true, false, false, false, false);
                }
            }
            wfDebug("STA: done\n");
            $wgOut->addHTML("Done.");
            $wgOut->redirect('');
        }
    }
function UW_GenericEditPage_extractCategoriesIntoBox( &$text ) {
	global $wgDBprefix, $wgAddCategory, $wgSuggestCategory, $wgRequest,
		$wgEmergencyContact, $wgUseCategoryPage;
	$out = "";

	

	/* build an array of the categories, either from a page
	 * or from all available categories in the wiki */
	$categories = array();
	if ( $wgUseCategoryPage ) {

		// from the specified page
		$revision = Revision::newFromTitle ( Title::newFromDBKey ( wfMsgForContent( 'gep-categorypage' ) ) );
		$results = $revision ? split ( "\n", $revision->getText() ) : array();
		foreach ( $results as $result ) {
			if ( trim( $result ) != '' )
				$categories[] = Title::newFromText ( trim ( $result ) )->getDBkey();
		}
	} else {

		// all the categories
		$db = wfGetDB ( DB_MASTER );
		$results = $db->resultObject ( $db->query(
			"select distinct cl_to from {$wgDBprefix}categorylinks order by cl_to" ) );

		while ( $result = $results->next() )
			$categories[] = $result->cl_to;
	}

	// extract the categories on this page
	$regex = "/\[\[category:(.+?)(?:\|.*)?\]\]/i";
	preg_match_all ( $regex, strtolower( $text ), $matches );
	$text = preg_replace ( $regex, "", $text );

	// an array of the categories on the page (in db form)
	$on_page = array();
	foreach ( $matches[1] as $cat )
		$on_page[] = strtolower ( Title::newFromText ( $cat )->getDBkey() );

	/* add any categories that may have been passed with the
	 * GET request as if they started out on the page */
	$data = $wgRequest->getValues();
	foreach ( $data as $key => $value ) {
		if ( $key == 'category' ) {
			$category = substr ( $value, 9 ); // value = category-categoryname
			$on_page[] = strtolower ( $category );
			if ( !in_array ( $category, $categories ) )
				$categories[] = $category;
		}
	}

	/* add checkboxes for the categories,
	 * with ones from the page already checked */
	$out .= "<div id='category-box'><h3>" . wfMsg ( 'gep-categories' ) . "</h3>";
	foreach ( $categories as $category ) {
		$fm_id = "category-$category";
		$caption = Title::newFromDBkey ( $category )->getText();
		$checked = in_array ( strtolower ( $category ), $on_page )
			? "checked='checked'" : '';

		$out .= "
			<div>
				<input type='checkbox' name='$fm_id' id='$fm_id' $checked/>
				<label for='$fm_id'>$caption</label>
			</div>
		";
	}

	// add a text field to add new categories
	if ( $wgAddCategory ) {
		$out .= "
			<div class='add'>
				<label for='fm-add-cat'>" . wfMsg ( 'gep-addcategory' ) . "</label>
				<input type='text' id='fm-add-cat' autocomplete='off' />
				<input type='button' value='" . wfMsg ( 'gep-addcategorybutton' ) . "' id='fm-add-cat-button' />
			</div>
			<script type='text/javascript'>
				// hook up the 'add category' box events
				Uniwiki.GenericEditPage.Events.add_category();
			</script>
		";
	}

	/* add a text field to suggest a category
	 * as email to $wgEmergencyContact */
	if ( $wgSuggestCategory ) {
		$out .= "
			<div class='suggest'>
				<label for='fm-suggest-cat'>" . wfMsg ( 'gep-suggestcategory' ) . "</label>
				<input type='text' id='fm-suggest-cat' autocomplete='off' />
				<input type='button' value='" . wfMsg ( 'gep-suggestcategorybutton' ) . "' id='fm-suggest-cat-button' />
			</div>
			<script type='text/javascript'>
				$('fm-suggest-cat-button').addEvent ('click', function() {
					var field = this.getPrevious();
					var that = this;

					// only if a category name was entered...
					var cat_name = field.value.trim();
					if (cat_name != '') {
						sajax_do_call ('UW_GenericEditPage_emailSuggestion', [cat_name], function (msg) {

							/* got response from the server, append it after the
							 * suggest form (so subsequent suggestions are injected
							 * ABOVE existing suggetions before they're removed) */
							var n = new Element ('div')
								.injectAfter ('fm-suggest-cat-button', 'after')
								.appendText (msg.responseText)
								.highlight();

							/* fade out and destroy the notification within
							 * a timely manner, to keep the DOM tidy */
							(function() {  n.fade()     }).delay(6000);
							(function() {  n.destroy()  }).delay(8000);
						});

						// clear the suggestion
						field.value = '';
					}
				});

				// catch the ENTER key in the suggestion box,
				// to prevent the entire edit form from submitting
				$('fm-suggest-cat').addEvent ('keypress', function (e) {
					if (e.key == 'enter') {
						this.getNext().fireEvent ('click');
						e.stop();
					}
				});
			</script>
		";
	}

	// end of category box
	$out .= "</div>";
	return $out;
}
        #echo "{$title->getFullURL()}, {$href}\n";
        #if (preg_match("@/url?q=" . $title->getFullURL() . "@", $href))
        if ($href == $turl) {
            $found[] = $title;
            return $index;
        }
        $index++;
    }
    return 0;
}
$dbw = wfGetDB(DB_MASTER);
$dbw->query("insert IGNORE into google_indexed (gi_page, gi_page_created) select fe_page, fe_timestamp from firstedit where fe_user_text='WRM'");
$res = $dbw->select(array('google_indexed', 'page'), array("page_title", "page_id"), array("page_id = gi_page"), "checkGoogleIndex", array("ORDER BY" => "gi_times_checked, rand()", "LIMIT" => 500));
$titles = array();
while ($row = $dbw->fetchObject($res)) {
    $titles[] = Title::newFromDBKey($row->page_title);
}
foreach ($titles as $t) {
    if (!$t) {
        continue;
    }
    $ts = wfTimestampNow();
    $ret = isIndexed($t);
    #echo "got return of $ret\n"; exit;
    $dbw = wfGetDB(DB_MASTER);
    $opts = array('gl_page' => $t->getArticleID(), 'gl_pos' => $ret == null ? 0 : 1, 'gl_checked' => $ts);
    if ($ret == null) {
        $opts['gl_err_str'] = $wgLastCurlError;
        $opts['gl_err'] = 1;
    }
    $dbw->insert('google_indexed_log', $opts);
Example #20
0
if (!isset($argv[0])) {
    echo "Usage: php maintenance/generate_xml.php urls.txt\n";
    return;
}
$dbr = wfGetDB(DB_SLAVE);
$urls = split("\n", file_get_contents($argv[0]));
$valid_sections = array("steps", "tips", "warnings", "things", "sources", "videos");
$dom = new DOMDocument("1.0");
$root = $dom->createElement("wikihowmedia");
$dom->appendChild($root);
foreach ($urls as $url) {
    if (trim($url) == "") {
        continue;
    }
    $url = str_replace("http://www.wikihow.com/", "", $url);
    $t = Title::newFromDBKey(urldecode($url));
    if (!$t) {
        echo "Can't get title from {$url}\n";
        continue;
    }
    $r = Revision::newFromTitle($t);
    if (!$r) {
        echo "Can't get revision from {$url}\n";
        continue;
    }
    $text = $r->getText();
    $a = $dom->createElement("article");
    // title
    $x = $dom->createElement("title");
    $x->appendChild($dom->createTextNode($t->getText()));
    $a->appendChild($x);
	private function showRecommendations()
	{
		global $wgRequest, $wgUser, $wgOut;

		// check if camel parameter is set, otherwise use current user
		$user = $wgRequest->getText('camel');
		if (!$user)
			$user = $wgUser->getName();

		$rand_mode = $wgRequest->getText('random');

		$wgOut->addWikiText('==Kamele mit ähnlichem Geschmack wie '.$user.'==');

		// get database access
		$dbr = wfGetDB( DB_SLAVE );
		
		$res = $dbr->query( $this->createSimCamelsQuery($dbr, $user) . ' LIMIT 10');

		$out = '';
		foreach( $res as $row ) {
			$title = Title::newFromDBKey($row->page_title);
			$name = explode('/',$title->getText());
        		$out .= "\n# [[{{ns:2}}:" . $row->page_title . '|' . $name[0] . ']] (' . round(floatval($row->metric)*100,1) . ' Punkte)';
		}
		$wgOut->addWikiText($out);


		$wgOut->addWikiText('==Leseempfehlungen für '.$user.'==');

		$res = $dbr->query( $this->createRecommendationsQuery($dbr, $user, $rand_mode) . ' LIMIT 20');
		$out = '';

		foreach( $res as $row ) {
			$title = Title::newFromDBKey($row->page_title);
        		$out .= "\n# [[:{{ns:" . $row->page_namespace . '}}:' . $row->page_title . '|' . $title->getText() . ']] (' . round(floatval($row->metric),1) . ' Punkte)';
		}
		$wgOut->addWikiText($out);

	}
Example #22
0
 function execute($par)
 {
     global $wgRequest, $wgContLang, $wgOut, $wgSpamBlacklistArticle, $wgUser, $wgScript;
     $title = Title::newFromDBKey($wgRequest->getVal('target'));
     $diff = $wgRequest->getVal('diff2');
     $rcid = $wgRequest->getVal('rcid');
     $rdfrom = $wgRequest->getVal('rdfrom');
     $wgOut->setHTMLTitle(wfMsg('pagetitle', 'Spam Tool'));
     // can the user even edit this?
     $sb = Title::newFromDBKey($wgSpamBlacklistArticle);
     if (!$sb->userCanEdit()) {
         $wgOut->addHTML(wfMsg('spamdifftool_cantedit'));
         return;
     }
     // do the processing
     if ($wgRequest->wasPosted()) {
         if ($wgRequest->getVal('confirm', null) != null) {
             $t = Title::newFromDBKey($wgSpamBlacklistArticle);
             $a = new Article($t);
             $text = $a->getContent();
             // insert the before the <pre> at the bottom  if there is one
             $i = strrpos($text, "</pre>");
             if ($i !== false) {
                 $text = substr($text, 0, $i) . $wgRequest->getVal('newurls') . "\n" . substr($text, $i);
             } else {
                 $text .= "\n" . $wgRequest->getVal('newurls');
             }
             $watch = false;
             if ($wgUser->getID() > 0) {
                 $watch = $wgUser->isWatched($t);
             }
             $a->updateArticle($text, wfMsg('spamdifftool_summary'), false, $watch);
             $returnto = $wgRequest->getVal('returnto', null);
             if ($returnto != null && $returnto != '') {
                 $wgOut->redirect($wgScript . "?" . urldecode($returnto));
             }
             // clear the redirect set by updateArticle
             return;
         }
         $vals = $wgRequest->getValues();
         $text = '';
         $urls = array();
         $source = wfMsgForContent('top_level_domains');
         $tlds = split("\n", $source);
         foreach ($vals as $key => $value) {
             if (strpos($key, "http://") === 0) {
                 $url = str_replace("%2E", ".", $key);
                 if ($value == 'none') {
                     continue;
                 }
                 switch ($value) {
                     case 'domain':
                         $t = "";
                         foreach ($tlds as $tld) {
                             if (preg_match("/" . $tld . "/i", $url)) {
                                 $t = $tld;
                                 $url = preg_replace("/" . $tld . "/i", "", $url, 1);
                                 break;
                             }
                         }
                         $url = preg_replace("@^http://([^/]*\\.)?([^./]+\\.[^./]+).*\$@", "\$2", $url);
                         $url = str_replace(".", "\\.", $url);
                         // escape the periods
                         $url .= $t;
                         break;
                     case 'subdomain':
                         $url = str_replace("http://", "", $url);
                         $url = str_replace(".", "\\.", $url);
                         // escape the periods
                         $url = preg_replace("/^([^\\/]*)\\/.*/", "\$1", $url);
                         // trim everything after the slash
                         break;
                     case 'dir':
                         $url = str_replace("http://", "", $url);
                         $url = preg_replace("@^([^/]*\\.)?([^./]+\\.[^./]+(/[^/?]*)?).*\$@", "\$1\$2", $url);
                         // trim everything after the slash
                         $url = preg_replace("/^(.*)\\/\$/", "\$1", $url);
                         // trim trailing / if one exists
                         $url = str_replace(".", "\\.", $url);
                         // escape the periods
                         $url = str_replace("/", "\\/", $url);
                         // escape the slashes
                         break;
                 }
                 if (!isset($urls[$url])) {
                     $text .= "{$url}\n";
                     $urls[$url] = true;
                 }
             }
         }
         if (trim($text) == '') {
             $wgOut->addHTML(wfMsg('spamdifftool_notext', $wgScript . "?" . urldecode($wgRequest->getVal('returnto'))));
             return;
         }
         $wgOut->addHTML("<form method=POST>\n\t\t\t\t\t<input type='hidden' name='confirm' value='true'>\n\t\t\t\t\t<input type='hidden' name='newurls' value=\"" . htmlspecialchars($text) . "\">\n\t\t\t\t\t<input type='hidden' name='returnto' value=\"" . htmlspecialchars($wgRequest->getVal('returnto')) . "\">\n\t\t\t\t");
         $wgOut->addHTML(wfMsg('spamdifftool_confirm') . "<pre style='padding: 10px'>{$text}</pre>");
         $wgOut->addHTML("</table><input type=submit value=\"" . htmlspecialchars(wfMsg('submit')) . "\"></form>");
         return;
     }
     if (!is_null($diff)) {
         require_once 'DifferenceEngine.php';
         // Get the last edit not by this guy
         $current = Revision::newFromTitle($title);
         $dbw = wfGetDB(DB_MASTER);
         $user = intval($current->getUser());
         $user_text = $dbw->addQuotes($current->getUserText());
         $s = $dbw->selectRow('revision', array('rev_id', 'rev_timestamp'), array('rev_page' => $current->getPage(), "rev_user <> {$user} OR rev_user_text <> {$user_text}"), $fname, array('USE INDEX' => 'page_timestamp', 'ORDER BY' => 'rev_timestamp DESC'));
         if ($s) {
             // set oldid
             $oldid = $s->rev_id;
         }
         if ($wgRequest->getVal('oldid2') < $oldid) {
             $oldid = $wgRequest->getVal('oldid2');
         }
         $de = new DifferenceEngine($title, $oldid, $diff, $rcid);
         $de->loadText();
         $otext = $de->mOldtext;
         $ntext = $de->mNewtext;
         $ota = explode("\n", $wgContLang->segmentForDiff($otext));
         $nta = explode("\n", $wgContLang->segmentForDiff($ntext));
         $diffs = new Diff($ota, $nta);
         foreach ($diffs->edits as $edit) {
             if ($edit->type != 'copy' && $edit->closing != "") {
                 $text .= implode("\n", $edit->closing) . "\n";
             }
         }
     } else {
         if ($title != "") {
             $a = new Article($title);
             $text = $a->getContent(true);
         }
     }
     $matches = array();
     $preg = "/http:\\/\\/[^] \n'\"\\>\\<]*/im";
     preg_match_all($preg, $text, $matches);
     if (sizeof($matches[0]) == 0) {
         $wgOut->addHTML(wfMsg('spamdifftool_no_urls_detected', $wgScript . "?" . urldecode($wgRequest->getVal('returnto'))));
         return;
     }
     $wgOut->addHTML("\n\t\t\t<form method='POST'>\n\t\t\t\t\t<input type='hidden' name='returnto' value=\"" . htmlspecialchars($wgRequest->getVal('returnto')) . "\">\n\t\t\t\t<style type='text/css'>\n\t\t\t\t\t\ttd.spam-url-row {\n\t\t\t\t\t\t\tborder: 1px solid #ccc;\n\t\t\t\t\t\t}\n\t\t\t\t</style> " . wfMsg('spamdifftool_urls_detected') . "\n\t\t\t<br/><br/><table cellpadding='5px' width='100%'>");
     $urls = array();
     foreach ($matches as $match) {
         foreach ($match as $url) {
             if (isset($urls[$url])) {
                 continue;
             }
             // avoid dupes
             $urls[$url] = true;
             $name = htmlspecialchars(str_replace(".", "%2E", $url));
             $wgOut->addHTML("<tr>\n\t\t\t\t\t<td class='spam-url-row'><b>{$url}</b><br/>\n\t\t\t\t\t" . wfMsg('spamdifftool_block') . " &nbsp;&nbsp;\n\t\t\t\t\t<INPUT type='radio' name=\"" . $name . "\"\tvalue='domain' checked> " . wfMsg('spamdifftool_option_domain') . "\n\t\t\t\t\t<INPUT type='radio' name=\"" . $name . "\"\tvalue='subdomain'> " . wfMsg('spamdifftool_option_subdomain') . "\n\t\t\t\t\t<INPUT type='radio' name=\"" . $name . "\"\tvalue='dir'>" . wfMsg('spamdifftool_option_directory') . "\n\t\t\t\t\t<INPUT type='radio' name=\"" . $name . "\"\tvalue='none'>" . wfMsg('spamdifftool_option_none') . "\n\t\t\t\t</td>\n\t\t\t\t</tr>\n\t\t\t\t");
         }
     }
     $wgOut->addHTML("</table><input type=submit value=\"" . htmlspecialchars(wfMsg('submit')) . "\"></form>");
     // DifferenceEngine directly fetched the revision:
     $RevIdFetched = $de->mNewid;
 }
Example #23
0
  function execute($par)
  {
      global $wgRequest, $wgUser, $wgOut;
      if (!in_array('sysop', $wgUser->getGroups()) && !in_array('newarticlepatrol', $wgUser->getRights())) {
          $wgOut->setArticleRelated(false);
          $wgOut->setRobotpolicy('noindex,nofollow');
          $wgOut->errorpage('nosuchspecialpage', 'nospecialpagetext');
          return;
      }
      wfLoadExtensionMessages('RequestTopic');
      list($limit, $offset) = wfCheckLimits();
      $wgOut->setHTMLTitle('Manage Suggested Topics - wikiHow');
      $wgOut->addHTML('<script type="text/javascript" language="javascript" src="' . wfGetPad('/extensions/min/f/extensions/wikihow/winpop.js?rev=') . WH_SITEREV . '"></script>
 	<link rel="stylesheet" href="' . wfGetPad('/extensions/min/f/extensions/wikihow/winpop.css?rev=') . WH_SITEREV . '" type="text/css" />');
      $wgOut->setRobotPolicy('noindex,nofollow');
      $dbr = wfGetDB(DB_SLAVE);
      $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>');
      if ($wgRequest->wasPosted()) {
          $accept = array();
          $reject = array();
          $updates = array();
          $newnames = array();
          foreach ($wgRequest->getValues() as $key => $value) {
              $id = str_replace("ar_", "", $key);
              if ($value == 'accept') {
                  $accept[] = $id;
              } elseif ($value == 'reject') {
                  $reject[] = $id;
              } elseif (strpos($key, 'st_newname_') !== false) {
                  $updates[str_replace('st_newname_', '', $key)] = $value;
                  $newnames[str_replace('st_newname_', '', $key)] = $value;
              }
          }
          $dbw = wfGetDB(DB_MASTER);
          if (count($accept) > 0) {
              $dbw->update('suggested_titles', array('st_patrolled' => 1), array('st_id' => $accept), __METHOD__);
          }
          if (count($reject) > 0) {
              $dbw->delete('suggested_titles', array('st_id' => $reject), __METHOD__);
          }
          foreach ($updates as $u => $v) {
              $t = Title::newFromText($v);
              if (!$t) {
                  continue;
              }
              // renames occassionally cause conflicts with existing requests, that's a bummer
              if (isset($newnames[$u])) {
                  $page = $dbr->selectField('page', array('page_id'), array('page_title' => $t->getDBKey()), __METHOD__);
                  if ($page) {
                      // wait, this article is already written, doh
                      $notify = $dbr->selectField('suggested_titles', array('st_notify'), array('st_id' => $u), __METHOD__);
                      if ($notify) {
                          $dbw->insert('suggested_notify', array('sn_page' => $page, 'sn_notify' => $notify, 'sn_timestamp' => wfTimestampNow(TS_MW)), __METHOD__);
                      }
                      $dbw->delete('suggested_titles', array('st_id' => $u), __METHOD__);
                  }
                  $id = $dbr->selectField('suggested_titles', array('st_id'), array('st_title' => $t->getDBKey()), __METHOD__);
                  if ($id) {
                      // well, it already exists... like the Highlander, there can be only one
                      $notify = $dbr->selectField('suggested_titles', array('st_notify'), array('st_id' => $u), __METHOD__);
                      if ($notify) {
                          // append the notify to the existing
                          $dbw->update('suggested_titles', array('st_notify = concat(st_notify, ' . $dbr->addQuotes("\n" . $notify) . ")"), array('st_id' => $id), __METHOD__);
                      }
                      // delete the old one
                      $dbw->delete('suggested_titles', array('st_id' => $u), __METHOD__);
                  }
              }
              $dbw->update('suggested_titles', array('st_title' => $t->getDBKey()), array('st_id' => $u), __METHOD__);
          }
          $wgOut->addHTML(count($accept) . " suggestions accepted, " . count($reject) . " suggestions rejected.");
      }
      $sql = "SELECT st_title, st_user_text, st_category, st_id\n\t\t\t\tFROM suggested_titles WHERE st_used=0\n\t\t\t\tAND st_patrolled=0 ORDER BY st_suggested DESC LIMIT {$offset}, {$limit}";
      $res = $dbr->query($sql, __METHOD__);
      $wgOut->addHTML("<br/><br/>\n\t\t\t\t<form action='/Special:ManageSuggestedTopics' method='POST' name='suggested_topics_manage'>\n\t\t\t\t<table class='suggested_titles_list wh_block'>\n\t\t\t\t<tr class='st_top_row'>\n\t\t\t\t<td class='st_title'>Article request</td>\n\t\t\t\t<td>Category</td>\n\t\t\t\t<td>Edit Title</td>\n\t\t\t\t<td>Requestor</td>\n\t\t\t\t<td>Accept</td>\n\t\t\t\t<td>Reject</td>\n\t\t\t</tr>\n\t\t\t");
      $count = 0;
      foreach ($res as $row) {
          $t = Title::newFromDBKey($row->st_title);
          if (!$t) {
              continue;
          }
          $c = "";
          if ($count % 2 == 1) {
              $c = "class='st_on'";
          }
          $u = User::newFromName($row->st_user_text);
          $wgOut->addHTML("<tr {$c}>\n\t\t\t\t\t<input type='hidden' name='st_newname_{$row->st_id}' value=''/>\n\t\t\t\t\t<td class='st_title_m' id='st_display_id_{$row->st_id}'>{$t->getText()}</td>\n\t\t\t\t\t<td>{$row->st_category}</td>\n\t\t\t\t\t<td><a href='' onclick='javascript:editSuggestion({$row->st_id}); return false;'>Edit</a></td>\n\t\t\t\t\t" . ($u ? "<td><a href='{$u->getUserPage()->getFullURL()}' target='new'>{$u->getName()}</a></td>" : "<td>{$row->st_user_text}</td>") . "<td class='st_radio'><input type='radio' name='ar_{$row->st_id}' value='accept'></td>\n\t\t\t\t\t<td class='st_radio'><input type='radio' name='ar_{$row->st_id}' value='reject'></td>\n\t\t\t\t</tr>");
          $count++;
      }
      $wgOut->addHTML("</table>\n\t\t\t<br/><br/>\n\t\t\t<table width='100%'><tr><td style='text-align:right;'><input type='submit' value='Submit' class='button secondary' /></td></tr></table>\n\t\t\t</form>\n\t\t\t");
  }
Example #24
0
function notifyRequester($article, $user, $user, $text, $summary)
{
    global $wgTitle, $wgRequest;
    $requested = $wgRequest->getVal('requested', null);
    if ($requested != null && $summary != "Request now answered.") {
        $actualTitleObj = Title::newFromDBKey("Request:" . $wgTitle->getDBKey());
        $actualkey = $wgTitle->getDBKey();
        if ($requested != $actualkey) {
            $ot = Title::newFromDBKey("Request:" . $requested);
            $nt = Title::newFromDBKey("Request:" . $actualkey);
            $error = $ot->moveTo($nt);
            if ($error !== true) {
                echo $error;
            }
            $actualTitleObj = $nt;
        }
        Request::notifyRequest($wgTitle, $actualTitleObj);
        // strip categories
        $at = new Article($actualTitleObj);
        $text = $at->getContent(true);
        //echo $t->getFullText();
        $text = ereg_replace("[\\[]+Category\\:([- ]*[.]?[a-zA-Z0-9_/-?&%])*[]]+", "", $text);
        $text .= "[[Category:Answered Requests]]";
        $at->updateArticle($text, "Request now answered.", true, false);
    }
    return true;
}
Example #25
0
 function getCategoryOptions($default = "")
 {
     global $wgUser;
     // only do this for logged in users
     $t = Title::newFromDBKey("WikiHow:" . wfMsg('requestcategories'));
     $r = Revision::newFromTitle($t);
     if (!$r) {
         return '';
     }
     $cat_array = split("\n", $r->getText());
     $s = "";
     foreach ($cat_array as $line) {
         $line = trim($line);
         if ($line == "" || strpos($line, "[[") === 0) {
             continue;
         }
         $tokens = split(":", $line);
         $val = "";
         $val = trim($tokens[sizeof($tokens) - 1]);
         $s .= "<OPTION VALUE=\"" . $val . "\">" . $line . "</OPTION>\n";
     }
     $s = str_replace("\"{$default}\"", "\"{$default}\" SELECTED", $s);
     return $s;
 }
 function writeOutput($par)
 {
     global $wgUser, $wgOut, $wgLang, $wgTitle, $wgMemc, $wgDBname;
     global $wgRequest, $wgSitename, $wgLanguageCode;
     global $wgFeedClasses, $wgFilterCallback, $wgWhitelistEdit, $wgParser;
     wfLoadExtensionMessages('Postcomment');
     $wgOut->setRobotpolicy("noindex,nofollow");
     $fname = "wfSpecialPostcomment";
     //echo "topic: " . $wgRequest->getVal("topic_name") . "<BR>";
     //echo "title: " . $wgRequest->getVal("title") . "<BR>";
     //echo "comment: " . $wgRequest->getVal("comment_text") . "<BR>";
     //echo "new_topic id " . $wgRequest->getVal("new_topic") . "<BR>";
     $target = !empty($par) ? $par : $wgRequest->getVal("target");
     $t = Title::newFromDBKey($target);
     $update = true;
     if (!$t || !$t->userCanEdit()) {
         return;
     }
     if (!$wgUser->isAllowed('edit')) {
         return;
     }
     if ($t == null) {
         $wgOut->errorPage('postcomment', 'postcomment_invalidrequest');
         return;
     }
     $article = new Article($t);
     $user = $wgUser->getName();
     $real_name = User::whoIsReal($wgUser->getID());
     if ($real_name == "") {
         $real_name = $user;
     }
     $dateStr = $wgLang->timeanddate(wfTimestampNow());
     $comment = $wgRequest->getVal("comment_text");
     foreach ($wgRequest->getValues() as $key => $value) {
         if (strpos($key, "comment_text") === 0) {
             $comment = $value;
             break;
         }
     }
     $topic = $wgRequest->getVal("topic_name");
     //echo "$dateStr<br/>";
     // remove leading space, tends to be a problem with a lot of talk page comments as it breaks the
     // HTML on the page
     $comment = preg_replace('/\\n[ ]*/', "\n", trim($comment));
     // Check to see if the user is also getting a thumbs up. If so, append the thumbs message and give a thumbs up
     if ($wgRequest->getVal('thumb')) {
         $comment .= "\n\n" . wfMsg('qn_thumbs_up');
         $userName = explode(":", $wgRequest->getVal('target'));
         ThumbsUp::quickNoteThumb($wgRequest->getVal('revold'), $wgRequest->getVal('revnew'), $wgRequest->getVal('pageid'), $userName[1]);
     }
     $formattedComment = wfMsg('postcomment_formatted_comment', $dateStr, $user, $real_name, $comment);
     if ($wgRequest->getVal('fromajax') == 'true') {
         $wgOut->setArticleBodyOnly(true);
     }
     $text = "";
     $r = Revision::newFromTitle($t);
     if ($r) {
         $text = $r->getText();
     }
     $text .= "\n\n{$formattedComment}\n\n";
     $wgOut->setStatusCode(500);
     //echo "updating with text:<br/> $text";
     //exit;
     $tmp = "";
     if ($wgUser->isBlocked()) {
         $wgOut->blockedPage();
         return;
     }
     if (!$wgUser->getID() && $wgWhitelistEdit) {
         $this->userNotLoggedInPage();
         return;
     }
     if (wfReadOnly()) {
         $wgOut->readOnlyPage();
         return;
     }
     if ($target == "Spam-Blacklist") {
         $wgOut->readOnlyPage();
         return;
     }
     if ($wgUser->pingLimiter()) {
         $wgOut->rateLimited();
         return;
     }
     if ($wgFilterCallback && $wgFilterCallback($t, $text, $tmp)) {
         # Error messages or other handling should be performed by the filter function
         return;
     }
     $matches = array();
     $preg = "/http:\\/\\/[^] \n'\">]*/";
     $mod = str_ireplace('http://www.wikihow.com', '', $comment);
     preg_match_all($preg, $mod, $matches);
     if (sizeof($matches[0]) > 2) {
         $wgOut->errorPage("postcomment", "postcomment_urls_limit");
         return;
     }
     if (trim(strip_tags($comment)) == "") {
         $wgOut->errorpage("postcomment", "postcomment_nopostingtoadd");
         return;
     }
     if (!$t->userCanEdit()) {
         $wgOut->errorpage("postcomment", "postcomment_discussionprotected");
         return;
     }
     $watch = false;
     if ($wgUser->getID() > 0) {
         $watch = $wgUser->isWatched($t);
     }
     $fc = new FancyCaptcha();
     $pass_captcha = $fc->passCaptcha();
     if (!$pass_captcha && $wgUser->getID() == 0) {
         $wgOut->addHTML("Sorry, please enter the correct word. Click <a onclick='window.location.reload(true);'>here</a> to get a new one.<br/><br/>");
         return;
     }
     $article->doEdit($text, "");
     if ($wgRequest->getVal('jsonresponse') == 'true') {
         $article->loadLastEdit(true);
         $this->revId = $article->getRevIdFetched();
     }
     //XX Vu added to notify users of usertalk updates
     if ($t->getNamespace() == NS_USER_TALK) {
         AuthorEmailNotification::notifyUserTalk($t->getArticleID(), $wgUser->getID(), $comment);
     }
     $wgOut->setStatusCode(200);
     if ($wgRequest->getVal('fromajax') == 'true') {
         $wgOut->redirect('');
         $wgTitle = $t;
         $formattedComment = $wgParser->preSaveTransform($formattedComment, $t, $wgUser, new ParserOptions());
         $wgOut->addHTML($wgOut->parse("\n" . $formattedComment));
         return;
     }
 }