Don't bug out if no files were found
[lhc/web/wiklou.git] / maintenance / importImages.php
1 <?php
2
3 /**
4 * Maintenance script to import one or more images from the local file system into
5 * the wiki without using the web-based interface
6 *
7 * @addtogroup Maintenance
8 * @author Rob Church <robchur@gmail.com>
9 */
10
11 require_once( 'commandLine.inc' );
12 require_once( 'importImages.inc.php' );
13 echo( "Import Images\n\n" );
14
15 # Need a directory and at least one extension
16 if( count( $args ) > 1 ) {
17
18 $dir = array_shift( $args );
19
20 # Check the allowed extensions
21 while( $ext = array_shift( $args ) ) {
22 $exts[] = ltrim( $ext, '.' );
23 }
24
25 # Search the directory given and pull out suitable candidates
26 $files = findFiles( $dir, $exts );
27
28 # Initialise the user for this operation
29 $user = isset( $options['user'] )
30 ? User::newFromName( $options['user'] )
31 : User::newFromName( 'Maintenance script' );
32 if( !$user instanceof User )
33 $user = User::newFromName( 'Maintenance script' );
34 $wgUser = $user;
35
36 # Get the upload comment
37 $comment = isset( $options['comment'] )
38 ? $options['comment']
39 : 'Importing image file';
40
41 # Get the license specifier
42 $license = isset( $options['license'] ) ? $options['license'] : '';
43
44 # Batch "upload" operation
45 global $wgUploadDirectory;
46 if( count( $files ) > 0 ) {
47 foreach( $files as $file ) {
48 $base = wfBaseName( $file );
49
50 # Validate a title
51 $title = Title::makeTitleSafe( NS_IMAGE, $base );
52 if( !is_object( $title ) ) {
53 echo( "{$base} could not be imported; a valid title cannot be produced\n" );
54 continue;
55 }
56
57 # Check existence
58 $image = wfLocalFile( $title );
59 if( $image->exists() ) {
60 echo( "{$base} could not be imported; a file with this name exists in the wiki\n" );
61 continue;
62 }
63
64 # Stash the file
65 echo( "Saving {$base}..." );
66
67 $archive = $image->publish( $file );
68 if ( WikiError::isError( $archive ) ) {
69 echo( "failed.\n" );
70 continue;
71 }
72 echo( "importing..." );
73
74 if ( $image->recordUpload( $archive, $comment, $license ) ) {
75 # We're done!
76 echo( "done.\n" );
77 } else {
78 echo( "failed.\n" );
79 }
80 }
81 }
82
83 } else {
84 showUsage();
85 }
86
87 exit();
88
89 function showUsage( $reason = false ) {
90 if( $reason ) {
91 echo( $reason . "\n" );
92 }
93
94 echo <<<END
95 USAGE: php importImages.php [options] <dir> <ext1> ...
96
97 <dir> : Path to the directory containing images to be imported
98 <ext1+> File extensions to import
99
100 Options:
101 --user=<username> Set username of uploader, default 'Image import script'
102 --comment=<text> Set upload summary comment, default 'Importing image file'
103 --license=<code> Use an optional license template
104
105 END;
106 exit();
107 }
108
109 ?>