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