Completed
Pull Request — master (#88)
by Julius
02:39
created

Parser::parseDir()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 5

Importance

Changes 0
Metric Value
dl 0
loc 18
ccs 12
cts 12
cp 1
rs 9.3554
c 0
b 0
f 0
cc 5
nc 4
nop 2
crap 5
1
<?php
2
/**
3
 * Copyright (c) 2014 Robin Appelman <[email protected]>
4
 * This file is licensed under the Licensed under the MIT license:
5
 * http://opensource.org/licenses/MIT
6
 */
7
8
namespace Icewind\SMB\Wrapped;
9
10
use Icewind\SMB\Exception\AccessDeniedException;
11
use Icewind\SMB\Exception\AlreadyExistsException;
12
use Icewind\SMB\Exception\AuthenticationException;
13
use Icewind\SMB\Exception\Exception;
14
use Icewind\SMB\Exception\FileInUseException;
15
use Icewind\SMB\Exception\InvalidHostException;
16
use Icewind\SMB\Exception\InvalidParameterException;
17
use Icewind\SMB\Exception\InvalidResourceException;
18
use Icewind\SMB\Exception\InvalidTypeException;
19
use Icewind\SMB\Exception\NoLoginServerException;
20
use Icewind\SMB\Exception\NotEmptyException;
21
use Icewind\SMB\Exception\NotFoundException;
22
23
class Parser {
24
	const MSG_NOT_FOUND = 'Error opening local file ';
25
26
	/**
27
	 * @var string
28
	 */
29
	protected $timeZone;
30
31
	/**
32
	 * @var string
33
	 */
34
	private $host;
35
36
	// see error.h
37
	const EXCEPTION_MAP = [
38
		ErrorCodes::LogonFailure      => AuthenticationException::class,
39
		ErrorCodes::PathNotFound      => NotFoundException::class,
40
		ErrorCodes::ObjectNotFound    => NotFoundException::class,
41
		ErrorCodes::NoSuchFile        => NotFoundException::class,
42
		ErrorCodes::NameCollision     => AlreadyExistsException::class,
43
		ErrorCodes::AccessDenied      => AccessDeniedException::class,
44
		ErrorCodes::DirectoryNotEmpty => NotEmptyException::class,
45
		ErrorCodes::FileIsADirectory  => InvalidTypeException::class,
46
		ErrorCodes::NotADirectory     => InvalidTypeException::class,
47
		ErrorCodes::SharingViolation  => FileInUseException::class,
48
		ErrorCodes::InvalidParameter  => InvalidParameterException::class
49
	];
50
51
	const MODE_STRINGS = [
52
		'R' => FileInfo::MODE_READONLY,
53
		'H' => FileInfo::MODE_HIDDEN,
54
		'S' => FileInfo::MODE_SYSTEM,
55
		'D' => FileInfo::MODE_DIRECTORY,
56
		'A' => FileInfo::MODE_ARCHIVE,
57
		'N' => FileInfo::MODE_NORMAL
58
	];
59
60
	/**
61
	 * @param string $timeZone
62
	 */
63 1088
	public function __construct($timeZone) {
64 1088
		$this->timeZone = $timeZone;
65 1088
	}
66
67 80
	private function getErrorCode($line) {
68 80
		$parts = explode(' ', $line);
69 80
		foreach ($parts as $part) {
70 80
			if (substr($part, 0, 9) === 'NT_STATUS') {
71 80
				return $part;
72
			}
73
		}
74 8
		return false;
75
	}
76
77 80
	public function checkForError($output, $path) {
78 80
		if (strpos($output[0], 'does not exist')) {
79
			throw new NotFoundException($path);
80
		}
81 80
		$error = $this->getErrorCode($output[0]);
82
83 80
		if (substr($output[0], 0, strlen(self::MSG_NOT_FOUND)) === self::MSG_NOT_FOUND) {
84 4
			$localPath = substr($output[0], strlen(self::MSG_NOT_FOUND));
85 4
			throw new InvalidResourceException('Failed opening local file "' . $localPath . '" for writing');
86
		}
87
88 80
		throw Exception::fromMap(self::EXCEPTION_MAP, $error, $path);
89
	}
90
91
	/**
92
	 * check if the first line holds a connection failure
93
	 *
94
	 * @param $line
95
	 * @throws AuthenticationException
96
	 * @throws InvalidHostException
97
	 * @throws NoLoginServerException
98
	 * @throws AccessDeniedException
99
	 */
100 1040
	public function checkConnectionError($line) {
101 1040
		$line = rtrim($line, ')');
102 1040
		if (substr($line, -23) === ErrorCodes::LogonFailure) {
103 4
			throw new AuthenticationException('Invalid login');
104
		}
105 1036
		if (substr($line, -26) === ErrorCodes::BadHostName) {
106
			throw new InvalidHostException('Invalid hostname');
107
		}
108 1036
		if (substr($line, -22) === ErrorCodes::Unsuccessful) {
109 12
			throw new InvalidHostException('Connection unsuccessful');
110
		}
111 1028
		if (substr($line, -28) === ErrorCodes::ConnectionRefused) {
112
			throw new InvalidHostException('Connection refused');
113
		}
114 1028
		if (substr($line, -26) === ErrorCodes::NoLogonServers) {
115
			throw new NoLoginServerException('No login server');
116
		}
117 1028
		if (substr($line, -23) === ErrorCodes::AccessDenied) {
118
			throw new AccessDeniedException('Access denied');
119
		}
120 1028
	}
121
122 460
	public function parseMode($mode) {
123 460
		$result = 0;
124 460
		foreach (self::MODE_STRINGS as $char => $val) {
125 460
			if (strpos($mode, $char) !== false) {
126 460
				$result |= $val;
127
			}
128
		}
129 460
		return $result;
130
	}
131
132 16
	public function parseStat($output) {
133 16
		$data = [];
134 16
		foreach ($output as $line) {
135
			// A line = explode statement may not fill all array elements
136
			// properly. May happen when accessing non Windows Fileservers
137 16
			$words = explode(':', $line, 2);
138 16
			$name = isset($words[0]) ? $words[0] : '';
139 16
			$value = isset($words[1]) ? $words[1] : '';
140 16
			$value = trim($value);
141
142 16
			if (!isset($data[$name])) {
143 16
				$data[$name] = $value;
144
			}
145
		}
146
		return [
147 16
			'mtime' => strtotime($data['write_time']),
148 16
			'mode'  => hexdec(substr($data['attributes'], strpos($data['attributes'], '('), -1)),
149 16
			'size'  => isset($data['stream']) ? (int)(explode(' ', $data['stream'])[1]) : 0
150
		];
151
	}
152
153 1008
	public function parseDir($output, $basePath) {
154
		//last line is used space
155 1008
		array_pop($output);
156 1008
		$regex = '/^\s*(.*?)\s\s\s\s+(?:([NDHARS]*)\s+)?([0-9]+)\s+(.*)$/';
157
		//2 spaces, filename, optional type, size, date
158 1008
		$content = [];
159 1008
		foreach ($output as $line) {
160 1008
			if (preg_match($regex, $line, $matches)) {
161 1008
				list(, $name, $mode, $size, $time) = $matches;
162 1008
				if ($name !== '.' and $name !== '..') {
163 428
					$mode = $this->parseMode($mode);
164 428
					$time = strtotime($time . ' ' . $this->timeZone);
165 718
					$content[] = new FileInfo($basePath . '/' . $name, $name, $size, $time, $mode);
166
				}
167
			}
168
		}
169 1008
		return $content;
170
	}
171
172 8
	public function parseListShares($output) {
173 8
		$shareNames = [];
174 8
		foreach ($output as $line) {
175 8
			if (strpos($line, '|')) {
176
				list($type, $name, $description) = explode('|', $line);
177
				if (strtolower($type) === 'disk') {
178
					$shareNames[$name] = $description;
179
				}
180 8
			} elseif (strpos($line, 'Disk')) {
181
				// new output format
182 8
				list($name, $description) = explode('Disk', $line);
183 8
				$shareNames[trim($name)] = trim($description);
184
			}
185
		}
186 8
		return $shareNames;
187
	}
188
}
189