Ejemplo n.º 1
0
 public function importArticles($filePath)
 {
     $row = 0;
     $tagMap = ConciergeTag::getTagMap();
     $newTags = array();
     if (($handle = fopen(&$filePath, "r")) !== FALSE) {
         while (($data = fgetcsv($handle, 10000000, "\t", '"')) !== FALSE) {
             if ($row != 0) {
                 list($pageId, $url, $userUrl, $tags, $completed) = $data;
                 $t = Title::newFromId($pageId);
                 if ($t && $t->exists()) {
                     $tags = explode(",", $tags);
                     foreach ($tags as $k => $tag) {
                         $tags[$k] = trim($tag);
                     }
                     $datum = array('t' => $t, 'userUrl' => $userUrl, 'tags' => $tags, 'completed' => $completed);
                     $newData[] = $datum;
                     $newTags = array_unique(array_merge($newTags, $this->getNewTags($tagMap, $tags)));
                 } else {
                     $this->debug("ERROR - No article found for: {$url}");
                 }
             }
             $row++;
         }
     }
     $this->addTags($newTags);
     $this->addArticles($newData);
     $this->addArticleTags($newData);
 }
Ejemplo n.º 2
0
 function logRestore($itemId, $low, $hi, $reason, $count)
 {
     $title = Title::newFromId($itemId);
     $params = array($itemId, $low, $hi);
     $log = new LogPage('accuracy', true);
     $log->addEntry($this->logType, $title, wfMsg('clearratings_logrestore', $reason, $title->getFullText(), $count), $params);
 }
 public function execute()
 {
     $this->println('Adding missing file links for attachments.');
     try {
         $dbr = \wfGetDB(DB_SLAVE);
         $res = $dbr->select('page_attachment_data', '*');
         if (!$res->numRows()) {
             $this->println('No attachments found.  No links added.');
             break;
         } else {
             foreach ($res as $row) {
                 $linkFromPageId = $row->attached_to_page_id;
                 $linkToFileId = $row->attachment_page_id;
                 $linkToFileTitle = \Title::newFromId($linkToFileId);
                 $linkToFileDatabaseKey = $linkToFileTitle->getDBkey();
                 if (!$this->isLinkExist($linkFromPageId, $linkToFileDatabaseKey)) {
                     $linkFromPageTitle = \Title::newFromId($linkFromPageId);
                     $linkToFileName = $linkToFileTitle->getText();
                     $this->println('Adding missing link from page [' . $linkFromPageTitle . '] to attachment file [' . $linkToFileName . ']');
                     $linkToFileWikiPage = \WikiPage::factory($linkToFileTitle);
                     $linkToFileWikiPage->doPurge();
                     $this->addLink($linkFromPageId, $linkToFileDatabaseKey);
                 }
             }
             $this->println('Finished adding file links.');
         }
     } catch (Exception $e) {
         $this->println('Failed to add file links.  Error: [' . $e->getMessage() . ']');
     }
 }
	public static function getCategoriesWithPSDefined(){
		$cat_titles = array();
		$dbr = wfGetDB( DB_SLAVE );
		//get the result set, query : select page_props
		$res = $dbr->select( 'page_props',
			array(
				'pp_page',
				'pp_propname',
				'pp_value'
			),
			array(
				'pp_propname' => 'PageSchema'
			)
		);
		while ( $row = $dbr->fetchRow( $res ) ) {
			if( $row[2] != null ){
				$page_id_cat = $row[0];
				if( Title::newFromId($page_id_cat)->getNamespace() == NS_CATEGORY){
					$cat_text = Title::newFromId($page_id_cat)->getText();
					$cat_titles[] = $cat_text;
				}
			}
		}
		$dbr->freeResult( $res );
		return $cat_titles;
	}
 /**
  * Show the special page
  *
  * @param $par Mixed: parameter passed to the page or null
  */
 public function execute($par)
 {
     global $wgUser, $wgOut, $wgRequest;
     // Check permissions
     if (!Link::canAdmin()) {
         $this->displayRestrictionError();
         return;
     }
     // Is the database locked or not?
     if (wfReadOnly()) {
         $wgOut->readOnlyPage();
         return false;
     }
     // No access for blocked users
     if ($wgUser->isBlocked()) {
         $wgOut->blockedPage(false);
         return false;
     }
     // Add CSS & JS
     $wgOut->addModules('ext.linkFilter');
     if ($wgRequest->wasPosted() && $_SESSION['alreadysubmitted'] == false) {
         $_SESSION['alreadysubmitted'] = true;
         // Update link
         $dbw = wfGetDB(DB_MASTER);
         $dbw->update('link', array('link_url' => $_POST['lf_URL'], 'link_description' => $_POST['lf_desc'], 'link_type' => intval($_POST['lf_type'])), array('link_page_id' => $wgRequest->getInt('id')), __METHOD__);
         $title = Title::newFromId($wgRequest->getInt('id'));
         $wgOut->redirect($title->getFullURL());
     } else {
         $wgOut->addHTML($this->displayEditForm());
     }
 }
Ejemplo n.º 6
0
 /**
  * Our query is on the whole revision table not just recent changes
  */
 private function getItems()
 {
     global $wgBlikiDefaultCat;
     $dbr = wfGetDB(DB_SLAVE);
     // Make the query condition and options
     $opts = array('ORDER BY' => 'rev_timestamp DESC');
     $cat = $this->params['q'] ?: $wgBlikiDefaultCat;
     $cat = Title::newFromText($cat, NS_CATEGORY)->getDBkey();
     $cond = array('page_id = rev_page', 'rev_deleted = 0', 'rev_parent_id = 0', 'cl_from = page_id', 'cl_to' => $cat);
     // Update the query condition and opts with the API params
     if ($this->params['from']) {
         $cond[] = 'rev_timestamp > ' . intval($this->params['from']);
     } elseif ($this->params['days']) {
         $cond[] = 'rev_timestamp > ' . $dbr->timestamp(time() - intval($this->params['days'] * 86400));
     }
     if ($this->params['limit']) {
         $opts['LIMIT'] = intval($this->params['limit']);
     }
     // Do the query
     $res = $dbr->select(array('page', 'revision', 'categorylinks'), 'page_id,rev_timestamp,rev_user_text', $cond, __METHOD__, $opts);
     // Build a list of feed items from the resulting article list
     $items = array();
     foreach ($res as $row) {
         $title = Title::newFromId($row->page_id);
         $items[] = new FeedItem($title->getPrefixedText(), $this->desc($title), $title->getFullUrl(), $row->rev_timestamp, $row->rev_user_text, '');
     }
     return $items;
 }
Ejemplo n.º 7
0
 /**
  * @param $id
  * @param int $flags
  *
  * @return null|Wall
  */
 public static function newFromId($id, $flags = 0)
 {
     $title = Title::newFromId($id, $flags);
     if (empty($title)) {
         return null;
     }
     return self::newFromTitle($title);
 }
 function executeGetData($articles)
 {
     foreach ($articles as $value) {
         $title = Title::newFromId($value);
         if (!empty($title) && ($img = wfFindFile($title))) {
             $this->addImagesList($title->getText(), $value, 1);
             $this->addToFiltredList($title->getText(), 1, $img->getWidth(), $img->getHeight(), $img->getMimeType());
         }
     }
 }
 function loadFromDb($articleIds)
 {
     foreach ($articleIds as $articleId) {
         $title = Title::newFromId($articleId);
         if (!empty($title) && ($img = wfFindFile($title))) {
             $this->addImage($title->getText(), $articleId, 1);
             $this->addImageDetails($title->getText(), 1, $img->getWidth(), $img->getHeight(), $img->getMimeType());
         }
     }
 }
 function formatResult($skin, $result)
 {
     global $wgContLang;
     $title = Title::newFromId($result->value);
     $dp = Title::makeTitle($result->namespace, $result->title);
     $from = $skin->makeKnownLinkObj($title, '');
     $edit = $skin->makeBrokenLinkObj($title, "(" . wfMsg("qbedit") . ")", 'redirect=no');
     $to = $skin->makeKnownLinkObj($dp, '');
     return "{$from} {$edit} => {$to}";
 }
 function formatResult($skin, $result)
 {
     global $wgContLang;
     $title = Title::newFromId($result->value);
     $dp = Title::makeTitle($result->namespace, $result->title);
     $from = $skin->makeKnownLinkObj($title, '');
     $edit = $skin->makeKnownLinkObj($title, "(" . wfMsgHtml("qbedit") . ")", 'redirect=no&action=edit');
     $arr = $wgContLang->getArrow();
     $to = $skin->makeKnownLinkObj($dp, '');
     return "{$from} {$edit} {$arr} {$to}";
 }
Ejemplo n.º 12
0
function printVideo($vidId, &$vidTitle, &$t)
{
    $dbr = wfGetDB(DB_SLAVE);
    $res = $dbr->select('templatelinks', array('tl_from'), array('tl_namespace' => NS_VIDEO, 'tl_title' => $t->getDBKey()), __METHOD__, array('LIMIT 1'));
    if ($row = $dbr->fetchObject($res)) {
        $nt = Title::newFromId($row->tl_from);
        if ($nt && $nt->exists()) {
            $day30 = Pagestats::get30day($row->tl_from, $dbr);
            echo "{$vidId}\t{$vidTitle}\thttp://www.wikihow.com" . $nt->getLocalUrl() . "\t{$day30}\n";
        }
    }
}
Ejemplo n.º 13
0
 private function addStatChangeAction($action, $feed, $user)
 {
     if (!$feed instanceof WallNotificationAdminEntity) {
         return false;
     }
     $title = Title::newFromId($feed->data->message_id);
     if (empty($title)) {
         return false;
     }
     $this->internalAdd($feed->data->user_wallowner_id, '', $feed->data->user_removing_id, '', $feed->data->is_reply, $feed->data->message_id, $title->getNamespace(), $feed->data->parent_id, $feed->data->title, $action, $feed->data->reason, null);
     return true;
 }
Ejemplo n.º 14
0
 public function spellCheckArticles(&$pageIds)
 {
     //$pageIds = array(15985);
     foreach ($pageIds as $pageId) {
         $t = Title::newFromId($pageId);
         if ($t && $t->exists()) {
             $misspellings = $this->spellCheckArticle($t);
             //var_dump($t->getText());
             //var_dump($misspellings);
             $this->updateTables($t, $misspellings);
         }
     }
 }
Ejemplo n.º 15
0
 private function addStatChangeAction($action, $feed)
 {
     if (!$feed instanceof WallNotificationAdminEntity) {
         return false;
     }
     $data = $feed->data;
     $title = Title::newFromId($data->message_id);
     if (empty($title)) {
         return false;
     }
     $this->internalAdd($data->parent_page_id, $data->user_removing_id, '', $data->is_reply, $data->message_id, $title->getNamespace(), $data->parent_id, $data->title, $action, $data->reason, null);
     $this->getDB(DB_MASTER)->update('wall_history', array('deleted_or_removed' => $action == WH_DELETE || $action == WH_REMOVE ? 1 : 0), array('comment_id' => $data->message_id), __METHOD__);
     return true;
 }
Ejemplo n.º 16
0
 /** 
  * Get the titles of stub articles
  */
 static function findStubs($limit = false)
 {
     $dbr = wfGetDB(DB_SLAVE);
     $options = array();
     if ($limit) {
         $options['LIMIT'] = $limit;
     }
     $res = $dbr->select('categorylinks', array('cl_from'), array('cl_to' => 'Stub'), __METHOD__, $options);
     $titles = array();
     foreach ($res as $row) {
         $t = Title::newFromId($row->cl_from);
         if ($t && $t->getNamespace() == 0 && $t->getText() && sizeof($t->getText()) > 0) {
             $titles[] = $t;
         }
     }
     return $titles;
 }
Ejemplo n.º 17
0
 public function execute()
 {
     $params = $this->extractRequestParams();
     $pageid = $params['pageid'];
     $user = $this->getUser();
     $this->dieOnBadUser($user);
     $title = \Title::newFromId($pageid);
     if (!$title) {
         $this->dieUsageMsg(array('nosuchpageid', $pageid));
     }
     $rater = new PageRating($pageid);
     $rater->rate($user, $params['score']);
     $data = array();
     $data['myscore'] = $params['score'];
     $data['rated'] = wfTimestamp(TS_MW);
     $data['numrating'] = $rater->getNumRating();
     $data['averagescore'] = $rater->getRating();
     $this->getResult()->addValue(null, $this->getModuleName(), $data);
     return true;
 }
 public static function ajaxSetResponsibleEditors($sParams)
 {
     $aParams = FormatJson::decode($sParams, true);
     $iArticleId = $aParams['articleId'];
     $aEditors = $aParams['editorIds'];
     ResponsibleEditors::deleteResponsibleEditorsFromCache($iArticleId);
     $oRequestedTitle = Title::newFromId($iArticleId);
     if (!$oRequestedTitle->userCan('responsibleeditors-changeresponsibility')) {
         return json_encode(array('success' => false, 'msg' => wfMessage('bs-responsibleeditors-error-ajax-not-allowed')->plain()));
     }
     $dbw = wfGetDB(DB_MASTER);
     $dbw->begin();
     $res = $dbw->select('bs_responsible_editors', 're_user_id', array('re_page_id' => $iArticleId));
     $aCurrentEditorIds = array();
     foreach ($res as $row) {
         $aCurrentEditorIds[] = $row->re_user_id;
     }
     $aRemovedEditorIds = array_diff($aCurrentEditorIds, $aEditors);
     $aNewEditorIds = array_diff($aEditors, $aCurrentEditorIds);
     $aUntouchedEditorIds = array_intersect($aCurrentEditorIds, $aEditors);
     if (!empty($aNewEditorIds) && BsConfig::get('MW::ResponsibleEditors::AddArticleToREWatchLists') == true) {
         foreach ($aNewEditorIds as $iUserId) {
             $oNewEditorUser = User::newFromId($iUserId);
             if (!$oNewEditorUser->isWatched($oRequestedTitle)) {
                 $oNewEditorUser->addWatch($oRequestedTitle);
             }
         }
     }
     //Remove all
     $dbw->delete('bs_responsible_editors', array('re_page_id' => $iArticleId));
     //Add all --> to maintain position! As log as re_position field is not used properly...
     $iPosition = 0;
     foreach ($aEditors as $iEditor) {
         $dbw->insert('bs_responsible_editors', array('re_page_id' => $iArticleId, 're_user_id' => $iEditor, 're_position' => $iPosition));
         $iPosition++;
     }
     $dbw->commit();
     self::notifyAffectedUsers($aNewEditorIds, $aRemovedEditorIds, $aUntouchedEditorIds, $iArticleId);
     $oRequestedTitle->invalidateCache();
     return FormatJson::encode(array('success' => true));
 }
Ejemplo n.º 19
0
 public static function isForum()
 {
     global $wgTitle;
     if ($wgTitle instanceof Title) {
         if ($wgTitle->isSpecial('Forum') || in_array($wgTitle->getNamespace(), self::$forumNamespaces)) {
             return true;
         } else {
             if ($wgTitle->getNamespace() === NS_USER_WALL_MESSAGE) {
                 $mainTitle = Title::newFromId($wgTitle->getText());
                 /*
                  * if we visit the thread using Thread:xxxxx url, $wgTitle's namespace is 1201 for both, wall and forum
                  * threads. But when we create new title from it using newFromId, we're able to distinguish those two
                  */
                 if ($mainTitle instanceof Title) {
                     return in_array($mainTitle->getNamespace(), self::$forumNamespaces);
                 }
             }
         }
     }
     return false;
 }
 /**
  * Load the deletion queue item for a given page.
  * @param $article Integer/Article Article object or article ID for the article in question.
  */
 static function newFromArticle($article)
 {
     if ($article instanceof Article) {
         // No need to do anything
     } elseif ($article instanceof Title) {
         $article = new Article($article);
     } elseif (!is_object($article)) {
         $article = new Article(Title::newFromId($article));
         // WTF? Why can't we load an article without a title?
     } else {
         throw new MWException("Bad argument to DeleteQueueItem constructor (" . gettype($article) . ")");
     }
     if (isset($article->mDeleteQueueItem) && $article->mDeleteQueueItem instanceof DeleteQueueItem) {
         return $article->mDeleteQueueItem;
     }
     $item = new DeleteQueueItem();
     $item->mArticle = $article;
     $item->mArticleID = $article->getId();
     $article->mDeleteQueueItem = $item;
     return $item;
 }
Ejemplo n.º 21
0
 private function loadReplyIdsFromDB($master = false)
 {
     // this is a direct way to get IDs
     // the other one is in Wall.class done in a grouped way
     // (fetch for many threads at once, set with ->setReplies)
     $title = Title::newFromId($this->mThreadId);
     if (empty($title)) {
         $title = Title::newFromId($this->mThreadId, Title::GAID_FOR_UPDATE);
     }
     if (empty($title)) {
         return;
     }
     $dbr = wfGetDB($master ? DB_MASTER : DB_SLAVE);
     $threadId = $title->getArticleID();
     $result = $dbr->select(array('comments_index'), array('distinct comment_id'), array('parent_comment_id = ' . $threadId), __METHOD__, array('ORDER BY' => 'comment_id ASC'));
     $list = array();
     while ($row = $dbr->fetchObject($result)) {
         $list[] = $row->comment_id;
     }
     $this->setReplies($list);
 }
 /** 
  * 
  */
 public function execute()
 {
     global $wgOut, $wgUser, $wgRequest;
     $userGroups = $wgUser->getGroups();
     if (!in_array('staff', $userGroups)) {
         $wgOut->setRobotpolicy('noindex,nofollow');
         $wgOut->showErrorPage('nosuchspecialpage', 'nospecialpagetext');
         return;
     }
     $userId = $wgRequest->getVal('user_id', '');
     $pageId = $wgRequest->getVal('page_id', '');
     if ($userId && $pageId) {
         $user = User::newFromId($userId);
         $title = Title::newFromId($pageId);
         if ($user && $title) {
             $wgOut->setArticleBodyOnly(true);
             $wgOut->addHTML($this->showReasons($user, $title));
         }
     } else {
         $wgOut->setArticleBodyOnly(true);
         $wgOut->addHTML($this->showUsers());
     }
 }
 /**
  * @deprecated legacy entry point for cached JS requests
  */
 public function checkData()
 {
     $articleId = $this->getVal('articleId');
     $title = Title::newFromId($articleId);
     if (empty($articleId) || empty($title)) {
         $this->replace = false;
         $this->articleId = $articleId;
         return;
     }
     $messages = RelatedForumDiscussionController::getData($articleId);
     $timediff = time() - $messages['lastupdate'];
     $this->lastupdate = $messages['lastupdate'];
     $this->timediff = $timediff;
     unset($messages['lastupdate']);
     if ($timediff < 24 * 60 * 60) {
         $this->replace = true;
         $this->html = $this->app->renderView("RelatedForumDiscussion", "relatedForumDiscussion", array('messages' => $messages));
     } else {
         $this->replace = false;
         $this->html = '';
     }
     $this->response->setFormat(WikiaResponse::FORMAT_JSON);
     $this->response->setCacheValidity(6 * 60 * 60, WikiaResponse::CACHE_DISABLED);
 }
 public static function loadRecommendations($filename)
 {
     $f = fopen($filename, "r");
     while (!feof($f)) {
         $l = fgets($f);
         $l = chop($l);
         $s = preg_split("@\t@", $l);
         if (sizeof($s) >= 3) {
             $u = User::newFromName($s[0]);
             $t = Title::newFromId($s[1]);
             $score = intVal($s[2]);
             if ($u && $t && $score) {
                 RecommendationPresenter::addRecommendation($u, $t, $score);
                 if (sizeof($s) > 3) {
                     $n = 3;
                     while ($n < sizeof($s)) {
                         RecommendationPresenter::addRecommendationReason($u, $t, intVal($s[$n]));
                         $n++;
                     }
                 }
             }
         }
     }
 }
<?php

require_once 'commandLine.inc';
require_once "{$IP}/extensions/wikihow/titus/Titus.class.php";
require_once "{$IP}/extensions/wikihow/DatabaseHelper.class.php";
$dbw = DatabaseBase::factory('mysql');
$dbw->open(TITUS_DB_HOST, WH_DATABASE_MAINTENANCE_USER, WH_DATABASE_MAINTENANCE_PASSWORD, TitusDB::getDBName());
$rows = DatabaseHelper::batchSelect('titus_intl', 'ti_page_id', array('ti_language_code' => $wgLanguageCode), __METHOD__, array(), 2000, $dbw);
$deletedPageIds = array();
foreach ($rows as $row) {
    $t = Title::newFromId($row->ti_page_id);
    if (!($t && $t->exists() && $t->getNamespace() == NS_MAIN)) {
        $deletedPageIds[] = $row->ti_page_id;
    }
}
$chunks = array_chunk($deletedPageIds, 500);
foreach ($chunks as $chunk) {
    $aids = "(" . implode(",", $chunk) . ")";
    $sql = "DELETE FROM titus_intl where ti_page_id IN {$aids} AND ti_language_code='{$wgLanguageCode}'";
    var_dump($sql);
    $dbw->query($sql);
}
Ejemplo n.º 26
0
 /**
  * Move tracked text in a given page
  */
 function doPage($pageId)
 {
     $title = Title::newFromId($pageId);
     if ($title) {
         $titleText = $title->getPrefixedText();
     } else {
         $titleText = '[deleted]';
     }
     $dbr = wfGetDB(DB_SLAVE);
     // Finish any incomplete transactions
     if (!$this->copyOnly) {
         $this->finishIncompleteMoves(array('bt_page' => $pageId));
         $this->syncDBs();
     }
     $startId = 0;
     $trx = new CgzCopyTransaction($this, $this->pageBlobClass);
     while (true) {
         $res = $dbr->select(array('blob_tracking', 'text'), '*', array('bt_page' => $pageId, 'bt_text_id > ' . $dbr->addQuotes($startId), 'bt_moved' => 0, 'bt_new_url IS NULL', 'bt_text_id=old_id'), __METHOD__, array('ORDER BY' => 'bt_text_id', 'LIMIT' => $this->batchSize));
         if (!$res->numRows()) {
             break;
         }
         $lastTextId = 0;
         foreach ($res as $row) {
             if ($lastTextId == $row->bt_text_id) {
                 // Duplicate (null edit)
                 continue;
             }
             $lastTextId = $row->bt_text_id;
             // Load the text
             $text = Revision::getRevisionText($row);
             if ($text === false) {
                 $this->critical("Error loading {$row->bt_rev_id}/{$row->bt_text_id}");
                 continue;
             }
             // Queue it
             if (!$trx->addItem($text, $row->bt_text_id)) {
                 $this->debug("{$titleText}: committing blob with " . $trx->getSize() . " items");
                 $trx->commit();
                 $trx = new CgzCopyTransaction($this, $this->pageBlobClass);
                 $this->waitForSlaves();
             }
         }
         $startId = $row->bt_text_id;
     }
     $this->debug("{$titleText}: committing blob with " . $trx->getSize() . " items");
     $trx->commit();
 }
Ejemplo n.º 27
0
 function getLastArticle($userName)
 {
     global $wgUser;
     $lastArticle = null;
     $res = ProfileBox::fetchEditedData($userName, 1);
     foreach ($res as $row) {
         $t = Title::newFromId($row->page_id);
         if ($t && $t->exists()) {
             $lastArticle = '[[' . $t->getFullText() . ']]';
         }
     }
     return $lastArticle;
 }
Ejemplo n.º 28
0
 /**
  * 
  * get list of article titles releated to messages
  * 
  * @param array $messageId
  */
 function getMessagesRelatedArticleTitles($messageIds, $orderBy = 'order_index')
 {
     wfProfileIn(__METHOD__);
     $ids = $this->getMessagesRelatedArticleIds($messageIds, $orderBy);
     $titles = array();
     foreach ($ids as $val) {
         $title = Title::newFromId($val);
         if (!empty($title)) {
             $titles[] = $title;
         }
     }
     wfProfileOut(__METHOD__);
     return $titles;
 }
 /**
  * Mostly copied from SpecialProtectedPages
  *
  * @param string $field
  * @param string $value
  * @return string
  * @throws MWException
  */
 function formatValue($field, $value)
 {
     /** @var $row object */
     $row = $this->mCurrentRow;
     $title = Title::newFromId($row->id);
     $pageLink = Linker::link($title);
     switch ($field) {
         case 'id':
             $formatted = $pageLink;
             break;
         case 'rev_id':
             if ($value === null) {
                 $formatted = 'לא אושר אף פעם';
             } else {
                 $formatted = $row->rev_id === $row->latest_id ? 'מאושר' : 'לא מאושר ' . $this->getDiffLink($title, $row->latest_id, $row->rev_id);
             }
             break;
         case 'ap_review_timestamp':
             $formatted = $row->rev_id === $row->latest_id ? $formatted = $this->getLanguage()->userTimeAndDate($value, $this->getUser()) : '-';
             break;
         default:
             $formatted = $value;
     }
     return $formatted;
 }
Ejemplo n.º 30
0
 public function execute()
 {
     $action = $this->getMain()->getVal('type');
     $page = $this->getMain()->getVal('pageid');
     try {
         // If post is set, get the post object by id
         // By fetching the post object, we also validate the id
         $postList = $this->getMain()->getVal('postid');
         $postList = $this->parsePostList($postList);
         switch ($action) {
             case 'list':
                 if (!$page) {
                     $this->dieNoParam('pageid');
                 }
                 $this->getResult()->addValue(null, $this->getModuleName(), $this->fetchPosts($page));
                 break;
             case 'like':
                 if (!$postList) {
                     $this->dieNoParam('postid');
                 }
                 foreach ($postList as $post) {
                     $post->setUserAttitude($this->getUser(), Post::ATTITUDE_LIKE);
                 }
                 $this->getResult()->addValue(null, $this->getModuleName(), '');
                 break;
             case 'dislike':
                 if (!$postList) {
                     $this->dieNoParam('postid');
                 }
                 foreach ($postList as $post) {
                     $post->setUserAttitude($this->getUser(), Post::ATTITUDE_NORMAL);
                 }
                 $this->getResult()->addValue(null, $this->getModuleName(), '');
                 break;
             case 'report':
                 if (!$postList) {
                     $this->dieNoParam('postid');
                 }
                 foreach ($postList as $post) {
                     $post->setUserAttitude($this->getUser(), Post::ATTITUDE_REPORT);
                 }
                 $this->getResult()->addValue(null, $this->getModuleName(), '');
                 break;
             case 'delete':
                 if (!$postList) {
                     $this->dieNoParam('postid');
                 }
                 foreach ($postList as $post) {
                     $post->delete($this->getUser());
                 }
                 $this->getResult()->addValue(null, $this->getModuleName(), '');
                 break;
             case 'recover':
                 if (!$postList) {
                     $this->dieNoParam('postid');
                 }
                 foreach ($postList as $post) {
                     $post->recover($this->getUser());
                 }
                 $this->getResult()->addValue(null, $this->getModuleName(), '');
                 break;
             case 'erase':
                 if (!$postList) {
                     $this->dieNoParam('postid');
                 }
                 foreach ($postList as $post) {
                     $post->erase($this->getUser());
                 }
                 $this->getResult()->addValue(null, $this->getModuleName(), '');
                 break;
             case 'post':
                 if (!$page) {
                     $this->dieNoParam('pageid');
                 }
                 $text = $this->getMain()->getVal('content');
                 if (!$text) {
                     $this->dieNoParam('content');
                 }
                 // Permission check
                 Post::checkIfCanPost($this->getUser());
                 $spam = !SpamFilter::validate($text);
                 // Parse as wikitext if specified
                 if ($this->getMain()->getCheck('wikitext')) {
                     $parser = new \Parser();
                     $opt = new \ParserOptions($this->getUser());
                     $opt->setEditSection(false);
                     $output = $parser->parse($text, \Title::newFromId($page), $opt);
                     $text = $output->getText();
                     unset($parser);
                     unset($opt);
                     unset($output);
                 }
                 $data = array('id' => null, 'pageid' => $page, 'userid' => $this->getUser()->getId(), 'username' => $this->getUser()->getName(), 'text' => $text, 'parentid' => count($postList) ? $postList[0]->id : null, 'status' => $spam ? Post::STATUS_SPAM : Post::STATUS_NORMAL, 'like' => 0, 'report' => 0);
                 $postObject = new Post($data);
                 global $wgMaxNestLevel;
                 // Restrict max nest level
                 if ($postObject->getNestLevel() > $wgMaxNestLevel) {
                     $postObject->parentid = $postObject->getParent()->parentid;
                     $postObject->parent = $postObject->getParent()->parent;
                 }
                 $postObject->post();
                 if ($spam) {
                     global $wgTriggerFlowThreadHooks;
                     if ($wgTriggerFlowThreadHooks) {
                         \Hooks::run('FlowThreadSpammed', array($postObject));
                     }
                 }
                 $this->getResult()->addValue(null, $this->getModuleName(), '');
                 break;
             default:
                 $this->dieUsage("Unrecognized value for parameter 'type': {$action}", 'unknown_type');
         }
     } catch (\UsageException $e) {
         throw $e;
     } catch (\Exception $e) {
         $this->getResult()->addValue("error", 'code', 'unknown_error');
         $this->getResult()->addValue("error", 'info', $e->getMessage());
     }
     return true;
 }