summaryrefslogtreecommitdiff
path: root/www/wiki/extensions/SemanticMediaWiki/src/Utils/TempFile.php
blob: 518f624d1785d6265839fdf3c72a87066a00b3e6 (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
<?php

namespace SMW\Utils;

use RuntimeException;

/**
 * @license GNU GPL v2+
 * @since 3.0
 *
 * @author mwjames
 */
class TempFile extends File {

	/**
	 * @since 3.0
	 *
	 * @return string
	 * @throws RuntimeException
	 */
	public function generate() {

		$args = func_get_args();
		$key = array_shift( $args );

		if ( $args === [] ) {
			$key = '';
		}

		return $this->get(
			$key . substr( base_convert( md5( json_encode( $args ) ), 16, 32 ), 0, 12 )
		);
	}

	/**
	 * @since 3.0
	 *
	 * @param string $file
	 *
	 * @return string
	 * @throws RuntimeException
	 */
	public function get( $file ) {

		$tmpDir = [];
		$path = '';

		if ( isset( $GLOBALS['wgTmpDirectory'] ) ) {
			$tmpDir[] = $GLOBALS['wgTmpDirectory'];
		}

		$tmpDir[] = sys_get_temp_dir();
		$tmpDir[] = ini_get( 'upload_tmp_dir' );

		foreach ( $tmpDir as $tmp ) {
			if ( $tmp != '' && is_dir( $tmp ) && is_writable( $tmp ) ) {
				$path = $tmp;
				break;
			}
		}

		if ( $path !== '' ) {
			return str_replace( [ '\\', '/' ], DIRECTORY_SEPARATOR, $path . '/' . $file );
		}

		throw new RuntimeException( 'No writable temporary directory could be found.' );
	}

}