summaryrefslogtreecommitdiff
path: root/includes/FileStore.php
blob: c01350c0e205e6691a02dbcd68d3c9130b2747a9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
<?php

/**
 * @todo document (needs one-sentence top-level class description).
 */
class FileStore {
	const DELETE_ORIGINAL = 1;

	/**
	 * Fetch the FileStore object for a given storage group
	 */
	static function get( $group ) {
		global $wgFileStore;

		if( isset( $wgFileStore[$group] ) ) {
			$info = $wgFileStore[$group];
			return new FileStore( $group,
				$info['directory'],
				$info['url'],
				intval( $info['hash'] ) );
		} else {
			return null;
		}
	}

	private function __construct( $group, $directory, $path, $hash ) {
		$this->mGroup = $group;
		$this->mDirectory = $directory;
		$this->mPath = $path;
		$this->mHashLevel = $hash;
	}

	/**
	 * Acquire a lock; use when performing write operations on a store.
	 * This is attached to your master database connection, so if you
	 * suffer an uncaught error the lock will be released when the
	 * connection is closed.
	 *
	 * @todo Probably only works on MySQL. Abstract to the Database class?
	 */
	static function lock() {
		global $wgDBtype;
		if ($wgDBtype != 'mysql')
			return true;
		$dbw = wfGetDB( DB_MASTER );
		$lockname = $dbw->addQuotes( FileStore::lockName() );
		$result = $dbw->query( "SELECT GET_LOCK($lockname, 5) AS lockstatus", __METHOD__ );
		$row = $dbw->fetchObject( $result );
		$dbw->freeResult( $result );

		if( $row->lockstatus == 1 ) {
			return true;
		} else {
			wfDebug( __METHOD__." failed to acquire lock\n" );
			return false;
		}
	}

	/**
	 * Release the global file store lock.
	 */
	static function unlock() {
		global $wgDBtype;
		if ($wgDBtype != 'mysql')
			return true;
		$dbw = wfGetDB( DB_MASTER );
		$lockname = $dbw->addQuotes( FileStore::lockName() );
		$result = $dbw->query( "SELECT RELEASE_LOCK($lockname)", __METHOD__ );
		$dbw->fetchObject( $result );
		$dbw->freeResult( $result );
	}

	private static function lockName() {
		return 'MediaWiki.' . wfWikiID() . '.FileStore';
	}

	/**
	 * Copy a file into the file store from elsewhere in the filesystem.
	 * Should be protected by FileStore::lock() to avoid race conditions.
	 *
	 * @param $key storage key string
	 * @param $flags
	 *  DELETE_ORIGINAL - remove the source file on transaction commit.
	 *
	 * @throws FSException if copy can't be completed
	 * @return FSTransaction
	 */
	function insert( $key, $sourcePath, $flags=0 ) {
		$destPath = $this->filePath( $key );
		return $this->copyFile( $sourcePath, $destPath, $flags );
	}

	/**
	 * Copy a file from the file store to elsewhere in the filesystem.
	 * Should be protected by FileStore::lock() to avoid race conditions.
	 *
	 * @param $key storage key string
	 * @param $flags
	 *  DELETE_ORIGINAL - remove the source file on transaction commit.
	 *
	 * @throws FSException if copy can't be completed
	 * @return FSTransaction on success
	 */
	function export( $key, $destPath, $flags=0 ) {
		$sourcePath = $this->filePath( $key );
		return $this->copyFile( $sourcePath, $destPath, $flags );
	}

	private function copyFile( $sourcePath, $destPath, $flags=0 ) {
		if( !file_exists( $sourcePath ) ) {
			// Abort! Abort!
			throw new FSException( "missing source file '$sourcePath'" );
		}

		$transaction = new FSTransaction();

		if( $flags & self::DELETE_ORIGINAL ) {
			$transaction->addCommit( FSTransaction::DELETE_FILE, $sourcePath );
		}

		if( file_exists( $destPath ) ) {
			// An identical file is already present; no need to copy.
		} else {
			if( !file_exists( dirname( $destPath ) ) ) {
				wfSuppressWarnings();
				$ok = mkdir( dirname( $destPath ), 0777, true );
				wfRestoreWarnings();

				if( !$ok ) {
					throw new FSException(
						"failed to create directory for '$destPath'" );
				}
			}

			wfSuppressWarnings();
			$ok = copy( $sourcePath, $destPath );
			wfRestoreWarnings();

			if( $ok ) {
				wfDebug( __METHOD__." copied '$sourcePath' to '$destPath'\n" );
				$transaction->addRollback( FSTransaction::DELETE_FILE, $destPath );
			} else {
				throw new FSException(
					__METHOD__." failed to copy '$sourcePath' to '$destPath'" );
			}
		}

		return $transaction;
	}

	/**
	 * Delete a file from the file store.
	 * Caller's responsibility to make sure it's not being used by another row.
	 *
	 * File is not actually removed until transaction commit.
	 * Should be protected by FileStore::lock() to avoid race conditions.
	 *
	 * @param $key storage key string
	 * @throws FSException if file can't be deleted
	 * @return FSTransaction
	 */
	function delete( $key ) {
		$destPath = $this->filePath( $key );
		if( false === $destPath ) {
			throw new FSException( "file store does not contain file '$key'" );
		} else {
			return FileStore::deleteFile( $destPath );
		}
	}

	/**
	 * Delete a non-managed file on a transactional basis.
	 *
	 * File is not actually removed until transaction commit.
	 * Should be protected by FileStore::lock() to avoid race conditions.
	 *
	 * @param $path file to remove
	 * @throws FSException if file can't be deleted
	 * @return FSTransaction
	 *
	 * @todo Might be worth preliminary permissions check
	 */
	static function deleteFile( $path ) {
		if( file_exists( $path ) ) {
			$transaction = new FSTransaction();
			$transaction->addCommit( FSTransaction::DELETE_FILE, $path );
			return $transaction;
		} else {
			throw new FSException( "cannot delete missing file '$path'" );
		}
	}

	/**
	 * Stream a contained file directly to HTTP output.
	 * Will throw a 404 if file is missing; 400 if invalid key.
	 * @return true on success, false on failure
	 */
	function stream( $key ) {
		$path = $this->filePath( $key );
		if( $path === false ) {
			wfHttpError( 400, "Bad request", "Invalid or badly-formed filename." );
			return false;
		}

		if( file_exists( $path ) ) {
			// Set the filename for more convenient save behavior from browsers
			// FIXME: Is this safe?
			header( 'Content-Disposition: inline; filename="' . $key . '"' );

			require_once 'StreamFile.php';
			wfStreamFile( $path );
		} else {
			return wfHttpError( 404, "Not found",
				"The requested resource does not exist." );
		}
	}

	/**
	 * Confirm that the given file key is valid.
	 * Note that a valid key may refer to a file that does not exist.
	 *
	 * Key should consist of a 31-digit base-36 SHA-1 hash and
	 * an optional alphanumeric extension, all lowercase.
	 * The whole must not exceed 64 characters.
	 *
	 * @param $key
	 * @return boolean
	 */
	static function validKey( $key ) {
		return preg_match( '/^[0-9a-z]{31,32}(\.[0-9a-z]{1,31})?$/', $key );
	}


	/**
	 * Calculate file storage key from a file on disk.
	 * You must pass an extension to it, as some files may be calculated
	 * out of a temporary file etc.
	 *
	 * @param $path to file
	 * @param $extension
	 * @return string or false if could not open file or bad extension
	 */
	static function calculateKey( $path, $extension ) {
		wfSuppressWarnings();
		$hash = sha1_file( $path );
		wfRestoreWarnings();
		if( $hash === false ) {
			wfDebug( __METHOD__.": couldn't hash file '$path'\n" );
			return false;
		}

		$base36 = wfBaseConvert( $hash, 16, 36, 31 );
		if( $extension == '' ) {
			$key = $base36;
		} else {
			$key = $base36 . '.' . $extension;
		}

		// Sanity check
		if( self::validKey( $key ) ) {
			return $key;
		} else {
			wfDebug( __METHOD__.": generated bad key '$key'\n" );
			return false;
		}
	}

	/**
	 * Return filesystem path to the given file.
	 * Note that the file may or may not exist.
	 * @return string or false if an invalid key
	 */
	function filePath( $key ) {
		if( self::validKey( $key ) ) {
			return $this->mDirectory . DIRECTORY_SEPARATOR .
				$this->hashPath( $key, DIRECTORY_SEPARATOR );
		} else {
			return false;
		}
	}

	/**
	 * Return URL path to the given file, if the store is public.
	 * @return string or false if not public
	 */
	function urlPath( $key ) {
		if( $this->mUrl && self::validKey( $key ) ) {
			return $this->mUrl . '/' . $this->hashPath( $key, '/' );
		} else {
			return false;
		}
	}

	private function hashPath( $key, $separator ) {
		$parts = array();
		for( $i = 0; $i < $this->mHashLevel; $i++ ) {
			$parts[] = $key{$i};
		}
		$parts[] = $key;
		return implode( $separator, $parts );
	}
}

/**
 * Wrapper for file store transaction stuff.
 *
 * FileStore methods may return one of these for undoable operations;
 * you can then call its rollback() or commit() methods to perform
 * final cleanup if dependent database work fails or succeeds.
 */
class FSTransaction {
	const DELETE_FILE = 1;

	/**
	 * Combine more items into a fancier transaction
	 */
	function add( FSTransaction $transaction ) {
		$this->mOnCommit = array_merge(
			$this->mOnCommit, $transaction->mOnCommit );
		$this->mOnRollback = array_merge(
			$this->mOnRollback, $transaction->mOnRollback );
	}

	/**
	 * Perform final actions for success.
	 * @return true if actions applied ok, false if errors
	 */
	function commit() {
		return $this->apply( $this->mOnCommit );
	}

	/**
	 * Perform final actions for failure.
	 * @return true if actions applied ok, false if errors
	 */
	function rollback() {
		return $this->apply( $this->mOnRollback );
	}

	// --- Private and friend functions below...

	function __construct() {
		$this->mOnCommit = array();
		$this->mOnRollback = array();
	}

	function addCommit( $action, $path ) {
		$this->mOnCommit[] = array( $action, $path );
	}

	function addRollback( $action, $path ) {
		$this->mOnRollback[] = array( $action, $path );
	}

	private function apply( $actions ) {
		$result = true;
		foreach( $actions as $item ) {
			list( $action, $path ) = $item;
			if( $action == self::DELETE_FILE ) {
				wfSuppressWarnings();
				$ok = unlink( $path );
				wfRestoreWarnings();
				if( $ok )
					wfDebug( __METHOD__.": deleting file '$path'\n" );
				else
					wfDebug( __METHOD__.": failed to delete file '$path'\n" );
				$result = $result && $ok;
			}
		}
		return $result;
	}
}

/**
 * @ingroup Exception
 */
class FSException extends MWException { }