User: Admin Date: 21.02.2015 Time: 13:26
Example #1
0
    /**
     * Log article related event.
     *
     * @param Article $p_article
     * @param string $p_text
     * @param int $p_userId
     * @param int $p_eventId
     * @param bool $p_short
     *
     * @return void
     */
    public static function ArticleMessage(Article $p_article, $p_text, $p_userId = NULL, $p_eventId = 0, $p_short = FALSE)
    {
        ob_start();

        echo getGS('Article'), ': ', $p_article->getTitle();

        if (!$p_short) { // add publication, issue, section
            echo ' (';
            echo getGS('Publication'), ': ', $p_article->getPublicationId();
            echo ', ';
            echo getGS('Issue'), ': ', $p_article->getIssueNumber();
            echo ', ';
            echo getGS('Section'), ': ', $p_article->getSectionNumber();
            echo ")\n";
        }

        // generate url
        $url = ShortURL::GetURL($p_article->getPublicationId(),
            $p_article->getLanguageId(),
            $p_article->getIssueNumber(),
            $p_article->getSectionNumber(),
            $p_article->getArticleNumber());
        if (strpos($url, 'http') !== FALSE) { // no url for deleted
            echo getGS('Article URL'), ': ', $url, "\n";
        }

        echo getGS('Article Number'), ': ', $p_article->getArticleNumber(), "\n";
        echo getGS('Language'), ': ', $p_article->getLanguageName(), "\n";

        echo "\n";
        echo getGS('Action') . ': ', $p_text;

        $message = ob_get_clean();
        self::Message($message, $p_userId, $p_eventId);
    }
 function convert($newFormat, $pageName, $calName, $redirect, $go)
 {
     $search = "{$pageName}/{$calName}";
     $pages = PrefixSearch::titleSearch($search, 1000000);
     //search upto 1,000,000 events (no performace issue)
     $count = $erroredCount = 0;
     foreach ($pages as $page) {
         $retval = false;
         $newPage = $this->convertToNewPage($page, $newFormat);
         $article = new Article(Title::newFromText($page));
         if ($newPage != '') {
             $fromTitle = Title::newFromText($page);
             $toTitle = Title::newFromText($newPage);
             $articleNew = new Article(Title::newFromText($newPage));
             if (!$article->isRedirect() && !$articleNew->exists()) {
                 if ($go) {
                     $retval = $fromTitle->moveTo($toTitle, true, 'CalendarConversion', $redirect);
                 } else {
                     if ($count < 10) {
                         $testRun .= '&nbsp;&nbsp;' . $page . '  &rarr;&rarr;  ' . $newPage . '<br>';
                     }
                 }
             }
         }
     }
     unset($pages);
     if ($go) {
         $ret = "Conversion completed.";
     } else {
         $ret = "<b>Test Results, add '<i>go</i>' to the <i>dateConverter</i> tag to convert:</b><br>{$testRun}";
     }
     return $ret;
 }
 public static function deleteArticle($id)
 {
     if (isset($id)) {
         $article = new Article($id);
         $article->delete();
     }
 }
 function execute()
 {
     global $wgRequest, $wgOut, $wgUser, $wgArticle;
     $sitting_of = $wgRequest->getVal('sitting_of');
     $session_number = $wgRequest->getVal('session_number');
     $sitting_start_date_time = $wgRequest->getVal('sitting_start_date_and_time');
     $sitting_end_date_time = $wgRequest->getVal('sitting_end_date_and_time');
     $sitting_session_number = $wgRequest->getVal('sitting_session_number');
     $wpEditToken = $wgRequest->getVal('wpEditToken');
     $sitting_desc = $wgRequest->getVal('sitting_desc');
     $sitting_start_date = substr($sitting_start_date_time, 0, strpos($sitting_start_date_time, ' '));
     $sitting_start_time = substr($sitting_start_date_time, strpos($sitting_start_date_time, ' ') + 1);
     $sitting_end_date = substr($sitting_end_date_time, 0, strpos($sitting_end_date_time, ' '));
     $sitting_end_time = substr($sitting_end_date_time, strpos($sitting_end_date_time, ' ') + 1);
     $sitting_name = $sitting_of . '-' . $sitting_start_date;
     //$sitting_of.'-'.$sitting_start_date_time.'-'
     $title = Title::newFromText($sitting_name, MV_NS_SITTING);
     $wgArticle = new Article($title);
     $wgArticle->doEdit($sitting_desc, wfMsg('mv_summary_add_sitting'));
     $dbkey = $title->getDBKey();
     $sitting = new MV_Sitting(array('name' => $dbkey, 'start_date' => $sitting_start_date, 'start_time' => $sitting_start_time, 'end_date' => $sitting_end_date, 'end_time' => $sitting_end_time));
     //$sitting->db_load_sitting();
     //$sitting->db_load_streams();
     if ($sitting->insertSitting()) {
         if ($wgArticle->exists()) {
             $wgOut->redirect($title->getLocalURL("action=staff"));
         } else {
             $html .= 'Article ' . $sitting_name . ' does not exist';
             $wgOut->addHtml($html);
         }
     } else {
         $WgOut->addHTML('Error: Duplicate Sitting Name?');
     }
 }
Example #5
0
 /**
  * Run a createPage job
  * @return boolean success
  */
 function run()
 {
     if (is_null($this->title)) {
         $this->error = "createPage: Invalid title";
         return false;
     }
     $article = new Article($this->title, 0);
     if (!$article) {
         $this->error = 'createPage: Article not found "' . $this->title->getPrefixedDBkey() . '"';
         return false;
     }
     $page_text = $this->params['page_text'];
     // change global $wgUser variable to the one
     // specified by the job only for the extent of this
     // replacement
     global $wgUser;
     $actual_user = $wgUser;
     $wgUser = User::newFromId($this->params['user_id']);
     $edit_summary = '';
     if (array_key_exists('edit_summary', $this->params)) {
         $edit_summary = $this->params['edit_summary'];
     }
     $article->doEdit($page_text, $edit_summary);
     $wgUser = $actual_user;
     return true;
 }
Example #6
0
 public function generateFeed()
 {
     $articles = $this->getArticles();
     $feed = Feed::make();
     // set your feed's title, description, link, pubdate and language
     $feed->title = 'cnBeta1';
     $feed->description = '一个干净、现代、开放的cnBeta';
     $feed->logo = 'http://cnbeta1.com/assets/img/cnbeta1.png';
     $feed->link = URL::to('feed');
     $feed->pubdate = $articles[0]['date'];
     $feed->lang = 'zh-cn';
     foreach ($articles as $article) {
         $articleModel = new Article($article['article_id']);
         try {
             $articleModel->load();
         } catch (Exception $ex) {
             Log::error('feed: fail to fetch article: ' . $article['article_id'] . ', error: ' . $ex->getMessage());
         }
         $content = $article['intro'];
         $content .= $articleModel->data['content'] ? $articleModel->data['content'] : '';
         // set item's title, author, url, pubdate, description and content
         $feed->add($article['title'], 'cnBeta1', URL::to($article['article_id']), $article['date'], $content, $content);
     }
     $this->data = $feed->render('atom', -1);
     $this->saveToCache();
 }
 public function testGetsReadableMetaData()
 {
     $article = new Article();
     $article->title = 'My first Article';
     $article->author = 'Huang Yu Kai';
     $this->assertEquals('"My first Article" was written by Huang Yu Kai', $article->meta());
 }
Example #8
0
 public function execute()
 {
     $params = $this->extractRequestParams();
     $titleObj = null;
     if (!isset($params['title'])) {
         $this->dieUsageMsg(array('missingparam', 'title'));
     }
     if (!isset($params['user'])) {
         $this->dieUsageMsg(array('missingparam', 'user'));
     }
     $titleObj = Title::newFromText($params['title']);
     if (!$titleObj) {
         $this->dieUsageMsg(array('invalidtitle', $params['title']));
     }
     if (!$titleObj->exists()) {
         $this->dieUsageMsg(array('notanarticle'));
     }
     // We need to be able to revert IPs, but getCanonicalName rejects them
     $username = User::isIP($params['user']) ? $params['user'] : User::getCanonicalName($params['user']);
     if (!$username) {
         $this->dieUsageMsg(array('invaliduser', $params['user']));
     }
     $articleObj = new Article($titleObj);
     $summary = isset($params['summary']) ? $params['summary'] : "";
     $details = null;
     $retval = $articleObj->doRollback($username, $summary, $params['token'], $params['markbot'], $details);
     if ($retval) {
         // We don't care about multiple errors, just report one of them
         $this->dieUsageMsg(reset($retval));
     }
     $info = array('title' => $titleObj->getPrefixedText(), 'pageid' => intval($details['current']->getPage()), 'summary' => $details['summary'], 'revid' => intval($details['newid']), 'old_revid' => intval($details['current']->getID()), 'last_revid' => intval($details['target']->getID()));
     $this->getResult()->addValue(null, $this->getModuleName(), $info);
 }
 /**
  * Hook entry when article is change
  *
  * @param Article $article
  */
 public static function onArticleSaveComplete(&$article, &$user, $text, $summary, $minoredit, $watchthis, $sectionanchor, &$flags, $revision, &$status, $baseRevId, &$redirect)
 {
     $title = $article->getTitle();
     $ce = new CategoryExhibitionSection(null);
     $ce->setTouched($title);
     return true;
 }
Example #10
0
 /**
  * 文章添加
  */
 public function actionCreate()
 {
     $model = new Article();
     $addonarticle = new Addonarticle();
     if (isset($_POST['Article'])) {
         $transaction = Yii::app()->db->beginTransaction();
         try {
             $model->attributes = $_POST['Article'];
             if (!$model->save()) {
                 Tool::logger('article', var_export($model->getErrors(), true));
                 throw new CException('文章生成失败');
             }
             $aid = $model->primaryKey;
             $addonarticle->attributes = $_POST['Addonarticle'];
             if (!$addonarticle->save()) {
                 Tool::logger('article', var_export($addonarticle->getErrors(), true));
                 throw new CException('文章附表生成失败');
             }
             $this->redirect(array('list'));
         } catch (Exception $e) {
             Tool::logger('article', $e->getMessage());
             $transaction->rollback();
         }
     }
     $this->render('create', array('model' => $model, 'addonarticle' => $addonarticle));
 }
 /**
  * Show the special page
  *
  * @param $par Mixed: parameter passed to the page or null
  */
 public function execute($par)
 {
     global $wgOut, $wgUser, $wgRequest;
     // Set page title and other stuff
     $this->setHeaders();
     # Show a message if the database is in read-only mode
     if (wfReadOnly()) {
         $wgOut->readOnlyPage();
         return;
     }
     # If user is blocked, s/he doesn't need to access this page
     if ($wgUser->isBlocked()) {
         throw new UserBlockedError($this->getUser()->mBlock);
     }
     $title = $wgRequest->getVal('wpTitle');
     $category = $wgRequest->getVal('wpCategory');
     if (empty($title) || empty($category)) {
         return;
     }
     $oTitle = Title::newFromText($title);
     if (!is_object($oTitle)) {
         return;
     }
     $oArticle = new Article($oTitle);
     if ($oTitle->exists()) {
         $text = $oArticle->getContent();
     } else {
         $text = self::getCreateplate($category);
     }
     $text .= "\n[[Category:" . $category . ']]';
     $oArticle->doEdit($text, wfMsgForContent('createincategory-comment', $category));
     $wgOut->redirect($oTitle->getFullUrl());
 }
 function newAttachmentData($id)
 {
     $obj = $this->cacheManager->retrieveAtachmentData($id);
     if ($obj instanceof \PageAttachment\Attachment\AttachmentData) {
         $pageAttachmentData = $obj;
     } else {
         $title = \Title::newFromID($id);
         $article = new \Article($title, NS_FILE);
         $file = \wfFindFile($title);
         $size = $file->getSize();
         $description = $this->replaceHtmlTags($file->getDescriptionText());
         $dateUploaded = $article->getTimestamp();
         $uploadedBy = null;
         if ($this->runtimeConfig->isShowUserRealName()) {
             $uploadedBy = \User::whoIsReal($article->getUser());
         }
         if ($uploadedBy == null) {
             $uploadedBy = \User::whoIs($article->getUser());
         }
         $attachedToPages = null;
         if ($this->securityManager->isRemoveAttachmentPermanentlyEnabled()) {
             $attachedToPages = $this->getAttachedToPages($id);
         }
         $pageAttachmentData = new AttachmentData($id, $title, $size, $description, $dateUploaded, $uploadedBy, $attachedToPages);
         $this->cacheManager->storeAttachmentData($pageAttachmentData);
     }
     return $pageAttachmentData;
 }
 /**
  * Returns percentile quality of articleId or null if not found
  * @return int|null
  */
 public function getArticleQuality()
 {
     $cacheKey = wfMemcKey(__CLASS__, self::CACHE_BUSTER, $this->articleId);
     $percentile = $this->app->wg->Memc->get($cacheKey);
     if ($percentile === false) {
         $title = Title::newFromID($this->articleId);
         if ($title === null) {
             return null;
         }
         $article = new Article($title);
         $parserOutput = $article->getParserOutput();
         if (!$parserOutput) {
             //MAIN-3592
             $this->error(__METHOD__, ['message' => 'Article::getParserOutput returned false', 'articleId' => $this->articleId]);
             return null;
         }
         $inputs = ['outbound' => 0, 'inbound' => 0, 'length' => 0, 'sections' => 0, 'images' => 0];
         /**
          *  $title->getLinksTo() and  $title->getLinksFrom() function are
          * too expensive to call it here as we want only the number of links
          */
         $inputs['outbound'] = $this->countOutboundLinks($this->articleId);
         $inputs['inbound'] = $this->countInboundLinks($this->articleId);
         $inputs['sections'] = count($parserOutput->getSections());
         $inputs['images'] = count($parserOutput->getImages());
         $inputs['length'] = $this->getCharsCountFromHTML($parserOutput->getText());
         $quality = $this->computeFormula($inputs);
         $percentile = $this->searchPercentile($quality);
         $this->app->wg->Memc->set($cacheKey, $percentile, self::MEMC_CACHE_TIME);
     }
     return $percentile;
 }
 function getContent()
 {
     $err_msg = $_SESSION['LOGIN_RESULT'];
     $_SESSION['LOGIN_RESULT'] = "";
     $p = array();
     $d = new News($this->db_conn);
     //$d->debug = 1;
     $limit_str = " LIMIT 0, 5";
     $p['news_type'] = 1;
     $lists1 = $d->getListArray($p, $limit_str);
     $p['news_type'] = 2;
     $lists2 = $d->getListArray($p, $limit_str);
     $a = new Article($this->db_conn);
     $p['article_type'] = 1;
     $art1 = $a->getListArray($p, " LIMIT 0, 1");
     $p['article_type'] = 2;
     $art2 = $a->getListArray($p, " LIMIT 0, 1");
     $this->assign('data', $d);
     $this->assign('lists1', $lists1);
     $this->assign('lists2', $lists2);
     $this->assign('art1', $art1[0]);
     $this->assign('art2', $art2[0]);
     $this->assign('errmsg', $err_msg);
     //$this->assign('content_page', $this->template.$this->list_tpl);
 }
	/**
	 * Run a pageSchemasCreatePage job
	 * @return boolean success
	 */
	function run() {
		wfProfileIn( __METHOD__ );

		if ( is_null( $this->title ) ) {
			$this->error = "pageSchemasCreatePage: Invalid title";
			wfProfileOut( __METHOD__ );
			return false;
		}
		$article = new Article( $this->title );
		if ( !$article ) {
			$this->error = 'pageSchemasCreatePage: Article not found "' . $this->title->getPrefixedDBkey() . '"';
			wfProfileOut( __METHOD__ );
			return false;
		}

		$page_text = $this->params['page_text'];
		// change global $wgUser variable to the one
		// specified by the job only for the extent of this
		// replacement
		global $wgUser;
		$actual_user = $wgUser;
		$wgUser = User::newFromId( $this->params['user_id'] );
		$edit_summary = wfMsgForContent( 'ps-generatepages-editsummary' );
		$article->doEdit( $page_text, $edit_summary );
		$wgUser = $actual_user;
		wfProfileOut( __METHOD__ );
		return true;
	}
function createPost($info, $subject, $super = null)
{
    $userName = $info['user'];
    if (strpos($userName, '#') !== false) {
        $pos = strpos($userName, '#');
        $userName = substr($userName, 0, $pos);
    }
    $user = User::newFromName($userName, false);
    if (!$user) {
        throw new MWException("Username " . $info['user'] . " is invalid.");
    }
    global $article;
    if ($super) {
        $title = Threads::newReplyTitle($super, $user);
    } else {
        $title = Threads::newThreadTitle($subject, $article);
    }
    print "Creating thread {$title} as a subthread of " . ($super ? $super->title() : 'none') . "\n";
    $root = new Article($title);
    $root->doEdit($info['content'], 'Imported from JSON', EDIT_NEW, false, $user);
    $t = LqtView::postEditUpdates($super ? 'reply' : 'new', $super, $root, $article, $subject, 'Imported from JSON', null);
    $t = Threads::withId($t->id());
    // Some weirdness.
    return $t;
}
Example #17
0
 /**
  * A naive wrapper for \WikiPage::doEdit().
  */
 public function edit()
 {
     $responseData = new \StdClass();
     $responseData->success = false;
     $responseData->title = null;
     $responseData->text = null;
     $responseData->summary = null;
     $responseData->user_id = 0;
     $responseData->user_name = null;
     $this->response->setFormat('json');
     $this->response->setCacheValidity(\WikiaResponse::CACHE_DISABLED);
     if ($this->getVal('secret') != $this->wg->TheSchwartzSecretToken || !$this->request->wasPosted()) {
         $this->response->setVal('data', $responseData);
         return;
     }
     $titleText = $this->getVal('title');
     $responseData->title = $titleText;
     $title = \Title::newFromText($titleText);
     \Wikia\Util\Assert::true($title instanceof \Title);
     $article = new \Article($title);
     \Wikia\Util\Assert::true($article instanceof \Article);
     $text = $this->getVal('text');
     $responseData->text = $text;
     $summary = $this->getVal('summary');
     $responseData->summary = $summary;
     if ($this->wg->User->isLoggedIn()) {
         $responseData->user_id = $this->wg->User->getId();
         $responseData->user_name = $this->wg->User->getName();
         $responseData->success = $article->doEdit($text, $summary)->isOK();
     }
     $this->response->setVal('data', $responseData);
 }
 /**
  * Create category.
  *
  * @param $category String: Name of category to create.
  * @param $code String: Code of language that the category is for.
  * @param $level String: Level that the category is for.
  */
 public static function create($category, $code, $level = null)
 {
     $category = strip_tags($category);
     $title = Title::makeTitleSafe(NS_CATEGORY, $category);
     if ($title === null || $title->exists()) {
         return;
     }
     global $wgLanguageCode;
     $language = BabelLanguageCodes::getName($code, $wgLanguageCode);
     if ($level === null) {
         $text = wfMsgForContent('babel-autocreate-text-main', $language, $code);
     } else {
         $text = wfMsgForContent('babel-autocreate-text-levels', $level, $language, $code);
     }
     $user = self::user();
     # Do not add a message if the username is invalid or if the account that adds it, is blocked
     if (!$user || $user->isBlocked()) {
         return;
     }
     if (!$title->quickUserCan('create', $user)) {
         return;
         # The Babel AutoCreate account is not allowed to create the page
     }
     /* $article->doEdit will call $wgParser->parse.
      * Calling Parser::parse recursively is baaaadd... (bug 29245)
      * @todo FIXME: surely there is a better way?
      */
     global $wgParser, $wgParserConf;
     $oldParser = $wgParser;
     $parserClass = $wgParserConf['class'];
     $wgParser = new $parserClass($wgParserConf);
     $article = new Article($title, 0);
     $article->doEdit($text, wfMsgForContent('babel-autocreate-reason', wfMsgForContent('babel-url')), EDIT_FORCE_BOT, false, $user);
     $wgParser = $oldParser;
 }
Example #19
0
 public function index($year = null)
 {
     $Article = new Article();
     $offset = $limit = null;
     $params = array();
     $params[] = 'Type = ' . $this->getArticleType();
     if ($year && is_numeric($year)) {
         $params[] = $Article->getParam('year', $year);
     } else {
         $offset = 0;
         $limit = 10;
     }
     $Tag = null;
     if (Request::get('tag')) {
         $Tag = new Tag();
         $Tag = $Tag->findItem(array('Name = ' . Request::get('tag')));
         $params[] = $Article->getParam('tag', Request::get('tag'));
     }
     $Paginator = new Paginator($Article->findSize($params), $this->getLimit(), $this->getPage());
     $this->getView()->set('Articles', $Article->findShortList($params, 'PostedAt desc, Id desc', $this->getOffset(), $this->getLimit()));
     $this->getView()->set('Paginator', $Paginator);
     $this->getView()->set('Current', $year);
     $this->getView()->set('Tag', $Tag);
     return $this->getView()->render();
 }
Example #20
0
 public function toTimeline()
 {
     $article = new Article($this->article_id);
     $article->load();
     $hot_comment = isset($article->data['hotlist']) && !empty($article->data['hotlist']) ? ' ——“' . $article->data['hotlist'][0]['content'] . '”' : '';
     return '【' . $this->title . '】' . $hot_comment . ' http://cnbeta1.com/' . $this->article_id;
 }
Example #21
0
 public function execute()
 {
     global $wgUser, $wgTitle, $wgArticle;
     $userName = $this->getOption('u', 'Maintenance script');
     $reason = $this->getOption('r', '');
     $protection = "sysop";
     if ($this->hasOption('semiprotect')) {
         $protection = "autoconfirmed";
     } elseif ($this->hasOption('unprotect')) {
         $protection = "";
     }
     $wgUser = User::newFromName($userName);
     $restrictions = array('edit' => $protection, 'move' => $protection);
     $wgTitle = Title::newFromText($this->getArg());
     if (!$wgTitle) {
         $this->error("Invalid title", true);
     }
     $wgArticle = new Article($wgTitle);
     # un/protect the article
     $this->output("Updating protection status... ");
     $success = $wgArticle->updateRestrictions($restrictions, $reason);
     if ($success) {
         $this->output("done\n");
     } else {
         $this->output("failed\n");
     }
 }
Example #22
0
 function execute($par)
 {
     global $wgOut, $wgRequest, $wgUseTidy;
     wfLoadExtensionMessages('SpecialCite');
     // Having tidy on causes whitespace and <pre> tags to
     // be generated around the output of the CiteOutput
     // class TODO FIXME.
     $wgUseTidy = false;
     $this->setHeaders();
     $this->outputHeader();
     $page = isset($par) ? $par : $wgRequest->getText('page');
     $id = $wgRequest->getInt('id');
     $title = Title::newFromText($page);
     if ($title) {
         $article = new Article($title);
     }
     $cform = new CiteForm($title);
     if (!$title || !$article->exists()) {
         $cform->execute();
     } else {
         $cform->execute();
         $cout = new CiteOutput($title, $article, $id);
         $cout->execute();
     }
 }
 public static function onArticleViewAfterParser(Article $article, ParserOutput $parserOutput)
 {
     global $wgCityId, $wgDBname;
     // we collect production data from Oasis only
     /*
     $app = F::app();
     if ( !$app->checkSkin( 'oasis', $app->wg->Skin )
     		|| $app->wg->DevelEnvironment || $app->wg->StagingEnvironment ) {
     	return true;
     }
     */
     if (class_exists('WScribeClient')) {
         try {
             $title = $article->getTitle();
             $fields = array('wikiId' => intval($wgCityId), 'databaseName' => $wgDBname, 'articleId' => $title->getArticleID(), 'namespaceId' => $title->getNamespace(), 'articleTitle' => $title->getText(), 'parserTime' => $parserOutput->getPerformanceStats('time'), 'wikitextSize' => $parserOutput->getPerformanceStats('wikitextSize'), 'htmlSize' => $parserOutput->getPerformanceStats('htmlSize'), 'expFuncCount' => $parserOutput->getPerformanceStats('expFuncCount'), 'nodeCount' => $parserOutput->getPerformanceStats('nodeCount'), 'postExpandSize' => $parserOutput->getPerformanceStats('postExpandSize'), 'tempArgSize' => $parserOutput->getPerformanceStats('tempArgSize'));
             $data = json_encode($fields);
             WScribeClient::singleton(self::SCRIBE_KEY)->send($data);
         } catch (TException $e) {
             Wikia::log(__METHOD__, 'scribeClient exception', $e->getMessage());
         }
     }
     // Logging parser activity for monitoring
     // wiki and article info are sent to logstash anyways so no need to repeat them here
     WikiaLogger::instance()->info("Parser execution", ['parser-time' => round($parserOutput->getPerformanceStats('time') * 1000), 'node-count' => (int) $parserOutput->getPerformanceStats('nodeCount'), 'wikitext-size' => (int) $parserOutput->getPerformanceStats('wikitextSize'), 'skin-name' => RequestContext::getMain()->getSkin()->getSkinName()]);
     return true;
 }
Example #24
0
 public static function fromID($id)
 {
     $sql = "SELECT *, COALESCE(release_date, created_date) AS \"date\" FROM articles WHERE id = ?";
     $sth = DatabaseHelper::getInstance()->prepare($sql);
     $sth->bindParam(1, $id);
     $sth->execute();
     $res = $sth->fetch(PDO::FETCH_ASSOC);
     if ($res == false) {
         throw new Exception("Impossible de trouver cet article", 404);
     }
     $instance = new Article($res["id"], $res["title"], $res["summary"], $res["content"], null, null);
     $instance->_author = User::fromID($res["author_id"]);
     $instance->_categories = array();
     $instance->_date = $res["date"];
     $instance->_published = $res["published"];
     $instance->_last_modified_date = $res["last_modified_date"];
     $instance->_comment_fb_url = DOMAIN_NAME . WEBAPP_WEBSITE_URL . "news/" . $instance->_id;
     $instance->_comments = $instance->queryCommentsCount();
     // Get the count of articles.
     $sql = "SELECT * FROM categories INNER JOIN articles_categories ON (articles_categories.category_id = categories.id) WHERE article_id = ?";
     $sth = DatabaseHelper::getInstance()->prepare($sql);
     $sth->bindParam(1, $id);
     $sth->execute();
     while ($row = $sth->fetch()) {
         array_push($instance->_categories, $row);
     }
     return $instance;
 }
Example #25
0
 /**
  * Purges the cache of a page
  */
 public function execute()
 {
     global $wgUser;
     $params = $this->extractRequestParams();
     if (!$wgUser->isAllowed('purge')) {
         $this->dieUsageMsg(array('cantpurge'));
     }
     if (!isset($params['titles'])) {
         $this->dieUsageMsg(array('missingparam', 'titles'));
     }
     $result = array();
     foreach ($params['titles'] as $t) {
         $r = array();
         $title = Title::newFromText($t);
         if (!$title instanceof Title) {
             $r['title'] = $t;
             $r['invalid'] = '';
             $result[] = $r;
             continue;
         }
         ApiQueryBase::addTitleInfo($r, $title);
         if (!$title->exists()) {
             $r['missing'] = '';
             $result[] = $r;
             continue;
         }
         $article = new Article($title);
         $article->doPurge();
         // Directly purge and skip the UI part of purge().
         $r['purged'] = '';
         $result[] = $r;
     }
     $this->getResult()->setIndexedTagName($result, 'page');
     $this->getResult()->addValue(null, $this->getModuleName(), $result);
 }
Example #26
0
 /**
  * Run a refreshLinks job
  * @return boolean success
  */
 function run()
 {
     global $wgTitle, $wgUser, $wgLang, $wrGedcomExportDirectory;
     $wgTitle = $this->title;
     // FakeTitle (the default) generates errors when accessed, and sometimes I log wgTitle, so set it to something else
     $wgUser = User::newFromName('WeRelate agent');
     // set the user
     $treeId = $this->params['tree_id'];
     $treeName = $this->params['name'];
     $treeUser = $this->params['user'];
     $filename = "{$wrGedcomExportDirectory}/{$treeId}.ged";
     $ge = new GedcomExporter();
     $error = $ge->exportGedcom($treeId, $filename);
     if ($error) {
         $this->error = $error;
         return false;
     }
     // leave a message for the tree requester
     $userTalkTitle = Title::newFromText($treeUser, NS_USER_TALK);
     $article = new Article($userTalkTitle, 0);
     if ($article->getID() != 0) {
         $text = $article->getContent();
     } else {
         $text = '';
     }
     $title = Title::makeTitle(NS_SPECIAL, 'Trees');
     $msg = wfMsg('GedcomExportReady', $wgLang->date(wfTimestampNow(), true, false), $treeName, $title->getFullURL(wfArrayToCGI(array('action' => 'downloadExport', 'user' => $treeUser, 'name' => $treeName))));
     $text .= "\n\n" . $msg;
     $success = $article->doEdit($text, 'GEDCOM export ready');
     if (!$success) {
         $this->error = 'Unable to edit user talk page: ' . $treeUser;
         return false;
     }
     return true;
 }
Example #27
0
 function getCriteria()
 {
     $total_crit = array();
     $article_search = new Article($this->dbcon);
     if ($crit = $this->getData('sqlwhere')) {
         if ($bad_spot = strpos($crit, "or typeid")) {
             $crit = substr($crit, 0, $bad_spot) . ")";
         }
         $total_crit[] = $crit;
     }
     if ($id = $this->getData('class_id')) {
         #$total_crit[] = "class =".$id;
         $total_crit[] = $article_search->makeCriteriaClass($id);
     }
     if ($id = $this->getData('section_id')) {
         $section =& new Section($this->dbcon, $id);
         $section_crit = $section->getDisplayCriteria();
         $crit = join(' AND ', $article_search->makeCriteria($section_crit));
         $total_crit[] = $crit;
     }
     if (empty($total_crit)) {
         return false;
     }
     return "( " . join(" " . $this->getCombineLogic() . " ", $total_crit) . " ) AND " . $article_search->makeCriteriaDisplayable();
 }
Example #28
0
 /**
  *
  */
 public function getSimpleFormatForArticle(\Article $article)
 {
     $measurement = \Wikia\Measurements\Time::start([__CLASS__, __METHOD__]);
     $cacheKey = wfMemcKey("SimpleJson", $article->getPage()->getId(), self::SIMPLE_JSON_SCHEMA_VERSION);
     $jsonSimple = $this->app->wg->memc->get($cacheKey);
     if ($jsonSimple === false) {
         /**
          * Prevention from circular references, when parsing articles with tabs.
          *
          * E.g. when page contains tab, which is actually link to itself,
          * or if any tab contains tab, which referenced to given page.
          *
          * @see DivContainingHeadersVisitor::parseTabview
          */
         \Wikia\JsonFormat\HtmlParser::markAsVisited($article->getTitle()->getText());
         $jsonFormatRootNode = $this->getJsonFormatForArticle($article);
         // We have finished parsing of article, so we can clean array of visited articles
         \Wikia\JsonFormat\HtmlParser::clearVisited();
         $simplifier = new Wikia\JsonFormat\JsonFormatSimplifier();
         $jsonSimple = $simplifier->simplify($jsonFormatRootNode, $article->getTitle()->getText());
         $this->app->wg->memc->set($cacheKey, $jsonSimple, self::SIMPLE_JSON_CACHE_EXPIRATION);
     }
     $measurement->stop();
     return $jsonSimple;
 }
Example #29
0
 public function execute()
 {
     global $wgUser;
     if (!$wgUser->isLoggedIn()) {
         $this->dieUsage('You must be logged-in to have a watchlist', 'notloggedin');
     }
     $params = $this->extractRequestParams();
     $title = Title::newFromText($params['title']);
     if (!$title) {
         $this->dieUsageMsg(array('invalidtitle', $params['title']));
     }
     $article = new Article($title);
     $res = array('title' => $title->getPrefixedText());
     if ($params['unwatch']) {
         $res['unwatched'] = '';
         $success = $article->doUnwatch();
     } else {
         $res['watched'] = '';
         $success = $article->doWatch();
     }
     if (!$success) {
         $this->dieUsageMsg(array('hookaborted'));
     }
     $this->getResult()->addValue(null, $this->getModuleName(), $res);
 }
 /**
  * Run a dtImport job
  * @return boolean success
  */
 function run()
 {
     wfProfileIn(__METHOD__);
     if (is_null($this->title)) {
         $this->error = "dtImport: Invalid title";
         wfProfileOut(__METHOD__);
         return false;
     }
     $article = new Article($this->title);
     if (!$article) {
         $this->error = 'dtImport: Article not found "' . $this->title->getPrefixedDBkey() . '"';
         wfProfileOut(__METHOD__);
         return false;
     }
     $for_pages_that_exist = $this->params['for_pages_that_exist'];
     if ($for_pages_that_exist == 'skip' && $this->title->exists()) {
         return true;
     }
     // change global $wgUser variable to the one specified by
     // the job only for the extent of this import
     global $wgUser;
     $actual_user = $wgUser;
     $wgUser = User::newFromId($this->params['user_id']);
     $text = $this->params['text'];
     if ($for_pages_that_exist == 'append' && $this->title->exists()) {
         $text = $article->getContent() . "\n" . $text;
     }
     $edit_summary = $this->params['edit_summary'];
     $article->doEdit($text, $edit_summary);
     $wgUser = $actual_user;
     wfProfileOut(__METHOD__);
     return true;
 }