ImageBuilder   A
last analyzed

Complexity

Total Complexity 27

Size/Duplication

Total Lines 189
Duplicated Lines 3.7 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
dl 7
loc 189
rs 10
c 0
b 0
f 0
wmc 27
lcom 1
cbo 4

14 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 12 1
A execute() 0 13 3
A getRepo() 0 7 2
A build() 0 4 1
A init() 7 7 1
B progress() 0 26 2
A buildTable() 0 17 3
A buildImage() 0 4 1
A imageCallback() 0 7 1
A buildOldImage() 0 3 1
A oldimageCallback() 0 12 2
A crawlMissing() 0 3 1
A checkMissingImage() 0 11 2
B addMissingImage() 0 39 6

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 40 and the first side effect is on line 33.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
/**
3
 * Update image metadata records.
4
 *
5
 * Usage: php rebuildImages.php [--missing] [--dry-run]
6
 * Options:
7
 *   --missing  Crawl the uploads dir for images without records, and
8
 *              add them only.
9
 *
10
 * Copyright © 2005 Brion Vibber <[email protected]>
11
 * https://www.mediawiki.org/
12
 *
13
 * This program is free software; you can redistribute it and/or modify
14
 * it under the terms of the GNU General Public License as published by
15
 * the Free Software Foundation; either version 2 of the License, or
16
 * (at your option) any later version.
17
 *
18
 * This program is distributed in the hope that it will be useful,
19
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21
 * GNU General Public License for more details.
22
 *
23
 * You should have received a copy of the GNU General Public License along
24
 * with this program; if not, write to the Free Software Foundation, Inc.,
25
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
26
 * http://www.gnu.org/copyleft/gpl.html
27
 *
28
 * @file
29
 * @author Brion Vibber <brion at pobox.com>
30
 * @ingroup Maintenance
31
 */
32
33
require_once __DIR__ . '/Maintenance.php';
34
35
/**
36
 * Maintenance script to update image metadata records.
37
 *
38
 * @ingroup Maintenance
39
 */
40
class ImageBuilder extends Maintenance {
41
42
	/**
43
	 * @var Database
44
	 */
45
	protected $dbw;
46
47
	function __construct() {
48
		parent::__construct();
49
50
		global $wgUpdateCompatibleMetadata;
51
		// make sure to update old, but compatible img_metadata fields.
52
		$wgUpdateCompatibleMetadata = true;
53
54
		$this->addDescription( 'Script to update image metadata records' );
55
56
		$this->addOption( 'missing', 'Check for files without associated database record' );
57
		$this->addOption( 'dry-run', 'Only report, don\'t update the database' );
58
	}
59
60
	public function execute() {
0 ignored issues
show
Coding Style introduced by
execute uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
61
		$this->dbw = $this->getDB( DB_MASTER );
62
		$this->dryrun = $this->hasOption( 'dry-run' );
0 ignored issues
show
Bug introduced by
The property dryrun does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
63
		if ( $this->dryrun ) {
64
			$GLOBALS['wgReadOnly'] = 'Dry run mode, image upgrades are suppressed';
65
		}
66
67
		if ( $this->hasOption( 'missing' ) ) {
68
			$this->crawlMissing();
69
		} else {
70
			$this->build();
71
		}
72
	}
73
74
	/**
75
	 * @return FileRepo
76
	 */
77
	function getRepo() {
78
		if ( !isset( $this->repo ) ) {
79
			$this->repo = RepoGroup::singleton()->getLocalRepo();
0 ignored issues
show
Bug introduced by
The property repo does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
80
		}
81
82
		return $this->repo;
83
	}
84
85
	function build() {
86
		$this->buildImage();
87
		$this->buildOldImage();
88
	}
89
90 View Code Duplication
	function init( $count, $table ) {
91
		$this->processed = 0;
0 ignored issues
show
Bug introduced by
The property processed does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
92
		$this->updated = 0;
0 ignored issues
show
Bug introduced by
The property updated does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
93
		$this->count = $count;
0 ignored issues
show
Bug introduced by
The property count does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
94
		$this->startTime = microtime( true );
0 ignored issues
show
Bug introduced by
The property startTime does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
95
		$this->table = $table;
0 ignored issues
show
Bug introduced by
The property table does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
96
	}
97
98
	function progress( $updated ) {
99
		$this->updated += $updated;
100
		$this->processed++;
101
		if ( $this->processed % 100 != 0 ) {
102
			return;
103
		}
104
		$portion = $this->processed / $this->count;
105
		$updateRate = $this->updated / $this->processed;
106
107
		$now = microtime( true );
108
		$delta = $now - $this->startTime;
109
		$estimatedTotalTime = $delta / $portion;
110
		$eta = $this->startTime + $estimatedTotalTime;
111
		$rate = $this->processed / $delta;
112
113
		$this->output( sprintf( "%s: %6.2f%% done on %s; ETA %s [%d/%d] %.2f/sec <%.2f%% updated>\n",
114
			wfTimestamp( TS_DB, intval( $now ) ),
115
			$portion * 100.0,
116
			$this->table,
117
			wfTimestamp( TS_DB, intval( $eta ) ),
118
			$this->processed,
119
			$this->count,
120
			$rate,
121
			$updateRate * 100.0 ) );
122
		flush();
123
	}
124
125
	function buildTable( $table, $key, $callback ) {
126
		$count = $this->dbw->selectField( $table, 'count(*)', '', __METHOD__ );
127
		$this->init( $count, $table );
128
		$this->output( "Processing $table...\n" );
129
130
		$result = $this->getDB( DB_REPLICA )->select( $table, '*', [], __METHOD__ );
131
132
		foreach ( $result as $row ) {
133
			$update = call_user_func( $callback, $row, null );
134
			if ( $update ) {
135
				$this->progress( 1 );
136
			} else {
137
				$this->progress( 0 );
138
			}
139
		}
140
		$this->output( "Finished $table... $this->updated of $this->processed rows updated\n" );
141
	}
142
143
	function buildImage() {
144
		$callback = [ $this, 'imageCallback' ];
145
		$this->buildTable( 'image', 'img_name', $callback );
146
	}
147
148
	function imageCallback( $row, $copy ) {
149
		// Create a File object from the row
150
		// This will also upgrade it
151
		$file = $this->getRepo()->newFileFromRow( $row );
0 ignored issues
show
Bug introduced by
The method newFileFromRow() does not exist on FileRepo. Did you maybe mean newFile()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
152
153
		return $file->getUpgraded();
154
	}
155
156
	function buildOldImage() {
157
		$this->buildTable( 'oldimage', 'oi_archive_name', [ $this, 'oldimageCallback' ] );
158
	}
159
160
	function oldimageCallback( $row, $copy ) {
161
		// Create a File object from the row
162
		// This will also upgrade it
163
		if ( $row->oi_archive_name == '' ) {
164
			$this->output( "Empty oi_archive_name for oi_name={$row->oi_name}\n" );
165
166
			return false;
167
		}
168
		$file = $this->getRepo()->newFileFromRow( $row );
0 ignored issues
show
Bug introduced by
The method newFileFromRow() does not exist on FileRepo. Did you maybe mean newFile()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
169
170
		return $file->getUpgraded();
171
	}
172
173
	function crawlMissing() {
174
		$this->getRepo()->enumFiles( [ $this, 'checkMissingImage' ] );
175
	}
176
177
	function checkMissingImage( $fullpath ) {
178
		$filename = wfBaseName( $fullpath );
179
		$row = $this->dbw->selectRow( 'image',
180
			[ 'img_name' ],
181
			[ 'img_name' => $filename ],
182
			__METHOD__ );
183
184
		if ( !$row ) { // file not registered
185
			$this->addMissingImage( $filename, $fullpath );
186
		}
187
	}
188
189
	function addMissingImage( $filename, $fullpath ) {
190
		global $wgContLang;
191
192
		$timestamp = $this->dbw->timestamp( $this->getRepo()->getFileTimestamp( $fullpath ) );
193
194
		$altname = $wgContLang->checkTitleEncoding( $filename );
195
		if ( $altname != $filename ) {
196
			if ( $this->dryrun ) {
197
				$filename = $altname;
198
				$this->output( "Estimating transcoding... $altname\n" );
199
			} else {
200
				# @todo FIXME: create renameFile()
201
				$filename = $this->renameFile( $filename );
0 ignored issues
show
Bug introduced by
The method renameFile() does not seem to exist on object<ImageBuilder>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
202
			}
203
		}
204
205
		if ( $filename == '' ) {
206
			$this->output( "Empty filename for $fullpath\n" );
207
208
			return;
209
		}
210
		if ( !$this->dryrun ) {
211
			$file = wfLocalFile( $filename );
212
			if ( !$file->recordUpload(
213
				'',
214
				'(recovered file, missing upload log entry)',
215
				'',
216
				'',
217
				'',
218
				false,
219
				$timestamp
220
			) ) {
221
				$this->output( "Error uploading file $fullpath\n" );
222
223
				return;
224
			}
225
		}
226
		$this->output( $fullpath . "\n" );
227
	}
228
}
229
230
$maintClass = 'ImageBuilder';
231
require_once RUN_MAINTENANCE_IF_MAIN;
232