MediaWiki master
importTextFiles.php
Go to the documentation of this file.
1<?php
16use Wikimedia\Timestamp\TimestampFormat as TS;
17
18// @codeCoverageIgnoreStart
19require_once __DIR__ . '/Maintenance.php';
20// @codeCoverageIgnoreEnd
21
29 public function __construct() {
30 parent::__construct();
31 $this->addDescription( 'Reads in text files and imports their content to pages of the wiki' );
32 $this->addOption( 'user', 'Username to which edits should be attributed. ' .
33 'Default: "Maintenance script"', false, true, 'u' );
34 $this->addOption( 'summary', 'Specify edit summary for the edits', false, true, 's' );
35 $this->addOption( 'use-timestamp', 'Use the modification date of the text file ' .
36 'as the timestamp for the edit' );
37 $this->addOption( 'overwrite', 'Overwrite existing pages. If --use-timestamp is passed, this ' .
38 'will only overwrite pages if the file has been modified since the page was last modified.' );
39 $this->addOption( 'prefix', 'A string to place in front of the file name', false, true, 'p' );
40 $this->addOption( 'bot', 'Mark edits as bot edits in the recent changes list.' );
41 $this->addOption( 'rc', 'Place revisions in RecentChanges.' );
42 $this->addArg( 'files', 'Files to import' );
43 }
44
45 public function execute() {
46 $userName = $this->getOption( 'user', false );
47 $summary = $this->getOption( 'summary', 'Imported from text file' );
48 $useTimestamp = $this->hasOption( 'use-timestamp' );
49 $rc = $this->hasOption( 'rc' );
50 $bot = $this->hasOption( 'bot' );
51 $overwrite = $this->hasOption( 'overwrite' );
52 $prefix = $this->getOption( 'prefix', '' );
53
54 // Get all the arguments. A loop is required since Maintenance doesn't
55 // support an arbitrary number of arguments.
56 $files = [];
57 $i = 0;
58 // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition
59 while ( $arg = $this->getArg( $i++ ) ) {
60 if ( file_exists( $arg ) ) {
61 $files[$arg] = file_get_contents( $arg );
62 } else {
63 // use glob to support the Windows shell, which doesn't automatically
64 // expand wildcards
65 $found = false;
66 foreach ( glob( $arg ) as $filename ) {
67 $found = true;
68 $files[$filename] = file_get_contents( $filename );
69 }
70 if ( !$found ) {
71 $this->fatalError( "Fatal error: The file '$arg' does not exist!" );
72 }
73 }
74 }
75
76 $count = count( $files );
77 $this->output( "Importing $count pages...\n" );
78
79 if ( $userName === false ) {
80 $user = User::newSystemUser( User::MAINTENANCE_SCRIPT_USER, [ 'steal' => true ] );
81 } else {
82 $user = User::newFromName( $userName );
83 }
84
85 if ( !$user ) {
86 $this->fatalError( "Invalid username\n" );
87 }
88 if ( $user->isAnon() ) {
89 $user->addToDatabase();
90 }
91
92 $exit = 0;
93
94 $successCount = 0;
95 $failCount = 0;
96 $skipCount = 0;
97
98 $revLookup = $this->getServiceContainer()->getRevisionLookup();
99 $recentChangeFactory = $this->getServiceContainer()->getRecentChangeFactory();
100
101 foreach ( $files as $file => $text ) {
102 $pageName = $prefix . pathinfo( $file, PATHINFO_FILENAME );
103 $timestamp = $useTimestamp ? wfTimestamp( TS::UNIX, filemtime( $file ) ) : wfTimestampNow();
104
105 $title = Title::newFromText( $pageName );
106 // Have to check for # manually, since it gets interpreted as a fragment
107 if ( !$title || $title->hasFragment() ) {
108 $this->error( "Invalid title $pageName. Skipping.\n" );
109 $skipCount++;
110 continue;
111 }
112
113 $exists = $title->exists();
114 $oldRevID = $title->getLatestRevID();
115 $oldRevRecord = $oldRevID ? $revLookup->getRevisionById( $oldRevID ) : null;
116 $actualTitle = $title->getPrefixedText();
117
118 if ( $exists ) {
119 $touched = wfTimestamp( TS::UNIX, $title->getTouched() );
120 if ( !$overwrite ) {
121 $this->output( "Title $actualTitle already exists. Skipping.\n" );
122 $skipCount++;
123 continue;
124 } elseif ( $useTimestamp && intval( $touched ) >= intval( $timestamp ) ) {
125 $this->output( "File for title $actualTitle has not been modified since the " .
126 "destination page was touched. Skipping.\n" );
127 $skipCount++;
128 continue;
129 }
130 }
131
132 $content = ContentHandler::makeContent( rtrim( $text ), $title );
133 $rev = new WikiRevision();
134 $rev->setContent( SlotRecord::MAIN, $content );
135 $rev->setTitle( $title );
136 $rev->setUserObj( $user );
137 $rev->setComment( $summary );
138 $rev->setTimestamp( $timestamp );
139
140 if ( $exists &&
141 $overwrite &&
142 $rev->getContent()->equals( $oldRevRecord->getContent( SlotRecord::MAIN ) )
143 ) {
144 $this->output( "File for title $actualTitle contains no changes from the current " .
145 "revision. Skipping.\n" );
146 $skipCount++;
147 continue;
148 }
149
150 $status = $rev->importOldRevision();
151 $newId = $title->getLatestRevID();
152
153 if ( $status ) {
154 $action = $exists ? 'updated' : 'created';
155 $this->output( "Successfully $action $actualTitle\n" );
156 $successCount++;
157 } else {
158 $action = $exists ? 'update' : 'create';
159 $this->output( "Failed to $action $actualTitle\n" );
160 $failCount++;
161 $exit = 1;
162 }
163
164 // Create the RecentChanges entry if necessary
165 if ( $rc && $status ) {
166 if ( $exists ) {
167 if ( is_object( $oldRevRecord ) ) {
168 $recentChange = $recentChangeFactory->createEditRecentChange(
169 $timestamp,
170 $title,
171 $rev->getMinor(),
172 $user,
173 $summary,
174 $oldRevID,
175 $bot,
176 '',
177 $oldRevRecord->getSize(),
178 $rev->getSize(),
179 $newId,
180 // the pages don't need to be patrolled
181 1
182 );
183
184 $recentChangeFactory->insertRecentChange( $recentChange );
185 }
186 } else {
187 $recentChange = $recentChangeFactory->createNewPageRecentChange(
188 $timestamp,
189 $title,
190 $rev->getMinor(),
191 $user,
192 $summary,
193 $bot,
194 '',
195 $rev->getSize(),
196 $newId,
197 1
198 );
199
200 $recentChangeFactory->insertRecentChange( $recentChange );
201 }
202 }
203 }
204
205 $this->output( "Done! $successCount succeeded, $skipCount skipped.\n" );
206 if ( $exit ) {
207 $this->fatalError( "Import failed with $failCount failed pages.\n", $exit );
208 }
209 }
210}
211
212// @codeCoverageIgnoreStart
213$maintClass = ImportTextFiles::class;
214require_once RUN_MAINTENANCE_IF_MAIN;
215// @codeCoverageIgnoreEnd
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
wfTimestamp( $outputtype=TS::UNIX, $ts=0)
Get a timestamp string in one of various formats.
Maintenance script which reads in text files and imports their content to a page of the wiki.
execute()
Do the actual work.
__construct()
Default constructor.
Base class for content handling.
Represents a revision, log entry or upload during the import process.
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
addArg( $arg, $description, $required=true, $multi=false)
Add some args that are needed.
getArg( $argId=0, $default=null)
Get an argument.
output( $out, $channel=null)
Throw some output to the user.
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
hasOption( $name)
Checks to see if a particular option was set.
getOption( $name, $default=null)
Get an option, or return the default.
error( $err, $die=0)
Throw an error to the user.
getServiceContainer()
Returns the main service container.
addDescription( $text)
Set the description text.
Value object representing a content slot associated with a page revision.
Represents a title within MediaWiki.
Definition Title.php:69
User class for the MediaWiki software.
Definition User.php:130