Completed
Pull Request — master (#6201)
by Jan-Christoph
16:23
created

File   A

Complexity

Total Complexity 30

Size/Duplication

Total Lines 161
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 161
rs 10
wmc 30
lcom 1
cbo 5

4 Methods

Rating   Name   Duplication   Size   Complexity  
A init() 0 19 4
F write() 0 72 14
C getEntries() 0 42 11
A getLogFilePath() 0 3 1
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 Georg Ehrke <[email protected]>
8
 * @author Lukas Reschke <[email protected]>
9
 * @author Michael Gapczynski <[email protected]>
10
 * @author Morris Jobke <[email protected]>
11
 * @author Phiber2000 <[email protected]>
12
 * @author Robin Appelman <[email protected]>
13
 * @author Roeland Jago Douma <[email protected]>
14
 * @author Thomas Müller <[email protected]>
15
 * @author Thomas Pulzer <[email protected]>
16
 * @author Vincent Petry <[email protected]>
17
 * @author Roger Szabo <[email protected]>
18
 *
19
 * @license AGPL-3.0
20
 *
21
 * This code is free software: you can redistribute it and/or modify
22
 * it under the terms of the GNU Affero General Public License, version 3,
23
 * as published by the Free Software Foundation.
24
 *
25
 * This program is distributed in the hope that it will be useful,
26
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
27
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
28
 * GNU Affero General Public License for more details.
29
 *
30
 * You should have received a copy of the GNU Affero General Public License, version 3,
31
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
32
 *
33
 */
34
35
namespace OC\Log;
36
37
/**
38
 * logging utilities
39
 *
40
 * Log is saved at data/nextcloud.log (on default)
41
 */
42
43
class File {
44
	static protected $logFile;
45
46
	/**
47
	 * Init class data
48
	 */
49
	public static function init() {
50
		$systemConfig = \OC::$server->getSystemConfig();
51
		$defaultLogFile = $systemConfig->getValue("datadirectory", \OC::$SERVERROOT.'/data').'/nextcloud.log';
52
		self::$logFile = $systemConfig->getValue("logfile", $defaultLogFile);
53
54
		/**
55
		 * Fall back to default log file if specified logfile does not exist
56
		 * and can not be created.
57
		 */
58
		if (!file_exists(self::$logFile)) {
59
			if(!is_writable(dirname(self::$logFile))) {
60
				self::$logFile = $defaultLogFile;
61
			} else {
62
				if(!touch(self::$logFile)) {
63
					self::$logFile = $defaultLogFile;
64
				}
65
			}
66
		}
67
	}
68
69
	/**
70
	 * write a message in the log
71
	 * @param string $app
72
	 * @param string $message
73
	 * @param int $level
74
	 */
75
	public static function write($app, $message, $level) {
76
		$config = \OC::$server->getSystemConfig();
77
78
		// default to ISO8601
79
		$format = $config->getValue('logdateformat', \DateTime::ATOM);
80
		$logTimeZone = $config->getValue('logtimezone', 'UTC');
81
		try {
82
			$timezone = new \DateTimeZone($logTimeZone);
83
		} catch (\Exception $e) {
84
			$timezone = new \DateTimeZone('UTC');
85
		}
86
		$time = \DateTime::createFromFormat("U.u", number_format(microtime(true), 4, ".", ""));
87
		if ($time === false) {
88
			$time = new \DateTime(null, $timezone);
89
		} else {
90
			// apply timezone if $time is created from UNIX timestamp
91
			$time->setTimezone($timezone);
92
		}
93
		$request = \OC::$server->getRequest();
94
		$reqId = $request->getId();
95
		$remoteAddr = $request->getRemoteAddress();
96
		// remove username/passwords from URLs before writing the to the log file
97
		$time = $time->format($format);
98
		$url = ($request->getRequestUri() !== '') ? $request->getRequestUri() : '--';
99
		$method = is_string($request->getMethod()) ? $request->getMethod() : '--';
100
		if($config->getValue('installed', false)) {
101
			$user = (\OC_User::getUser()) ? \OC_User::getUser() : '--';
102
		} else {
103
			$user = '--';
104
		}
105
		$userAgent = $request->getHeader('User-Agent') ?: '--';
106
		$version = $config->getValue('version', '');
107
		$entry = compact(
108
			'reqId',
109
			'level',
110
			'time',
111
			'remoteAddr',
112
			'user',
113
			'app',
114
			'method',
115
			'url',
116
			'message',
117
			'userAgent',
118
			'version'
119
		);
120
		// PHP's json_encode only accept proper UTF-8 strings, loop over all
121
		// elements to ensure that they are properly UTF-8 compliant or convert
122
		// them manually.
123
		foreach($entry as $key => $value) {
124
			if(is_string($value)) {
125
				$testEncode = json_encode($value);
126
				if($testEncode === false) {
127
					$entry[$key] = utf8_encode($value);
128
				}
129
			}
130
		}
131
		$entry = json_encode($entry, JSON_PARTIAL_OUTPUT_ON_ERROR);
132
		$handle = @fopen(self::$logFile, 'a');
133
		if ((fileperms(self::$logFile) & 0777) != 0640) {
134
			@chmod(self::$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...
135
		}
136
		if ($handle) {
137
			fwrite($handle, $entry."\n");
138
			fclose($handle);
139
		} else {
140
			// Fall back to error_log
141
			error_log($entry);
142
		}
143
		if (php_sapi_name() === 'cli-server') {
144
			error_log($message, 4);
145
		}
146
	}
147
148
	/**
149
	 * get entries from the log in reverse chronological order
150
	 * @param int $limit
151
	 * @param int $offset
152
	 * @return array
153
	 */
154
	public static function getEntries($limit=50, $offset=0) {
155
		self::init();
156
		$minLevel = \OC::$server->getSystemConfig()->getValue("loglevel", \OCP\Util::WARN);
157
		$entries = array();
158
		$handle = @fopen(self::$logFile, 'rb');
159
		if ($handle) {
160
			fseek($handle, 0, SEEK_END);
161
			$pos = ftell($handle);
162
			$line = '';
163
			$entriesCount = 0;
164
			$lines = 0;
165
			// Loop through each character of the file looking for new lines
166
			while ($pos >= 0 && ($limit === null ||$entriesCount < $limit)) {
167
				fseek($handle, $pos);
168
				$ch = fgetc($handle);
169
				if ($ch == "\n" || $pos == 0) {
170
					if ($line != '') {
171
						// Add the first character if at the start of the file,
172
						// because it doesn't hit the else in the loop
173
						if ($pos == 0) {
174
							$line = $ch.$line;
175
						}
176
						$entry = json_decode($line);
177
						// Add the line as an entry if it is passed the offset and is equal or above the log level
178
						if ($entry->level >= $minLevel) {
179
							$lines++;
180
							if ($lines > $offset) {
181
								$entries[] = $entry;
182
								$entriesCount++;
183
							}
184
						}
185
						$line = '';
186
					}
187
				} else {
188
					$line = $ch.$line;
189
				}
190
				$pos--;
191
			}
192
			fclose($handle);
193
		}
194
		return $entries;
195
	}
196
197
	/**
198
	 * @return string
199
	 */
200
	public static function getLogFilePath() {
201
		return self::$logFile;
202
	}
203
}
204