Completed
Push — master ( 08cbd8...4395cf )
by Lukas
16:54 queued 03:37
created

File::write()   D

Complexity

Conditions 10
Paths 384

Size

Total Lines 59
Code Lines 47

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 10
eloc 47
c 1
b 0
f 0
nc 384
nop 3
dl 0
loc 59
rs 4.8648

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 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
			'remoteAddr',
110
			'app',
111
			'message',
112
			'level',
113
			'time',
114
			'method',
115
			'url',
116
			'user',
117
			'userAgent',
118
			'version'
119
		);
120
		$entry = json_encode($entry);
121
		$handle = @fopen(self::$logFile, 'a');
122
		@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...
123
		if ($handle) {
124
			fwrite($handle, $entry."\n");
125
			fclose($handle);
126
		} else {
127
			// Fall back to error_log
128
			error_log($entry);
129
		}
130
		if (php_sapi_name() === 'cli-server') {
131
			error_log($message, 4);
132
		}
133
	}
134
135
	/**
136
	 * get entries from the log in reverse chronological order
137
	 * @param int $limit
138
	 * @param int $offset
139
	 * @return array
140
	 */
141
	public static function getEntries($limit=50, $offset=0) {
142
		self::init();
143
		$minLevel = \OC::$server->getSystemConfig()->getValue("loglevel", \OCP\Util::WARN);
144
		$entries = array();
145
		$handle = @fopen(self::$logFile, 'rb');
146
		if ($handle) {
147
			fseek($handle, 0, SEEK_END);
148
			$pos = ftell($handle);
149
			$line = '';
150
			$entriesCount = 0;
151
			$lines = 0;
152
			// Loop through each character of the file looking for new lines
153
			while ($pos >= 0 && ($limit === null ||$entriesCount < $limit)) {
154
				fseek($handle, $pos);
155
				$ch = fgetc($handle);
156
				if ($ch == "\n" || $pos == 0) {
157
					if ($line != '') {
158
						// Add the first character if at the start of the file,
159
						// because it doesn't hit the else in the loop
160
						if ($pos == 0) {
161
							$line = $ch.$line;
162
						}
163
						$entry = json_decode($line);
164
						// Add the line as an entry if it is passed the offset and is equal or above the log level
165
						if ($entry->level >= $minLevel) {
166
							$lines++;
167
							if ($lines > $offset) {
168
								$entries[] = $entry;
169
								$entriesCount++;
170
							}
171
						}
172
						$line = '';
173
					}
174
				} else {
175
					$line = $ch.$line;
176
				}
177
				$pos--;
178
			}
179
			fclose($handle);
180
		}
181
		return $entries;
182
	}
183
184
	/**
185
	 * @return string
186
	 */
187
	public static function getLogFilePath() {
188
		return self::$logFile;
189
	}
190
}
191