Client.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. <?php
  2. declare(strict_types=1);
  3. namespace Sabre\DAV;
  4. use Sabre\HTTP;
  5. use Sabre\Uri;
  6. /**
  7. * SabreDAV DAV client.
  8. *
  9. * This client wraps around Curl to provide a convenient API to a WebDAV
  10. * server.
  11. *
  12. * NOTE: This class is experimental, it's api will likely change in the future.
  13. *
  14. * @copyright Copyright (C) fruux GmbH (https://fruux.com/)
  15. * @author Evert Pot (http://evertpot.com/)
  16. * @license http://sabre.io/license/ Modified BSD License
  17. */
  18. class Client extends HTTP\Client
  19. {
  20. /**
  21. * The xml service.
  22. *
  23. * Uset this service to configure the property and namespace maps.
  24. *
  25. * @var mixed
  26. */
  27. public $xml;
  28. /**
  29. * The elementMap.
  30. *
  31. * This property is linked via reference to $this->xml->elementMap.
  32. * It's deprecated as of version 3.0.0, and should no longer be used.
  33. *
  34. * @deprecated
  35. *
  36. * @var array
  37. */
  38. public $propertyMap = [];
  39. /**
  40. * Base URI.
  41. *
  42. * This URI will be used to resolve relative urls.
  43. *
  44. * @var string
  45. */
  46. protected $baseUri;
  47. /**
  48. * Basic authentication.
  49. */
  50. const AUTH_BASIC = 1;
  51. /**
  52. * Digest authentication.
  53. */
  54. const AUTH_DIGEST = 2;
  55. /**
  56. * NTLM authentication.
  57. */
  58. const AUTH_NTLM = 4;
  59. /**
  60. * Identity encoding, which basically does not nothing.
  61. */
  62. const ENCODING_IDENTITY = 1;
  63. /**
  64. * Deflate encoding.
  65. */
  66. const ENCODING_DEFLATE = 2;
  67. /**
  68. * Gzip encoding.
  69. */
  70. const ENCODING_GZIP = 4;
  71. /**
  72. * Sends all encoding headers.
  73. */
  74. const ENCODING_ALL = 7;
  75. /**
  76. * Content-encoding.
  77. *
  78. * @var int
  79. */
  80. protected $encoding = self::ENCODING_IDENTITY;
  81. /**
  82. * Constructor.
  83. *
  84. * Settings are provided through the 'settings' argument. The following
  85. * settings are supported:
  86. *
  87. * * baseUri
  88. * * userName (optional)
  89. * * password (optional)
  90. * * proxy (optional)
  91. * * authType (optional)
  92. * * encoding (optional)
  93. *
  94. * authType must be a bitmap, using self::AUTH_BASIC, self::AUTH_DIGEST
  95. * and self::AUTH_NTLM. If you know which authentication method will be
  96. * used, it's recommended to set it, as it will save a great deal of
  97. * requests to 'discover' this information.
  98. *
  99. * Encoding is a bitmap with one of the ENCODING constants.
  100. */
  101. public function __construct(array $settings)
  102. {
  103. if (!isset($settings['baseUri'])) {
  104. throw new \InvalidArgumentException('A baseUri must be provided');
  105. }
  106. parent::__construct();
  107. $this->baseUri = $settings['baseUri'];
  108. if (isset($settings['proxy'])) {
  109. $this->addCurlSetting(CURLOPT_PROXY, $settings['proxy']);
  110. }
  111. if (isset($settings['userName'])) {
  112. $userName = $settings['userName'];
  113. $password = isset($settings['password']) ? $settings['password'] : '';
  114. if (isset($settings['authType'])) {
  115. $curlType = 0;
  116. if ($settings['authType'] & self::AUTH_BASIC) {
  117. $curlType |= CURLAUTH_BASIC;
  118. }
  119. if ($settings['authType'] & self::AUTH_DIGEST) {
  120. $curlType |= CURLAUTH_DIGEST;
  121. }
  122. if ($settings['authType'] & self::AUTH_NTLM) {
  123. $curlType |= CURLAUTH_NTLM;
  124. }
  125. } else {
  126. $curlType = CURLAUTH_BASIC | CURLAUTH_DIGEST;
  127. }
  128. $this->addCurlSetting(CURLOPT_HTTPAUTH, $curlType);
  129. $this->addCurlSetting(CURLOPT_USERPWD, $userName.':'.$password);
  130. }
  131. if (isset($settings['encoding'])) {
  132. $encoding = $settings['encoding'];
  133. $encodings = [];
  134. if ($encoding & self::ENCODING_IDENTITY) {
  135. $encodings[] = 'identity';
  136. }
  137. if ($encoding & self::ENCODING_DEFLATE) {
  138. $encodings[] = 'deflate';
  139. }
  140. if ($encoding & self::ENCODING_GZIP) {
  141. $encodings[] = 'gzip';
  142. }
  143. $this->addCurlSetting(CURLOPT_ENCODING, implode(',', $encodings));
  144. }
  145. $this->addCurlSetting(CURLOPT_USERAGENT, 'sabre-dav/'.Version::VERSION.' (http://sabre.io/)');
  146. $this->xml = new Xml\Service();
  147. // BC
  148. $this->propertyMap = &$this->xml->elementMap;
  149. }
  150. /**
  151. * Does a PROPFIND request with filtered response returning only available properties.
  152. *
  153. * The list of requested properties must be specified as an array, in clark
  154. * notation.
  155. *
  156. * Depth should be either 0 or 1. A depth of 1 will cause a request to be
  157. * made to the server to also return all child resources.
  158. *
  159. * For depth 0, just the array of properties for the resource is returned.
  160. *
  161. * For depth 1, the returned array will contain a list of resource names as keys,
  162. * and an array of properties as values.
  163. *
  164. * The array of properties will contain the properties as keys with their values as the value.
  165. * Only properties that are actually returned from the server without error will be
  166. * returned, anything else is discarded.
  167. *
  168. * @param 1|0 $depth
  169. */
  170. public function propFind($url, array $properties, $depth = 0): array
  171. {
  172. $result = $this->doPropFind($url, $properties, $depth);
  173. // If depth was 0, we only return the top item
  174. if (0 === $depth) {
  175. reset($result);
  176. $result = current($result);
  177. return isset($result[200]) ? $result[200] : [];
  178. }
  179. $newResult = [];
  180. foreach ($result as $href => $statusList) {
  181. $newResult[$href] = isset($statusList[200]) ? $statusList[200] : [];
  182. }
  183. return $newResult;
  184. }
  185. /**
  186. * Does a PROPFIND request with unfiltered response.
  187. *
  188. * The list of requested properties must be specified as an array, in clark
  189. * notation.
  190. *
  191. * Depth should be either 0 or 1. A depth of 1 will cause a request to be
  192. * made to the server to also return all child resources.
  193. *
  194. * For depth 0, just the multi-level array of status and properties for the resource is returned.
  195. *
  196. * For depth 1, the returned array will contain a list of resources as keys and
  197. * a multi-level array containing status and properties as value.
  198. *
  199. * The multi-level array of status and properties is formatted the same as what is
  200. * documented for parseMultiStatus.
  201. *
  202. * All properties that are actually returned from the server are returned by this method.
  203. *
  204. * @param 1|0 $depth
  205. */
  206. public function propFindUnfiltered(string $url, array $properties, int $depth = 0): array
  207. {
  208. $result = $this->doPropFind($url, $properties, $depth);
  209. // If depth was 0, we only return the top item
  210. if (0 === $depth) {
  211. reset($result);
  212. return current($result);
  213. } else {
  214. return $result;
  215. }
  216. }
  217. /**
  218. * Does a PROPFIND request.
  219. *
  220. * The list of requested properties must be specified as an array, in clark
  221. * notation.
  222. *
  223. * Depth should be either 0 or 1. A depth of 1 will cause a request to be
  224. * made to the server to also return all child resources.
  225. *
  226. * The returned array will contain a list of resources as keys and
  227. * a multi-level array containing status and properties as value.
  228. *
  229. * The multi-level array of status and properties is formatted the same as what is
  230. * documented for parseMultiStatus.
  231. *
  232. * @param 1|0 $depth
  233. */
  234. private function doPropFind($url, array $properties, $depth = 0): array
  235. {
  236. $dom = new \DOMDocument('1.0', 'UTF-8');
  237. $dom->formatOutput = true;
  238. $root = $dom->createElementNS('DAV:', 'd:propfind');
  239. $prop = $dom->createElement('d:prop');
  240. foreach ($properties as $property) {
  241. list(
  242. $namespace,
  243. $elementName
  244. ) = \Sabre\Xml\Service::parseClarkNotation($property);
  245. if ('DAV:' === $namespace) {
  246. $element = $dom->createElement('d:'.$elementName);
  247. } else {
  248. $element = $dom->createElementNS($namespace, 'x:'.$elementName);
  249. }
  250. $prop->appendChild($element);
  251. }
  252. $dom->appendChild($root)->appendChild($prop);
  253. $body = $dom->saveXML();
  254. $url = $this->getAbsoluteUrl($url);
  255. $request = new HTTP\Request('PROPFIND', $url, [
  256. 'Depth' => $depth,
  257. 'Content-Type' => 'application/xml',
  258. ], $body);
  259. $response = $this->send($request);
  260. if ((int) $response->getStatus() >= 400) {
  261. throw new HTTP\ClientHttpException($response);
  262. }
  263. return $this->parseMultiStatus($response->getBodyAsString());
  264. }
  265. /**
  266. * Updates a list of properties on the server.
  267. *
  268. * The list of properties must have clark-notation properties for the keys,
  269. * and the actual (string) value for the value. If the value is null, an
  270. * attempt is made to delete the property.
  271. *
  272. * @param string $url
  273. *
  274. * @return bool
  275. */
  276. public function propPatch($url, array $properties)
  277. {
  278. $propPatch = new Xml\Request\PropPatch();
  279. $propPatch->properties = $properties;
  280. $xml = $this->xml->write(
  281. '{DAV:}propertyupdate',
  282. $propPatch
  283. );
  284. $url = $this->getAbsoluteUrl($url);
  285. $request = new HTTP\Request('PROPPATCH', $url, [
  286. 'Content-Type' => 'application/xml',
  287. ], $xml);
  288. $response = $this->send($request);
  289. if ($response->getStatus() >= 400) {
  290. throw new HTTP\ClientHttpException($response);
  291. }
  292. if (207 === $response->getStatus()) {
  293. // If it's a 207, the request could still have failed, but the
  294. // information is hidden in the response body.
  295. $result = $this->parseMultiStatus($response->getBodyAsString());
  296. $errorProperties = [];
  297. foreach ($result as $href => $statusList) {
  298. foreach ($statusList as $status => $properties) {
  299. if ($status >= 400) {
  300. foreach ($properties as $propName => $propValue) {
  301. $errorProperties[] = $propName.' ('.$status.')';
  302. }
  303. }
  304. }
  305. }
  306. if ($errorProperties) {
  307. throw new HTTP\ClientException('PROPPATCH failed. The following properties errored: '.implode(', ', $errorProperties));
  308. }
  309. }
  310. return true;
  311. }
  312. /**
  313. * Performs an HTTP options request.
  314. *
  315. * This method returns all the features from the 'DAV:' header as an array.
  316. * If there was no DAV header, or no contents this method will return an
  317. * empty array.
  318. *
  319. * @return array
  320. */
  321. public function options()
  322. {
  323. $request = new HTTP\Request('OPTIONS', $this->getAbsoluteUrl(''));
  324. $response = $this->send($request);
  325. $dav = $response->getHeader('Dav');
  326. if (!$dav) {
  327. return [];
  328. }
  329. $features = explode(',', $dav);
  330. foreach ($features as &$v) {
  331. $v = trim($v);
  332. }
  333. return $features;
  334. }
  335. /**
  336. * Performs an actual HTTP request, and returns the result.
  337. *
  338. * If the specified url is relative, it will be expanded based on the base
  339. * url.
  340. *
  341. * The returned array contains 3 keys:
  342. * * body - the response body
  343. * * httpCode - a HTTP code (200, 404, etc)
  344. * * headers - a list of response http headers. The header names have
  345. * been lowercased.
  346. *
  347. * For large uploads, it's highly recommended to specify body as a stream
  348. * resource. You can easily do this by simply passing the result of
  349. * fopen(..., 'r').
  350. *
  351. * This method will throw an exception if an HTTP error was received. Any
  352. * HTTP status code above 399 is considered an error.
  353. *
  354. * Note that it is no longer recommended to use this method, use the send()
  355. * method instead.
  356. *
  357. * @param string $method
  358. * @param string $url
  359. * @param string|resource|null $body
  360. *
  361. * @throws clientException, in case a curl error occurred
  362. *
  363. * @return array
  364. */
  365. public function request($method, $url = '', $body = null, array $headers = [])
  366. {
  367. $url = $this->getAbsoluteUrl($url);
  368. $response = $this->send(new HTTP\Request($method, $url, $headers, $body));
  369. return [
  370. 'body' => $response->getBodyAsString(),
  371. 'statusCode' => (int) $response->getStatus(),
  372. 'headers' => array_change_key_case($response->getHeaders()),
  373. ];
  374. }
  375. /**
  376. * Returns the full url based on the given url (which may be relative). All
  377. * urls are expanded based on the base url as given by the server.
  378. *
  379. * @param string $url
  380. *
  381. * @return string
  382. */
  383. public function getAbsoluteUrl($url)
  384. {
  385. return Uri\resolve(
  386. $this->baseUri,
  387. (string) $url
  388. );
  389. }
  390. /**
  391. * Parses a WebDAV multistatus response body.
  392. *
  393. * This method returns an array with the following structure
  394. *
  395. * [
  396. * 'url/to/resource' => [
  397. * '200' => [
  398. * '{DAV:}property1' => 'value1',
  399. * '{DAV:}property2' => 'value2',
  400. * ],
  401. * '404' => [
  402. * '{DAV:}property1' => null,
  403. * '{DAV:}property2' => null,
  404. * ],
  405. * ],
  406. * 'url/to/resource2' => [
  407. * .. etc ..
  408. * ]
  409. * ]
  410. *
  411. * @param string $body xml body
  412. *
  413. * @return array
  414. */
  415. public function parseMultiStatus($body)
  416. {
  417. $multistatus = $this->xml->expect('{DAV:}multistatus', $body);
  418. $result = [];
  419. foreach ($multistatus->getResponses() as $response) {
  420. $result[$response->getHref()] = $response->getResponseProperties();
  421. }
  422. return $result;
  423. }
  424. }