Merge "Add support for PHP7 random_bytes in favor of mcrypt_create_iv"
[lhc/web/wiklou.git] / includes / import / WikiRevision.php
1 <?php
2 /**
3 * MediaWiki page data importer.
4 *
5 * Copyright © 2003,2005 Brion Vibber <brion@pobox.com>
6 * https://www.mediawiki.org/
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
22 *
23 * @file
24 * @ingroup SpecialPage
25 */
26
27 /**
28 * Represents a revision, log entry or upload during the import process.
29 * This class sticks closely to the structure of the XML dump.
30 *
31 * @ingroup SpecialPage
32 */
33 class WikiRevision {
34 /** @todo Unused? */
35 public $importer = null;
36
37 /** @var Title */
38 public $title = null;
39
40 /** @var int */
41 public $id = 0;
42
43 /** @var string */
44 public $timestamp = "20010115000000";
45
46 /**
47 * @var int
48 * @todo Can't find any uses. Public, because that's suspicious. Get clarity. */
49 public $user = 0;
50
51 /** @var string */
52 public $user_text = "";
53
54 /** @var User */
55 public $userObj = null;
56
57 /** @var string */
58 public $model = null;
59
60 /** @var string */
61 public $format = null;
62
63 /** @var string */
64 public $text = "";
65
66 /** @var int */
67 protected $size;
68
69 /** @var Content */
70 public $content = null;
71
72 /** @var ContentHandler */
73 protected $contentHandler = null;
74
75 /** @var string */
76 public $comment = "";
77
78 /** @var bool */
79 public $minor = false;
80
81 /** @var string */
82 public $type = "";
83
84 /** @var string */
85 public $action = "";
86
87 /** @var string */
88 public $params = "";
89
90 /** @var string */
91 public $fileSrc = '';
92
93 /** @var bool|string */
94 public $sha1base36 = false;
95
96 /**
97 * @var bool
98 * @todo Unused?
99 */
100 public $isTemp = false;
101
102 /** @var string */
103 public $archiveName = '';
104
105 protected $filename;
106
107 /** @var mixed */
108 protected $src;
109
110 /** @todo Unused? */
111 public $fileIsTemp;
112
113 /** @var bool */
114 private $mNoUpdates = false;
115
116 /** @var Config $config */
117 private $config;
118
119 public function __construct( Config $config ) {
120 $this->config = $config;
121 }
122
123 /**
124 * @param Title $title
125 * @throws MWException
126 */
127 public function setTitle( $title ) {
128 if ( is_object( $title ) ) {
129 $this->title = $title;
130 } elseif ( is_null( $title ) ) {
131 throw new MWException( "WikiRevision given a null title in import. "
132 . "You may need to adjust \$wgLegalTitleChars." );
133 } else {
134 throw new MWException( "WikiRevision given non-object title in import." );
135 }
136 }
137
138 /**
139 * @param int $id
140 */
141 public function setID( $id ) {
142 $this->id = $id;
143 }
144
145 /**
146 * @param string $ts
147 */
148 public function setTimestamp( $ts ) {
149 # 2003-08-05T18:30:02Z
150 $this->timestamp = wfTimestamp( TS_MW, $ts );
151 }
152
153 /**
154 * @param string $user
155 */
156 public function setUsername( $user ) {
157 $this->user_text = $user;
158 }
159
160 /**
161 * @param User $user
162 */
163 public function setUserObj( $user ) {
164 $this->userObj = $user;
165 }
166
167 /**
168 * @param string $ip
169 */
170 public function setUserIP( $ip ) {
171 $this->user_text = $ip;
172 }
173
174 /**
175 * @param string $model
176 */
177 public function setModel( $model ) {
178 $this->model = $model;
179 }
180
181 /**
182 * @param string $format
183 */
184 public function setFormat( $format ) {
185 $this->format = $format;
186 }
187
188 /**
189 * @param string $text
190 */
191 public function setText( $text ) {
192 $this->text = $text;
193 }
194
195 /**
196 * @param string $text
197 */
198 public function setComment( $text ) {
199 $this->comment = $text;
200 }
201
202 /**
203 * @param bool $minor
204 */
205 public function setMinor( $minor ) {
206 $this->minor = (bool)$minor;
207 }
208
209 /**
210 * @param mixed $src
211 */
212 public function setSrc( $src ) {
213 $this->src = $src;
214 }
215
216 /**
217 * @param string $src
218 * @param bool $isTemp
219 */
220 public function setFileSrc( $src, $isTemp ) {
221 $this->fileSrc = $src;
222 $this->fileIsTemp = $isTemp;
223 }
224
225 /**
226 * @param string $sha1base36
227 */
228 public function setSha1Base36( $sha1base36 ) {
229 $this->sha1base36 = $sha1base36;
230 }
231
232 /**
233 * @param string $filename
234 */
235 public function setFilename( $filename ) {
236 $this->filename = $filename;
237 }
238
239 /**
240 * @param string $archiveName
241 */
242 public function setArchiveName( $archiveName ) {
243 $this->archiveName = $archiveName;
244 }
245
246 /**
247 * @param int $size
248 */
249 public function setSize( $size ) {
250 $this->size = intval( $size );
251 }
252
253 /**
254 * @param string $type
255 */
256 public function setType( $type ) {
257 $this->type = $type;
258 }
259
260 /**
261 * @param string $action
262 */
263 public function setAction( $action ) {
264 $this->action = $action;
265 }
266
267 /**
268 * @param array $params
269 */
270 public function setParams( $params ) {
271 $this->params = $params;
272 }
273
274 /**
275 * @param bool $noupdates
276 */
277 public function setNoUpdates( $noupdates ) {
278 $this->mNoUpdates = $noupdates;
279 }
280
281 /**
282 * @return Title
283 */
284 public function getTitle() {
285 return $this->title;
286 }
287
288 /**
289 * @return int
290 */
291 public function getID() {
292 return $this->id;
293 }
294
295 /**
296 * @return string
297 */
298 public function getTimestamp() {
299 return $this->timestamp;
300 }
301
302 /**
303 * @return string
304 */
305 public function getUser() {
306 return $this->user_text;
307 }
308
309 /**
310 * @return User
311 */
312 public function getUserObj() {
313 return $this->userObj;
314 }
315
316 /**
317 * @return string
318 */
319 public function getText() {
320 return $this->text;
321 }
322
323 /**
324 * @return ContentHandler
325 */
326 public function getContentHandler() {
327 if ( is_null( $this->contentHandler ) ) {
328 $this->contentHandler = ContentHandler::getForModelID( $this->getModel() );
329 }
330
331 return $this->contentHandler;
332 }
333
334 /**
335 * @return Content
336 */
337 public function getContent() {
338 if ( is_null( $this->content ) ) {
339 $handler = $this->getContentHandler();
340 $this->content = $handler->unserializeContent( $this->text, $this->getFormat() );
341 }
342
343 return $this->content;
344 }
345
346 /**
347 * @return string
348 */
349 public function getModel() {
350 if ( is_null( $this->model ) ) {
351 $this->model = $this->getTitle()->getContentModel();
352 }
353
354 return $this->model;
355 }
356
357 /**
358 * @return string
359 */
360 public function getFormat() {
361 if ( is_null( $this->format ) ) {
362 $this->format = $this->getContentHandler()->getDefaultFormat();
363 }
364
365 return $this->format;
366 }
367
368 /**
369 * @return string
370 */
371 public function getComment() {
372 return $this->comment;
373 }
374
375 /**
376 * @return bool
377 */
378 public function getMinor() {
379 return $this->minor;
380 }
381
382 /**
383 * @return mixed
384 */
385 public function getSrc() {
386 return $this->src;
387 }
388
389 /**
390 * @return bool|string
391 */
392 public function getSha1() {
393 if ( $this->sha1base36 ) {
394 return Wikimedia\base_convert( $this->sha1base36, 36, 16 );
395 }
396 return false;
397 }
398
399 /**
400 * @return string
401 */
402 public function getFileSrc() {
403 return $this->fileSrc;
404 }
405
406 /**
407 * @return bool
408 */
409 public function isTempSrc() {
410 return $this->isTemp;
411 }
412
413 /**
414 * @return mixed
415 */
416 public function getFilename() {
417 return $this->filename;
418 }
419
420 /**
421 * @return string
422 */
423 public function getArchiveName() {
424 return $this->archiveName;
425 }
426
427 /**
428 * @return mixed
429 */
430 public function getSize() {
431 return $this->size;
432 }
433
434 /**
435 * @return string
436 */
437 public function getType() {
438 return $this->type;
439 }
440
441 /**
442 * @return string
443 */
444 public function getAction() {
445 return $this->action;
446 }
447
448 /**
449 * @return string
450 */
451 public function getParams() {
452 return $this->params;
453 }
454
455 /**
456 * @return bool
457 */
458 public function importOldRevision() {
459 $dbw = wfGetDB( DB_MASTER );
460
461 # Sneak a single revision into place
462 $user = $this->getUserObj() ?: User::newFromName( $this->getUser() );
463 if ( $user ) {
464 $userId = intval( $user->getId() );
465 $userText = $user->getName();
466 } else {
467 $userId = 0;
468 $userText = $this->getUser();
469 $user = new User;
470 }
471
472 // avoid memory leak...?
473 Title::clearCaches();
474
475 $page = WikiPage::factory( $this->title );
476 $page->loadPageData( 'fromdbmaster' );
477 if ( !$page->exists() ) {
478 // must create the page...
479 $pageId = $page->insertOn( $dbw );
480 $created = true;
481 $oldcountable = null;
482 } else {
483 $pageId = $page->getId();
484 $created = false;
485
486 $prior = $dbw->selectField( 'revision', '1',
487 [ 'rev_page' => $pageId,
488 'rev_timestamp' => $dbw->timestamp( $this->timestamp ),
489 'rev_user_text' => $userText,
490 'rev_comment' => $this->getComment() ],
491 __METHOD__
492 );
493 if ( $prior ) {
494 // @todo FIXME: This could fail slightly for multiple matches :P
495 wfDebug( __METHOD__ . ": skipping existing revision for [[" .
496 $this->title->getPrefixedText() . "]], timestamp " . $this->timestamp . "\n" );
497 return false;
498 }
499 }
500
501 if ( !$pageId ) {
502 // This seems to happen if two clients simultaneously try to import the
503 // same page
504 wfDebug( __METHOD__ . ': got invalid $pageId when importing revision of [[' .
505 $this->title->getPrefixedText() . ']], timestamp ' . $this->timestamp . "\n" );
506 return false;
507 }
508
509 // Select previous version to make size diffs correct
510 // @todo This assumes that multiple revisions of the same page are imported
511 // in order from oldest to newest.
512 $prevId = $dbw->selectField( 'revision', 'rev_id',
513 [
514 'rev_page' => $pageId,
515 'rev_timestamp <= ' . $dbw->addQuotes( $dbw->timestamp( $this->timestamp ) ),
516 ],
517 __METHOD__,
518 [ 'ORDER BY' => [
519 'rev_timestamp DESC',
520 'rev_id DESC', // timestamp is not unique per page
521 ]
522 ]
523 );
524
525 # @todo FIXME: Use original rev_id optionally (better for backups)
526 # Insert the row
527 $revision = new Revision( [
528 'title' => $this->title,
529 'page' => $pageId,
530 'content_model' => $this->getModel(),
531 'content_format' => $this->getFormat(),
532 // XXX: just set 'content' => $this->getContent()?
533 'text' => $this->getContent()->serialize( $this->getFormat() ),
534 'comment' => $this->getComment(),
535 'user' => $userId,
536 'user_text' => $userText,
537 'timestamp' => $this->timestamp,
538 'minor_edit' => $this->minor,
539 'parent_id' => $prevId,
540 ] );
541 $revision->insertOn( $dbw );
542 $changed = $page->updateIfNewerOn( $dbw, $revision );
543
544 if ( $changed !== false && !$this->mNoUpdates ) {
545 wfDebug( __METHOD__ . ": running updates\n" );
546 // countable/oldcountable stuff is handled in WikiImporter::finishImportPage
547 $page->doEditUpdates(
548 $revision,
549 $user,
550 [ 'created' => $created, 'oldcountable' => 'no-change' ]
551 );
552 }
553
554 return true;
555 }
556
557 public function importLogItem() {
558 $dbw = wfGetDB( DB_MASTER );
559
560 $user = $this->getUserObj() ?: User::newFromName( $this->getUser() );
561 if ( $user ) {
562 $userId = intval( $user->getId() );
563 $userText = $user->getName();
564 } else {
565 $userId = 0;
566 $userText = $this->getUser();
567 }
568
569 # @todo FIXME: This will not record autoblocks
570 if ( !$this->getTitle() ) {
571 wfDebug( __METHOD__ . ": skipping invalid {$this->type}/{$this->action} log time, timestamp " .
572 $this->timestamp . "\n" );
573 return false;
574 }
575 # Check if it exists already
576 // @todo FIXME: Use original log ID (better for backups)
577 $prior = $dbw->selectField( 'logging', '1',
578 [ 'log_type' => $this->getType(),
579 'log_action' => $this->getAction(),
580 'log_timestamp' => $dbw->timestamp( $this->timestamp ),
581 'log_namespace' => $this->getTitle()->getNamespace(),
582 'log_title' => $this->getTitle()->getDBkey(),
583 'log_comment' => $this->getComment(),
584 # 'log_user_text' => $this->user_text,
585 'log_params' => $this->params ],
586 __METHOD__
587 );
588 // @todo FIXME: This could fail slightly for multiple matches :P
589 if ( $prior ) {
590 wfDebug( __METHOD__
591 . ": skipping existing item for Log:{$this->type}/{$this->action}, timestamp "
592 . $this->timestamp . "\n" );
593 return false;
594 }
595 $log_id = $dbw->nextSequenceValue( 'logging_log_id_seq' );
596 $data = [
597 'log_id' => $log_id,
598 'log_type' => $this->type,
599 'log_action' => $this->action,
600 'log_timestamp' => $dbw->timestamp( $this->timestamp ),
601 'log_user' => $userId,
602 'log_user_text' => $userText,
603 'log_namespace' => $this->getTitle()->getNamespace(),
604 'log_title' => $this->getTitle()->getDBkey(),
605 'log_comment' => $this->getComment(),
606 'log_params' => $this->params
607 ];
608 $dbw->insert( 'logging', $data, __METHOD__ );
609
610 return true;
611 }
612
613 /**
614 * @return bool
615 */
616 public function importUpload() {
617 # Construct a file
618 $archiveName = $this->getArchiveName();
619 if ( $archiveName ) {
620 wfDebug( __METHOD__ . "Importing archived file as $archiveName\n" );
621 $file = OldLocalFile::newFromArchiveName( $this->getTitle(),
622 RepoGroup::singleton()->getLocalRepo(), $archiveName );
623 } else {
624 $file = wfLocalFile( $this->getTitle() );
625 $file->load( File::READ_LATEST );
626 wfDebug( __METHOD__ . 'Importing new file as ' . $file->getName() . "\n" );
627 if ( $file->exists() && $file->getTimestamp() > $this->getTimestamp() ) {
628 $archiveName = $file->getTimestamp() . '!' . $file->getName();
629 $file = OldLocalFile::newFromArchiveName( $this->getTitle(),
630 RepoGroup::singleton()->getLocalRepo(), $archiveName );
631 wfDebug( __METHOD__ . "File already exists; importing as $archiveName\n" );
632 }
633 }
634 if ( !$file ) {
635 wfDebug( __METHOD__ . ': Bad file for ' . $this->getTitle() . "\n" );
636 return false;
637 }
638
639 # Get the file source or download if necessary
640 $source = $this->getFileSrc();
641 $autoDeleteSource = $this->isTempSrc();
642 if ( !strlen( $source ) ) {
643 $source = $this->downloadSource();
644 $autoDeleteSource = true;
645 }
646 if ( !strlen( $source ) ) {
647 wfDebug( __METHOD__ . ": Could not fetch remote file.\n" );
648 return false;
649 }
650
651 $tmpFile = new TempFSFile( $source );
652 if ( $autoDeleteSource ) {
653 $tmpFile->autocollect();
654 }
655
656 $sha1File = ltrim( sha1_file( $source ), '0' );
657 $sha1 = $this->getSha1();
658 if ( $sha1 && ( $sha1 !== $sha1File ) ) {
659 wfDebug( __METHOD__ . ": Corrupt file $source.\n" );
660 return false;
661 }
662
663 $user = $this->getUserObj() ?: User::newFromName( $this->getUser() );
664
665 # Do the actual upload
666 if ( $archiveName ) {
667 $status = $file->uploadOld( $source, $archiveName,
668 $this->getTimestamp(), $this->getComment(), $user );
669 } else {
670 $flags = 0;
671 $status = $file->upload( $source, $this->getComment(), $this->getComment(),
672 $flags, false, $this->getTimestamp(), $user );
673 }
674
675 if ( $status->isGood() ) {
676 wfDebug( __METHOD__ . ": Successful\n" );
677 return true;
678 } else {
679 wfDebug( __METHOD__ . ': failed: ' . $status->getHTML() . "\n" );
680 return false;
681 }
682 }
683
684 /**
685 * @return bool|string
686 */
687 public function downloadSource() {
688 if ( !$this->config->get( 'EnableUploads' ) ) {
689 return false;
690 }
691
692 $tempo = tempnam( wfTempDir(), 'download' );
693 $f = fopen( $tempo, 'wb' );
694 if ( !$f ) {
695 wfDebug( "IMPORT: couldn't write to temp file $tempo\n" );
696 return false;
697 }
698
699 // @todo FIXME!
700 $src = $this->getSrc();
701 $data = Http::get( $src, [], __METHOD__ );
702 if ( !$data ) {
703 wfDebug( "IMPORT: couldn't fetch source $src\n" );
704 fclose( $f );
705 unlink( $tempo );
706 return false;
707 }
708
709 fwrite( $f, $data );
710 fclose( $f );
711
712 return $tempo;
713 }
714
715 }