Completed
Push — stable3.0 ( 04db6f...bd43cd )
by Robin
03:57
created

Parser::getErrorCode()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

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