diff --git a/Hooks.php b/Hooks.php index 9fe5193..66453d8 100644 --- a/Hooks.php +++ b/Hooks.php @@ -5,20 +5,16 @@ class WatchAnalyticsHooks { /** * Handler for PersonalUrls hook. Replace the "watchlist" item on the user * toolbar ('personal URLs') with a link to Special:PendingReviews. - * * @see http://www.mediawiki.org/wiki/Manual:Hooks/PersonalUrls * - * @param &$personal_urls Array of URLs to append to. - * @param &$title Title of page being visited. - * - * @return bool true in all cases + * @param array &$personal_urls Array of URLs to append to. + * @return bool */ - static public function onPersonalUrls ( &$personal_urls /*, &$title ,$sk*/ ) { - + public static function onPersonalUrls( array &$personal_urls ) { global $wgUser, $wgOut; $user = $wgUser; - if ( !$user->isAllowed('pendingreviewslink') ) { + if ( !$user->isAllowed( 'pendingreviewslink' ) ) { return true; } @@ -32,9 +28,9 @@ static public function onPersonalUrls ( &$personal_urls /*, &$title ,$sk*/ ) { $maxPendingDays = $watchStats['max_pending_days']; // Determine CSS class of Watchlist/PendingReviews link - $personal_urls['watchlist']['class'] = array( 'mw-watchanalytics-watchlist-badge' ); + $personal_urls['watchlist']['class'] = [ 'mw-watchanalytics-watchlist-badge' ]; if ( $numPending != 0 ) { - $personal_urls['watchlist']['class'] = array( 'mw-watchanalytics-watchlist-pending' ); + $personal_urls['watchlist']['class'] = [ 'mw-watchanalytics-watchlist-pending' ]; } // Determine text of Watchlist/PendingReviews link @@ -42,8 +38,7 @@ static public function onPersonalUrls ( &$personal_urls /*, &$title ,$sk*/ ) { if ( $maxPendingDays > $egPendingReviewsEmphasizeDays ) { $personal_urls['watchlist']['class'][] = 'mw-watchanalytics-watchlist-pending-old'; $text = wfMessage( 'watchanalytics-personal-url-old' )->params( $numPending, $maxPendingDays )->text(); - } - else { + } else { // when $sk (third arg) available, replace wfMessage with $sk->msg() $text = wfMessage( 'watchanalytics-personal-url' )->params( $numPending )->text(); } @@ -70,11 +65,10 @@ static public function onPersonalUrls ( &$personal_urls /*, &$title ,$sk*/ ) { * * @return bool true in all cases */ - static public function onBeforePageDisplay ( $out /*, $skin*/ ) { + public static function onBeforePageDisplay( $out /*, $skin*/ ) { $user = $out->getUser(); $title = $out->getTitle(); - # # 1) Is user's oldest pending review is old enough to require emphasis # @@ -86,14 +80,13 @@ static public function onBeforePageDisplay ( $out /*, $skin*/ ) { global $egPendingReviewsEmphasizeDays; if ( $user->watchStats['max_pending_days'] > $egPendingReviewsEmphasizeDays ) { - $out->addModules( array( 'ext.watchanalytics.shakependingreviews' ) ); + $out->addModules( [ 'ext.watchanalytics.shakependingreviews' ] ); } - # # 2) Insert page scores # - if ( in_array( $title->getNamespace() , $GLOBALS['egWatchAnalyticsPageScoreNamespaces'] ) + if ( in_array( $title->getNamespace(), $GLOBALS['egWatchAnalyticsPageScoreNamespaces'] ) && $user->isAllowed( 'viewpagescore' ) && PageScore::pageScoreIsEnabled() ) { @@ -103,7 +96,6 @@ static public function onBeforePageDisplay ( $out /*, $skin*/ ) { $out->addModuleStyles( 'ext.watchanalytics.pagescores.styles' ); } - // REMOVED FOR MW 1.27 // # // # 3) If user has reviewed page on this page load show "unreview" option @@ -111,15 +103,15 @@ static public function onBeforePageDisplay ( $out /*, $skin*/ ) { // $reviewHandler = ReviewHandler::pageHasBeenReviewed(); // if ( $reviewHandler ) { - // // display "unreview" button - // $out->addScript( $reviewHandler->getTemplate() ); - // $wgOut->addModules( [ - // 'ext.watchanalytics.reviewhandler.scripts', - // 'ext.watchanalytics.reviewhandler.styles' - // ] ); + // // display "unreview" button + // $out->addScript( $reviewHandler->getTemplate() ); + // $wgOut->addModules( [ + // 'ext.watchanalytics.reviewhandler.scripts', + // 'ext.watchanalytics.reviewhandler.styles' + // ] ); - // // record change in user/page stats - // WatchStateRecorder::recordReview( $user, $title ); + // // record change in user/page stats + // WatchStateRecorder::recordReview( $user, $title ); // } @@ -149,9 +141,8 @@ static public function onBeforePageDisplay ( $out /*, $skin*/ ) { * * @return bool true in all cases */ - static public function onTitleMoveComplete ( Title &$originalTitle, Title &$newTitle, + public static function onTitleMoveComplete( Title &$originalTitle, Title &$newTitle, User &$user, $oldid, $newid, $reason = null ) { - # # Record move in watch stats # @@ -172,19 +163,19 @@ static public function onTitleMoveComplete ( Title &$originalTitle, Title &$newT $dbw = wfGetDB( DB_MASTER ); $results = $dbw->select( 'watchlist', - array( 'wl_user', 'wl_notificationtimestamp' ), - array( 'wl_namespace' => $oldNS, 'wl_title' => $oldDBkey ), + [ 'wl_user', 'wl_notificationtimestamp' ], + [ 'wl_namespace' => $oldNS, 'wl_title' => $oldDBkey ], __METHOD__ ); # Construct array to replace into the watchlist - $values = array(); + $values = []; foreach ( $results as $oldRow ) { - $values[] = array( + $values[] = [ 'wl_user' => $oldRow->wl_user, 'wl_namespace' => $newNS, 'wl_title' => $newDBkey, 'wl_notificationtimestamp' => $oldRow->wl_notificationtimestamp, - ); + ]; } if ( empty( $values ) ) { @@ -197,7 +188,7 @@ static public function onTitleMoveComplete ( Title &$originalTitle, Title &$newT # some other DBMSes, mostly due to poor simulation by us $dbw->replace( 'watchlist', - array( array( 'wl_user', 'wl_namespace', 'wl_title' ) ), + [ [ 'wl_user', 'wl_namespace', 'wl_title' ] ], $values, __METHOD__ ); @@ -208,13 +199,13 @@ static public function onTitleMoveComplete ( Title &$originalTitle, Title &$newT /** * Register magic-word variable ID to hide page score from select pages. * - * @see FIXME (include link to hook documentation) + * @see FIXME (include link to hook documentation) * - * @param Array $magicWordVariableIDs array of names of magic words + * @param Array &$magicWordVariableIDs array of names of magic words * * @return bool */ - static public function addMagicWordVariableIDs( &$magicWordVariableIDs ) { + public static function addMagicWordVariableIDs( &$magicWordVariableIDs ) { $magicWordVariableIDs[] = 'MAG_NOPAGESCORE'; return true; } @@ -223,14 +214,14 @@ static public function addMagicWordVariableIDs( &$magicWordVariableIDs ) { * Set values in the page_props table based on the presence of the * 'NOPAGESCORE' magic word in a page * - * @see FIXME (include link to hook documentation) + * @see FIXME (include link to hook documentation) * - * @param Parser $parser reference to MediaWiki parser. - * @param string $text FIXME html/wikitext? of output page before complete + * @param Parser &$parser reference to MediaWiki parser. + * @param string &$text FIXME html/wikitext? of output page before complete * * @return bool */ - static public function handleMagicWords( &$parser, &$text ) { + public static function handleMagicWords( &$parser, &$text ) { $magicWord = MagicWord::get( 'MAG_NOPAGESCORE' ); if ( $magicWord->matchAndRemove( $text ) ) { // $parser->mOutput->setProperty( 'approvedrevs', 'y' ); @@ -251,8 +242,7 @@ static public function handleMagicWords( &$parser, &$text ) { * * @return bool */ - static public function onPageViewUpdates ( WikiPage $wikiPage, User $user ) { - + public static function onPageViewUpdates( WikiPage $wikiPage, User $user ) { $title = $wikiPage->getTitle(); $reviewHandler = ReviewHandler::setup( $user, $title ); @@ -285,21 +275,21 @@ static public function onPageViewUpdates ( WikiPage $wikiPage, User $user ) { * * @see https://www.mediawiki.org/wiki/Manual:Hooks/PageContentSaveComplete * - * @param WikiPage $article + * @param WikiPage $wikipage * - * @return boolean + * @return bool */ - static public function onPageContentSaveComplete ( $article ) { - WatchStateRecorder::recordPageChange( $article ); + public static function onPageContentSaveComplete( WikiPage $wikipage ) { + WatchStateRecorder::recordPageChange( $wikipage ); return true; } public static function onLanguageGetMagic( &$magicWords, $langCode ) { switch ( $langCode ) { default: - $magicWords['underwatched_categories'] = array( 0, 'underwatched_categories' ); - $magicWords['watchers_needed'] = array( 0, 'watchers_needed' ); - $magicWords['MAG_NOPAGESCORE'] = array( 0, '__NOPAGESCORE__' ); + $magicWords['underwatched_categories'] = [ 0, 'underwatched_categories' ]; + $magicWords['watchers_needed'] = [ 0, 'watchers_needed' ]; + $magicWords['MAG_NOPAGESCORE'] = [ 0, '__NOPAGESCORE__' ]; } return true; } diff --git a/WatchAnalytics.i18n.magic.php b/WatchAnalytics.i18n.magic.php index 13d1d5c..cb922a7 100644 --- a/WatchAnalytics.i18n.magic.php +++ b/WatchAnalytics.i18n.magic.php @@ -1,13 +1,13 @@ array( - 0, // zero means case-insensitive, 1 means case sensitive - 'underwatched_categories' - ), - 'watchers_needed' => array( - 0, // zero means case-insensitive, 1 means case sensitive - 'watchers_needed' - ), - 'MAG_NOPAGESCORE' => array( 0, '__NOPAGESCORE__' ), -); \ No newline at end of file +$magicWords['en'] = [ + 'underwatched_categories' => [ + 0, // zero means case-insensitive, 1 means case sensitive + 'underwatched_categories' + ], + 'watchers_needed' => [ + 0, // zero means case-insensitive, 1 means case sensitive + 'watchers_needed' + ], + 'MAG_NOPAGESCORE' => [ 0, '__NOPAGESCORE__' ], +]; diff --git a/WatchAnalyticsUser.php b/WatchAnalyticsUser.php index 43eb1c8..f4d44d9 100644 --- a/WatchAnalyticsUser.php +++ b/WatchAnalyticsUser.php @@ -1,93 +1,40 @@ user = $user; } - - /* - SELECT watchlist.wl_title, user.user_name - FROM watchlist - LEFT JOIN user ON - user.user_id = watchlist.wl_user - WHERE - wl_notificationtimestamp IS NOT NULL - AND user.user_name = 'Cmavridi'; - */ - // SELECT - // watchlist.wl_title AS title, - // watchlist.wl_namespace AS namespace, - // watchlist.wl_notificationtimestamp AS notification, - // user.user_name AS user_name, - // user.user_real_name AS real_name - // FROM watchlist - // LEFT JOIN user ON user.user_id = watchlist.wl_user - public function getPendingWatches () { - - $dbr = wfGetDB( DB_SLAVE ); + public function getPendingWatches() { + $dbr = wfGetDB( DB_REPLICA ); $res = $dbr->select( - array( 'w' => 'watchlist' ), - array( + [ 'w' => 'watchlist' ], + [ 'w.wl_namespace AS namespace_id', 'w.wl_title AS title_text', 'w.wl_notificationtimestamp AS notification_timestamp', - ), + ], 'w.wl_notificationtimestamp IS NOT NULL AND w.wl_user=' . $this->user->getId(), __METHOD__, - array( + [ // "DISTINCT", // "GROUP BY" => "w.hit_year, w.hit_month, w.hit_day", // "ORDER BY" => "w.hit_year DESC, w.hit_month DESC, w.hit_day DESC", "LIMIT" => "100000", - ), + ], null // array( 'u' => array( 'LEFT JOIN', 'u.user-id=w.wl_user' ) ) ); - $this->pendingWatches = array(); + $this->pendingWatches = []; while ( $row = $dbr->fetchRow( $res ) ) { // $title = Title::newFromText( $row['title_text'], $row['notification_timestamp'] ); $this->pendingWatches[] = $row; - } return $this; diff --git a/includes/PageScore.php b/includes/PageScore.php index 63eca90..59503eb 100644 --- a/includes/PageScore.php +++ b/includes/PageScore.php @@ -1,37 +1,4 @@ mTitle = $title; - $this->cssColorClasses = array( + $this->cssColorClasses = [ 'excellent', // 'good', 'okay', // 'warning', 'danger', - ); + ]; } - static public function noPageScore () { + public static function noPageScore() { self::$displayPageScore = false; } - static public function pageScoreIsEnabled () { + public static function pageScoreIsEnabled() { return self::$displayPageScore; } @@ -76,60 +42,53 @@ static public function pageScoreIsEnabled () { * * @return string */ - public function getWatchQuality () { + public function getWatchQuality() { $pwq = new PageWatchesQuery(); return round( $pwq->getPageWatchQuality( $this->mTitle ), 1 ); } - public function getReviewStatus () { + public function getReviewStatus() { return $this->getNumReviews(); } - public function getNumReviews () { - - $dbr = wfGetDB( DB_SLAVE ); - + public function getNumReviews() { + $dbr = wfGetDB( DB_REPLICA ); $pageData = $dbr->selectRow( 'watchlist', 'COUNT(*) AS num_reviews', - array( + [ 'wl_notificationtimestamp IS NULL', 'wl_namespace' => $this->mTitle->getNamespace(), 'wl_title' => $this->mTitle->getDBkey() - ), + ], __METHOD__ ); return $pageData->num_reviews; - } - public function getScoreColor ( $score, $configVariable ) { - + public function getScoreColor( $score, $configVariable ) { $scoreArr = $GLOBALS[ $configVariable ]; $scoreArrCount = count( $scoreArr ); - for ( $i = 0; $i < $scoreArrCount; $i++ ) { // ) as $index => $upperBound + for ( $i = 0; $i < $scoreArrCount; $i++ ) { // ) as $index => $upperBound if ( $score > $scoreArr[ $i ] ) { return $this->cssColorClasses[ $i ]; } } return $this->cssColorClasses[ count( $scoreArr ) ]; - } - - public function getPageScoreTemplate () { - + public function getPageScoreTemplate() { // simple explanation of what PageScores are $pageScoresTooltip = wfMessage( 'watch-analytics-page-score-tooltip' )->text(); // @FIXME: Replace with special page showing page stats // $pageScoresHelpPageLink = Title::makeTitle( NS_HELP, "Page Scores" )->getInternalURL(); - $pageScoresHelpPageLink = SpecialPage::getTitleFor( 'PageStatistics' )->getInternalURL( array( + $pageScoresHelpPageLink = SpecialPage::getTitleFor( 'PageStatistics' )->getInternalURL( [ 'page' => $this->mTitle->getPrefixedText() - ) ); + ] ); // when MW 1.25 is released (very soon) replace this with a mustache template $template = @@ -139,23 +98,19 @@ public function getPageScoreTemplate () { . ""; return ""; - } - public function getBadge ( $label, $score, $color, $showLabel = false ) { - + public function getBadge( $label, $score, $color, $showLabel = false ) { // @todo FIXME: make the javascript apply a class to handle this, so this can just apply a class if ( $showLabel ) { $leftStyle = " style='display:inherit; border-radius: 4px 0 0 4px;'"; $rightStyle = " style='border-radius: 0 4px 4px 0;'"; - } - else { + } else { $leftStyle = ""; $rightStyle = ""; } - return - "
+ return "
$label
@@ -163,10 +118,9 @@ public function getBadge ( $label, $score, $color, $showLabel = false ) { $score
"; - } - public function getScrutinyBadge ( $showLabel = false ) { + public function getScrutinyBadge( $showLabel = false ) { $scrutinyScore = $this->getWatchQuality(); $scrutinyLabel = wfMessage( 'watch-analytics-page-score-scrutiny-label' )->text(); $scrutinyColor = $this->getScoreColor( $scrutinyScore, 'egWatchAnalyticsWatchQualityColors' ); @@ -174,7 +128,7 @@ public function getScrutinyBadge ( $showLabel = false ) { return $this->getBadge( $scrutinyLabel, $scrutinyScore, $scrutinyColor, $showLabel ); } - public function getReviewsBadge ( $showLabel = false ) { + public function getReviewsBadge( $showLabel = false ) { $reviewsScore = $this->getReviewStatus(); $reviewsLabel = wfMessage( 'watch-analytics-page-score-reviews-label' )->text(); $reviewsColor = $this->getScoreColor( $reviewsScore, 'egWatchAnalyticsReviewStatusColors' ); diff --git a/includes/PageWatchesQuery.php b/includes/PageWatchesQuery.php index 52fe5b5..cdebd8e 100644 --- a/includes/PageWatchesQuery.php +++ b/includes/PageWatchesQuery.php @@ -1,47 +1,15 @@ 'watchanalytics-special-header-page-title', 'num_watches' => 'watchanalytics-special-header-watches', 'num_reviewed' => 'watchanalytics-special-header-reviewed-watches', @@ -49,11 +17,10 @@ class PageWatchesQuery extends WatchesQuery { 'max_pending_minutes' => 'watchanalytics-special-header-pending-maxtime', 'avg_pending_minutes' => 'watchanalytics-special-header-pending-averagetime', 'watch_quality' => 'watchanalytics-special-header-watch-quality', - ); + ]; public function getQueryInfo( $conds = null ) { - - $this->fields = array( + $this->fields = [ $this->sqlNsAndTitle, $this->sqlNumWatches, $this->sqlNumReviewed, @@ -61,27 +28,27 @@ public function getQueryInfo( $conds = null ) { $this->sqlMaxPendingMins, $this->sqlAvgPendingMins, $this->sqlWatchQuality, - ); + ]; - $this->conds = $conds ? $conds : array( 'p.page_namespace IS NOT NULL' ); + $this->conds = $conds ? $conds : [ 'p.page_namespace IS NOT NULL' ]; - $this->tables = array( 'w' => 'watchlist' ); + $this->tables = [ 'w' => 'watchlist' ]; - $this->join_conds = array(); + $this->join_conds = []; // optionally join the 'user_groups' table to filter by user group if ( $this->userGroupFilter ) { $this->tables['ug'] = 'user_groups'; - $this->join_conds['ug'] = array( + $this->join_conds['ug'] = [ 'RIGHT JOIN', "w.wl_user = ug.ug_user AND ug.ug_group = \"{$this->userGroupFilter}\"" - ); + ]; } // JOIN 'page' table $this->tables['p'] = 'page'; - $this->join_conds['p'] = array( + $this->join_conds['p'] = [ 'RIGHT JOIN', 'p.page_namespace=w.wl_namespace AND p.page_title=w.wl_title' - ); + ]; // optionally join the 'categorylinks' table to filter by page category if ( $this->categoryFilter ) { @@ -114,32 +81,30 @@ public function getQueryInfo( $conds = null ) { GROUP BY w2.wl_user )'; - $this->join_conds['user_watch_scores'] = array( + $this->join_conds['user_watch_scores'] = [ 'LEFT JOIN', 'user_watch_scores.user_name = w.wl_user' - ); + ]; - $this->options = array( + $this->options = [ // 'GROUP BY' => 'w.wl_title, w.wl_namespace' 'GROUP BY' => 'p.page_title, p.page_namespace', - ); + ]; return parent::getQueryInfo(); - } - public function getPageWatchesAndViews ( $pages ) { - - $dbr = wfGetDB( DB_SLAVE ); + public function getPageWatchesAndViews( $pages ) { + $dbr = wfGetDB( DB_REPLICA ); $pagesList = $dbr->makeList( $pages ); $queryInfo = $this->getQueryInfo( 'p.page_id IN (' . $pagesList . ')' ); $queryInfo['options'][ 'ORDER BY' ] = 'num_watches ASC'; - $cols = array( + $cols = [ 'p.page_id AS page_id', $this->sqlNumWatches, // 'SUM( IF(w.wl_title IS NOT NULL, 1, 0) ) AS num_watches' - ); + ]; global $egWatchAnalyticsPageCounter; if ( $egWatchAnalyticsPageCounter ) { @@ -148,9 +113,9 @@ public function getPageWatchesAndViews ( $pages ) { $countPageIdJoinCol = $egWatchAnalyticsPageCounter['join_column']; $cols[] = "counter.$countCol AS num_views"; - $queryInfo['join_conds']['counter'] = array( + $queryInfo['join_conds']['counter'] = [ 'LEFT JOIN' , "p.page_id = counter.$countPageIdJoinCol" - ); + ]; } $pageWatchStats = $dbr->select( @@ -162,7 +127,7 @@ public function getPageWatchesAndViews ( $pages ) { $queryInfo['join_conds'] ); - $return = array(); + $return = []; while ( $row = $pageWatchStats->fetchObject() ) { if ( ! isset( $row->num_views ) ) { $row->num_views = 1; @@ -171,48 +136,44 @@ public function getPageWatchesAndViews ( $pages ) { } return $return; - } - public function getPageWatchers ( $titleKey, $ns = NS_MAIN ) { - - $dbr = wfGetDB( DB_SLAVE ); + public function getPageWatchers( $titleKey, $ns = NS_MAIN ) { + $dbr = wfGetDB( DB_REPLICA ); $pageWatchStats = $dbr->select( - array( 'w' => 'watchlist' ), - array( 'wl_user', 'wl_notificationtimestamp' ), - array( + [ 'w' => 'watchlist' ], + [ 'wl_user', 'wl_notificationtimestamp' ], + [ 'w.wl_namespace' => $ns, 'w.wl_title' => $titleKey, - ), + ], __METHOD__, null, // no options null // no join conds (no other tables) ); - $return = array(); + $return = []; while ( $row = $pageWatchStats->fetchObject() ) { $return[] = $row; } return $return; - } - public function getPageWatchQuality ( Title $title ) { + public function getPageWatchQuality( Title $title ) { + $dbr = wfGetDB( DB_REPLICA ); - $dbr = wfGetDB( DB_SLAVE ); - - $queryInfo = $this->getQueryInfo( array( + $queryInfo = $this->getQueryInfo( [ 'p.page_namespace' => $title->getNamespace(), 'p.page_title' => $title->getDBkey(), - ) ); + ] ); $pageData = $dbr->selectRow( $queryInfo['tables'], - array( + [ $this->sqlWatchQuality - ), + ], $queryInfo['conds'], __METHOD__, $queryInfo['options'], @@ -222,11 +183,9 @@ public function getPageWatchQuality ( Title $title ) { // $row = $pageData->fetchObject(); if ( $pageData ) { return $pageData->watch_quality; - } - else { + } else { return 0; } - } } diff --git a/includes/PendingReview.php b/includes/PendingReview.php index 5feebc0..f73802f 100644 --- a/includes/PendingReview.php +++ b/includes/PendingReview.php @@ -1,37 +1,4 @@ exists() ) { - $dbr = wfGetDB( DB_SLAVE ); - + $dbr = wfGetDB( DB_REPLICA ); $revResults = $dbr->select( - array( 'r' => 'revision' ), + [ 'r' => 'revision' ], Revision::getQueryInfo()['fields'], // array( - // 'r.rev_id AS rev_id', - // 'r.rev_comment AS rev_comment', - // 'r.rev_user AS rev_user_id', - // 'r.rev_user_text AS rev_user_name', - // 'r.rev_timestamp AS rev_timestamp', - // 'r.rev_len AS rev_len', + // 'r.rev_id AS rev_id', + // 'r.rev_comment AS rev_comment', + // 'r.rev_user AS rev_user_id', + // 'r.rev_user_text AS rev_user_name', + // 'r.rev_timestamp AS rev_timestamp', + // 'r.rev_len AS rev_len', // ), "r.rev_page=$pageID AND r.rev_timestamp>=$notificationTimestamp", __METHOD__, - array( 'ORDER BY' => 'rev_timestamp ASC' ), + [ 'ORDER BY' => 'rev_timestamp ASC' ], null ); - $revsPending = array(); + $revsPending = []; while ( $rev = $revResults->fetchObject() ) { $revsPending[] = $rev; } $logResults = $dbr->select( - array( 'l' => 'logging' ), - array( '*' ), + [ 'l' => 'logging' ], + [ '*' ], // array( - // 'l.log_id AS log_id', - // 'l.log_type AS log_type', - // 'l.log_action AS log_action', - // 'l.log_timestamp AS log_timestamp', - // 'l.log_user AS log_user_id', - // 'l.log_user_text AS log_user_name', + // 'l.log_id AS log_id', + // 'l.log_type AS log_type', + // 'l.log_action AS log_action', + // 'l.log_timestamp AS log_timestamp', + // 'l.log_user AS log_user_id', + // 'l.log_user_text AS log_user_name', // ), "l.log_page=$pageID AND l.log_timestamp>=$notificationTimestamp AND l.log_type NOT IN ('interwiki','newusers','patrol','rights','upload')", __METHOD__, - array( 'ORDER BY' => 'log_timestamp ASC' ), + [ 'ORDER BY' => 'log_timestamp ASC' ], null ); - $logPending = array(); + $logPending = []; while ( $log = $logResults->fetchObject() ) { $logPending[] = $log; } @@ -144,8 +108,7 @@ public function __construct ( $row ) { $deletedTitle = false; $deletionLog = false; - } - else { + } else { $deletedNS = $row['namespace']; $deletedTitle = $row['title']; $deletionLog = $this->getDeletionLog( $deletedTitle, $deletedNS, $notificationTimestamp ); @@ -153,7 +116,6 @@ public function __construct ( $row ) { $revsPending = false; } - $this->notificationTimestamp = $notificationTimestamp; $this->title = $title; $this->newRevisions = $revsPending; @@ -162,41 +124,16 @@ public function __construct ( $row ) { $this->deletionLog = $deletionLog; $this->log = $logPending; $this->numReviewers = intval( $row['num_reviewed'] ); - } - /* - Make more like this: - - SELECT - p.page_id AS id, - w.wl_namespace AS namespace, - w.wl_title AS title, - w.wl_notificationtimestamp AS notificationtimestamp - FROM `watchlist` `w` - LEFT JOIN `page` `p` ON - ((p.page_namespace=w.wl_namespace AND p.page_title=w.wl_title)) - LEFT JOIN `logging` `log` ON - log.log_namespace = w.wl_namespace - AND log.log_title = w.wl_title - AND p.page_namespace IS NULL - AND p.page_title IS NULL - AND log.log_action = 'delete' - WHERE - w.wl_user=1 - AND w.wl_notificationtimestamp IS NOT NULL - ORDER BY w.wl_notificationtimestamp ASC; - - */ - static public function getPendingReviewsList ( User $user, $limit, $offset ) { - - $tables = array( + public static function getPendingReviewsList( User $user, $limit, $offset ) { + $tables = [ 'w' => 'watchlist', 'p' => 'page', 'log' => 'logging', - ); + ]; - $fields = array( + $fields = [ 'p.page_id AS page_id', 'log.log_action AS log_action', 'w.wl_namespace AS namespace', @@ -208,32 +145,31 @@ static public function getPendingReviewsList ( User $user, $limit, $offset ) { AND subwatch.wl_title = w.wl_title AND subwatch.wl_notificationtimestamp IS NULL ) AS num_reviewed', - ); + ]; $conds = 'w.wl_user=' . $user->getId() . ' AND w.wl_notificationtimestamp IS NOT NULL'; - $options = array( + $options = [ 'ORDER BY' => 'num_reviewed ASC, w.wl_notificationtimestamp ASC', 'OFFSET' => $offset, 'LIMIT' => $limit, - ); + ]; - $join_conds = array( - 'p' => array( + $join_conds = [ + 'p' => [ 'LEFT JOIN', 'p.page_namespace=w.wl_namespace AND p.page_title=w.wl_title' - ), - 'log' => array( + ], + 'log' => [ 'LEFT JOIN', 'log.log_namespace = w.wl_namespace ' . ' AND log.log_title = w.wl_title' . ' AND p.page_namespace IS NULL' . ' AND p.page_title IS NULL' . ' AND log.log_action IN ("delete","move")' - ), - ); - + ], + ]; - $dbr = wfGetDB( DB_SLAVE ); + $dbr = wfGetDB( DB_REPLICA ); $watchResult = $dbr->select( $tables, @@ -244,7 +180,7 @@ static public function getPendingReviewsList ( User $user, $limit, $offset ) { $join_conds ); - $pending = array(); + $pending = []; while ( $row = $dbr->fetchRow( $watchResult ) ) { @@ -255,16 +191,15 @@ static public function getPendingReviewsList ( User $user, $limit, $offset ) { return $pending; } - public function getDeletionLog ( $title, $ns, $notificationTimestamp ) { - - $dbr = wfGetDB( DB_SLAVE ); + public function getDeletionLog( $title, $ns, $notificationTimestamp ) { + $dbr = wfGetDB( DB_REPLICA ); $title = $dbr->addQuotes( $title ); // pages are deleted when (a) they are explicitly deleted or (b) they // are moved without leaving a redirect behind. $logResults = $dbr->select( - array( 'l' => 'logging' ), + [ 'l' => 'logging' ], [ 'log_id', 'log_type', @@ -282,10 +217,10 @@ public function getDeletionLog ( $title, $ns, $notificationTimestamp ) { "l.log_title=$title AND l.log_namespace=$ns AND l.log_timestamp>=$notificationTimestamp AND l.log_type IN ('delete','move')", __METHOD__, - array( 'ORDER BY' => 'log_timestamp ASC' ), + [ 'ORDER BY' => 'log_timestamp ASC' ], null ); - $logDeletes = array(); + $logDeletes = []; while ( $log = $logResults->fetchObject() ) { $logDeletes[] = $log; } @@ -293,14 +228,10 @@ public function getDeletionLog ( $title, $ns, $notificationTimestamp ) { return $logDeletes; } - - /** - * FIXME: This was copied from LogEntry::getParameters() because - * I couldn't find a cleaner way to do it. - * - * var $logParams is the content of the column log_params in the logging table - */ - public static function getMoveTarget ( $logParams ) { + public static function getMoveTarget( $logParams ) { + // FIXME: This was copied from LogEntry::getParameters() because + // I couldn't find a cleaner way to do it. + // $logParams the content of the column log_params in the logging table wfSuppressWarnings(); $unserializedParams = unserialize( $logParams ); @@ -314,12 +245,11 @@ public static function getMoveTarget ( $logParams ) { return $moveLogParams[ '4::target' ]; } else { - $moveLogParams = $logParams === '' ? array() : explode( "\n", $logParams ); + $moveLogParams = $logParams === '' ? [] : explode( "\n", $logParams ); // $this->legacy = true; return $moveLogParams[0]; } - } /** @@ -329,27 +259,24 @@ public static function getMoveTarget ( $logParams ) { * @param Title $title * @return string HTML for row */ - public function clearByUserAndTitle ( $user, $title ) { - + public function clearByUserAndTitle( $user, $title ) { $watch = WatchedItem::fromUserTitle( $user, $title ); $watch->resetNotificationTimestamp(); // $wgOut->addHTML( - // wfMessage( - // 'pendingreviews-clear-page-notification', - // $title->getFullText(), - // Xml::tags('a', - // array( - // 'href' => $this->getTitle()->getLocalUrl(), - // 'style' => 'font-weight:bold;', - // ), - // $this->getTitle() - // ) - // )->text() + // wfMessage( + // 'pendingreviews-clear-page-notification', + // $title->getFullText(), + // Xml::tags('a', + // array( + // 'href' => $this->getTitle()->getLocalUrl(), + // 'style' => 'font-weight:bold;', + // ), + // $this->getTitle() + // ) + // )->text() // ); return true; - - } } diff --git a/includes/ReviewHandler.php b/includes/ReviewHandler.php index 68ada32..0302ecb 100644 --- a/includes/ReviewHandler.php +++ b/includes/ReviewHandler.php @@ -1,37 +1,4 @@ user = $user; $this->title = $title; } - public static function setup ( User $user, Title $title ) { + public static function setup( User $user, Title $title ) { if ( ! $title->isWatchable() ) { self::$isReviewable = false; return false; @@ -82,40 +49,36 @@ public static function setup ( User $user, Title $title ) { * Get the "watch status" of a user for a page, e.g. whether they're watching * and, if they're watching, whether they have reviewed the latest revision. * + * @return int */ - public function getReviewStatus () { - - $dbr = wfGetDB( DB_SLAVE ); + public function getReviewStatus() { + $dbr = wfGetDB( DB_REPLICA ); // FIXME: probably should use User->getNotificationTimestmap() or something // but I'm on a plane and I don't know what is available to me without docs $row = $dbr->selectRow( 'watchlist', - array( 'wl_notificationtimestamp' ), - array( + [ 'wl_notificationtimestamp' ], + [ 'wl_user' => $this->user->getId(), 'wl_namespace' => $this->title->getNamespace(), 'wl_title' => $this->title->getDBkey(), - ), + ], __METHOD__, - array() + [] ); // user is not watching the page if ( $row === false ) { return -1; - } - else if ( $row->wl_notificationtimestamp === NULL ) { + } elseif ( $row->wl_notificationtimestamp === null ) { return 0; - } - else { + } else { return $row->wl_notificationtimestamp; } - } - public static function pageIsBeingReviewed () { - + public static function pageIsBeingReviewed() { // never setup if ( ! self::$isReviewable || self::$pageLoadHandler === null ) { return false; @@ -140,25 +103,23 @@ public static function pageIsBeingReviewed () { // or $newStatus is a timestamp greater than the original timestamp, meaning // they have reviewed a more recent version of the page than they had originally // if ( $newStatus < 1 || $newStatus > self::$pageLoadHandler->initial ) { - // self::$pageLoadHandler->final = $newStatus; - // return self::$pageLoadHandler; + // self::$pageLoadHandler->final = $newStatus; + // return self::$pageLoadHandler; // } // else { - // return false; + // return false; // } return true; - } - public function getTemplate () { - + public function getTemplate() { // $msg = wfMessage( 'watch-analytics-page-score-tooltip' )->text(); - $unReviewLink = SpecialPage::getTitleFor( 'PageStatistics' )->getInternalURL( array( + $unReviewLink = SpecialPage::getTitleFor( 'PageStatistics' )->getInternalURL( [ 'page' => $this->title->getPrefixedText(), 'unreview' => $this->initial - ) ); + ] ); $linkText = wfMessage( 'watchanalytics-unreview-button' )->text(); $bannerText = wfMessage( 'watchanalytics-unreview-banner-text' )->parse(); @@ -171,27 +132,24 @@ public function getTemplate () { "; return ""; - } - public function resetNotificationTimestamp ( $ts ) { - + public function resetNotificationTimestamp( $ts ) { $dbw = wfGetDB( DB_MASTER ); return $dbw->update( 'watchlist', - array( + [ 'wl_notificationtimestamp' => $ts, - ), - array( + ], + [ 'wl_user' => $this->user->getId(), 'wl_namespace' => $this->title->getNamespace(), 'wl_title' => $this->title->getDBkey(), - ), + ], __METHOD__, null ); - } } diff --git a/includes/UserWatchesQuery.php b/includes/UserWatchesQuery.php index aeb57e7..f602100 100644 --- a/includes/UserWatchesQuery.php +++ b/includes/UserWatchesQuery.php @@ -1,37 +1,4 @@ 'watchanalytics-special-header-user', 'num_watches' => 'watchanalytics-special-header-watches', 'num_pending' => 'watchanalytics-special-header-pending-watches', @@ -64,18 +31,17 @@ class UserWatchesQuery extends WatchesQuery { 'max_pending_minutes' => 'watchanalytics-special-header-pending-maxtime', 'avg_pending_minutes' => 'watchanalytics-special-header-pending-averagetime', 'engagement_score' => 'watchanalytics-special-header-engagement-score', - ); + ]; public function getQueryInfo( $conds = null ) { - - $this->tables = array( + $this->tables = [ 'w' => 'watchlist', 'u' => 'user', 'p' => 'page', 'log' => 'logging', - ); + ]; - $this->fields = array( + $this->fields = [ $this->sqlUserName, $this->sqlNumWatches, $this->sqlNumPending, @@ -83,39 +49,38 @@ public function getQueryInfo( $conds = null ) { $this->sqlMaxPendingMins, $this->sqlAvgPendingMins, $this->sqlEngagementScore, - ); + ]; - $this->conds = $conds ? $conds : array(); + $this->conds = $conds ? $conds : []; - $this->join_conds = array( - 'u' => array( + $this->join_conds = [ + 'u' => [ 'LEFT JOIN', 'u.user_id=w.wl_user' - ), - 'p' => array( + ], + 'p' => [ 'LEFT JOIN', 'p.page_namespace=w.wl_namespace AND p.page_title=w.wl_title' - ), - 'log' => array( + ], + 'log' => [ 'LEFT JOIN', 'log.log_namespace = w.wl_namespace ' . ' AND log.log_title = w.wl_title' . ' AND p.page_namespace IS NULL' . ' AND p.page_title IS NULL' . ' AND log.log_action = "delete"' - ), - ); + ], + ]; // optionally join the 'user_groups' table to filter by user group if ( $this->userGroupFilter ) { $this->tables['ug'] = 'user_groups'; - $this->join_conds['ug'] = array( + $this->join_conds['ug'] = [ 'RIGHT JOIN', "w.wl_user = ug.ug_user AND ug.ug_group = \"{$this->userGroupFilter}\"" - ); + ]; $noNullUsers = 'w.wl_user IS NOT NULL'; if ( is_array( $this->conds ) ) { $this->conds[] = $noNullUsers; - } - else if ( is_string( $this->conds ) ) { + } elseif ( is_string( $this->conds ) ) { $this->conds .= ' AND ' . $noNullUsers; } } @@ -125,12 +90,11 @@ public function getQueryInfo( $conds = null ) { $this->setCategoryFilterQueryInfo(); } - $this->options = array( + $this->options = [ 'GROUP BY' => 'w.wl_user' - ); + ]; return parent::getQueryInfo(); - } /** @@ -141,11 +105,10 @@ public function getQueryInfo( $conds = null ) { * @return array returns user watch info in an array with keys the same as * $this->fieldNames. */ - public function getUserWatchStats ( User $user ) { - + public function getUserWatchStats( User $user ) { $qInfo = $this->getQueryInfo(); - $dbr = wfGetDB( DB_SLAVE ); + $dbr = wfGetDB( DB_REPLICA ); $res = $dbr->select( $qInfo['tables'], @@ -161,7 +124,7 @@ public function getUserWatchStats ( User $user ) { // if user doesn't have any pages in watchlist, then no data will be // returned by this query. Create a "blank" row instead. if ( $row === false ) { - $row = array(); + $row = []; foreach ( $this->fieldNames as $name => $msg ) { $row[ $name ] = 0; } @@ -178,42 +141,41 @@ public function getUserWatchStats ( User $user ) { * @return Array returns user watch info in an array with user IDs as keys * and values being objects with params num_watches and num_pending. */ - public function getMultiUserWatchStats ( Array $userIds ) { - + public function getMultiUserWatchStats( array $userIds ) { if ( ! count( $userIds ) ) { - return array(); + return []; } - $fields = array( + $fields = [ 'w.wl_user', $this->sqlNumWatches, $this->sqlNumPending, - ); + ]; - $dbr = wfGetDB( DB_SLAVE ); + $dbr = wfGetDB( DB_REPLICA ); $res = $dbr->select( - array( + [ 'w' => 'watchlist' - ), + ], $fields, - array( + [ 'w.wl_user' => $userIds - ), + ], __METHOD__, - array( + [ 'GROUP BY' => 'w.wl_user' - ), // no options + ], // no options null // no joins ); - $return = array(); + $return = []; while ( $row = $res->fetchObject() ) { - $return[] = (object)array( + $return[] = (object)[ 'wl_user' => $row->wl_user, 'num_watches' => $row->num_watches, 'num_pending' => $row->num_pending, - ); + ]; } return $return; diff --git a/includes/WatchAnalyticsHtmlHelper.php b/includes/WatchAnalyticsHtmlHelper.php index 470ed79..5ebbaad 100644 --- a/includes/WatchAnalyticsHtmlHelper.php +++ b/includes/WatchAnalyticsHtmlHelper.php @@ -1,42 +1,8 @@ elements $numLI = count( $list ); @@ -45,8 +11,7 @@ static public function formatListArray ( $list, $columns = 1, $listType = 'ol' ) if ( $columns > 1 ) { $perCol = ceil( $numLI / $columns ); - } - else { + } else { $perCol = $numLI + 1; } @@ -76,7 +41,6 @@ static public function formatListArray ( $list, $columns = 1, $listType = 'ol' ) $html .= ""; return $html; - } } diff --git a/includes/WatchAnalyticsPageTablePager.php b/includes/WatchAnalyticsPageTablePager.php index 124e6ee..a06b355 100644 --- a/includes/WatchAnalyticsPageTablePager.php +++ b/includes/WatchAnalyticsPageTablePager.php @@ -2,7 +2,7 @@ class WatchAnalyticsPageTablePager extends WatchAnalyticsTablePager { - protected $isSortable = array( + protected $isSortable = [ 'page_ns_and_title' => true, 'num_watches' => true, 'num_reviewed' => true, @@ -10,9 +10,9 @@ class WatchAnalyticsPageTablePager extends WatchAnalyticsTablePager { 'max_pending_minutes' => true, 'avg_pending_minutes' => true, 'watch_quality' => true, - ); + ]; - public function __construct( $page, $conds, $filters = array() ) { + public function __construct( $page, $conds, $filters = [] ) { global $wgRequest; $this->watchQuery = new PageWatchesQuery(); @@ -26,7 +26,7 @@ public function __construct( $page, $conds, $filters = array() ) { $this->mDefaultDirection = false; } - $this->mExtraSortFields = array( 'num_watches', 'num_reviewed', 'page_ns_and_title' ); + $this->mExtraSortFields = [ 'num_watches', 'num_reviewed', 'page_ns_and_title' ]; } public function getQueryInfo() { @@ -36,18 +36,16 @@ public function getQueryInfo() { && $this->mQueryNamespace >= 0 && isset( $namespaces[ $this->mQueryNamespace ] ) ) { - $conds = array( + $conds = [ 'p.page_namespace = ' . $this->mQueryNamespace - ); - } - else { - $conds = array(); + ]; + } else { + $conds = []; } return $this->watchQuery->getQueryInfo( $conds ); } - public function formatValue ( $fieldName , $value ) { - + public function formatValue( $fieldName, $value ) { if ( $fieldName === 'page_ns_and_title' ) { $pageInfo = explode( ':', $value, 2 ); $pageNsIndex = $pageInfo[0]; @@ -59,49 +57,42 @@ public function formatValue ( $fieldName , $value ) { $titleNsText = $title->getNsText(); if ( $titleNsText === '' ) { $titleFullText = $title->getText(); - } - else { + } else { $titleFullText = $titleNsText . ':' . $title->getText(); } $pageLink = Xml::element( 'a', - array( 'href' => $titleURL ), + [ 'href' => $titleURL ], $titleFullText ); - // FIXME: page stats not currently enabled. Uncomment when enabled - $url = SpecialPage::getTitleFor( 'PageStatistics' )->getInternalURL( array( + $url = SpecialPage::getTitleFor( 'PageStatistics' )->getInternalURL( [ 'page' => $title->getPrefixedText() - ) ); + ] ); $msg = wfMessage( 'watchanalytics-view-page-stats' ); $pageStatsLink = Xml::element( 'a', - array( 'href' => $url ), + [ 'href' => $url ], $msg ); - $pageLink .= ' (' . $pageStatsLink . ' | ' . WatchSuggest::getWatchLink( $title ) . ')'; - return $pageLink; - } - else if ( $fieldName === 'max_pending_minutes' || $fieldName === 'avg_pending_minutes' ) { - return ( $value === NULL ) ? NULL : $this->watchQuery->createTimeStringFromMinutes( $value ); - } - else { + } elseif ( $fieldName === 'max_pending_minutes' || $fieldName === 'avg_pending_minutes' ) { + return ( $value === null ) ? null : $this->watchQuery->createTimeStringFromMinutes( $value ); + } else { return $value; } - } public function getFieldNames() { return $this->watchQuery->getFieldNames(); } - public function getDefaultSort () { + public function getDefaultSort() { return 'num_reviewed'; } diff --git a/includes/WatchAnalyticsParserFunctions.php b/includes/WatchAnalyticsParserFunctions.php index 20b2ec3..40b9d47 100644 --- a/includes/WatchAnalyticsParserFunctions.php +++ b/includes/WatchAnalyticsParserFunctions.php @@ -1,89 +1,53 @@ setFunctionHook( 'underwatched_categories', - array( + [ 'WatchAnalyticsParserFunctions', // class to call function from 'renderUnderwatchedCategories' // function to call within that class - ), + ], SFH_OBJECT_ARGS ); // pages needing watchers $parser->setFunctionHook( 'watchers_needed', - array( + [ 'WatchAnalyticsParserFunctions', 'renderWatchersNeeded' - ), + ], SFH_OBJECT_ARGS ); - return true; - } - static public function processArgs( $frame, $args, $defaults ) { - $new_args = array(); + public static function processArgs( $frame, $args, $defaults ) { + $new_args = []; $num_args = count( $args ); $num_defaults = count( $defaults ); $count = ( $num_args > $num_defaults ) ? $num_args : $num_defaults; for ( $i = 0; $i < $count; $i++ ) { - if ( isset( $args[$i] ) ) + if ( isset( $args[$i] ) ) { $new_args[$i] = trim( $frame->expand( $args[$i] ) ); - else + } else { $new_args[$i] = $defaults[$i]; + } } return $new_args; } - static public function renderUnderwatchedCategories ( &$parser, $frame, $args ) { - + public static function renderUnderwatchedCategories( &$parser, $frame, $args ) { // @TODO: currently these do nothing. The namespace arg needs to be text // provided by the user, so this method needs to convert "Main" to zero, etc // $args = self::processArgs( $frame, $args, array(0) ); // $namespace = $args[0]; - $dbr = wfGetDB( DB_SLAVE ); + $dbr = wfGetDB( DB_REPLICA ); $query = " SELECT * FROM ( @@ -111,15 +75,14 @@ static public function renderUnderwatchedCategories ( &$parser, $frame, $args ) $output = "{| class=\"wikitable sortable\"\n"; $output .= "! Category !! Number of Under-watched pages\n"; - $categories = array(); + $categories = []; while ( $row = $dbr->fetchObject( $result ) ) { - $pageCategories = explode( ';' , $row->categories ); + $pageCategories = explode( ';', $row->categories ); foreach ( $pageCategories as $cat ) { - if ( isset ( $categories[ $cat ] ) ) { + if ( isset( $categories[ $cat ] ) ) { $categories[ $cat ]++; - } - else { + } else { $categories[ $cat ] = 1; } } @@ -131,8 +94,7 @@ static public function renderUnderwatchedCategories ( &$parser, $frame, $args ) if ( $cat === '' ) { $catLink = "''Uncategorized''"; - } - else { + } else { $catTitle = Category::newFromName( $cat )->getTitle(); $catLink = "[[:$catTitle|" . $catTitle->getText() . "]]"; } @@ -146,12 +108,12 @@ static public function renderUnderwatchedCategories ( &$parser, $frame, $args ) return $output; } - static public function renderWatchersNeeded ( &$parser, $frame, $args ) { + public static function renderWatchersNeeded( &$parser, $frame, $args ) { global $wgUser; $wgUserId = $wgUser->getId(); - $args = self::processArgs( $frame, $args, array( 0, 60, 3, 10 ) ); + $args = self::processArgs( $frame, $args, [ 0, 60, 3, 10 ] ); $namespace = intval( $args[0] ); $numDays = intval( $args[1] ); $maxWatchers = intval( $args[2] ); @@ -159,7 +121,7 @@ static public function renderWatchersNeeded ( &$parser, $frame, $args ) { $rangeTimestamp = date( 'YmdHis', time() - ( $numDays * 24 * 60 * 60 ) ); - $dbr = wfGetDB( DB_SLAVE ); + $dbr = wfGetDB( DB_REPLICA ); if ( class_exists( 'Wiretap' ) && false ) { $query = @@ -193,8 +155,7 @@ static public function renderWatchersNeeded ( &$parser, $frame, $args ) { ORDER BY unique_hits DESC LIMIT 20"; - } - else { + } else { $query = "SELECT page_title, page_namespace FROM ( SELECT @@ -234,22 +195,21 @@ static public function renderWatchersNeeded ( &$parser, $frame, $args ) { // $output .= "* [[$title]] - '''[$watchURL watch]'''\n"; $output .= Xml::tags( 'li', - array(), + [], self::makeWatchLink( $row->page_namespace, $row->page_title ) ); } - $output = Xml::tags( 'ul', array(), $output ); + $output = Xml::tags( 'ul', [], $output ); - return array( + return [ 0 => $output, 'isHTML' => true, - ); - + ]; } - static protected function makeWatchLink ( $ns, $titleText ) { + protected static function makeWatchLink( $ns, $titleText ) { global $wgContLang, $wgUser; $context = RequestContext::getMain(); @@ -261,7 +221,7 @@ static protected function makeWatchLink ( $ns, $titleText ) { // Perhaps the parser function should offer an option as to whether or // not to display invalid pages? if ( !$nt ) { - return Html::element( 'span', array( 'class' => 'mw-invalidtitle' ), + return Html::element( 'span', [ 'class' => 'mw-invalidtitle' ], Linker::getInvalidTitleDescription( $context, $ns, $titleText ) ); } @@ -272,8 +232,8 @@ static protected function makeWatchLink ( $ns, $titleText ) { $wlink = Linker::linkKnown( $nt, $context->msg( 'watch' )->escaped(), - array( 'class' => 'mw-watch-link watch-analytics-watchers-needed-link' ), - array( 'action' => 'watch', 'token' => $token ) + [ 'class' => 'mw-watch-link watch-analytics-watchers-needed-link' ], + [ 'action' => 'watch', 'token' => $token ] ); return $context->getLanguage()->specialList( $plink, $wlink ); diff --git a/includes/WatchAnalyticsTablePager.php b/includes/WatchAnalyticsTablePager.php index e040e32..50ea5ca 100644 --- a/includes/WatchAnalyticsTablePager.php +++ b/includes/WatchAnalyticsTablePager.php @@ -2,7 +2,7 @@ abstract class WatchAnalyticsTablePager extends TablePager { - public function __construct( $page, $conds, $filters = array() ) { + public function __construct( $page, $conds, $filters = [] ) { $this->page = $page; $this->limit = $page->limit; $this->offset = $page->offset; @@ -32,40 +32,35 @@ public function __construct( $page, $conds, $filters = array() ) { } public function getIndexField() { - global $wgRequest; $sortField = $wgRequest->getVal( 'sort' ); if ( isset( $sortField ) && $this->isFieldSortable( $sortField ) ) { return $sortField; - } - else { + } else { return $this->getDefaultSort(); } - } public function isNavigationBarShown() { return true; } - public function isFieldSortable ( $field ) { + public function isFieldSortable( $field ) { if ( ! isset( $this->isSortable[$field] ) ) { return false; - } - else { + } else { return $this->isSortable[ $field ]; } } - /** * Do a query with specified parameters, rather than using the object * context * * @param string $offset index offset, inclusive - * @param $limit Integer: exact query limit - * @param $descending Boolean: query direction, false for ascending, true for descending + * @param int $limit exact query limit + * @param bool $descending Boolean: query direction, false for ascending, true for descending * @return ResultWrapper */ public function reallyDoQuery( $offset, $limit, $descending ) { @@ -78,18 +73,18 @@ public function reallyDoQuery( $offset, $limit, $descending ) { // code below adapted from MW 1.22 core, Pager.php, // IndexPager::buildQueryInfo() - $sortColumns = array_merge( array( $this->mIndexField ), $this->mExtraSortFields ); + $sortColumns = array_merge( [ $this->mIndexField ], $this->mExtraSortFields ); if ( $descending ) { $options['ORDER BY'] = $sortColumns; } else { - $orderBy = array(); + $orderBy = []; foreach ( $sortColumns as $col ) { $orderBy[] = $col . ' DESC'; } $options['ORDER BY'] = $orderBy; } if ( $offset != '' ) { - if ( intval ( $offset ) < 0 ) { + if ( intval( $offset ) < 0 ) { $offset = 0; } $options['OFFSET'] = $offset; @@ -97,11 +92,10 @@ public function reallyDoQuery( $offset, $limit, $descending ) { $options['LIMIT'] = intval( $limit ); // end adapted code - $dbr = wfGetDB( DB_SLAVE ); + $dbr = wfGetDB( DB_REPLICA ); return $dbr->select( $tables, $fields, $conds, __METHOD__, $options, $join_conds ); } - /** * Override IndexPager in includes/Pager.php. * @@ -115,17 +109,14 @@ public function getPagingQueries() { if ( isset( $this->offset ) ) { $offset = $this->offset; - } - else { + } else { $offset = 0; } - if ( $offset <= 0 ) { $queries['prev'] = false; $queries['first'] = false; - } - else if ( isset( $queries['prev']['offset'] ) ) { + } elseif ( isset( $queries['prev']['offset'] ) ) { $queries['prev']['offset'] = $offset - $this->limit; } @@ -134,10 +125,8 @@ public function getPagingQueries() { } return $queries; - } - /** * Creates form to filter Watch Analytics results (e.g. by user group or * page category). @@ -145,19 +134,20 @@ public function getPagingQueries() { * FIXME: this is the ugly method taken from SpecialAllmessages...I'm * hoping MW has a better way (templating engine?) to do this now than it * did when SpecialAllmessages was created... + * + * @return string */ public function buildForm() { global $wgScript; // user group filter - $groups = array( $this->msg( 'watchanalytics-user-group-no-filter' )->text() => '' ); + $groups = [ $this->msg( 'watchanalytics-user-group-no-filter' )->text() => '' ]; $rawGroups = User::getAllGroups(); foreach ( $rawGroups as $group ) { $labelMsg = $this->msg( 'group-' . $group ); if ( $labelMsg->exists() ) { $label = $labelMsg->text(); - } - else { + } else { $label = $group; } $groups[ $label ] = $group; @@ -166,15 +156,15 @@ public function buildForm() { $groupFilter->addOptions( $groups ); // category filter - $dbr = wfGetDB( DB_SLAVE ); + $dbr = wfGetDB( DB_REPLICA ); $result = $dbr->select( 'categorylinks', 'cl_to', '', __METHOD__, - array( 'DISTINCT' ) + [ 'DISTINCT' ] ); - $categories = array( $this->msg( 'watchanalytics-category-no-filter' )->text() => '' ); + $categories = [ $this->msg( 'watchanalytics-category-no-filter' )->text() => '' ]; while ( $row = $result->fetchRow() ) { $category = Category::newFromName( $row['cl_to'] ); $label = $category->getTitle()->getText(); @@ -186,7 +176,7 @@ public function buildForm() { $out = // create the form element - Xml::openElement( 'form', array( 'method' => 'get', 'action' => $wgScript, 'id' => 'ext-watchanalytics-form' ) ) . + Xml::openElement( 'form', [ 'method' => 'get', 'action' => $wgScript, 'id' => 'ext-watchanalytics-form' ] ) . // create fieldset Xml::fieldset( $this->msg( 'allmessages-filter-legend' )->text() ) . @@ -195,8 +185,7 @@ public function buildForm() { Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . // create table for form elements - Xml::openElement( 'table', array( 'class' => 'ext-watchanalytics-stats-filter-table' ) ) . "\n" . - + Xml::openElement( 'table', [ 'class' => 'ext-watchanalytics-stats-filter-table' ] ) . "\n" . // filter results by user group ' @@ -247,7 +236,7 @@ public function buildForm() { // FIXME: are all of these needed? are additional need to support // WatchAnalytics fields? - $this->getHiddenFields( array( 'title', 'prefix', 'filter', 'lang', 'limit', 'groupfilter', 'categoryfilter' ) ) . + $this->getHiddenFields( [ 'title', 'prefix', 'filter', 'lang', 'limit', 'groupfilter', 'categoryfilter' ] ) . // close fieldset and form elements Xml::closeElement( 'fieldset' ) . diff --git a/includes/WatchAnalyticsUserTablePager.php b/includes/WatchAnalyticsUserTablePager.php index 9769eb7..99e3759 100644 --- a/includes/WatchAnalyticsUserTablePager.php +++ b/includes/WatchAnalyticsUserTablePager.php @@ -2,7 +2,7 @@ class WatchAnalyticsUserTablePager extends WatchAnalyticsTablePager { - protected $isSortable = array( + protected $isSortable = [ 'user_name' => true, 'num_watches' => true, 'num_pending' => true, @@ -10,9 +10,9 @@ class WatchAnalyticsUserTablePager extends WatchAnalyticsTablePager { 'max_pending_minutes' => true, 'avg_pending_minutes' => true, 'engagement_score' => true, - ); + ]; - public function __construct( $page, $conds, $filters = array() ) { + public function __construct( $page, $conds, $filters = [] ) { $this->watchQuery = new UserWatchesQuery(); parent::__construct( $page, $conds, $filters ); } @@ -21,8 +21,7 @@ public function getQueryInfo() { return $this->watchQuery->getQueryInfo(); } - public function formatValue ( $fieldName , $value ) { - + public function formatValue( $fieldName, $value ) { if ( $fieldName === 'user_name' ) { $user_name = $value; @@ -39,32 +38,29 @@ public function formatValue ( $fieldName , $value ) { */ $url = Title::newFromText( 'Special:PendingReviews' )->getLocalUrl( - array( 'user' => $user_name ) + [ 'user' => $user_name ] ); $msg = wfMessage( 'watchanalytics-view-user-pendingreviews' ); $name .= ' (' . Xml::element( 'a', - array( 'href' => $url ), + [ 'href' => $url ], $msg ) . ')'; return $name; - } - else if ( $fieldName === 'max_pending_minutes' || $fieldName === 'avg_pending_minutes' ) { - return ( $value === NULL ) ? NULL : $this->watchQuery->createTimeStringFromMinutes( $value ); - } - else { + } elseif ( $fieldName === 'max_pending_minutes' || $fieldName === 'avg_pending_minutes' ) { + return ( $value === null ) ? null : $this->watchQuery->createTimeStringFromMinutes( $value ); + } else { return $value; } - } public function getFieldNames() { return $this->watchQuery->getFieldNames(); } - public function getDefaultSort () { + public function getDefaultSort() { return 'num_pending'; } diff --git a/includes/WatchAnalyticsWikiTablePager.php b/includes/WatchAnalyticsWikiTablePager.php index f01c72c..03205c8 100644 --- a/includes/WatchAnalyticsWikiTablePager.php +++ b/includes/WatchAnalyticsWikiTablePager.php @@ -2,7 +2,7 @@ class WatchAnalyticsWikiTablePager extends WatchAnalyticsTablePager { - protected $isSortable = array( + protected $isSortable = [ 'tracking_timestamp' => true, 'num_pages' => true, @@ -26,12 +26,12 @@ class WatchAnalyticsWikiTablePager extends WatchAnalyticsTablePager { 'content_num_one_watched' => true, 'content_num_unreviewed' => true, 'content_num_one_reviewed' => true, - ); + ]; public function __construct( $page, $conds ) { $this->watchQuery = new WikiWatchesQuery(); - parent::__construct( $page , $conds ); + parent::__construct( $page, $conds ); global $wgRequest; @@ -40,40 +40,36 @@ public function __construct( $page, $conds ) { $this->mDefaultDirection = false; } - $this->mExtraSortFields = array(); + $this->mExtraSortFields = []; } public function getQueryInfo() { return $this->watchQuery->getQueryInfo(); } - public function formatValue ( $fieldName , $value ) { - - $timeDiffFields = array( + public function formatValue( $fieldName, $value ) { + $timeDiffFields = [ 'max_pending_minutes', 'avg_pending_minutes', 'content_max_pending_minutes', 'content_avg_pending_minutes', - ); + ]; if ( in_array( $fieldName, $timeDiffFields ) ) { - return ( $value === NULL ) ? NULL : $this->watchQuery->createTimeStringFromMinutes( $value ); - } - else if ( $fieldName === 'tracking_timestamp' ) { + return ( $value === null ) ? null : $this->watchQuery->createTimeStringFromMinutes( $value ); + } elseif ( $fieldName === 'tracking_timestamp' ) { $ts = new MWTimestamp( $value ); return $ts->format( 'Y-m-d' ) . '
' . $ts->format( 'H:i:s' ); - } - else { + } else { return $value; } - } public function getFieldNames() { return $this->watchQuery->getFieldNames(); } - public function getDefaultSort () { + public function getDefaultSort() { return 'tracking_timestamp'; } @@ -84,7 +80,7 @@ public function getDefaultSort () { * * @return string empty string */ - public function buildForm () { + public function buildForm() { return ''; } -} \ No newline at end of file +} diff --git a/includes/WatchStateRecorder.php b/includes/WatchStateRecorder.php index 66bf5f8..2bac059 100644 --- a/includes/WatchStateRecorder.php +++ b/includes/WatchStateRecorder.php @@ -1,45 +1,11 @@ 0 ) ? intval( $withinHours ) : 1; $withinDays = floor( $withinHours / 24 ); if ( $withinDays > 0 ) { @@ -56,31 +22,27 @@ public function recordedWithinHours ( $withinHours = 1 ) { return true; } - public function getLatestAllWikiTimestamp () { - - $dbr = wfGetDB( DB_SLAVE ); + public function getLatestAllWikiTimestamp() { + $dbr = wfGetDB( DB_REPLICA ); $result = $dbr->selectRow( 'watch_tracking_wiki', 'tracking_timestamp', '', // conds __METHOD__, - array( + [ 'LIMIT' => 1, 'ORDER BY' => 'tracking_timestamp DESC', - ), + ], null // join_conds ); if ( $result && $result->tracking_timestamp ) { return new MWTimestamp( $result->tracking_timestamp ); - } - else { + } else { return new MWTimestamp( '19700101000000' ); } - } public function recordAll() { - $this->dbw = wfGetDB( DB_MASTER ); // get user and page info @@ -91,25 +53,24 @@ public function recordAll() { $pageQueryInfo = $pageWatchQuery->getQueryInfo(); // override fields - $userQueryInfo['fields'] = array( + $userQueryInfo['fields'] = [ 'u.user_id AS user_id', $userWatchQuery->sqlNumWatches, $userWatchQuery->sqlNumPending, - ); - $pageQueryInfo['fields'] = array( + ]; + $pageQueryInfo['fields'] = [ 'p.page_id AS page_id', 'p.page_namespace AS page_namespace', // needed only for all-wiki info $pageWatchQuery->sqlNumWatches, $pageWatchQuery->sqlNumReviewed, - ); + ]; - - $users = $this->fetchAllFromQueryInfo( $userQueryInfo, array( + $users = $this->fetchAllFromQueryInfo( $userQueryInfo, [ 'user_id', 'num_watches', 'num_pending' - ) ); - $pages = $this->fetchAllFromQueryInfo( $pageQueryInfo, array( + ] ); + $pages = $this->fetchAllFromQueryInfo( $pageQueryInfo, [ 'page_id', 'page_namespace', 'num_watches', 'num_reviewed' - ) ); + ] ); $now = new MWTimestamp(); $now = $now->format( 'YmdHis' ); @@ -140,8 +101,7 @@ public function recordAll() { if ( $pageNS === NS_MAIN ) { $nsMainUnwatched++; } - } - else if ( $numWatches === 1 ) { + } elseif ( $numWatches === 1 ) { $oneWatched++; if ( $pageNS === NS_MAIN ) { $nsMainOneWatched++; @@ -153,8 +113,7 @@ public function recordAll() { if ( $pageNS === NS_MAIN ) { $nsMainUnreviewed++; } - } - else if ( $numReviewed === 1 ) { + } elseif ( $numReviewed === 1 ) { $oneReviewed++; if ( $pageNS === NS_MAIN ) { $nsMainOneReviewed++; @@ -173,21 +132,21 @@ public function recordAll() { __METHOD__ ); - foreach ( array_chunk( $pages, 100 ) as $chunk ) { - $this->dbw->insert( - 'watch_tracking_page', - $chunk, - __METHOD__ - ); - } + foreach ( array_chunk( $pages, 100 ) as $chunk ) { + $this->dbw->insert( + 'watch_tracking_page', + $chunk, + __METHOD__ + ); + } // Get all wiki info $allWikiQueryInfo = $this->getWikiQueryInfo(); $mainWikiQueryInfo = $this->getWikiQueryInfo( NS_MAIN, 'content_' ); - $allNamespaces = $this->fetchAllFromQueryInfo( $allWikiQueryInfo, array( + $allNamespaces = $this->fetchAllFromQueryInfo( $allWikiQueryInfo, [ 'num_pages', 'num_watches', 'num_pending', 'max_pending_minutes', 'avg_pending_minutes' - ) ); + ] ); $allNamespaces[0][ 'max_pending_minutes' ] = $allNamespaces[0][ 'max_pending_minutes' ] @@ -197,10 +156,10 @@ public function recordAll() { $allNamespaces[0][ 'avg_pending_minutes' ] ? $allNamespaces[0][ 'avg_pending_minutes' ] : 0; - $contentOnly = $this->fetchAllFromQueryInfo( $mainWikiQueryInfo, array( + $contentOnly = $this->fetchAllFromQueryInfo( $mainWikiQueryInfo, [ 'content_num_pages', 'content_num_watches', 'content_num_pending', 'content_max_pending_minutes', 'content_avg_pending_minutes' - ) ); + ] ); $contentOnly[0][ 'content_max_pending_minutes' ] = $contentOnly[0][ 'content_max_pending_minutes' ] @@ -210,8 +169,7 @@ public function recordAll() { $contentOnly[0][ 'content_avg_pending_minutes' ] ? $contentOnly[0][ 'content_avg_pending_minutes' ] : 0; - - $allWikiAnalytics = $allNamespaces[0] + $contentOnly[0] + array( + $allWikiAnalytics = $allNamespaces[0] + $contentOnly[0] + [ 'tracking_timestamp' => $now, 'num_unwatched' => $unwatched, @@ -223,7 +181,7 @@ public function recordAll() { 'content_num_one_watched' => $nsMainOneWatched, 'content_num_unreviewed' => $nsMainUnreviewed, 'content_num_one_reviewed' => $nsMainOneReviewed, - ); + ]; $this->dbw->insert( 'watch_tracking_wiki', @@ -234,7 +192,7 @@ public function recordAll() { return true; } - public function fetchAllFromQueryInfo ( $queryInfo, $columnsToKeep ) { + public function fetchAllFromQueryInfo( $queryInfo, $columnsToKeep ) { $result = $this->dbw->select( $queryInfo['tables'], $queryInfo['fields'], @@ -244,7 +202,7 @@ public function fetchAllFromQueryInfo ( $queryInfo, $columnsToKeep ) { $queryInfo['join_conds'] ); - $output = array(); + $output = []; while ( $row = $result->fetchRow() ) { $c = count( $output ); @@ -256,51 +214,49 @@ public function fetchAllFromQueryInfo ( $queryInfo, $columnsToKeep ) { return $output; } - public function getWikiQueryInfo ( $namespace = false, $prefix = '' ) { - + public function getWikiQueryInfo( $namespace = false, $prefix = '' ) { $sqlNumPages = "COUNT( DISTINCT p.page_id ) AS {$prefix}num_pages"; $sqlNumWatches = "SUM( IF( w.wl_title IS NOT NULL, 1, 0) ) AS {$prefix}num_watches"; $sqlNumPending = "SUM( IF( w.wl_notificationtimestamp IS NULL, 0, 1) ) AS {$prefix}num_pending"; $sqlMaxPendingMins = "MAX( TIMESTAMPDIFF(MINUTE, w.wl_notificationtimestamp, UTC_TIMESTAMP()) ) AS {$prefix}max_pending_minutes"; $sqlAvgPendingMins = "AVG( TIMESTAMPDIFF(MINUTE, w.wl_notificationtimestamp, UTC_TIMESTAMP()) ) AS {$prefix}avg_pending_minutes"; - - $tables = array( + $tables = [ 'w' => 'watchlist', 'p' => 'page', - ); + ]; - $fields = array( + $fields = [ $sqlNumPages, $sqlNumWatches, $sqlNumPending, $sqlMaxPendingMins, $sqlAvgPendingMins, - ); + ]; - $join_conds = array( - 'p' => array( + $join_conds = [ + 'p' => [ 'RIGHT JOIN', 'p.page_namespace=w.wl_namespace AND p.page_title=w.wl_title' - ), - ); + ], + ]; - $options = array( + $options = [ // unlike pages, group by NOTHING // 'GROUP BY' => 'p.page_title, p.page_namespace' - ); + ]; $conds = ''; if ( $namespace !== false ) { $conds = 'p.page_namespace=' . $namespace; } - $return = array( + $return = [ 'tables' => $tables, 'fields' => $fields, 'join_conds' => $join_conds, 'conds' => $conds, 'options' => $options, - ); + ]; return $return; } @@ -308,44 +264,44 @@ public function getWikiQueryInfo ( $namespace = false, $prefix = '' ) { /** * Record relevant info in watch_tracking_page and watch_tracking_user * after a change to a page (e.g. an edit, a move, etc) + * + * @param WikiPage $wikipage + * @return bool */ - static public function recordPageChange ( $article ) { - + public static function recordPageChange( WikiPage $wikipage ) { $timestamp = date( "YmdHis", time() ); - $title = $article->getTitle(); + $title = $wikipage->getTitle(); // page watch stats list( $numWatchers, $numReviewed, $userIdArray ) = self::getPageWatchInfo( $title ); - // query for each users' total watches/reviews $userWQ = new UserWatchesQuery(); $userWatchStats = $userWQ->getMultiUserWatchStats( $userIdArray ); - $userInsertData = array(); + $userInsertData = []; foreach ( $userWatchStats as $uData ) { - $userInsertData[] = array( + $userInsertData[] = [ 'tracking_timestamp' => $timestamp, 'user_id' => $uData->wl_user, 'num_watches' => $uData->num_watches, 'num_pending' => $uData->num_pending, - ); + ]; } - $dbw = wfGetDB( DB_MASTER ); // insert into watch_tracking_page: $timestamp, $title->getId(), $numWatchers, $numReviewed $dbw->replace( 'watch_tracking_page', - array( array( 'tracking_timestamp', 'page_id' ) ), - array( - array( + [ [ 'tracking_timestamp', 'page_id' ] ], + [ + [ 'tracking_timestamp' => $timestamp, 'page_id' => $title->getArticleID(), 'num_watches' => $numWatchers, 'num_reviewed' => $numReviewed, - ), - ), + ], + ], __METHOD__ ); @@ -354,7 +310,7 @@ static public function recordPageChange ( $article ) { // watched to unwatched or unwatched to watched during the edit...maybe. $dbw->replace( 'watch_tracking_user', - array( array( 'tracking_timestamp', 'user_id' ) ), + [ [ 'tracking_timestamp', 'user_id' ] ], $userInsertData, __METHOD__ ); @@ -364,15 +320,13 @@ static public function recordPageChange ( $article ) { // all buildable by page table, except avg/max time return true; - } - static public function recordReview ( User $user, Title $title ) { - + public static function recordReview( User $user, Title $title ) { $timestamp = date( 'YmdHis', time() ); $userWQ = new UserWatchesQuery(); - $userWatchStats = $userWQ->getMultiUserWatchStats( array( $user->getId() ) ); + $userWatchStats = $userWQ->getMultiUserWatchStats( [ $user->getId() ] ); $dbw = wfGetDB( DB_MASTER ); @@ -382,13 +336,13 @@ static public function recordReview ( User $user, Title $title ) { // hasn't been cleared yet, suggesting it should be cleared again $dbw->replace( 'watch_tracking_user', - array( array( 'tracking_timestamp', 'user_id' ) ), - array( + [ [ 'tracking_timestamp', 'user_id' ] ], + [ 'tracking_timestamp' => $timestamp, 'user_id' => $userWatchStats[0]->wl_user, 'num_watches' => $userWatchStats[0]->num_watches, 'num_pending' => $userWatchStats[0]->num_pending, - ), + ], __METHOD__ ); @@ -397,22 +351,20 @@ static public function recordReview ( User $user, Title $title ) { $dbw->replace( 'watch_tracking_page', - array( array( 'tracking_timestamp', 'page_id' ) ), - array( + [ [ 'tracking_timestamp', 'page_id' ] ], + [ 'tracking_timestamp' => $timestamp, 'page_id' => $title->getArticleID(), 'num_watches' => $numWatchers, 'num_reviewed' => $numReviewed, - ), + ], __METHOD__ ); return true; - } - static public function getPageWatchInfo ( Title $title ) { - + public static function getPageWatchInfo( Title $title ) { // query for page watchers $pageWQ = new PageWatchesQuery(); $watchers = $pageWQ->getPageWatchers( $title->getDBkey(), $title->getNamespace() ); @@ -420,15 +372,15 @@ static public function getPageWatchInfo ( Title $title ) { // PHP count num watchers and reviewers (watchers could change if user (un)checks "watch this page" box) $numWatchers = count( $watchers ); $numReviewed = 0; - $userIdArray = array(); + $userIdArray = []; foreach ( $watchers as $w ) { - if ( $w->wl_notificationtimestamp === NULL ) { + if ( $w->wl_notificationtimestamp === null ) { $numReviewed++; } $userIdArray[] = $w->wl_user; } - return array( $numWatchers, $numReviewed, $userIdArray ); + return [ $numWatchers, $numReviewed, $userIdArray ]; } } diff --git a/includes/WatchSuggest.php b/includes/WatchSuggest.php index fd3ebdb..9804ec8 100644 --- a/includes/WatchSuggest.php +++ b/includes/WatchSuggest.php @@ -1,37 +1,4 @@ mUser = $user; - $this->dbr = wfGetDB( DB_SLAVE ); + $this->dbr = wfGetDB( DB_REPLICA ); } /** @@ -55,13 +22,12 @@ public function __construct ( User $user ) { * * @return bool */ - public function getWatchSuggestionList () { - + public function getWatchSuggestionList() { $html = ''; // gets id, NS and title of all pages in users watchlist in NS_MAIN $userWatchlist = $this->getUserWatchlist( $this->mUser, NS_MAIN ); - $linkedPages = array(); + $linkedPages = []; // if the user has pages from NS_MAIN in their watchlist then find all // pages linked to/from those pages @@ -69,7 +35,6 @@ public function getWatchSuggestionList () { $linkedPages = $this->getPagesRelatedByLinks( $userWatchlist ); } - if ( count( $linkedPages ) == 0 ) { // if the users watchlist in NS_MAIN is empty (e.g. probably a new user) @@ -82,18 +47,16 @@ public function getWatchSuggestionList () { __METHOD__ ); - $linkedPages = array(); + $linkedPages = []; // create "fake" $linkedPages where all pages in NS_MAIN are given the same number // of inbound/outbound links from the users watchlist while ( $row = $noWatchlist->fetchObject() ) { - $linkedPages[ $row->page_id ] = array( 'num_links' => 1 ); + $linkedPages[ $row->page_id ] = [ 'num_links' => 1 ]; } } - - $pageWatchQuery = new PageWatchesQuery; $pageWatchesAndViews = $pageWatchQuery->getPageWatchesAndViews( array_keys( $linkedPages ) ); @@ -105,19 +68,16 @@ public function getWatchSuggestionList () { $sortedPages = $this->sortPagesByWatchImportance( $linkedPages ); - global $wgUser; $userIsViewer = $wgUser->getId() == $this->mUser->getId(); - - $count = 1; $watchSuggestionsTitle = wfMessage( 'pendingreviews-watch-suggestion-title' )->text(); $watchSuggestionsDescription = wfMessage( 'pendingreviews-watch-suggestion-description' )->text(); global $egPendingReviewsNumberWatchSuggestions; - $watchSuggestionsLIs = array(); + $watchSuggestionsLIs = []; foreach ( $sortedPages as $pageId => $pageInfo ) { $suggestedTitle = Title::newFromID( $pageInfo[ 'page_id' ] ); @@ -132,8 +92,7 @@ public function getWatchSuggestionList () { if ( $userIsViewer ) { $watchLink = '' . self::getWatchLink( $suggestedTitle ) . ': '; - } - else { + } else { $watchLink = ''; } @@ -159,79 +118,70 @@ public function getWatchSuggestionList () { . WatchAnalyticsHtmlHelper::formatListArray( $this->getMostWatchesListArray( $numTopWatchers ), 2 ); return $html; - } - - - public function getUserWatchlist ( User $user, $namespaces = array() ) { - + public function getUserWatchlist( User $user, $namespaces = [] ) { if ( ! is_array( $namespaces ) ) { if ( intval( $namespaces ) < 0 ) { throw new MWException( __METHOD__ . ' argument $namespace requires integer or array' ); } - $namespaces = array( $namespaces ); + $namespaces = [ $namespaces ]; } if ( count( $namespaces ) > 1 ) { $namespaceCondition = 'AND p.page_namespace IN (' . $this->dbr->makeList( $namespaces ) . ')'; - } - else if ( count( $namespaces ) === 1 ) { + } elseif ( count( $namespaces ) === 1 ) { $namespaceCondition = 'AND p.page_namespace = ' . $namespaces[0]; - } - else { + } else { $namespaceCondition = ''; } $userId = $user->getId(); // SELECT - // p.page_id AS p_id, - // w.wl_title AS p_title + // p.page_id AS p_id, + // w.wl_title AS p_title // FROM page AS p // LEFT JOIN watchlist AS w - // ON ( - // w.wl_namespace = p.page_namespace - // AND w.wl_title = p.page_title - // ) + // ON ( + // w.wl_namespace = p.page_namespace + // AND w.wl_title = p.page_title + // ) // WHERE - // w.wl_user = $userId - // AND p.page_namespace = 0 + // w.wl_user = $userId + // AND p.page_namespace = 0 $userWatchlist = $this->dbr->select( - array( + [ 'p' => 'page', 'w' => 'watchlist', - ), - array( + ], + [ 'p.page_id AS p_id', 'w.wl_namespace AS p_namespace', 'w.wl_title AS p_title', - ), + ], "w.wl_user=$userId " . $namespaceCondition, __METHOD__, - array(), // options - array( - 'w' => array( + [], // options + [ + 'w' => [ 'LEFT JOIN', 'w.wl_namespace = p.page_namespace AND w.wl_title = p.page_title' - ) - ) + ] + ] ); - $return = array(); + $return = []; while ( $row = $userWatchlist->fetchObject() ) { $return[] = $row; } - return $return; } - - public function getPagesRelatedByLinks ( $userWatchlist ) { - - $userWatchlistPageIds = array(); - $userWatchlistPageTitles = array(); + public function getPagesRelatedByLinks( $userWatchlist ) { + $userWatchlistPageIds = []; + $userWatchlistPageTitles = []; foreach ( $userWatchlist as $row ) { $userWatchlistPageIds[] = $row->p_id; @@ -244,82 +194,75 @@ public function getPagesRelatedByLinks ( $userWatchlist ) { $titles = $this->dbr->makeList( $userWatchlistPageTitles ); // SELECT - // pl.pl_from AS pl_from_id, - // p_to.page_id AS pl_to_id + // pl.pl_from AS pl_from_id, + // p_to.page_id AS pl_to_id // FROM pagelinks AS pl // INNER JOIN page AS p_to - // ON ( - // pl.pl_namespace = p_to.page_namespace - // AND pl.pl_title = p_to.page_title - // ) + // ON ( + // pl.pl_namespace = p_to.page_namespace + // AND pl.pl_title = p_to.page_title + // ) // WHERE - // pl.pl_from IN ( ) - // OR ( pl.pl_namespace = 0 AND pl.pl_title IN ( ) ) + // pl.pl_from IN ( ) + // OR ( pl.pl_namespace = 0 AND pl.pl_title IN ( ) ) $where = "pl.pl_from IN ($ids) " . " OR ( pl.pl_namespace = 0 AND pl.pl_title IN ($titles) )"; - $linkedPagesResult = $this->dbr->select( - array( + [ 'pl' => 'pagelinks', 'p_to' => 'page', - ), - array( + ], + [ 'pl.pl_from AS pl_from_id', 'p_to.page_id AS pl_to_id', - ), + ], $where, __METHOD__, - array(), // options - array( - 'p_to' => array( + [], // options + [ + 'p_to' => [ 'INNER JOIN', 'pl.pl_namespace = p_to.page_namespace AND pl.pl_title = p_to.page_title' - ), - ) + ], + ] ); - $linkedPages = array(); + $linkedPages = []; while ( $row = $linkedPagesResult->fetchObject() ) { if ( ! isset( $linkedPages[ $row->pl_from_id ] ) ) { $linkedPages[ $row->pl_from_id ] = 1; - } - else { + } else { $linkedPages[ $row->pl_from_id ]++; } if ( ! isset( $linkedPages[ $row->pl_to_id ] ) ) { $linkedPages[ $row->pl_to_id ] = 1; - } - else { + } else { $linkedPages[ $row->pl_to_id ]++; } } - $linkedPagesToKeep = array(); + $linkedPagesToKeep = []; foreach ( $linkedPages as $pageId => $numLinks ) { if ( ! in_array( $pageId, $userWatchlistPageIds ) ) { - $linkedPagesToKeep[ $pageId ] = array( 'num_links' => $numLinks ); + $linkedPagesToKeep[ $pageId ] = [ 'num_links' => $numLinks ]; } } return $linkedPagesToKeep; - } - - public function sortPagesByWatchImportance ( $pages ) { - - $watches = array(); - $links = array(); - $watchNeedArray = array(); - $sortedPages = array(); + public function sortPagesByWatchImportance( $pages ) { + $watches = []; + $links = []; + $watchNeedArray = []; + $sortedPages = []; foreach ( $pages as $pageId => $pageData ) { if ( isset( $pageData[ 'num_watches' ] ) ) { $numWatches = intval( $pageData[ 'num_watches' ] ); $numViews = intval( $pageData[ 'num_views' ] ); - } - else { + } else { $numWatches = 0; $numViews = 0; } @@ -327,13 +270,13 @@ public function sortPagesByWatchImportance ( $pages ) { $watchNeed = $numLinks * pow( $numViews, 2 ); - $sortedPages[] = array( + $sortedPages[] = [ 'page_id' => $pageId, 'num_watches' => $numWatches, 'num_links' => $numLinks, 'num_views' => $numViews, 'watch_need' => $watchNeed, - ); + ]; $watches[] = $numWatches; $links[] = $numLinks; $watchNeedArray[] = $watchNeed; @@ -343,62 +286,47 @@ public function sortPagesByWatchImportance ( $pages ) { return $sortedPages; } - // SELECT - // u.user_name AS uname, - // u.user_real_name AS name, - // COUNT( * ) AS user_watches - // FROM - // watchlist AS w - // RIGHT JOIN page AS p ON - // (w.wl_namespace = p.page_namespace AND w.wl_title = p.page_title) - // LEFT JOIN user AS u ON - // (w.wl_user = u.user_id) - // WHERE - // p.page_is_redirect = 0 - // GROUP BY w.wl_user - // ORDER BY user_watches DESC - public function getMostWatchesListArray ( $limit = 20 ) { - + public function getMostWatchesListArray( $limit = 20 ) { $mostWatches = $this->dbr->select( - array( + [ 'w' => 'watchlist', 'p' => 'page', 'u' => 'user', - ), - array( + ], + [ 'u.user_name AS user_name', 'u.user_real_name AS real_name', 'COUNT( * ) AS user_watches', - ), + ], 'p.page_is_redirect = 0 AND w.wl_user != 0', // no redirects, and don't include maintenance scripts and other non-users __METHOD__, - array( + [ 'GROUP BY' => 'w.wl_user', 'ORDER BY' => 'user_watches DESC', 'LIMIT' => $limit, - ), - array( - 'p' => array( + ], + [ + 'p' => [ 'RIGHT JOIN', 'w.wl_namespace = p.page_namespace AND w.wl_title = p.page_title' - ), - 'u' => array( + ], + 'u' => [ 'LEFT JOIN', 'w.wl_user = u.user_id' - ), - ) + ], + ] ); - $return = array(); + $return = []; $count = 0; while ( $user = $mostWatches->fetchObject() ) { $count++; // CONSIDERING usering real name // if ( $user->real_name ) { - // $displayName = $user->real_name; + // $displayName = $user->real_name; // } // else { - // $displayName = $user->user_name; + // $displayName = $user->user_name; // } $watchUser = User::newFromName( $user->user_name ); @@ -414,33 +342,30 @@ public function getMostWatchesListArray ( $limit = 20 ) { } return $return; - } - public static function getWatchLink ( Title $title ) { - + public static function getWatchLink( Title $title ) { global $wgUser; // action=watch&token=9d1186bca6dd20866e607538b92be6c8%2B%5C - $watchLinkURL = $title->getLinkURL( array( + $watchLinkURL = $title->getLinkURL( [ 'action' => 'watch', 'token' => WatchAction::getWatchToken( $title, $wgUser ), - ) ); + ] ); $watchLink = Xml::element( 'a', - array( + [ 'href' => $watchLinkURL, 'class' => 'pendingreviews-watch-suggest-link', 'suggest-title-prefixed-text' => $title->getPrefixedDBkey(), 'thanks-msg' => wfMessage( 'pendingreviews-watch-suggestion-thanks' )->text()// FIXME: there's a better way - ), + ], wfMessage( 'pendingreviews-watch-suggestion-watchlink' )->text() ); return $watchLink; - } } diff --git a/includes/WatchesQuery.php b/includes/WatchesQuery.php index 9690534..f3e969c 100644 --- a/includes/WatchesQuery.php +++ b/includes/WatchesQuery.php @@ -1,37 +1,4 @@ 1 ) ? 's' : '' ); } @@ -118,7 +83,7 @@ public function createTimeStringFromMinutes ( $totalMinutes ) { } public function getFieldNames() { - $output = array(); + $output = []; foreach ( $this->fieldNames as $dbKey => $msg ) { $output[$dbKey] = wfMessage( $msg )->text(); @@ -128,45 +93,43 @@ public function getFieldNames() { } public function getQueryInfo() { + $this->conds = $this->conds ? $this->conds : []; - $this->conds = $this->conds ? $this->conds : array(); - - if ( isset ( $this->limit ) ) { + if ( isset( $this->limit ) ) { $this->options['LIMIT'] = $this->limit; } - if ( isset ( $this->offset ) ) { + if ( isset( $this->offset ) ) { $this->options['OFFSET'] = $this->offset; } - $return = array( + $return = [ 'tables' => $this->tables, 'fields' => $this->fields, 'join_conds' => $this->join_conds, 'conds' => $this->conds, 'options' => $this->options, - ); + ]; return $return; - } - public function setUserGroupFilter ( $ugf ) { + public function setUserGroupFilter( $ugf ) { if ( $ugf ) { $this->userGroupFilter = $ugf; } } - public function setCategoryFilter ( $cf ) { + public function setCategoryFilter( $cf ) { if ( $cf ) { $this->categoryFilter = $cf; } } - public function setCategoryFilterQueryInfo () { + public function setCategoryFilterQueryInfo() { $this->tables['cat'] = 'categorylinks'; - $this->join_conds['cat'] = array( + $this->join_conds['cat'] = [ 'RIGHT JOIN', 'cat.cl_from = p.page_id AND cat.cl_to = "' . $this->categoryFilter . '"' - ); + ]; } } diff --git a/includes/WikiWatchesQuery.php b/includes/WikiWatchesQuery.php index 376cabd..c7569e6 100644 --- a/includes/WikiWatchesQuery.php +++ b/includes/WikiWatchesQuery.php @@ -1,48 +1,15 @@ 'watchanalytics-special-header-timestamp', 'num_pages' => 'watchanalytics-special-header-num-pages', - 'num_watches' => 'watchanalytics-special-header-watches', - 'num_pending' => 'watchanalytics-special-header-pending-watches', - 'max_pending_minutes' => 'watchanalytics-special-header-pending-maxtime', - 'avg_pending_minutes' => 'watchanalytics-special-header-pending-averagetime', + 'num_watches' => 'watchanalytics-special-header-watches', + 'num_pending' => 'watchanalytics-special-header-pending-watches', + 'max_pending_minutes' => 'watchanalytics-special-header-pending-maxtime', + 'avg_pending_minutes' => 'watchanalytics-special-header-pending-averagetime', 'num_unwatched' => 'watchanalytics-special-header-num-unwatched', 'num_one_watched' => 'watchanalytics-special-header-num-one-watched', @@ -59,15 +26,14 @@ class WikiWatchesQuery extends WatchesQuery { // 'content_num_one_watched' => 'watchanalytics-special-header-main-num-one-watched', // 'content_num_unreviewed' => 'watchanalytics-special-header-main-num-unreviewed', // 'content_num_one_reviewed' => 'watchanalytics-special-header-main-num-one-reviewed', - ); + ]; public function getQueryInfo( $conds = null ) { - - $this->tables = array( + $this->tables = [ 'w' => 'watch_tracking_wiki' - ); + ]; - $this->fields = array( + $this->fields = [ 'tracking_timestamp', 'num_pages', @@ -91,16 +57,15 @@ public function getQueryInfo( $conds = null ) { // 'content_num_one_watched', // 'content_num_unreviewed', // 'content_num_one_reviewed', - ); + ]; - $this->conds = $conds ? $conds : array(); + $this->conds = $conds ? $conds : []; - $this->join_conds = array(); + $this->join_conds = []; - $this->options = array(); + $this->options = []; return parent::getQueryInfo(); - } } diff --git a/maintenance/addCategoryToWatchlist.php b/maintenance/addCategoryToWatchlist.php index e78a7d0..a2bd286 100644 --- a/maintenance/addCategoryToWatchlist.php +++ b/maintenance/addCategoryToWatchlist.php @@ -30,21 +30,15 @@ // Allow people to have different layouts. if ( ! isset( $IP ) ) { $IP = __DIR__ . '/../../../'; - if ( getenv("MW_INSTALL_PATH") ) { - $IP = getenv("MW_INSTALL_PATH"); + if ( getenv( "MW_INSTALL_PATH" ) ) { + $IP = getenv( "MW_INSTALL_PATH" ); } } -require_once( "$IP/maintenance/Maintenance.php" ); +require_once "$IP/maintenance/Maintenance.php"; class WatchAnalyticsAddCategoryToWatchlist extends Maintenance { - /** - * Add description - * - * @param string $varName add description - * @return null - */ public function __construct() { parent::__construct(); @@ -62,18 +56,11 @@ public function __construct() { true, true ); // $this->addOption( - // 'dry-run', - // "List whether a page will be added to a user's watchlist, but do not perform action", - // false, true ); - + // 'dry-run', + // "List whether a page will be added to a user's watchlist, but do not perform action", + // false, true ); } - /** - * Add description - * - * @param string $varName add description - * @return null - */ public function execute() { $dbw = wfGetDB( DB_MASTER ); @@ -83,12 +70,11 @@ public function execute() { foreach ( $namesArray as $i => $u ) { $namesArray[$i] = trim( $u ); } - } - else { + } else { die( 'You must supply at least one username' ); } - $users = array(); + $users = []; foreach ( $namesArray as $username ) { $users[] = User::newFromName( $username ); } @@ -99,8 +85,7 @@ public function execute() { foreach ( $catsArray as $i => $c ) { $catsArray[$i] = trim( $c ); } - } - else { + } else { die( 'You must supply at least one category' ); } @@ -124,8 +109,7 @@ public function execute() { if ( $watchedItem->isWatched() ) { $this->output( "already watching\n" ); - } - else { + } else { $watchedItem->addWatch(); $this->output( "added to watchlist\n" ); } @@ -142,4 +126,4 @@ public function execute() { } $maintClass = "WatchAnalyticsAddCategoryToWatchlist"; -require_once( DO_MAINTENANCE ); +require_once RUN_MAINTENANCE_IF_MAIN; diff --git a/maintenance/forgivePendingReviews.php b/maintenance/forgivePendingReviews.php index 29666e1..1351ecc 100644 --- a/maintenance/forgivePendingReviews.php +++ b/maintenance/forgivePendingReviews.php @@ -29,12 +29,12 @@ // Allow people to have different layouts. if ( ! isset( $IP ) ) { $IP = __DIR__ . '/../../../'; - if ( getenv("MW_INSTALL_PATH") ) { - $IP = getenv("MW_INSTALL_PATH"); + if ( getenv( "MW_INSTALL_PATH" ) ) { + $IP = getenv( "MW_INSTALL_PATH" ); } } -require_once( "$IP/maintenance/Maintenance.php" ); +require_once "$IP/maintenance/Maintenance.php"; class WatchAnalyticsForgivePendingReviews extends Maintenance { @@ -63,33 +63,8 @@ public function __construct() { 'reviewedby', 'Limit forgiveness to pages which have been reviewed by at least the specified number of people (default ' . $this->forgiveBefore . ')', false, true ); - } - // $query = - // "SELECT - // u.user_name AS user_name, - // p.page_title AS title, - // w.wl_notificationtimestamp AS pending_since - // FROM watchlist AS w - // LEFT JOIN page AS p ON - // w.wl_title = p.page_title - // AND w.wl_namespace = p.page_namespace - // LEFT JOIN user AS u ON - // u.user_id = w.wl_user - // WHERE - // w.wl_notificationtimestamp IS NOT NULL - // AND w.wl_notificationtimestamp < $forgiveBefore - // AND ( - // SELECT COUNT(*) - // FROM watchlist AS w2 - // WHERE - // w.wl_namespace = w2.wl_namespace - // AND w.wl_title = w2.wl_title - // AND w2.wl_notificationtimestamp IS NULL - // ) >= $reviewedBy - // $usernames - // ORDER BY w.wl_notificationtimestamp DESC;"; public function execute() { $dbw = wfGetDB( DB_MASTER ); @@ -102,12 +77,10 @@ public function execute() { $namesForDB = $dbw->makeList( $namesArray ); $usernames = "AND u.user_name IN ($namesForDB)"; - } - else { + } else { $usernames = ''; } - $forgiveBefore = $this->getOption( 'forgivebefore', $this->forgiveBefore ); $reviewedBy = $this->getOption( 'reviewedby', $this->reviewedBy ); @@ -144,4 +117,4 @@ public function execute() { } $maintClass = "WatchAnalyticsForgivePendingReviews"; -require_once( DO_MAINTENANCE ); +require_once RUN_MAINTENANCE_IF_MAIN; diff --git a/maintenance/watchAnalyticsRecordState.php b/maintenance/watchAnalyticsRecordState.php index 9b81f00..400389a 100644 --- a/maintenance/watchAnalyticsRecordState.php +++ b/maintenance/watchAnalyticsRecordState.php @@ -29,12 +29,12 @@ // Allow people to have different layouts. if ( ! isset( $IP ) ) { $IP = __DIR__ . '/../../../'; - if ( getenv("MW_INSTALL_PATH") ) { - $IP = getenv("MW_INSTALL_PATH"); + if ( getenv( "MW_INSTALL_PATH" ) ) { + $IP = getenv( "MW_INSTALL_PATH" ); } } -require_once( "$IP/maintenance/Maintenance.php" ); +require_once "$IP/maintenance/Maintenance.php"; class WatchAnalyticsRecordState extends Maintenance { @@ -52,4 +52,4 @@ public function execute() { } $maintClass = "WatchAnalyticsRecordState"; -require_once( DO_MAINTENANCE ); +require_once RUN_MAINTENANCE_IF_MAIN; diff --git a/schema/WatchAnalyticsUpdaterHooks.php b/schema/WatchAnalyticsUpdaterHooks.php index f300b4f..fe68b63 100644 --- a/schema/WatchAnalyticsUpdaterHooks.php +++ b/schema/WatchAnalyticsUpdaterHooks.php @@ -10,7 +10,6 @@ public static function onParserTestTables( &$tables ) { } public static function addSchemaUpdates( $updater = null ) { - // NOTE: this SQL file adds tables watch_tracking_user, // watch_tracking_page and watch_tracking_wiki. Since no changes have // been made to the database schema over the life of this extension so @@ -21,7 +20,7 @@ public static function addSchemaUpdates( $updater = null ) { // DB updates // For now, there's just a single SQL file for all DB types. // if ( $updater->getDB()->getType() == 'mysql' ) { - $updater->addExtensionUpdate( array( 'addTable', 'watch_tracking_user', __DIR__ . '/WatchAnalytics.sql', true ) ); + $updater->addExtensionUpdate( [ 'addTable', 'watch_tracking_user', __DIR__ . '/WatchAnalytics.sql', true ] ); // } return true; diff --git a/specials/SpecialClearPendingReviews.php b/specials/SpecialClearPendingReviews.php index 2ab408a..efaad31 100644 --- a/specials/SpecialClearPendingReviews.php +++ b/specials/SpecialClearPendingReviews.php @@ -22,7 +22,7 @@ public function execute( $par ) { $wgOut->addModules( 'ext.watchanalytics.clearpendingreviews.scripts' ); $output = $this->getOutput(); - //Defines input form + // Defines input form $formDescriptor = [ 'start' => [ 'section' => 'section1', @@ -37,7 +37,7 @@ public function execute( $par ) { 'type' => 'text', 'required' => 'true', 'validation-callback' => [ $this, 'validateTime' ], - 'help' => 'Current time: '.date('YmdHi').'00', + 'help' => 'Current time: ' . date( 'YmdHi' ) . '00', ], 'category' => [ 'section' => 'section2', @@ -58,7 +58,6 @@ public function execute( $par ) { $form->setSubmitName( 'preview' ); $form->setSubmitCallback( [ $this, 'trySubmit' ] ); $form->show(); - } public function validateTime( $dateField, $allData ) { @@ -66,12 +65,12 @@ public function validateTime( $dateField, $allData ) { return wfMessage( 'clearpendingreviews-date-invalid' )->inContentLanguage(); } - //Validates start time is before end time + // Validates start time is before end time if ( $allData['start'] > $allData['end'] ) { return wfMessage( 'clearpendingreviews-date-order-invalid' )->inContentLanguage(); } - //Verifys input format is ISO + // Verifys input format is ISO $dateTime = DateTime::createFromFormat( 'YmdHis', $dateField ); if ( $dateTime ) { return $dateTime->format( 'YmdHis' ) === $dateField; @@ -83,14 +82,14 @@ public function validateTime( $dateField, $allData ) { public function validateCategory( $categoryField, $allData ) { $bad_cat_name = false; - //Validates either Category or Title field is used - if ( empty( $categoryField ) && empty ( $allData['page'] ) ) { + // Validates either Category or Title field is used + if ( empty( $categoryField ) && empty( $allData['page'] ) ) { return wfMessage( 'clearpendingreviews-missing-date-category' )->inContentLanguage(); } - if ( empty ( $categoryField ) ) { + if ( empty( $categoryField ) ) { return true; } else { - //Verifys category exists in wiki + // Verifys category exists in wiki $category_title = Title::makeTitleSafe( NS_CATEGORY, $categoryField ); if ( !$category_title->exists() ) { return wfMessage( 'clearpendingreviews-category-invalid' )->inContentLanguage(); @@ -100,47 +99,46 @@ public function validateCategory( $categoryField, $allData ) { } /** - * @param array $data - * @param bool $clearPages - * @return $results - */ - + * @param array $data + * @param bool $clearPages + * @return $results + */ public static function doSearchQuery( $data, $clearPages ) { $dbw = wfGetDB( DB_REPLICA ); - $category = preg_replace('/\s+/', '_', $data['category']); - $page = preg_replace('/\s+/', '_', $data['page']); - $start = preg_replace('/\s+/', '', $data['start']); - $end = preg_replace('/\s+/', '', $data['end']); + $category = preg_replace( '/\s+/', '_', $data['category'] ); + $page = preg_replace( '/\s+/', '_', $data['page'] ); + $start = preg_replace( '/\s+/', '', $data['start'] ); + $end = preg_replace( '/\s+/', '', $data['end'] ); $conditions = ''; - if ($category) { + if ( $category ) { $conditions .= "c.cl_to='$category' AND "; } - if ($page) { + if ( $page ) { $conditions .= "w.wl_title LIKE '$page%' AND "; } - $tables = array( 'w' => 'watchlist', 'p' => 'page', 'c' => 'categorylinks' ); - $vars = array( 'w.*' ); + $tables = [ 'w' => 'watchlist', 'p' => 'page', 'c' => 'categorylinks' ]; + $vars = [ 'w.*' ]; $conditions .= "w.wl_notificationtimestamp IS NOT NULL AND w.wl_notificationtimestamp < $end AND w.wl_notificationtimestamp > $start"; - $join_conds = array( - 'p' => array( + $join_conds = [ + 'p' => [ 'LEFT JOIN', 'w.wl_title=p.page_title' - ), - 'c' => array( + ], + 'c' => [ 'LEFT JOIN', 'c.cl_from=p.page_id' - ) - ); + ] + ]; $results = $dbw->select( $tables, $vars, $conditions, __METHOD__, 'DISTINCT', $join_conds ); - if ( $clearPages == True ) { + if ( $clearPages == true ) { $dbw = wfGetDB( DB_MASTER ); - foreach ($results as $result ) { - $values = array('wl_notificationtimestamp' => null ); - $conds = array( 'wl_id' => $result->wl_id ); - $options = array(); + foreach ( $results as $result ) { + $values = [ 'wl_notificationtimestamp' => null ]; + $conds = [ 'wl_id' => $result->wl_id ]; + $options = []; $dbw->update( 'watchlist', $values, $conds, __METHOD__, $options ); } } @@ -149,40 +147,39 @@ public static function doSearchQuery( $data, $clearPages ) { } /** - * @param array $data - * @param object $form - * @return Status - */ - + * @param array $data + * @param object $form + * @return Status + */ public function trySubmit( $data, $form ) { $request = $this->getRequest(); $output = $this->getOutput(); $this->setHeaders(); - if (isset($_POST['clearpages'])) { - //Clears pending reviews - $results = $this->doSearchQuery( $data, True ); + if ( isset( $_POST['clearpages'] ) ) { + // Clears pending reviews + $results = $this->doSearchQuery( $data, true ); - //Count how many pages were cleared + // Count how many pages were cleared $pageCount = 0; foreach ( $results as $result ) { $pageCount = $pageCount + 1; } - //Log when pages are cleared in Special:Log + // Log when pages are cleared in Special:Log $logEntry = new ManualLogEntry( 'pendingreviews', 'clearreivews' ); $logEntry->setPerformer( $this->getUser() ); $logEntry->setTarget( $this->getPageTitle() ); $logEntry->setParameters( [ - '4::paramname' => '('.$pageCount.')', - '5::paramname' => '('.$data['category'].')', - '6::paramname' => '('.$data['page'].')', + '4::paramname' => '(' . $pageCount . ')', + '5::paramname' => '(' . $data['category'] . ')', + '6::paramname' => '(' . $data['page'] . ')', ] ); $logid = $logEntry->insert(); $logEntry->publish( $logid ); - Hooks::run( 'PendingReviewsCleared', [&$data, &$results, &$pageCount] ); + Hooks::run( 'PendingReviewsCleared', [ &$data, &$results, &$pageCount ] ); - //Create link back to Special:ClearPendingReviews + // Create link back to Special:ClearPendingReviews $pageLinkHtml = Linker::link( $this->getPageTitle() ); $output->addHTML( "" ); $output->addHTML( wfMessage( 'clearpendingreviews-success' )->numParams( $pageCount )->plain() ); @@ -191,36 +188,36 @@ public function trySubmit( $data, $form ) { $output->addHTML( wfMessage( 'clearpendingreviews-success-return' ) ); $output->addHTML( $pageLinkHtml ); - //Don't reload the form after clearing pages. + // Don't reload the form after clearing pages. return true; } else { - $results = $this->doSearchQuery( $data, False ); + $results = $this->doSearchQuery( $data, false ); $table = ''; $table .= ""; $table .= ""; $table .= ""; $table .= "
"; - $table .= "

".wfMessage( 'clearpendingreviews-pages-cleared' )."

"; + $table .= "

" . wfMessage( 'clearpendingreviews-pages-cleared' ) . "

"; $table .= "
    "; - $impactedPages = array(); - foreach ($results as $result) { + $impactedPages = []; + foreach ( $results as $result ) { $page = Title::makeTitle( $result->wl_namespace, $result->wl_title ); $pageLinkHtml = Linker::link( $page ); $impactedPages[] = $pageLinkHtml; } $impactedPages = array_unique( $impactedPages ); - foreach ($impactedPages as $impactedPage ) { - $table .= "
  • ".$impactedPage."
  • "; + foreach ( $impactedPages as $impactedPage ) { + $table .= "
  • " . $impactedPage . "
  • "; } $table .= "
"; $table .= "
"; - $table .= "

".wfMessage( 'clearpendingreviews-people-impacted' )."

"; + $table .= "

" . wfMessage( 'clearpendingreviews-people-impacted' ) . "

"; $table .= "
    "; - $impactedUsers = array(); - foreach ($results as $result ) { + $impactedUsers = []; + foreach ( $results as $result ) { $user = User::newFromId( $result->wl_user ); $userTitleObj = $user->getUserPage(); $userLinkHtml = Linker::link( $userTitleObj ); @@ -228,8 +225,8 @@ public function trySubmit( $data, $form ) { } $impactedUsers = array_unique( $impactedUsers ); - foreach ($impactedUsers as $impactedUser ) { - $table .= "
  • ".$impactedUser."
  • "; + foreach ( $impactedUsers as $impactedUser ) { + $table .= "
  • " . $impactedUser . "
  • "; } $table .= "
"; @@ -240,10 +237,10 @@ public function trySubmit( $data, $form ) { $form->setSubmitText( 'Clear pages' ); $form->setSubmitName( 'clearpages' ); $form->setSubmitDestructive(); - $form->setCancelTarget( $this->getPageTitle()); + $form->setCancelTarget( $this->getPageTitle() ); $form->showCancel(); - Hooks::run( 'PendingReviewsPreview', [&$data, &$results] ); - //Display preview of pages to be cleared + Hooks::run( 'PendingReviewsPreview', [ &$data, &$results ] ); + // Display preview of pages to be cleared $form->setPostText( $table ); return false; diff --git a/specials/SpecialPageStatistics.php b/specials/SpecialPageStatistics.php index 15ae2b1..f611b0a 100644 --- a/specials/SpecialPageStatistics.php +++ b/specials/SpecialPageStatistics.php @@ -3,13 +3,6 @@ class SpecialPageStatistics extends SpecialPage { public $mMode; - // protected $header_links = array( - // 'watchanalytics-pages-specialpage' => '', - // 'watchanalytics-users-specialpage' => 'users', - // 'watchanalytics-wikihistory-specialpage' => 'wikihistory', - // 'watchanalytics-watch-forcegraph-specialpage' => 'forcegraph', - // ); - public function __construct() { parent::__construct( @@ -32,13 +25,13 @@ public function execute( $parser = null ) { // @todo: probably don't need filters, but may want to show stats just // from a certain group of users // $filters = array( - // 'groupfilter' => $wgRequest->getVal( 'groupfilter', '' ), - // 'categoryfilter' => $wgRequest->getVal( 'categoryfilter', '' ), + // 'groupfilter' => $wgRequest->getVal( 'groupfilter', '' ), + // 'categoryfilter' => $wgRequest->getVal( 'categoryfilter', '' ), // ); // foreach( $filters as &$filter ) { - // if ( $filter === '' ) { - // $filter = false; - // } + // if ( $filter === '' ) { + // $filter = false; + // } // } // @todo: delete if multiple views not needed (thus, not requiring header call here) @@ -48,28 +41,23 @@ public function execute( $parser = null ) { if ( $unReviewTimestamp ) { $rh = new ReviewHandler( $wgUser, $this->mTitle ); $rh->resetNotificationTimestamp( $unReviewTimestamp ); - $wgOut->addModuleStyles( array( 'ext.watchanalytics.reviewhandler.styles' ) ); + $wgOut->addModuleStyles( [ 'ext.watchanalytics.reviewhandler.styles' ] ); $wgOut->addHTML( $this->unReviewMessage() ); } - $wgOut->addHTML( $this->getPageHeader() ); $this->renderPageStats(); - } - else if ( $requestedPage ) { + } elseif ( $requestedPage ) { // @todo FIXME: internationalize $wgOut->addHTML( "

\"$requestedPage\" is either not a page or is not watchable

" ); - } - else { + } else { $wgOut->addHTML( "

No page requested

" ); } - } public function getPageHeader() { global $wgOut; - $wgOut->addModuleStyles( array( 'ext.watchanalytics.pagescores.styles' ) ); - + $wgOut->addModuleStyles( [ 'ext.watchanalytics.pagescores.styles' ] ); $pageScore = new PageScore( $this->mTitle ); // $out->addScript( $pageScore->getPageScoreTemplate() ); @@ -105,28 +93,25 @@ public function getPageHeader() {
The number of people who have reviewed this page.
"; - } - public function renderPageStats () { - + public function renderPageStats() { global $wgOut; // @todo FIXME: internationalization $wgOut->setPageTitle( 'Page Statistics: ' . $this->mTitle->getPrefixedText() ); - $dbr = wfGetDB( DB_SLAVE ); + $dbr = wfGetDB( DB_REPLICA ); $html = ''; // Load the module for the D3.js force directed graph // $wgOut->addModules( 'ext.watchanalytics.forcegraph.scripts' ); // Load the styles for the D3.js force directed graph // $wgOut->addModuleStyles( 'ext.watchanalytics.forcegraph.styles' ); - // SELECT - // rev.rev_user, - // rev.rev_user_text, - // COUNT( * ) AS num_revisions + // rev.rev_user, + // rev.rev_user_text, + // COUNT( * ) AS num_revisions // FROM revision AS rev // LEFT JOIN page AS p ON p.page_id = rev.rev_page // WHERE p.page_title = "US_EVA_29_(US_EVA_IDA1_Cables)" AND p.page_namespace = 0 @@ -134,38 +119,36 @@ public function renderPageStats () { // ORDER BY num_revisions DESC # - # Page editors query + # Page editors query # $res = $dbr->select( - array( + [ 'rev' => 'revision', 'p' => 'page', - ), - array( + ], + [ 'rev.rev_user', 'rev.rev_user_text', 'COUNT( * ) AS num_revisions', - ), - array( + ], + [ 'p.page_title' => $this->mTitle->getDBkey(), 'p.page_namespace' => $this->mTitle->getNamespace(), - ), + ], __METHOD__, - array( + [ 'GROUP BY' => 'rev.rev_user', 'ORDER BY' => 'num_revisions DESC', - ), - array( - 'p' => array( + ], + [ + 'p' => [ 'LEFT JOIN', 'p.page_id = rev.rev_page' - ), - ) + ], + ] ); - - # - # Page editors + # Page editors # $html .= Xml::element( 'h2', null, wfMessage( 'watchanalytics-pagestats-editors-list-title' )->text() ); $html .= Xml::openElement( "ul" ); @@ -185,37 +168,34 @@ public function renderPageStats () { } $html .= Xml::closeElement( "ul" ); - # - # Watchers query + # Watchers query # $res = $dbr->select( - array( + [ 'w' => 'watchlist', 'u' => 'user', - ), - array( + ], + [ 'wl_user', 'u.user_name', 'wl_notificationtimestamp', - ), - array( + ], + [ 'wl_title' => $this->mTitle->getDBkey(), 'wl_namespace' => $this->mTitle->getNamespace(), - ), + ], __METHOD__, null, // no limits, order by, etc - array( - 'u' => array( + [ + 'u' => [ 'LEFT JOIN', 'u.user_id = w.wl_user' - ), - ) + ], + ] ); - - # - # Page watchers + # Page watchers # $html .= Xml::element( 'h2', null, wfMessage( 'watchanalytics-pagestats-watchers-title' )->text() ); $html .= Xml::openElement( "ul" ); @@ -225,8 +205,7 @@ public function renderPageStats () { if ( is_null( $row->wl_notificationtimestamp ) ) { $watcherMsg = 'watchanalytics-pagestats-watchers-list-item-reviewed'; - } - else { + } else { $watcherMsg = 'watchanalytics-pagestats-watchers-list-item-unreviewed'; } @@ -241,29 +220,20 @@ public function renderPageStats () { } $html .= Xml::closeElement( "ul" ); - - $wgOut->addHTML( $html ); $this->pageChart(); - } - public function unReviewMessage () { - + public function unReviewMessage() { // FIXME: Original self: this shouldn't use the same CSS ID. - // Newer self: Why not? - return - "

" . + // Newer self: Why not? + return "

" . wfMessage( 'watchanalytics-unreview-complete' )->parse() . "

"; - } - - - public function pageChart () { - + public function pageChart() { global $wgOut; $wgOut->addModules( 'ext.watchanalytics.charts' ); @@ -273,26 +243,26 @@ public function pageChart () { // $dateRangeStart = new MWTimestamp( date( 'YmdHis', strtotime( '2 weeks ago' ) ) ); // $dateRangeStart = $dateRangeStart->format('YmdHis'); - $dbr = wfGetDB( DB_SLAVE ); + $dbr = wfGetDB( DB_REPLICA ); $res = $dbr->select( - array( 'wtp' => 'watch_tracking_page' ), - array( + [ 'wtp' => 'watch_tracking_page' ], + [ "DATE_FORMAT( wtp.tracking_timestamp, '%Y-%m-%d %H:%i:%s' ) AS timestamp", "wtp.num_reviewed AS num_reviewed", - ), - array( + ], + [ 'page_id' => $this->mTitle->getArticleID(), // 'tracking_timestamp > ' . $dateRangeStart - ), + ], __METHOD__, - array( + [ "ORDER BY" => "wtp.tracking_timestamp DESC", "LIMIT" => "200", // MOST RECENT 100 changes - ), + ], null // join conditions ); - $data = array(); + $data = []; while ( $row = $dbr->fetchObject( $res ) ) { $data[ $row->timestamp ] = $row->num_reviewed; } @@ -302,7 +272,5 @@ public function pageChart () { $html .= ""; $wgOut->addHTML( $html ); - } } - diff --git a/specials/SpecialPendingReviews.php b/specials/SpecialPendingReviews.php index 83f6b46..3ce0107 100644 --- a/specials/SpecialPendingReviews.php +++ b/specials/SpecialPendingReviews.php @@ -33,12 +33,11 @@ class SpecialPendingReviews extends SpecialPage { public $mMode; - protected $header_links = array( + protected $header_links = [ 'watchanalytics-pages-specialpage' => '', 'watchanalytics-users-specialpage' => 'users', 'watchanalytics-wikihistory-specialpage' => 'wikihistory', - ); - + ]; /** * Constructor for Special Page. @@ -136,9 +135,9 @@ public function execute( $parser = null ) { // been deleted) if ( $item->title ) { $html .= $this->getStandardChangeRow( $item, $rowCount ); - } + // page has been deleted (or moved w/o a redirect) - else { + } else { $html .= $this->getDeletedPageRow( $item, $rowCount ); } @@ -161,10 +160,10 @@ public function execute( $parser = null ) { * Handles case where user clicked a link to clear a pending review * This will not display the pending reviews page. * + * @param Title $clearNotifyTitle * @return bool */ - public function handleClearNotification ( $clearNotifyTitle ) { - + public function handleClearNotification( $clearNotifyTitle ) { PendingReview::clearByUserAndTitle( $this->getUser(), $clearNotifyTitle ); $this->getOutput()->addHTML( @@ -172,15 +171,14 @@ public function handleClearNotification ( $clearNotifyTitle ) { 'pendingreviews-clear-page-notification', $clearNotifyTitle->getFullText(), Xml::tags( 'a', - array( + [ 'href' => $this->getTitle()->getLocalUrl(), 'style' => 'font-weight:bold;', - ), + ], $this->getTitle() ) )->text() ); - } /** @@ -188,8 +186,7 @@ public function handleClearNotification ( $clearNotifyTitle ) { * * @return bool */ - public function setPendingReviewsUser () { - + public function setPendingReviewsUser() { $viewingUser = $this->getUser(); // Check if a user has been specified. @@ -198,14 +195,12 @@ public function setPendingReviewsUser () { $this->mUser = User::newFromName( $requestUser ); if ( $this->mUser->getId() === $viewingUser ) { $this->mUserIsViewer = true; - } - else { + } else { $this->mUserIsViewer = false; } $this->getOutput()->setPageTitle( wfMessage( 'pendingreviews-user-page', $this->mUser->getName() )->text() ); - } - else { + } else { $this->mUser = $viewingUser; } @@ -217,11 +212,10 @@ public function setPendingReviewsUser () { * * @return null */ - public function setReviewLimit () { + public function setReviewLimit() { if ( $this->getRequest()->getVal( 'limit' ) ) { $this->reviewLimit = $this->getRequest()->getVal( 'limit' ); // FIXME: for consistency, shouldn't this be just "limit" - } - else { + } else { $this->reviewLimit = 20; } } @@ -231,11 +225,10 @@ public function setReviewLimit () { * * @return null */ - public function setReviewOffset () { + public function setReviewOffset() { if ( $this->getRequest()->getVal( 'offset' ) ) { $this->reviewOffset = $this->getRequest()->getVal( 'offset' ); - } - else { + } else { $this->reviewOffset = 0; } } @@ -246,8 +239,7 @@ public function setReviewOffset () { * * @return Title|false */ - public function getClearNotificationTitle () { - + public function getClearNotificationTitle() { $clearNotifyTitle = $this->getRequest()->getVal( 'clearNotificationTitle' ); if ( ! $clearNotifyTitle ) { @@ -263,7 +255,6 @@ public function getClearNotificationTitle () { return $title; } - /** * Generates row for a particular page in PendingReviews. * @@ -271,15 +262,13 @@ public function getClearNotificationTitle () { * @param int $rowCount used to determine if the row is odd or even * @return string HTML for row */ - public function getStandardChangeRow ( PendingReview $item, $rowCount ) { - + public function getStandardChangeRow( PendingReview $item, $rowCount ) { $combinedList = $this->combineLogAndChanges( $item->log, $item->newRevisions, $item->title ); $changes = $this->getPendingReviewChangesList( $combinedList ); if ( $item->title->isRedirect() ) { $reviewButton = $this->getAcceptRedirectButton( $item ); - } - else { + } else { $reviewButton = $this->getReviewButton( $item ); } @@ -288,7 +277,6 @@ public function getStandardChangeRow ( PendingReview $item, $rowCount ) { $displayTitle = '' . $item->title->getFullText() . ''; return $this->getRowHTML( $item, $rowCount, $displayTitle, $reviewButton, $historyButton, $changes ); - } /** @@ -300,16 +288,14 @@ public function getStandardChangeRow ( PendingReview $item, $rowCount ) { * @param int $rowCount used to determine if the row is odd or even * @return string HTML for row */ - public function getDeletedPageRow ( PendingReview $item, $rowCount ) { - + public function getDeletedPageRow( PendingReview $item, $rowCount ) { $pageWasMoved = false; $deletionLogLength = count( $item->deletionLog ); for ( $i = $deletionLogLength - 1; $i >= 0; $i-- ) { if ( $item->deletionLog[$i]->log_type == 'move' ) { $pageWasMoved = true; break; - } - else if ( $item->deletionLog[$i]->log_type == 'delete' ) { + } elseif ( $item->deletionLog[$i]->log_type == 'delete' ) { $pageWasMoved = false; break; } @@ -320,8 +306,7 @@ public function getDeletedPageRow ( PendingReview $item, $rowCount ) { if ( $pageWasMoved ) { $acceptDeletionButton = $this->getAcceptMoveWithoutRedirectButton( $item->deletedTitle, $item->deletedNS ); $displayMessage = 'pendingreviews-page-moved-no-redirect'; - } - else { + } else { $acceptDeletionButton = $this->getMarkDeleteReviewedButton( $item->deletedTitle, $item->deletedNS ); $displayMessage = 'pendingreviews-page-deleted'; } @@ -347,25 +332,27 @@ public function getDeletedPageRow ( PendingReview $item, $rowCount ) { * @param string $changes * @return string HTML for pending review of a given page */ - public function getRowHTML ( PendingReview $item, $rowCount, $displayTitle, $buttonOne, $buttonTwo, $changes ) { - + public function getRowHTML( PendingReview $item, $rowCount, $displayTitle, $buttonOne, $buttonTwo, $changes ) { // FIXME: wow this is ugly $rowClass = ( $rowCount % 2 === 0 ) ? 'pendingreviews-even-row' : 'pendingreviews-odd-row'; if ( $item->numReviewers > $GLOBALS['egPendingReviewsOrangePagesThreshold'] ) { $reviewCriticality = 'green'; // page is "green" because it has lots of reviewers - } - else if ( $item->numReviewers > $GLOBALS['egPendingReviewsRedPagesThreshold'] ) { + } elseif ( $item->numReviewers > $GLOBALS['egPendingReviewsRedPagesThreshold'] ) { $reviewCriticality = 'orange'; - } - else { + } else { $reviewCriticality = 'red'; // page is red because it has very few reviewers } $reviewCriticalityClass = 'pendingreviews-criticality-' . $reviewCriticality; - $classAndAttr = "class='pendingreviews-row $rowClass $reviewCriticalityClass pendingreviews-row-$rowCount' pendingreviews-row-count='$rowCount'"; + $classAndAttr = "class='pendingreviews-row $rowClass " . + "$reviewCriticalityClass pendingreviews-row-$rowCount' " . + "pendingreviews-row-count='$rowCount'"; - $html = "$displayTitle$buttonOne $buttonTwo"; + $html = "" . + "$displayTitle" . + "" . + "$buttonOne $buttonTwo"; $html .= "$changes"; @@ -378,40 +365,37 @@ public function getRowHTML ( PendingReview $item, $rowCount, $displayTitle, $but * @param PendingReview $item * @return string HTML for button */ - public function getReviewButton ( $item ) { - + public function getReviewButton( $item ) { if ( count( $item->newRevisions ) > 0 ) { // returns essentially the negative-oneth revision...the one before // the wl_notificationtimestamp revision...or null/false if none exists? $mostRecentReviewed = Revision::newFromRow( $item->newRevisions[0] )->getPrevious(); - } - else { + } else { $mostRecentReviewed = false; // no previous revision, the user has not reviewed the first! } if ( $mostRecentReviewed ) { - $diffURL = $item->title->getLocalURL( array( + $diffURL = $item->title->getLocalURL( [ 'diff' => '', 'oldid' => $mostRecentReviewed->getId() - ) ); + ] ); $diffLink = Xml::element( 'a', - array( 'href' => $diffURL, 'class' => 'pendingreviews-green-button', 'target' => "_blank" ), + [ 'href' => $diffURL, 'class' => 'pendingreviews-green-button', 'target' => "_blank" ], wfMessage( 'watchanalytics-pendingreviews-diff-revisions', count( $item->newRevisions ) )->text() ); - } - else { + } else { $latest = Revision::newFromTitle( $item->title ); - $diffURL = $item->title->getLocalURL( array( 'oldid' => $latest->getId() ) ); + $diffURL = $item->title->getLocalURL( [ 'oldid' => $latest->getId() ] ); $diffLink = Xml::element( 'a', - array( 'href' => $diffURL, 'class' => 'pendingreviews-green-button', 'target' => "_blank" ), + [ 'href' => $diffURL, 'class' => 'pendingreviews-green-button', 'target' => "_blank" ], $this->msg( 'watchanalytics-pendingreviews-users-first-view' )->text() ); @@ -426,18 +410,17 @@ public function getReviewButton ( $item ) { * @param PendingReview $item * @return string HTML for button */ - public function getHistoryButton ( $item ) { + public function getHistoryButton( $item ) { return Xml::element( 'a', - array( - 'href' => $item->title->getLocalURL( array( 'action' => 'history' ) ), + [ + 'href' => $item->title->getLocalURL( [ 'action' => 'history' ] ), 'class' => 'pendingreviews-dark-blue-button', 'target' => "_blank" - ), + ], wfMessage( 'watchanalytics-pendingreviews-history-link' )->text() ); } - /** * Creates a button which marks a deleted or redirected page as "reviewed" * (e.g. nullifies notification timestamp in watchlist). This function is @@ -457,17 +440,17 @@ public function getHistoryButton ( $item ) { * * @return string HTML for button */ - public function getClearNotificationButton ( $titleText, $namespace, $buttonMsg, $buttonClass ) { + public function getClearNotificationButton( $titleText, $namespace, $buttonMsg, $buttonClass ) { return Xml::element( 'a', - array( - 'href' => $this->getTitle()->getLocalURL( array( + [ + 'href' => $this->getTitle()->getLocalURL( [ 'clearNotificationTitle' => $titleText, 'clearNotificationNS' => $namespace, - ) ), + ] ), 'class' => $buttonClass, 'pending-namespace' => $namespace, 'pending-title' => $titleText, - ), + ], wfMessage( $buttonMsg )->text() ); } @@ -481,7 +464,7 @@ public function getClearNotificationButton ( $titleText, $namespace, $buttonMsg, * * @return string HTML for button */ - public function getMarkDeleteReviewedButton ( $titleText, $namespace ) { + public function getMarkDeleteReviewedButton( $titleText, $namespace ) { return $this->getClearNotificationButton( $titleText, $namespace, 'pendingreviews-accept-deletion', 'pendingreviews-red-button pendingreviews-accept-deletion' @@ -499,7 +482,7 @@ public function getMarkDeleteReviewedButton ( $titleText, $namespace ) { * * @return string HTML for button */ - public function getAcceptMoveWithoutRedirectButton ( $titleText, $namespace ) { + public function getAcceptMoveWithoutRedirectButton( $titleText, $namespace ) { return $this->getClearNotificationButton( $titleText, $namespace, 'pendingreviews-accept-move-without-redirect', 'pendingreviews-orange-button pendingreviews-accept-deletion' @@ -513,7 +496,7 @@ public function getAcceptMoveWithoutRedirectButton ( $titleText, $namespace ) { * * @return string HTML for button */ - public function getAcceptRedirectButton ( $item ) { + public function getAcceptRedirectButton( $item ) { $titleText = $item->title->getDBkey(); $namespace = $item->title->getNamespace(); @@ -527,11 +510,10 @@ public function getAcceptRedirectButton ( $item ) { * Creates a button bringing user to the talk page of the user who deleted * the page, allowing them to ask questions about why the page was deleted. * - * @param $deletionLog + * @param array $deletionLog * @return string HTML for button */ - public function getDeleterTalkButton ( $deletionLog ) { - + public function getDeleterTalkButton( array $deletionLog ) { if ( count( $deletionLog ) == 0 ) { return ''; } @@ -542,17 +524,16 @@ public function getDeleterTalkButton ( $deletionLog ) { $userTalk = $user->getTalkPage(); if ( $userTalk->exists() ) { - $talkQueryString = array(); - } - else { - $talkQueryString = array( 'action' => 'edit' ); + $talkQueryString = []; + } else { + $talkQueryString = [ 'action' => 'edit' ]; } return Xml::element( 'a', - array( + [ 'href' => $userTalk->getLocalURL( $talkQueryString ), 'class' => 'pendingreviews-dark-blue-button' // pendingreviews-delete-talk-button - ), + ], wfMessage( 'pendingreviews-page-deleted-talk', $user->getUserPage()->getFullText() )->text() ); } @@ -560,9 +541,10 @@ public function getDeleterTalkButton ( $deletionLog ) { /** * Creates simple header stating how many pending reviews the user has. * + * @param User $user * @return string HTML for header */ - public function getPageHeader( $user ) { + public function getPageHeader( User $user ) { $userWatch = new UserWatchesQuery(); $watchStats = $userWatch->getUserWatchStats( $user ); $numPendingReviews = $watchStats['num_pending']; @@ -580,12 +562,12 @@ public function getPageHeader( $user ) { $html .= '

'; $nextReviewSet = $this->reviewOffset + $this->reviewLimit; - $prevReviewSet = max( array( 0, $this->reviewOffset - $this->reviewLimit ) ); + $prevReviewSet = max( [ 0, $this->reviewOffset - $this->reviewLimit ] ); $currentURL = $this->getPageTitle()->getLocalUrl(); $viewingUser = ''; // if ( $this->mUser ) { - // $viewingUser = '&user='.$this->mUser; + // $viewingUser = '&user='.$this->mUser; // } $linkClass = "pendingreviews-nav-link"; @@ -602,19 +584,19 @@ public function getPageHeader( $user ) { $html .= Xml::element( 'a', - array( - 'href' => $currentURL.'?offset='.$prevReviewSet.$viewingUser, + [ + 'href' => $currentURL . '?offset=' . $prevReviewSet . $viewingUser, 'class' => $prevLinkClass, - ), + ], wfMessage( 'watchanalytics-pendingreviews-prev-revisions' )->text() ); $html .= Xml::element( 'a', - array( - 'href' => $currentURL.'?offset='.$nextReviewSet.$viewingUser, + [ + 'href' => $currentURL . '?offset=' . $nextReviewSet . $viewingUser, 'class' => $nextLinkClass, - ), + ], wfMessage( 'watchanalytics-pendingreviews-next-revisions' )->text() ); @@ -626,10 +608,9 @@ public function getPageHeader( $user ) { * * @return string HTML for legend (table) */ - public function getPendingReviewsLegend () { - + public function getPendingReviewsLegend() { $redMaxReviewers = $GLOBALS['egPendingReviewsRedPagesThreshold'] - 1; - $orangeMaxReviewers = $GLOBALS['egPendingReviewsOrangePagesThreshold'] - 1; + $orangeMaxReviewers = $GLOBALS['egPendingReviewsOrangePagesThreshold'] - 1; $redReviewersMsg = $this->msg( 'pendingreviews-reviewer-criticality-red', @@ -651,7 +632,6 @@ public function getPendingReviewsLegend () { $orangeReviewersMsg $greenReviewersMsg "; - } /** @@ -660,24 +640,22 @@ public function getPendingReviewsLegend () { * @todo FIXME: documentation...why does this do what it does? * @todo FIXME: cleanup temporary code * - * @param $log - * @param $revisions - * @param $title + * @param array $log + * @param array $revisions + * @param Title $title * @return array */ - protected function combineLogAndChanges( $log, $revisions, $title ) { - + protected function combineLogAndChanges( array $log, array $revisions, Title $title ) { // if ( $title->getNamespace() === NS_FILE ) { // } - // $log = array_reverse( $log ); // $revisions = array_reverse( $revisions ); $logI = 0; $revI = 0; - $combinedArray = array(); + $combinedArray = []; while ( count( $log ) > 0 && count( $revisions ) > 0 ) { @@ -686,8 +664,7 @@ protected function combineLogAndChanges( $log, $revisions, $title ) { if ( $revTs > $logTs ) { $combinedArray[] = array_shift( $log ); - } - else { + } else { $combinedArray[] = array_shift( $revisions ); } @@ -699,7 +676,6 @@ protected function combineLogAndChanges( $log, $revisions, $title ) { $combinedArray = array_merge( $combinedArray, $revisions, $log ); return $combinedArray; - } /** @@ -710,44 +686,43 @@ protected function combineLogAndChanges( $log, $revisions, $title ) { * @param object $logEntry * @return Message HTML for button */ - protected function getLogChangeMessage ( $logEntry ) { - + protected function getLogChangeMessage( $logEntry ) { // add pendingreviews-edited-by? - $messages = array( - 'approval' => array( + $messages = [ + 'approval' => [ 'approve' => 'pendingreviews-log-approved', 'unapprove' => 'pendingreviews-log-unapproved' - ), - 'delete' => array( + ], + 'delete' => [ 'delete' => 'pendingreviews-log-delete', 'restore' => 'pendingreviews-log-restore', - ), - 'import' => array( + ], + 'import' => [ 'upload' => 'pendingreviews-log-import-upload', - ), - 'move' => array( + ], + 'move' => [ 'move' => 'pendingreviews-log-move', 'move_redir' => 'pendingreviews-log-move-redir', - ), - 'protect' => array( + ], + 'protect' => [ 'protect' => 'pendingreviews-log-protect', 'unprotect' => 'pendingreviews-log-unprotect', 'modify' => 'pendingreviews-log-modify-protect', - ), - 'upload' => array( + ], + 'upload' => [ 'upload' => 'pendingreviews-log-upload-new', 'overwrite' => 'pendingreviews-log-upload-overwrite', - ), - ); + ], + ]; // get user page of user who created the log entry - $userPage = Title::makeTitle( NS_USER , $logEntry->log_user_text )->getFullText(); + $userPage = Title::makeTitle( NS_USER, $logEntry->log_user_text )->getFullText(); // if a message exists for the particular log type, handle it as follows if ( isset( $messages[ $logEntry->log_type ][ $logEntry->log_action ] ) ) { // all messages will use the executing users user-page - $messageParams = array( $userPage ); + $messageParams = [ $userPage ]; // if the log action is move or move_redir, the move target is in the message if ( $logEntry->log_action == 'move' || $logEntry->log_action == 'move_redir' ) { @@ -760,13 +735,10 @@ protected function getLogChangeMessage ( $logEntry ) { return wfMessage( $messages[ $logEntry->log_type ][ $logEntry->log_action ], $messageParams ); - } - // if no message exists for the log type and action, handling with "unknown change" - else { + } else { return wfMessage( 'pendingreviews-log-unknown-change', $userPage ); } - } /** @@ -775,30 +747,28 @@ protected function getLogChangeMessage ( $logEntry ) { * @param array $combinedList * @return string HTML */ - public function getPendingReviewChangesList ( $combinedList ) { - $changes = array(); + public function getPendingReviewChangesList( $combinedList ) { + $changes = []; foreach ( $combinedList as $change ) { if ( isset( $change->log_timestamp ) ) { $changeTs = $change->log_timestamp; $changeText = $this->getLogChangeMessage( $change ); - } - else { + } else { $rev = Revision::newFromRow( $change ); $changeTs = $change->rev_timestamp; - $userPage = Title::makeTitle( NS_USER , $change->rev_user_text )->getFullText(); + $userPage = Title::makeTitle( NS_USER, $change->rev_user_text )->getFullText(); $comment = $rev->getComment(); if ( $comment ) { $comment = '' . Linker::formatComment( $comment ) . ''; - $changeText = ' ' . wfMessage( 'pendingreviews-with-comment', array( $userPage ) )->parse() . ' ' . $comment; - } - else { + $changeText = ' ' . wfMessage( 'pendingreviews-with-comment', [ $userPage ] )->parse() . ' ' . $comment; + } else { $changeText = ' ' . wfMessage( 'pendingreviews-edited-by', $userPage )->parse(); } } $changeTs = Xml::element( 'span', - array( 'class' => 'pendingreviews-changes-list-time' ), + [ 'class' => 'pendingreviews-changes-list-time' ], ( new MWTimestamp( $changeTs ) )->getHumanTimestamp() ) . ' '; diff --git a/specials/SpecialWatchAnalytics.php b/specials/SpecialWatchAnalytics.php index 0332fc9..aab1cf4 100644 --- a/specials/SpecialWatchAnalytics.php +++ b/specials/SpecialWatchAnalytics.php @@ -3,13 +3,12 @@ class SpecialWatchAnalytics extends SpecialPage { public $mMode; - protected $header_links = array( + protected $header_links = [ 'watchanalytics-pages-specialpage' => '', 'watchanalytics-users-specialpage' => 'users', 'watchanalytics-wikihistory-specialpage' => 'wikihistory', 'watchanalytics-watch-forcegraph-specialpage' => 'forcegraph', - ); - + ]; public function __construct() { parent::__construct( @@ -19,7 +18,7 @@ public function __construct() { ); } - public function execute ( $parser = null ) { + public function execute( $parser = null ) { global $wgRequest, $wgOut; $this->setHeaders(); @@ -37,10 +36,10 @@ public function execute ( $parser = null ) { $wgOut->addHTML( '

' . wfMessage( 'watchanalytics-all-wiki-stats-recorded' )->text() . '

' ); } - $filters = array( + $filters = [ 'groupfilter' => $wgRequest->getVal( 'groupfilter', '' ), 'categoryfilter' => $wgRequest->getVal( 'categoryfilter', '' ), - ); + ]; foreach ( $filters as &$filter ) { if ( $filter === '' ) { $filter = false; @@ -50,50 +49,46 @@ public function execute ( $parser = null ) { $wgOut->addHTML( $this->getPageHeader() ); if ( $this->mMode == 'users' ) { $this->usersList( $filters ); - } - else if ( $this->mMode == 'wikihistory' ) { + } elseif ( $this->mMode == 'wikihistory' ) { $this->wikiHistory(); - } - else if ( $this->mMode == 'forcegraph' ) { + } elseif ( $this->mMode == 'forcegraph' ) { $this->forceGraph(); - } - else { + } else { $this->pagesList( $filters ); } } public function getPageHeader() { - // show the names of the four lists of pages, with the one // corresponding to the current "mode" not being linked // SELECT - // COUNT(*) AS watches, - // SUM( IF(watchlist.wl_notificationtimestamp IS NULL, 0, 1) ) AS num_pending, - // SUM( IF(watchlist.wl_notificationtimestamp IS NULL, 0, 1) ) * 100 / COUNT(*) AS percent_pending + // COUNT(*) AS watches, + // SUM( IF(watchlist.wl_notificationtimestamp IS NULL, 0, 1) ) AS num_pending, + // SUM( IF(watchlist.wl_notificationtimestamp IS NULL, 0, 1) ) * 100 / COUNT(*) AS percent_pending // FROM watchlist // INNER JOIN page ON page.page_namespace = watchlist.wl_namespace AND page.page_title = watchlist.wl_title; $dbr = wfGetDB( DB_SLAVE ); - $dbr = wfGetDB( DB_SLAVE ); + $dbr = wfGetDB( DB_REPLICA ); // $res = $dbr->select( - // array( - // 'w' => 'watchlist', - // 'p' => 'page', - // ), - // array( - // "COUNT(*) AS watches", - // "SUM( IF(watchlist.wl_notificationtimestamp IS NULL, 0, 1) ) AS num_pending", - // "SUM( IF(watchlist.wl_notificationtimestamp IS NULL, 0, 1) ) * 100 / COUNT(*) AS percent_pending", - // ), - // null, // conditions - // __METHOD__, - // array(), // options - // array( - // 'page' => array( - // 'INNER JOIN', 'p.page_namespace=w.wl_namespace AND p.page_title=w.wl_title' - // ) - // ) + // array( + // 'w' => 'watchlist', + // 'p' => 'page', + // ), + // array( + // "COUNT(*) AS watches", + // "SUM( IF(watchlist.wl_notificationtimestamp IS NULL, 0, 1) ) AS num_pending", + // "SUM( IF(watchlist.wl_notificationtimestamp IS NULL, 0, 1) ) * 100 / COUNT(*) AS percent_pending", + // ), + // null, // conditions + // __METHOD__, + // array(), // options + // array( + // 'page' => array( + // 'INNER JOIN', 'p.page_namespace=w.wl_namespace AND p.page_title=w.wl_title' + // ) + // ) // ); $res = $dbr->query( ' @@ -107,11 +102,11 @@ public function getPageHeader() { $allWikiData = $dbr->fetchRow( $res ); - list( $watches, $pending, $percent ) = array( + list( $watches, $pending, $percent ) = [ $allWikiData['num_watches'], $allWikiData['num_pending'], $allWikiData['percent_pending'] - ); + ]; $percent = round( $percent, 1 ); $stateOf = "The state of the Wiki: $watches watches of which $percent% ($pending) are pending"; @@ -124,12 +119,10 @@ public function getPageHeader() { $header = '' . wfMessage( 'watchanalytics-view' )->text() . ''; $header .= Xml::tags( 'ul', null, $navLinks ) . "\n"; - return $stateOf . Xml::tags( 'div', array( 'class' => 'special-watchanalytics-header' ), $header ); - + return $stateOf . Xml::tags( 'div', [ 'class' => 'special-watchanalytics-header' ], $header ); } public function createHeaderLink( $msg, $query_param ) { - $WatchAnalyticsTitle = SpecialPage::getTitleFor( $this->getName() ); if ( $this->mMode == $query_param ) { @@ -138,38 +131,37 @@ public function createHeaderLink( $msg, $query_param ) { wfMessage( $msg )->text() ); } else { - $show = ( $query_param == '' ) ? array() : array( 'show' => $query_param ); + $show = ( $query_param == '' ) ? [] : [ 'show' => $query_param ]; return Xml::element( 'a', - array( 'href' => $WatchAnalyticsTitle->getLocalURL( $show ) ), + [ 'href' => $WatchAnalyticsTitle->getLocalURL( $show ) ], wfMessage( $msg )->text() ); } - } - public function pagesList ( $filters ) { + public function pagesList( $filters ) { return $this->createTablePager( 'watchanalytics-special-pages-pagetitle', - new WatchAnalyticsPageTablePager( $this, array(), $filters ) + new WatchAnalyticsPageTablePager( $this, [], $filters ) ); } - public function usersList ( $filters ) { + public function usersList( $filters ) { return $this->createTablePager( 'watchanalytics-special-users-pagetitle', - new WatchAnalyticsUserTablePager( $this, array(), $filters ) + new WatchAnalyticsUserTablePager( $this, [], $filters ) ); } - public function wikiHistory () { + public function wikiHistory() { return $this->createTablePager( 'watchanalytics-special-wikihistory-pagetitle', - new WatchAnalyticsWikiTablePager( $this, array() ) + new WatchAnalyticsWikiTablePager( $this, [] ) ); } - public function createTablePager ( $titleMsg, WatchAnalyticsTablePager $tablePager ) { - global $wgOut, $wgRequest; + public function createTablePager( $titleMsg, WatchAnalyticsTablePager $tablePager ) { + global $wgOut; $wgOut->setPageTitle( wfMessage( $titleMsg )->text() ); @@ -181,71 +173,56 @@ public function createTablePager ( $titleMsg, WatchAnalyticsTablePager $tablePag $html .= $tablePager->getNavigationBar(); $html .= $body; $html .= $tablePager->getNavigationBar(); - } - else { + } else { $html .= '

' . wfMsgHTML( 'listusers-noresult' ) . '

'; } $wgOut->addHTML( $html ); return true; } - public function forceGraph () { - + public function forceGraph() { global $wgOut; $wgOut->setPageTitle( 'Watch Analytics: User/Page Watch Relationships' ); - $dbr = wfGetDB( DB_SLAVE ); + $dbr = wfGetDB( DB_REPLICA ); // Load the module for the D3.js force directed graph $wgOut->addModules( 'ext.watchanalytics.forcegraph.scripts' ); // Load the styles for the D3.js force directed graph $wgOut->addModuleStyles( 'ext.watchanalytics.forcegraph.styles' ); - // SELECT - // watchlist.wl_title AS title, - // watchlist.wl_notificationtimestamp AS notification, - // user.user_name AS user_name, - // user.user_real_name AS real_name - // FROM watchlist - // LEFT JOIN user ON user.user_id = watchlist.wl_user - // WHERE - // wl_namespace = 0 - // AND user.user_name IN (\'Lwelsh\',\'Swray\',\'Balpert\',\'Ejmontal\',\'Cmavridi\', \'Sgeffert\', \'Smulhern\', \'Kgjohns1\', \'Bscheib\', \'Ssjohns5\') - // LIMIT 20000 - $res = $dbr->select( - array( + [ 'w' => 'watchlist', 'u' => 'user', 'p' => 'page', - ), - array( + ], + [ 'w.wl_title AS title', 'w.wl_notificationtimestamp as notification', 'u.user_name as user_name', 'u.user_real_name AS real_name', - ), + ], 'w.wl_namespace = 0 AND p.page_is_redirect = 0', __METHOD__, - array( + [ "LIMIT" => "100000", - ), - array( - 'u' => array( + ], + [ + 'u' => [ 'LEFT JOIN', 'u.user_id = w.wl_user' - ), - 'p' => array( + ], + 'p' => [ 'RIGHT JOIN', 'w.wl_title = p.page_title AND w.wl_namespace = p.page_namespace' - ), - ) + ], + ] ); - - $nodes = array(); - $pages = array(); - $users = array(); - $links = array(); + $nodes = []; + $pages = []; + $users = []; + $links = []; while ( $row = $res->fetchRow() ) { // if the page isn't in $pages, then it's also not in $nodes @@ -256,11 +233,11 @@ public function forceGraph () { $pages[ $row['title'] ] = $nextNode; // $nodes[ $nextNode ] = $row['title']; - $nodes[ $nextNode ] = array( + $nodes[ $nextNode ] = [ "name" => $row['title'], "label" => $row['title'], "group" => 1 - ); + ]; } // same for users...add to $users and $nodes accordingly @@ -270,44 +247,41 @@ public function forceGraph () { $users[ $row['user_name'] ] = $nextNode; $nodes[ $nextNode ] = $row['user_name']; - if ( $row['real_name'] !== NULL && trim( $row['real_name'] ) !== '' ) { + if ( $row['real_name'] !== null && trim( $row['real_name'] ) !== '' ) { $displayName = $row['real_name']; - } - else { + } else { $displayName = $row['user_name']; } - $nodes[ $nextNode ] = array( + $nodes[ $nextNode ] = [ "name" => $displayName, "label" => $displayName, "group" => 2, "weight" => 1 - ); + ]; - } - else { + } else { $userNodeIndex = $users[ $row['user_name'] ]; $nodes[ $userNodeIndex ]['weight']++; } - if ( $row['notification'] == NULL ) { + if ( $row['notification'] == null ) { $linkClass = "link"; - } - else { + } else { $linkClass = "unreviewed"; } // if ( $linkClass !== "unreviewed" ) { - $links[] = array( + $links[] = [ "source" => $users[ $row['user_name'] ], "target" => $pages[ $row['title'] ], "value" => 1, "linkclass" => $linkClass - ); + ]; // } } - $json = array( "nodes" => $nodes, "links" => $links ); + $json = [ "nodes" => $nodes, "links" => $links ]; $json = json_encode( $json ); // , JSON_PRETTY_PRINT ); $html = '

' . wfMessage( 'watchanalytics-watch-forcegraph-header' )->text() . '

'; @@ -316,7 +290,5 @@ public function forceGraph () { // $html .= "
$json
"; // easy testing $html .= ""; $wgOut->addHTML( $html ); - } } -