Completed
Push — master ( a56ec1...2aa108 )
by Morris
44:44 queued 16:07
created

File::write()   F

Complexity

Conditions 14
Paths 3072

Size

Total Lines 73
Code Lines 54

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 14
eloc 54
nc 3072
nop 3
dl 0
loc 73
rs 2.3293
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * @copyright Copyright (c) 2016, ownCloud, Inc.
4
 *
5
 * @author Andreas Fischer <[email protected]>
6
 * @author Bart Visscher <[email protected]>
7
 * @author duritong <[email protected]>
8
 * @author Georg Ehrke <[email protected]>
9
 * @author Joas Schilling <[email protected]>
10
 * @author Juan Pablo Villafáñez <[email protected]>
11
 * @author Lukas Reschke <[email protected]>
12
 * @author Michael Gapczynski <[email protected]>
13
 * @author Morris Jobke <[email protected]>
14
 * @author Phiber2000 <[email protected]>
15
 * @author Robin Appelman <[email protected]>
16
 * @author Roeland Jago Douma <[email protected]>
17
 * @author Roger Szabo <[email protected]>
18
 * @author Thomas Müller <[email protected]>
19
 * @author Thomas Pulzer <[email protected]>
20
 * @author Vincent Petry <[email protected]>
21
 *
22
 * @license AGPL-3.0
23
 *
24
 * This code is free software: you can redistribute it and/or modify
25
 * it under the terms of the GNU Affero General Public License, version 3,
26
 * as published by the Free Software Foundation.
27
 *
28
 * This program is distributed in the hope that it will be useful,
29
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
30
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
31
 * GNU Affero General Public License for more details.
32
 *
33
 * You should have received a copy of the GNU Affero General Public License, version 3,
34
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
35
 *
36
 */
37
38
namespace OC\Log;
39
use OC\SystemConfig;
40
use OCP\Log\IFileBased;
41
use OCP\Log\IWriter;
42
use OCP\ILogger;
43
44
/**
45
 * logging utilities
46
 *
47
 * Log is saved at data/nextcloud.log (on default)
48
 */
49
50
class File implements IWriter, IFileBased {
51
	/** @var string */
52
	protected $logFile;
53
	/** @var SystemConfig */
54
	private $config;
55
56
	public function __construct(string $path, string $fallbackPath = '', SystemConfig $config) {
57
		$this->logFile = $path;
58
		if (!file_exists($this->logFile)) {
59
			if(
60
				(
61
					!is_writable(dirname($this->logFile))
62
					|| !touch($this->logFile)
63
				)
64
				&& $fallbackPath !== ''
65
			) {
66
				$this->logFile = $fallbackPath;
67
			}
68
		}
69
		$this->config = $config;
70
	}
71
72
	/**
73
	 * write a message in the log
74
	 * @param string $app
75
	 * @param string|array $message
76
	 * @param int $level
77
	 */
78
	public function write(string $app, $message, int $level) {
79
		// default to ISO8601
80
		$format = $this->config->getValue('logdateformat', \DateTime::ATOM);
81
		$logTimeZone = $this->config->getValue('logtimezone', 'UTC');
82
		try {
83
			$timezone = new \DateTimeZone($logTimeZone);
84
		} catch (\Exception $e) {
85
			$timezone = new \DateTimeZone('UTC');
86
		}
87
		$time = \DateTime::createFromFormat("U.u", number_format(microtime(true), 4, ".", ""));
88
		if ($time === false) {
89
			$time = new \DateTime(null, $timezone);
90
		} else {
91
			// apply timezone if $time is created from UNIX timestamp
92
			$time->setTimezone($timezone);
93
		}
94
		$request = \OC::$server->getRequest();
95
		$reqId = $request->getId();
96
		$remoteAddr = $request->getRemoteAddress();
97
		// remove username/passwords from URLs before writing the to the log file
98
		$time = $time->format($format);
99
		$url = ($request->getRequestUri() !== '') ? $request->getRequestUri() : '--';
100
		$method = is_string($request->getMethod()) ? $request->getMethod() : '--';
101
		if($this->config->getValue('installed', false)) {
102
			$user = \OC_User::getUser() ? \OC_User::getUser() : '--';
103
		} else {
104
			$user = '--';
105
		}
106
		$userAgent = $request->getHeader('User-Agent');
107
		if ($userAgent === '') {
108
			$userAgent = '--';
109
		}
110
		$version = $this->config->getValue('version', '');
111
		$entry = compact(
112
			'reqId',
113
			'level',
114
			'time',
115
			'remoteAddr',
116
			'user',
117
			'app',
118
			'method',
119
			'url',
120
			'message',
121
			'userAgent',
122
			'version'
123
		);
124
		// PHP's json_encode only accept proper UTF-8 strings, loop over all
125
		// elements to ensure that they are properly UTF-8 compliant or convert
126
		// them manually.
127
		foreach($entry as $key => $value) {
128
			if(is_string($value)) {
129
				$testEncode = json_encode($value);
130
				if($testEncode === false) {
131
					$entry[$key] = utf8_encode($value);
132
				}
133
			}
134
		}
135
		$entry = json_encode($entry, JSON_PARTIAL_OUTPUT_ON_ERROR);
136
		$handle = @fopen($this->logFile, 'a');
137
		if ((fileperms($this->logFile) & 0777) != 0640) {
138
			@chmod($this->logFile, 0640);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
139
		}
140
		if ($handle) {
141
			fwrite($handle, $entry."\n");
142
			fclose($handle);
143
		} else {
144
			// Fall back to error_log
145
			error_log($entry);
146
		}
147
		if (php_sapi_name() === 'cli-server') {
148
			error_log($message, 4);
149
		}
150
	}
151
152
	/**
153
	 * get entries from the log in reverse chronological order
154
	 * @param int $limit
155
	 * @param int $offset
156
	 * @return array
157
	 */
158
	public function getEntries(int $limit=50, int $offset=0):array {
159
		$minLevel = $this->config->getValue("loglevel", ILogger::WARN);
160
		$entries = array();
161
		$handle = @fopen($this->logFile, 'rb');
162
		if ($handle) {
163
			fseek($handle, 0, SEEK_END);
164
			$pos = ftell($handle);
165
			$line = '';
166
			$entriesCount = 0;
167
			$lines = 0;
168
			// Loop through each character of the file looking for new lines
169
			while ($pos >= 0 && ($limit === null ||$entriesCount < $limit)) {
170
				fseek($handle, $pos);
171
				$ch = fgetc($handle);
172
				if ($ch == "\n" || $pos == 0) {
173
					if ($line != '') {
174
						// Add the first character if at the start of the file,
175
						// because it doesn't hit the else in the loop
176
						if ($pos == 0) {
177
							$line = $ch.$line;
178
						}
179
						$entry = json_decode($line);
180
						// Add the line as an entry if it is passed the offset and is equal or above the log level
181
						if ($entry->level >= $minLevel) {
182
							$lines++;
183
							if ($lines > $offset) {
184
								$entries[] = $entry;
185
								$entriesCount++;
186
							}
187
						}
188
						$line = '';
189
					}
190
				} else {
191
					$line = $ch.$line;
192
				}
193
				$pos--;
194
			}
195
			fclose($handle);
196
		}
197
		return $entries;
198
	}
199
200
	/**
201
	 * @return string
202
	 */
203
	public function getLogFilePath():string {
204
		return $this->logFile;
205
	}
206
}
207