Use batch inserts for watchlist
[lhc/web/wiklou.git] / includes / WatchedItem.php
1 <?php
2 /**
3 * Accessor and mutator for watchlist 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 * @ingroup Watchlist
22 */
23
24 /**
25 * Representation of a pair of user and title for watchlist entries.
26 *
27 * @ingroup Watchlist
28 */
29 class WatchedItem {
30 /**
31 * Constant to specify that user rights 'editmywatchlist' and
32 * 'viewmywatchlist' should not be checked.
33 * @since 1.22
34 */
35 const IGNORE_USER_RIGHTS = 0;
36
37 /**
38 * Constant to specify that user rights 'editmywatchlist' and
39 * 'viewmywatchlist' should be checked.
40 * @since 1.22
41 */
42 const CHECK_USER_RIGHTS = 1;
43
44 /** @var Title */
45 public $mTitle;
46
47 /** @var User */
48 public $mUser;
49
50 /** @var int */
51 public $mCheckRights;
52
53 /** @var bool */
54 private $loaded = false;
55
56 /** @var bool */
57 private $watched;
58
59 /** @var string */
60 private $timestamp;
61
62 /**
63 * Create a WatchedItem object with the given user and title
64 * @since 1.22 $checkRights parameter added
65 * @param User $user The user to use for (un)watching
66 * @param Title $title The title we're going to (un)watch
67 * @param int $checkRights Whether to check the 'viewmywatchlist' and 'editmywatchlist' rights.
68 * Pass either WatchedItem::IGNORE_USER_RIGHTS or WatchedItem::CHECK_USER_RIGHTS.
69 * @return WatchedItem
70 */
71 public static function fromUserTitle( $user, $title,
72 $checkRights = WatchedItem::CHECK_USER_RIGHTS
73 ) {
74 $wl = new WatchedItem;
75 $wl->mUser = $user;
76 $wl->mTitle = $title;
77 $wl->mCheckRights = $checkRights;
78
79 return $wl;
80 }
81
82 /**
83 * Title being watched
84 * @return Title
85 */
86 protected function getTitle() {
87 return $this->mTitle;
88 }
89
90 /**
91 * Helper to retrieve the title namespace
92 * @return int
93 */
94 protected function getTitleNs() {
95 return $this->getTitle()->getNamespace();
96 }
97
98 /**
99 * Helper to retrieve the title DBkey
100 * @return string
101 */
102 protected function getTitleDBkey() {
103 return $this->getTitle()->getDBkey();
104 }
105
106 /**
107 * Helper to retrieve the user id
108 * @return int
109 */
110 protected function getUserId() {
111 return $this->mUser->getId();
112 }
113
114 /**
115 * Return an array of conditions to select or update the appropriate database
116 * row.
117 *
118 * @return array
119 */
120 private function dbCond() {
121 return array(
122 'wl_user' => $this->getUserId(),
123 'wl_namespace' => $this->getTitleNs(),
124 'wl_title' => $this->getTitleDBkey(),
125 );
126 }
127
128 /**
129 * Load the object from the database
130 */
131 private function load() {
132 if ( $this->loaded ) {
133 return;
134 }
135 $this->loaded = true;
136
137 // Only loggedin user can have a watchlist
138 if ( $this->mUser->isAnon() ) {
139 $this->watched = false;
140 return;
141 }
142
143 // some pages cannot be watched
144 if ( !$this->getTitle()->isWatchable() ) {
145 $this->watched = false;
146 return;
147 }
148
149 # Pages and their talk pages are considered equivalent for watching;
150 # remember that talk namespaces are numbered as page namespace+1.
151
152 $dbr = wfGetDB( DB_SLAVE );
153 $row = $dbr->selectRow( 'watchlist', 'wl_notificationtimestamp',
154 $this->dbCond(), __METHOD__ );
155
156 if ( $row === false ) {
157 $this->watched = false;
158 } else {
159 $this->watched = true;
160 $this->timestamp = $row->wl_notificationtimestamp;
161 }
162 }
163
164 /**
165 * Check permissions
166 * @param string $what 'viewmywatchlist' or 'editmywatchlist'
167 */
168 private function isAllowed( $what ) {
169 return !$this->mCheckRights || $this->mUser->isAllowed( $what );
170 }
171
172 /**
173 * Is mTitle being watched by mUser?
174 * @return bool
175 */
176 public function isWatched() {
177 if ( !$this->isAllowed( 'viewmywatchlist' ) ) {
178 return false;
179 }
180
181 $this->load();
182 return $this->watched;
183 }
184
185 /**
186 * Get the notification timestamp of this entry.
187 *
188 * @return bool|null|string False if the page is not watched, the value of
189 * the wl_notificationtimestamp field otherwise
190 */
191 public function getNotificationTimestamp() {
192 if ( !$this->isAllowed( 'viewmywatchlist' ) ) {
193 return false;
194 }
195
196 $this->load();
197 if ( $this->watched ) {
198 return $this->timestamp;
199 } else {
200 return false;
201 }
202 }
203
204 /**
205 * Reset the notification timestamp of this entry
206 *
207 * @param bool $force Whether to force the write query to be executed even if the
208 * page is not watched or the notification timestamp is already NULL.
209 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
210 */
211 public function resetNotificationTimestamp( $force = '', $oldid = 0 ) {
212 // Only loggedin user can have a watchlist
213 if ( wfReadOnly() || $this->mUser->isAnon() || !$this->isAllowed( 'editmywatchlist' ) ) {
214 return;
215 }
216
217 if ( $force != 'force' ) {
218 $this->load();
219 if ( !$this->watched || $this->timestamp === null ) {
220 return;
221 }
222 }
223
224 $title = $this->getTitle();
225 if ( !$oldid ) {
226 // No oldid given, assuming latest revision; clear the timestamp.
227 $notificationTimestamp = null;
228 } elseif ( !$title->getNextRevisionID( $oldid ) ) {
229 // Oldid given and is the latest revision for this title; clear the timestamp.
230 $notificationTimestamp = null;
231 } else {
232 // See if the version marked as read is more recent than the one we're viewing.
233 // Call load() if it wasn't called before due to $force.
234 $this->load();
235
236 if ( $this->timestamp === null ) {
237 // This can only happen if $force is enabled.
238 $notificationTimestamp = null;
239 } else {
240 // Oldid given and isn't the latest; update the timestamp.
241 // This will result in no further notification emails being sent!
242 $dbr = wfGetDB( DB_SLAVE );
243 $notificationTimestamp = $dbr->selectField(
244 'revision', 'rev_timestamp',
245 array( 'rev_page' => $title->getArticleID(), 'rev_id' => $oldid )
246 );
247 // We need to go one second to the future because of various strict comparisons
248 // throughout the codebase
249 $ts = new MWTimestamp( $notificationTimestamp );
250 $ts->timestamp->add( new DateInterval( 'PT1S' ) );
251 $notificationTimestamp = $ts->getTimestamp( TS_MW );
252
253 if ( $notificationTimestamp < $this->timestamp ) {
254 if ( $force != 'force' ) {
255 return;
256 } else {
257 // This is a little silly…
258 $notificationTimestamp = $this->timestamp;
259 }
260 }
261 }
262 }
263
264 // If the page is watched by the user (or may be watched), update the timestamp on any
265 // any matching rows
266 $dbw = wfGetDB( DB_MASTER );
267 $dbw->update( 'watchlist', array( 'wl_notificationtimestamp' => $notificationTimestamp ),
268 $this->dbCond(), __METHOD__ );
269 $this->timestamp = null;
270 }
271
272 /**
273 * @param WatchedItem[] $items
274 * @return bool
275 */
276 static public function batchAddWatch( array $items ) {
277 $section = new ProfileSection( __METHOD__ );
278
279 if ( wfReadOnly() ) {
280 return false;
281 }
282
283 $rows = array();
284 foreach ( $items as $item ) {
285 // Only loggedin user can have a watchlist
286 if ( $item->mUser->isAnon() || !$item->isAllowed( 'editmywatchlist' ) ) {
287 continue;
288 }
289 $rows[] = array(
290 'wl_user' => $item->getUserId(),
291 'wl_namespace' => MWNamespace::getSubject( $item->getTitleNs() ),
292 'wl_title' => $item->getTitleDBkey(),
293 'wl_notificationtimestamp' => null,
294 );
295 // Every single watched page needs now to be listed in watchlist;
296 // namespace:page and namespace_talk:page need separate entries:
297 $rows[] = array(
298 'wl_user' => $item->getUserId(),
299 'wl_namespace' => MWNamespace::getTalk( $item->getTitleNs() ),
300 'wl_title' => $item->getTitleDBkey(),
301 'wl_notificationtimestamp' => null
302 );
303 $item->watched = true;
304 }
305
306 if ( !$rows ) {
307 return false;
308 }
309
310 $dbw = wfGetDB( DB_MASTER );
311 foreach( array_chunk( $rows, 100 ) as $toInsert ) {
312 // Use INSERT IGNORE to avoid overwriting the notification timestamp
313 // if there's already an entry for this page
314 $dbw->insert( 'watchlist', $toInsert, __METHOD__, 'IGNORE' );
315 }
316
317 return true;
318 }
319
320 /**
321 * Given a title and user (assumes the object is setup), add the watch to the database.
322 * @return bool
323 */
324 public function addWatch() {
325 return self::batchAddWatch( array( $this ) );
326 }
327
328 /**
329 * Same as addWatch, only the opposite.
330 * @return bool
331 */
332 public function removeWatch() {
333 wfProfileIn( __METHOD__ );
334
335 // Only loggedin user can have a watchlist
336 if ( wfReadOnly() || $this->mUser->isAnon() || !$this->isAllowed( 'editmywatchlist' ) ) {
337 wfProfileOut( __METHOD__ );
338 return false;
339 }
340
341 $success = false;
342 $dbw = wfGetDB( DB_MASTER );
343 $dbw->delete( 'watchlist',
344 array(
345 'wl_user' => $this->getUserId(),
346 'wl_namespace' => MWNamespace::getSubject( $this->getTitleNs() ),
347 'wl_title' => $this->getTitleDBkey(),
348 ), __METHOD__
349 );
350 if ( $dbw->affectedRows() ) {
351 $success = true;
352 }
353
354 # the following code compensates the new behavior, introduced by the
355 # enotif patch, that every single watched page needs now to be listed
356 # in watchlist namespace:page and namespace_talk:page had separate
357 # entries: clear them
358 $dbw->delete( 'watchlist',
359 array(
360 'wl_user' => $this->getUserId(),
361 'wl_namespace' => MWNamespace::getTalk( $this->getTitleNs() ),
362 'wl_title' => $this->getTitleDBkey(),
363 ), __METHOD__
364 );
365
366 if ( $dbw->affectedRows() ) {
367 $success = true;
368 }
369
370 $this->watched = false;
371
372 wfProfileOut( __METHOD__ );
373 return $success;
374 }
375
376 /**
377 * Check if the given title already is watched by the user, and if so
378 * add watches on a new title. To be used for page renames and such.
379 *
380 * @param Title $ot Page title to duplicate entries from, if present
381 * @param Title $nt Page title to add watches on
382 */
383 public static function duplicateEntries( $ot, $nt ) {
384 WatchedItem::doDuplicateEntries( $ot->getSubjectPage(), $nt->getSubjectPage() );
385 WatchedItem::doDuplicateEntries( $ot->getTalkPage(), $nt->getTalkPage() );
386 }
387
388 /**
389 * Handle duplicate entries. Backend for duplicateEntries().
390 *
391 * @param Title $ot
392 * @param Title $nt
393 *
394 * @return bool
395 */
396 private static function doDuplicateEntries( $ot, $nt ) {
397 $oldnamespace = $ot->getNamespace();
398 $newnamespace = $nt->getNamespace();
399 $oldtitle = $ot->getDBkey();
400 $newtitle = $nt->getDBkey();
401
402 $dbw = wfGetDB( DB_MASTER );
403 $res = $dbw->select( 'watchlist', 'wl_user',
404 array( 'wl_namespace' => $oldnamespace, 'wl_title' => $oldtitle ),
405 __METHOD__, 'FOR UPDATE'
406 );
407 # Construct array to replace into the watchlist
408 $values = array();
409 foreach ( $res as $s ) {
410 $values[] = array(
411 'wl_user' => $s->wl_user,
412 'wl_namespace' => $newnamespace,
413 'wl_title' => $newtitle
414 );
415 }
416
417 if ( empty( $values ) ) {
418 // Nothing to do
419 return true;
420 }
421
422 # Perform replace
423 # Note that multi-row replace is very efficient for MySQL but may be inefficient for
424 # some other DBMSes, mostly due to poor simulation by us
425 $dbw->replace(
426 'watchlist',
427 array( array( 'wl_user', 'wl_namespace', 'wl_title' ) ),
428 $values,
429 __METHOD__
430 );
431
432 return true;
433 }
434 }