Completed
Push — stable2 ( 929455...10fadc )
by Robin
13:53 queued 12:28
created

Parser::checkForError()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

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