RecentChange.php 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169
  1. <?php
  2. /**
  3. * Utility class for creating and accessing recent change entries.
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 2 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License along
  16. * with this program; if not, write to the Free Software Foundation, Inc.,
  17. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  18. * http://www.gnu.org/copyleft/gpl.html
  19. *
  20. * @file
  21. */
  22. use MediaWiki\ChangeTags\Taggable;
  23. use MediaWiki\MediaWikiServices;
  24. /**
  25. * Utility class for creating new RC entries
  26. *
  27. * mAttribs:
  28. * rc_id id of the row in the recentchanges table
  29. * rc_timestamp time the entry was made
  30. * rc_namespace namespace #
  31. * rc_title non-prefixed db key
  32. * rc_type is new entry, used to determine whether updating is necessary
  33. * rc_source string representation of change source
  34. * rc_minor is minor
  35. * rc_cur_id page_id of associated page entry
  36. * rc_user user id who made the entry
  37. * rc_user_text user name who made the entry
  38. * rc_actor actor id who made the entry
  39. * rc_comment edit summary
  40. * rc_this_oldid rev_id associated with this entry (or zero)
  41. * rc_last_oldid rev_id associated with the entry before this one (or zero)
  42. * rc_bot is bot, hidden
  43. * rc_ip IP address of the user in dotted quad notation
  44. * rc_new obsolete, use rc_type==RC_NEW
  45. * rc_patrolled boolean whether or not someone has marked this edit as patrolled
  46. * rc_old_len integer byte length of the text before the edit
  47. * rc_new_len the same after the edit
  48. * rc_deleted partial deletion
  49. * rc_logid the log_id value for this log entry (or zero)
  50. * rc_log_type the log type (or null)
  51. * rc_log_action the log action (or null)
  52. * rc_params log params
  53. *
  54. * mExtra:
  55. * prefixedDBkey prefixed db key, used by external app via msg queue
  56. * lastTimestamp timestamp of previous entry, used in WHERE clause during update
  57. * oldSize text size before the change
  58. * newSize text size after the change
  59. * pageStatus status of the page: created, deleted, moved, restored, changed
  60. *
  61. * temporary: not stored in the database
  62. * notificationtimestamp
  63. * numberofWatchingusers
  64. *
  65. * @todo Deprecate access to mAttribs (direct or via getAttributes). Right now
  66. * we're having to include both rc_comment and rc_comment_text/rc_comment_data
  67. * so random crap works right.
  68. */
  69. class RecentChange implements Taggable {
  70. // Constants for the rc_source field. Extensions may also have
  71. // their own source constants.
  72. const SRC_EDIT = 'mw.edit';
  73. const SRC_NEW = 'mw.new';
  74. const SRC_LOG = 'mw.log';
  75. const SRC_EXTERNAL = 'mw.external'; // obsolete
  76. const SRC_CATEGORIZE = 'mw.categorize';
  77. const PRC_UNPATROLLED = 0;
  78. const PRC_PATROLLED = 1;
  79. const PRC_AUTOPATROLLED = 2;
  80. /**
  81. * @var bool For save() - save to the database only, without any events.
  82. */
  83. const SEND_NONE = true;
  84. /**
  85. * @var bool For save() - do emit the change to RCFeeds (usually public).
  86. */
  87. const SEND_FEED = false;
  88. /** @var array */
  89. public $mAttribs = [];
  90. public $mExtra = [];
  91. /**
  92. * @var Title|false
  93. */
  94. public $mTitle = false;
  95. /**
  96. * @var User|false
  97. */
  98. private $mPerformer = false;
  99. public $numberofWatchingusers = 0; # Dummy to prevent error message in SpecialRecentChangesLinked
  100. public $notificationtimestamp;
  101. /**
  102. * @var int Line number of recent change. Default -1.
  103. */
  104. public $counter = -1;
  105. /**
  106. * @var array List of tags to apply
  107. */
  108. private $tags = [];
  109. /**
  110. * @var array Array of change types
  111. */
  112. private static $changeTypes = [
  113. 'edit' => RC_EDIT,
  114. 'new' => RC_NEW,
  115. 'log' => RC_LOG,
  116. 'external' => RC_EXTERNAL,
  117. 'categorize' => RC_CATEGORIZE,
  118. ];
  119. # Factory methods
  120. /**
  121. * @param mixed $row
  122. * @return RecentChange
  123. */
  124. public static function newFromRow( $row ) {
  125. $rc = new RecentChange;
  126. $rc->loadFromRow( $row );
  127. return $rc;
  128. }
  129. /**
  130. * Parsing text to RC_* constants
  131. * @since 1.24
  132. * @param string|array $type
  133. * @throws MWException
  134. * @return int|array RC_TYPE
  135. */
  136. public static function parseToRCType( $type ) {
  137. if ( is_array( $type ) ) {
  138. $retval = [];
  139. foreach ( $type as $t ) {
  140. $retval[] = self::parseToRCType( $t );
  141. }
  142. return $retval;
  143. }
  144. if ( !array_key_exists( $type, self::$changeTypes ) ) {
  145. throw new MWException( "Unknown type '$type'" );
  146. }
  147. return self::$changeTypes[$type];
  148. }
  149. /**
  150. * Parsing RC_* constants to human-readable test
  151. * @since 1.24
  152. * @param int $rcType
  153. * @return string $type
  154. */
  155. public static function parseFromRCType( $rcType ) {
  156. return array_search( $rcType, self::$changeTypes, true ) ?: "$rcType";
  157. }
  158. /**
  159. * Get an array of all change types
  160. *
  161. * @since 1.26
  162. *
  163. * @return array
  164. */
  165. public static function getChangeTypes() {
  166. return array_keys( self::$changeTypes );
  167. }
  168. /**
  169. * Obtain the recent change with a given rc_id value
  170. *
  171. * @param int $rcid The rc_id value to retrieve
  172. * @return RecentChange|null
  173. */
  174. public static function newFromId( $rcid ) {
  175. return self::newFromConds( [ 'rc_id' => $rcid ], __METHOD__ );
  176. }
  177. /**
  178. * Find the first recent change matching some specific conditions
  179. *
  180. * @param array $conds Array of conditions
  181. * @param mixed $fname Override the method name in profiling/logs
  182. * @param int $dbType DB_* constant
  183. *
  184. * @return RecentChange|null
  185. */
  186. public static function newFromConds(
  187. $conds,
  188. $fname = __METHOD__,
  189. $dbType = DB_REPLICA
  190. ) {
  191. $db = wfGetDB( $dbType );
  192. $rcQuery = self::getQueryInfo();
  193. $row = $db->selectRow(
  194. $rcQuery['tables'], $rcQuery['fields'], $conds, $fname, [], $rcQuery['joins']
  195. );
  196. if ( $row !== false ) {
  197. return self::newFromRow( $row );
  198. } else {
  199. return null;
  200. }
  201. }
  202. /**
  203. * Return the tables, fields, and join conditions to be selected to create
  204. * a new recentchanges object.
  205. * @since 1.31
  206. * @return array With three keys:
  207. * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
  208. * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
  209. * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
  210. */
  211. public static function getQueryInfo() {
  212. $commentQuery = CommentStore::getStore()->getJoin( 'rc_comment' );
  213. $actorQuery = ActorMigration::newMigration()->getJoin( 'rc_user' );
  214. return [
  215. 'tables' => [ 'recentchanges' ] + $commentQuery['tables'] + $actorQuery['tables'],
  216. 'fields' => [
  217. 'rc_id',
  218. 'rc_timestamp',
  219. 'rc_namespace',
  220. 'rc_title',
  221. 'rc_minor',
  222. 'rc_bot',
  223. 'rc_new',
  224. 'rc_cur_id',
  225. 'rc_this_oldid',
  226. 'rc_last_oldid',
  227. 'rc_type',
  228. 'rc_source',
  229. 'rc_patrolled',
  230. 'rc_ip',
  231. 'rc_old_len',
  232. 'rc_new_len',
  233. 'rc_deleted',
  234. 'rc_logid',
  235. 'rc_log_type',
  236. 'rc_log_action',
  237. 'rc_params',
  238. ] + $commentQuery['fields'] + $actorQuery['fields'],
  239. 'joins' => $commentQuery['joins'] + $actorQuery['joins'],
  240. ];
  241. }
  242. # Accessors
  243. /**
  244. * @param array $attribs
  245. */
  246. public function setAttribs( $attribs ) {
  247. $this->mAttribs = $attribs;
  248. }
  249. /**
  250. * @param array $extra
  251. */
  252. public function setExtra( $extra ) {
  253. $this->mExtra = $extra;
  254. }
  255. /**
  256. * @return Title
  257. */
  258. public function &getTitle() {
  259. if ( $this->mTitle === false ) {
  260. $this->mTitle = Title::makeTitle( $this->mAttribs['rc_namespace'], $this->mAttribs['rc_title'] );
  261. }
  262. return $this->mTitle;
  263. }
  264. /**
  265. * Get the User object of the person who performed this change.
  266. *
  267. * @return User
  268. */
  269. public function getPerformer() {
  270. if ( $this->mPerformer === false ) {
  271. if ( !empty( $this->mAttribs['rc_actor'] ) ) {
  272. $this->mPerformer = User::newFromActorId( $this->mAttribs['rc_actor'] );
  273. } elseif ( !empty( $this->mAttribs['rc_user'] ) ) {
  274. $this->mPerformer = User::newFromId( $this->mAttribs['rc_user'] );
  275. } elseif ( !empty( $this->mAttribs['rc_user_text'] ) ) {
  276. $this->mPerformer = User::newFromName( $this->mAttribs['rc_user_text'], false );
  277. } else {
  278. throw new MWException( 'RecentChange object lacks rc_actor, rc_user, and rc_user_text' );
  279. }
  280. }
  281. return $this->mPerformer;
  282. }
  283. /**
  284. * Writes the data in this object to the database
  285. *
  286. * For compatibility reasons, the SEND_ constants internally reference a value
  287. * that may seem negated from their purpose (none=true, feed=false). This is
  288. * because the parameter used to be called "$noudp", defaulting to false.
  289. *
  290. * @param bool $send self::SEND_FEED or self::SEND_NONE
  291. */
  292. public function save( $send = self::SEND_FEED ) {
  293. global $wgPutIPinRC, $wgUseEnotif, $wgShowUpdatedMarker;
  294. $dbw = wfGetDB( DB_MASTER );
  295. if ( !is_array( $this->mExtra ) ) {
  296. $this->mExtra = [];
  297. }
  298. if ( !$wgPutIPinRC ) {
  299. $this->mAttribs['rc_ip'] = '';
  300. }
  301. # Strict mode fixups (not-NULL fields)
  302. foreach ( [ 'minor', 'bot', 'new', 'patrolled', 'deleted' ] as $field ) {
  303. $this->mAttribs["rc_$field"] = (int)$this->mAttribs["rc_$field"];
  304. }
  305. # ...more fixups (NULL fields)
  306. foreach ( [ 'old_len', 'new_len' ] as $field ) {
  307. $this->mAttribs["rc_$field"] = isset( $this->mAttribs["rc_$field"] )
  308. ? (int)$this->mAttribs["rc_$field"]
  309. : null;
  310. }
  311. # If our database is strict about IP addresses, use NULL instead of an empty string
  312. $strictIPs = $dbw->getType() === 'postgres'; // legacy
  313. if ( $strictIPs && $this->mAttribs['rc_ip'] == '' ) {
  314. unset( $this->mAttribs['rc_ip'] );
  315. }
  316. # Trim spaces on user supplied text
  317. $this->mAttribs['rc_comment'] = trim( $this->mAttribs['rc_comment'] );
  318. # Fixup database timestamps
  319. $this->mAttribs['rc_timestamp'] = $dbw->timestamp( $this->mAttribs['rc_timestamp'] );
  320. # # If we are using foreign keys, an entry of 0 for the page_id will fail, so use NULL
  321. if ( $this->mAttribs['rc_cur_id'] == 0 ) {
  322. unset( $this->mAttribs['rc_cur_id'] );
  323. }
  324. $row = $this->mAttribs;
  325. # Convert mAttribs['rc_comment'] for CommentStore
  326. $comment = $row['rc_comment'];
  327. unset( $row['rc_comment'], $row['rc_comment_text'], $row['rc_comment_data'] );
  328. $row += CommentStore::getStore()->insert( $dbw, 'rc_comment', $comment );
  329. # Convert mAttribs['rc_user'] etc for ActorMigration
  330. $user = User::newFromAnyId(
  331. $row['rc_user'] ?? null,
  332. $row['rc_user_text'] ?? null,
  333. $row['rc_actor'] ?? null
  334. );
  335. unset( $row['rc_user'], $row['rc_user_text'], $row['rc_actor'] );
  336. $row += ActorMigration::newMigration()->getInsertValues( $dbw, 'rc_user', $user );
  337. # Don't reuse an existing rc_id for the new row, if one happens to be
  338. # set for some reason.
  339. unset( $row['rc_id'] );
  340. # Insert new row
  341. $dbw->insert( 'recentchanges', $row, __METHOD__ );
  342. # Set the ID
  343. $this->mAttribs['rc_id'] = $dbw->insertId();
  344. # Notify extensions
  345. // Avoid PHP 7.1 warning from passing $this by reference
  346. $rc = $this;
  347. Hooks::run( 'RecentChange_save', [ &$rc ] );
  348. if ( count( $this->tags ) ) {
  349. ChangeTags::addTags( $this->tags, $this->mAttribs['rc_id'],
  350. $this->mAttribs['rc_this_oldid'], $this->mAttribs['rc_logid'], null, $this );
  351. }
  352. if ( $send === self::SEND_FEED ) {
  353. // Emit the change to external applications via RCFeeds.
  354. $this->notifyRCFeeds();
  355. }
  356. # E-mail notifications
  357. if ( $wgUseEnotif || $wgShowUpdatedMarker ) {
  358. $editor = $this->getPerformer();
  359. $title = $this->getTitle();
  360. // Never send an RC notification email about categorization changes
  361. if (
  362. Hooks::run( 'AbortEmailNotification', [ $editor, $title, $this ] ) &&
  363. $this->mAttribs['rc_type'] != RC_CATEGORIZE
  364. ) {
  365. // @FIXME: This would be better as an extension hook
  366. // Send emails or email jobs once this row is safely committed
  367. $dbw->onTransactionCommitOrIdle(
  368. function () use ( $editor, $title ) {
  369. $enotif = new EmailNotification();
  370. $enotif->notifyOnPageChange(
  371. $editor,
  372. $title,
  373. $this->mAttribs['rc_timestamp'],
  374. $this->mAttribs['rc_comment'],
  375. $this->mAttribs['rc_minor'],
  376. $this->mAttribs['rc_last_oldid'],
  377. $this->mExtra['pageStatus']
  378. );
  379. },
  380. __METHOD__
  381. );
  382. }
  383. }
  384. // Update the cached list of active users
  385. if ( $this->mAttribs['rc_user'] > 0 ) {
  386. JobQueueGroup::singleton()->lazyPush( RecentChangesUpdateJob::newCacheUpdateJob() );
  387. }
  388. }
  389. /**
  390. * Notify all the feeds about the change.
  391. * @param array|null $feeds Optional feeds to send to, defaults to $wgRCFeeds
  392. */
  393. public function notifyRCFeeds( array $feeds = null ) {
  394. global $wgRCFeeds;
  395. if ( $feeds === null ) {
  396. $feeds = $wgRCFeeds;
  397. }
  398. $performer = $this->getPerformer();
  399. foreach ( $feeds as $params ) {
  400. $params += [
  401. 'omit_bots' => false,
  402. 'omit_anon' => false,
  403. 'omit_user' => false,
  404. 'omit_minor' => false,
  405. 'omit_patrolled' => false,
  406. ];
  407. if (
  408. ( $params['omit_bots'] && $this->mAttribs['rc_bot'] ) ||
  409. ( $params['omit_anon'] && $performer->isAnon() ) ||
  410. ( $params['omit_user'] && !$performer->isAnon() ) ||
  411. ( $params['omit_minor'] && $this->mAttribs['rc_minor'] ) ||
  412. ( $params['omit_patrolled'] && $this->mAttribs['rc_patrolled'] ) ||
  413. $this->mAttribs['rc_type'] == RC_EXTERNAL
  414. ) {
  415. continue;
  416. }
  417. $actionComment = $this->mExtra['actionCommentIRC'] ?? null;
  418. $feed = RCFeed::factory( $params );
  419. $feed->notify( $this, $actionComment );
  420. }
  421. }
  422. /**
  423. * @since 1.22
  424. * @deprecated since 1.29 Use RCFeed::factory() instead
  425. * @param string $uri URI to get the engine object for
  426. * @param array $params
  427. * @return RCFeedEngine The engine object
  428. * @throws MWException
  429. */
  430. public static function getEngine( $uri, $params = [] ) {
  431. // TODO: Merge into RCFeed::factory().
  432. global $wgRCEngines;
  433. $scheme = parse_url( $uri, PHP_URL_SCHEME );
  434. if ( !$scheme ) {
  435. throw new MWException( "Invalid RCFeed uri: '$uri'" );
  436. }
  437. if ( !isset( $wgRCEngines[$scheme] ) ) {
  438. throw new MWException( "Unknown RCFeedEngine scheme: '$scheme'" );
  439. }
  440. if ( defined( 'MW_PHPUNIT_TEST' ) && is_object( $wgRCEngines[$scheme] ) ) {
  441. return $wgRCEngines[$scheme];
  442. }
  443. return new $wgRCEngines[$scheme]( $params );
  444. }
  445. /**
  446. * Mark a given change as patrolled
  447. *
  448. * @param RecentChange|int $change RecentChange or corresponding rc_id
  449. * @param bool $auto For automatic patrol
  450. * @param string|string[]|null $tags Change tags to add to the patrol log entry
  451. * ($user should be able to add the specified tags before this is called)
  452. * @return array See doMarkPatrolled(), or null if $change is not an existing rc_id
  453. */
  454. public static function markPatrolled( $change, $auto = false, $tags = null ) {
  455. global $wgUser;
  456. $change = $change instanceof RecentChange
  457. ? $change
  458. : self::newFromId( $change );
  459. if ( !$change instanceof RecentChange ) {
  460. return null;
  461. }
  462. return $change->doMarkPatrolled( $wgUser, $auto, $tags );
  463. }
  464. /**
  465. * Mark this RecentChange as patrolled
  466. *
  467. * NOTE: Can also return 'rcpatroldisabled', 'hookaborted' and
  468. * 'markedaspatrollederror-noautopatrol' as errors
  469. * @param User $user User object doing the action
  470. * @param bool $auto For automatic patrol
  471. * @param string|string[]|null $tags Change tags to add to the patrol log entry
  472. * ($user should be able to add the specified tags before this is called)
  473. * @return array Array of permissions errors, see Title::getUserPermissionsErrors()
  474. */
  475. public function doMarkPatrolled( User $user, $auto = false, $tags = null ) {
  476. global $wgUseRCPatrol, $wgUseNPPatrol, $wgUseFilePatrol;
  477. // Fix up $tags so that the MarkPatrolled hook below always gets an array
  478. if ( $tags === null ) {
  479. $tags = [];
  480. } elseif ( is_string( $tags ) ) {
  481. $tags = [ $tags ];
  482. }
  483. $errors = [];
  484. // If recentchanges patrol is disabled, only new pages or new file versions
  485. // can be patrolled, provided the appropriate config variable is set
  486. if ( !$wgUseRCPatrol && ( !$wgUseNPPatrol || $this->getAttribute( 'rc_type' ) != RC_NEW ) &&
  487. ( !$wgUseFilePatrol || !( $this->getAttribute( 'rc_type' ) == RC_LOG &&
  488. $this->getAttribute( 'rc_log_type' ) == 'upload' ) ) ) {
  489. $errors[] = [ 'rcpatroldisabled' ];
  490. }
  491. // Automatic patrol needs "autopatrol", ordinary patrol needs "patrol"
  492. $right = $auto ? 'autopatrol' : 'patrol';
  493. $errors = array_merge( $errors, $this->getTitle()->getUserPermissionsErrors( $right, $user ) );
  494. if ( !Hooks::run( 'MarkPatrolled',
  495. [ $this->getAttribute( 'rc_id' ), &$user, false, $auto, &$tags ] )
  496. ) {
  497. $errors[] = [ 'hookaborted' ];
  498. }
  499. // Users without the 'autopatrol' right can't patrol their
  500. // own revisions
  501. if ( $user->getName() === $this->getAttribute( 'rc_user_text' ) &&
  502. !MediaWikiServices::getInstance()->getPermissionManager()
  503. ->userHasRight( $user, 'autopatrol' )
  504. ) {
  505. $errors[] = [ 'markedaspatrollederror-noautopatrol' ];
  506. }
  507. if ( $errors ) {
  508. return $errors;
  509. }
  510. // If the change was patrolled already, do nothing
  511. if ( $this->getAttribute( 'rc_patrolled' ) ) {
  512. return [];
  513. }
  514. // Actually set the 'patrolled' flag in RC
  515. $this->reallyMarkPatrolled();
  516. // Log this patrol event
  517. PatrolLog::record( $this, $auto, $user, $tags );
  518. Hooks::run(
  519. 'MarkPatrolledComplete',
  520. [ $this->getAttribute( 'rc_id' ), &$user, false, $auto ]
  521. );
  522. return [];
  523. }
  524. /**
  525. * Mark this RecentChange patrolled, without error checking
  526. * @return int Number of affected rows
  527. */
  528. public function reallyMarkPatrolled() {
  529. $dbw = wfGetDB( DB_MASTER );
  530. $dbw->update(
  531. 'recentchanges',
  532. [
  533. 'rc_patrolled' => self::PRC_PATROLLED
  534. ],
  535. [
  536. 'rc_id' => $this->getAttribute( 'rc_id' )
  537. ],
  538. __METHOD__
  539. );
  540. // Invalidate the page cache after the page has been patrolled
  541. // to make sure that the Patrol link isn't visible any longer!
  542. $this->getTitle()->invalidateCache();
  543. return $dbw->affectedRows();
  544. }
  545. /**
  546. * Makes an entry in the database corresponding to an edit
  547. *
  548. * @param string $timestamp
  549. * @param Title $title
  550. * @param bool $minor
  551. * @param User $user
  552. * @param string $comment
  553. * @param int $oldId
  554. * @param string $lastTimestamp
  555. * @param bool $bot
  556. * @param string $ip
  557. * @param int $oldSize
  558. * @param int $newSize
  559. * @param int $newId
  560. * @param int $patrol
  561. * @param array $tags
  562. * @return RecentChange
  563. */
  564. public static function notifyEdit(
  565. $timestamp, $title, $minor, $user, $comment, $oldId, $lastTimestamp,
  566. $bot, $ip = '', $oldSize = 0, $newSize = 0, $newId = 0, $patrol = 0,
  567. $tags = []
  568. ) {
  569. $rc = new RecentChange;
  570. $rc->mTitle = $title;
  571. $rc->mPerformer = $user;
  572. $rc->mAttribs = [
  573. 'rc_timestamp' => $timestamp,
  574. 'rc_namespace' => $title->getNamespace(),
  575. 'rc_title' => $title->getDBkey(),
  576. 'rc_type' => RC_EDIT,
  577. 'rc_source' => self::SRC_EDIT,
  578. 'rc_minor' => $minor ? 1 : 0,
  579. 'rc_cur_id' => $title->getArticleID(),
  580. 'rc_user' => $user->getId(),
  581. 'rc_user_text' => $user->getName(),
  582. 'rc_actor' => $user->getActorId(),
  583. 'rc_comment' => &$comment,
  584. 'rc_comment_text' => &$comment,
  585. 'rc_comment_data' => null,
  586. 'rc_this_oldid' => $newId,
  587. 'rc_last_oldid' => $oldId,
  588. 'rc_bot' => $bot ? 1 : 0,
  589. 'rc_ip' => self::checkIPAddress( $ip ),
  590. 'rc_patrolled' => intval( $patrol ),
  591. 'rc_new' => 0, # obsolete
  592. 'rc_old_len' => $oldSize,
  593. 'rc_new_len' => $newSize,
  594. 'rc_deleted' => 0,
  595. 'rc_logid' => 0,
  596. 'rc_log_type' => null,
  597. 'rc_log_action' => '',
  598. 'rc_params' => ''
  599. ];
  600. $rc->mExtra = [
  601. 'prefixedDBkey' => $title->getPrefixedDBkey(),
  602. 'lastTimestamp' => $lastTimestamp,
  603. 'oldSize' => $oldSize,
  604. 'newSize' => $newSize,
  605. 'pageStatus' => 'changed'
  606. ];
  607. DeferredUpdates::addCallableUpdate(
  608. function () use ( $rc, $tags ) {
  609. $rc->addTags( $tags );
  610. $rc->save();
  611. },
  612. DeferredUpdates::POSTSEND,
  613. wfGetDB( DB_MASTER )
  614. );
  615. return $rc;
  616. }
  617. /**
  618. * Makes an entry in the database corresponding to page creation
  619. * Note: the title object must be loaded with the new id using resetArticleID()
  620. *
  621. * @param string $timestamp
  622. * @param Title $title
  623. * @param bool $minor
  624. * @param User $user
  625. * @param string $comment
  626. * @param bool $bot
  627. * @param string $ip
  628. * @param int $size
  629. * @param int $newId
  630. * @param int $patrol
  631. * @param array $tags
  632. * @return RecentChange
  633. */
  634. public static function notifyNew(
  635. $timestamp, $title, $minor, $user, $comment, $bot,
  636. $ip = '', $size = 0, $newId = 0, $patrol = 0, $tags = []
  637. ) {
  638. $rc = new RecentChange;
  639. $rc->mTitle = $title;
  640. $rc->mPerformer = $user;
  641. $rc->mAttribs = [
  642. 'rc_timestamp' => $timestamp,
  643. 'rc_namespace' => $title->getNamespace(),
  644. 'rc_title' => $title->getDBkey(),
  645. 'rc_type' => RC_NEW,
  646. 'rc_source' => self::SRC_NEW,
  647. 'rc_minor' => $minor ? 1 : 0,
  648. 'rc_cur_id' => $title->getArticleID(),
  649. 'rc_user' => $user->getId(),
  650. 'rc_user_text' => $user->getName(),
  651. 'rc_actor' => $user->getActorId(),
  652. 'rc_comment' => &$comment,
  653. 'rc_comment_text' => &$comment,
  654. 'rc_comment_data' => null,
  655. 'rc_this_oldid' => $newId,
  656. 'rc_last_oldid' => 0,
  657. 'rc_bot' => $bot ? 1 : 0,
  658. 'rc_ip' => self::checkIPAddress( $ip ),
  659. 'rc_patrolled' => intval( $patrol ),
  660. 'rc_new' => 1, # obsolete
  661. 'rc_old_len' => 0,
  662. 'rc_new_len' => $size,
  663. 'rc_deleted' => 0,
  664. 'rc_logid' => 0,
  665. 'rc_log_type' => null,
  666. 'rc_log_action' => '',
  667. 'rc_params' => ''
  668. ];
  669. $rc->mExtra = [
  670. 'prefixedDBkey' => $title->getPrefixedDBkey(),
  671. 'lastTimestamp' => 0,
  672. 'oldSize' => 0,
  673. 'newSize' => $size,
  674. 'pageStatus' => 'created'
  675. ];
  676. DeferredUpdates::addCallableUpdate(
  677. function () use ( $rc, $tags ) {
  678. $rc->addTags( $tags );
  679. $rc->save();
  680. },
  681. DeferredUpdates::POSTSEND,
  682. wfGetDB( DB_MASTER )
  683. );
  684. return $rc;
  685. }
  686. /**
  687. * @param string $timestamp
  688. * @param Title $title
  689. * @param User $user
  690. * @param string $actionComment
  691. * @param string $ip
  692. * @param string $type
  693. * @param string $action
  694. * @param Title $target
  695. * @param string $logComment
  696. * @param string $params
  697. * @param int $newId
  698. * @param string $actionCommentIRC
  699. * @return bool
  700. */
  701. public static function notifyLog( $timestamp, $title, $user, $actionComment, $ip, $type,
  702. $action, $target, $logComment, $params, $newId = 0, $actionCommentIRC = ''
  703. ) {
  704. global $wgLogRestrictions;
  705. # Don't add private logs to RC!
  706. if ( isset( $wgLogRestrictions[$type] ) && $wgLogRestrictions[$type] != '*' ) {
  707. return false;
  708. }
  709. $rc = self::newLogEntry( $timestamp, $title, $user, $actionComment, $ip, $type, $action,
  710. $target, $logComment, $params, $newId, $actionCommentIRC );
  711. $rc->save();
  712. return true;
  713. }
  714. /**
  715. * @param string $timestamp
  716. * @param Title $title
  717. * @param User $user
  718. * @param string $actionComment
  719. * @param string $ip
  720. * @param string $type
  721. * @param string $action
  722. * @param Title $target
  723. * @param string $logComment
  724. * @param string $params
  725. * @param int $newId
  726. * @param string $actionCommentIRC
  727. * @param int $revId Id of associated revision, if any
  728. * @param bool $isPatrollable Whether this log entry is patrollable
  729. * @return RecentChange
  730. */
  731. public static function newLogEntry( $timestamp, $title, $user, $actionComment, $ip,
  732. $type, $action, $target, $logComment, $params, $newId = 0, $actionCommentIRC = '',
  733. $revId = 0, $isPatrollable = false ) {
  734. global $wgRequest;
  735. $permissionManager = MediaWikiServices::getInstance()->getPermissionManager();
  736. # # Get pageStatus for email notification
  737. switch ( $type . '-' . $action ) {
  738. case 'delete-delete':
  739. case 'delete-delete_redir':
  740. $pageStatus = 'deleted';
  741. break;
  742. case 'move-move':
  743. case 'move-move_redir':
  744. $pageStatus = 'moved';
  745. break;
  746. case 'delete-restore':
  747. $pageStatus = 'restored';
  748. break;
  749. case 'upload-upload':
  750. $pageStatus = 'created';
  751. break;
  752. case 'upload-overwrite':
  753. default:
  754. $pageStatus = 'changed';
  755. break;
  756. }
  757. // Allow unpatrolled status for patrollable log entries
  758. $canAutopatrol = $permissionManager->userHasRight( $user, 'autopatrol' );
  759. $markPatrolled = $isPatrollable ? $canAutopatrol : true;
  760. $rc = new RecentChange;
  761. $rc->mTitle = $target;
  762. $rc->mPerformer = $user;
  763. $rc->mAttribs = [
  764. 'rc_timestamp' => $timestamp,
  765. 'rc_namespace' => $target->getNamespace(),
  766. 'rc_title' => $target->getDBkey(),
  767. 'rc_type' => RC_LOG,
  768. 'rc_source' => self::SRC_LOG,
  769. 'rc_minor' => 0,
  770. 'rc_cur_id' => $target->getArticleID(),
  771. 'rc_user' => $user->getId(),
  772. 'rc_user_text' => $user->getName(),
  773. 'rc_actor' => $user->getActorId(),
  774. 'rc_comment' => &$logComment,
  775. 'rc_comment_text' => &$logComment,
  776. 'rc_comment_data' => null,
  777. 'rc_this_oldid' => $revId,
  778. 'rc_last_oldid' => 0,
  779. 'rc_bot' => $permissionManager->userHasRight( $user, 'bot' ) ?
  780. (int)$wgRequest->getBool( 'bot', true ) : 0,
  781. 'rc_ip' => self::checkIPAddress( $ip ),
  782. 'rc_patrolled' => $markPatrolled ? self::PRC_AUTOPATROLLED : self::PRC_UNPATROLLED,
  783. 'rc_new' => 0, # obsolete
  784. 'rc_old_len' => null,
  785. 'rc_new_len' => null,
  786. 'rc_deleted' => 0,
  787. 'rc_logid' => $newId,
  788. 'rc_log_type' => $type,
  789. 'rc_log_action' => $action,
  790. 'rc_params' => $params
  791. ];
  792. $rc->mExtra = [
  793. 'prefixedDBkey' => $title->getPrefixedDBkey(),
  794. 'lastTimestamp' => 0,
  795. 'actionComment' => $actionComment, // the comment appended to the action, passed from LogPage
  796. 'pageStatus' => $pageStatus,
  797. 'actionCommentIRC' => $actionCommentIRC
  798. ];
  799. return $rc;
  800. }
  801. /**
  802. * Constructs a RecentChange object for the given categorization
  803. * This does not call save() on the object and thus does not write to the db
  804. *
  805. * @since 1.27
  806. *
  807. * @param string $timestamp Timestamp of the recent change to occur
  808. * @param Title $categoryTitle Title of the category a page is being added to or removed from
  809. * @param User|null $user User object of the user that made the change
  810. * @param string $comment Change summary
  811. * @param Title $pageTitle Title of the page that is being added or removed
  812. * @param int $oldRevId Parent revision ID of this change
  813. * @param int $newRevId Revision ID of this change
  814. * @param string $lastTimestamp Parent revision timestamp of this change
  815. * @param bool $bot true, if the change was made by a bot
  816. * @param string $ip IP address of the user, if the change was made anonymously
  817. * @param int $deleted Indicates whether the change has been deleted
  818. * @param bool|null $added true, if the category was added, false for removed
  819. *
  820. * @return RecentChange
  821. */
  822. public static function newForCategorization(
  823. $timestamp,
  824. Title $categoryTitle,
  825. User $user = null,
  826. $comment,
  827. Title $pageTitle,
  828. $oldRevId,
  829. $newRevId,
  830. $lastTimestamp,
  831. $bot,
  832. $ip = '',
  833. $deleted = 0,
  834. $added = null
  835. ) {
  836. // Done in a backwards compatible way.
  837. $params = [
  838. 'hidden-cat' => WikiCategoryPage::factory( $categoryTitle )->isHidden()
  839. ];
  840. if ( $added !== null ) {
  841. $params['added'] = $added;
  842. }
  843. $rc = new RecentChange;
  844. $rc->mTitle = $categoryTitle;
  845. $rc->mPerformer = $user;
  846. $rc->mAttribs = [
  847. 'rc_timestamp' => $timestamp,
  848. 'rc_namespace' => $categoryTitle->getNamespace(),
  849. 'rc_title' => $categoryTitle->getDBkey(),
  850. 'rc_type' => RC_CATEGORIZE,
  851. 'rc_source' => self::SRC_CATEGORIZE,
  852. 'rc_minor' => 0,
  853. 'rc_cur_id' => $pageTitle->getArticleID(),
  854. 'rc_user' => $user ? $user->getId() : 0,
  855. 'rc_user_text' => $user ? $user->getName() : '',
  856. 'rc_actor' => $user ? $user->getActorId() : null,
  857. 'rc_comment' => &$comment,
  858. 'rc_comment_text' => &$comment,
  859. 'rc_comment_data' => null,
  860. 'rc_this_oldid' => $newRevId,
  861. 'rc_last_oldid' => $oldRevId,
  862. 'rc_bot' => $bot ? 1 : 0,
  863. 'rc_ip' => self::checkIPAddress( $ip ),
  864. 'rc_patrolled' => self::PRC_AUTOPATROLLED, // Always patrolled, just like log entries
  865. 'rc_new' => 0, # obsolete
  866. 'rc_old_len' => null,
  867. 'rc_new_len' => null,
  868. 'rc_deleted' => $deleted,
  869. 'rc_logid' => 0,
  870. 'rc_log_type' => null,
  871. 'rc_log_action' => '',
  872. 'rc_params' => serialize( $params )
  873. ];
  874. $rc->mExtra = [
  875. 'prefixedDBkey' => $categoryTitle->getPrefixedDBkey(),
  876. 'lastTimestamp' => $lastTimestamp,
  877. 'oldSize' => 0,
  878. 'newSize' => 0,
  879. 'pageStatus' => 'changed'
  880. ];
  881. return $rc;
  882. }
  883. /**
  884. * Get a parameter value
  885. *
  886. * @since 1.27
  887. *
  888. * @param string $name parameter name
  889. * @return mixed
  890. */
  891. public function getParam( $name ) {
  892. $params = $this->parseParams();
  893. return $params[$name] ?? null;
  894. }
  895. /**
  896. * Initialises the members of this object from a mysql row object
  897. *
  898. * @param mixed $row
  899. */
  900. public function loadFromRow( $row ) {
  901. $this->mAttribs = get_object_vars( $row );
  902. $this->mAttribs['rc_timestamp'] = wfTimestamp( TS_MW, $this->mAttribs['rc_timestamp'] );
  903. // rc_deleted MUST be set
  904. $this->mAttribs['rc_deleted'] = $row->rc_deleted;
  905. if ( isset( $this->mAttribs['rc_ip'] ) ) {
  906. // Clean up CIDRs for Postgres per T164898. ("127.0.0.1" casts to "127.0.0.1/32")
  907. $n = strpos( $this->mAttribs['rc_ip'], '/' );
  908. if ( $n !== false ) {
  909. $this->mAttribs['rc_ip'] = substr( $this->mAttribs['rc_ip'], 0, $n );
  910. }
  911. }
  912. $comment = CommentStore::getStore()
  913. // Legacy because $row may have come from self::selectFields()
  914. ->getCommentLegacy( wfGetDB( DB_REPLICA ), 'rc_comment', $row, true )
  915. ->text;
  916. $this->mAttribs['rc_comment'] = &$comment;
  917. $this->mAttribs['rc_comment_text'] = &$comment;
  918. $this->mAttribs['rc_comment_data'] = null;
  919. $user = User::newFromAnyId(
  920. $this->mAttribs['rc_user'] ?? null,
  921. $this->mAttribs['rc_user_text'] ?? null,
  922. $this->mAttribs['rc_actor'] ?? null
  923. );
  924. $this->mAttribs['rc_user'] = $user->getId();
  925. $this->mAttribs['rc_user_text'] = $user->getName();
  926. $this->mAttribs['rc_actor'] = $user->getActorId();
  927. }
  928. /**
  929. * Get an attribute value
  930. *
  931. * @param string $name Attribute name
  932. * @return mixed
  933. */
  934. public function getAttribute( $name ) {
  935. if ( $name === 'rc_comment' ) {
  936. return CommentStore::getStore()
  937. ->getComment( 'rc_comment', $this->mAttribs, true )->text;
  938. }
  939. if ( $name === 'rc_user' || $name === 'rc_user_text' || $name === 'rc_actor' ) {
  940. $user = User::newFromAnyId(
  941. $this->mAttribs['rc_user'] ?? null,
  942. $this->mAttribs['rc_user_text'] ?? null,
  943. $this->mAttribs['rc_actor'] ?? null
  944. );
  945. if ( $name === 'rc_user' ) {
  946. return $user->getId();
  947. }
  948. if ( $name === 'rc_user_text' ) {
  949. return $user->getName();
  950. }
  951. if ( $name === 'rc_actor' ) {
  952. return $user->getActorId();
  953. }
  954. }
  955. return $this->mAttribs[$name] ?? null;
  956. }
  957. /**
  958. * @return array
  959. */
  960. public function getAttributes() {
  961. return $this->mAttribs;
  962. }
  963. /**
  964. * Gets the end part of the diff URL associated with this object
  965. * Blank if no diff link should be displayed
  966. * @param bool $forceCur
  967. * @return string
  968. */
  969. public function diffLinkTrail( $forceCur ) {
  970. if ( $this->mAttribs['rc_type'] == RC_EDIT ) {
  971. $trail = "curid=" . (int)( $this->mAttribs['rc_cur_id'] ) .
  972. "&oldid=" . (int)( $this->mAttribs['rc_last_oldid'] );
  973. if ( $forceCur ) {
  974. $trail .= '&diff=0';
  975. } else {
  976. $trail .= '&diff=' . (int)( $this->mAttribs['rc_this_oldid'] );
  977. }
  978. } else {
  979. $trail = '';
  980. }
  981. return $trail;
  982. }
  983. /**
  984. * Returns the change size (HTML).
  985. * The lengths can be given optionally.
  986. * @param int $old
  987. * @param int $new
  988. * @return string
  989. */
  990. public function getCharacterDifference( $old = 0, $new = 0 ) {
  991. if ( $old === 0 ) {
  992. $old = $this->mAttribs['rc_old_len'];
  993. }
  994. if ( $new === 0 ) {
  995. $new = $this->mAttribs['rc_new_len'];
  996. }
  997. if ( $old === null || $new === null ) {
  998. return '';
  999. }
  1000. return ChangesList::showCharacterDifference( $old, $new );
  1001. }
  1002. private static function checkIPAddress( $ip ) {
  1003. global $wgRequest;
  1004. if ( $ip ) {
  1005. if ( !IP::isIPAddress( $ip ) ) {
  1006. throw new MWException( "Attempt to write \"" . $ip .
  1007. "\" as an IP address into recent changes" );
  1008. }
  1009. } else {
  1010. $ip = $wgRequest->getIP();
  1011. if ( !$ip ) {
  1012. $ip = '';
  1013. }
  1014. }
  1015. return $ip;
  1016. }
  1017. /**
  1018. * Check whether the given timestamp is new enough to have a RC row with a given tolerance
  1019. * as the recentchanges table might not be cleared out regularly (so older entries might exist)
  1020. * or rows which will be deleted soon shouldn't be included.
  1021. *
  1022. * @param mixed $timestamp MWTimestamp compatible timestamp
  1023. * @param int $tolerance Tolerance in seconds
  1024. * @return bool
  1025. */
  1026. public static function isInRCLifespan( $timestamp, $tolerance = 0 ) {
  1027. global $wgRCMaxAge;
  1028. return wfTimestamp( TS_UNIX, $timestamp ) > time() - $tolerance - $wgRCMaxAge;
  1029. }
  1030. /**
  1031. * Parses and returns the rc_params attribute
  1032. *
  1033. * @since 1.26
  1034. *
  1035. * @return mixed|bool false on failed unserialization
  1036. */
  1037. public function parseParams() {
  1038. $rcParams = $this->getAttribute( 'rc_params' );
  1039. Wikimedia\suppressWarnings();
  1040. $unserializedParams = unserialize( $rcParams );
  1041. Wikimedia\restoreWarnings();
  1042. return $unserializedParams;
  1043. }
  1044. /**
  1045. * Tags to append to the recent change,
  1046. * and associated revision/log
  1047. *
  1048. * @since 1.28
  1049. *
  1050. * @param string|string[] $tags
  1051. */
  1052. public function addTags( $tags ) {
  1053. if ( is_string( $tags ) ) {
  1054. $this->tags[] = $tags;
  1055. } else {
  1056. $this->tags = array_merge( $tags, $this->tags );
  1057. }
  1058. }
  1059. }