PageRenderTime 54ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/webdavlib.php

https://github.com/thepurpleblob/gumoodle
PHP | 1712 lines | 914 code | 157 blank | 641 comment | 185 complexity | 56c0e9ec028d68953abe7be8f0e4d294 MD5 | raw file
Possible License(s): Apache-2.0, GPL-3.0, BSD-3-Clause, LGPL-2.1, AGPL-3.0, MPL-2.0-no-copyleft-exception, LGPL-3.0

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. // This file is part of Moodle - http://moodle.org/
  3. //
  4. // Moodle is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // Moodle is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
  16. /**
  17. * webdav_client v0.1.5, a php based webdav client class.
  18. * class webdav client. a php based nearly RFC 2518 conforming client.
  19. *
  20. * This class implements methods to get access to an webdav server.
  21. * Most of the methods are returning boolean false on error, an integer status (http response status) on success
  22. * or an array in case of a multistatus response (207) from the webdav server. Look at the code which keys are used in arrays.
  23. * It's your responsibility to handle the webdav server responses in an proper manner.
  24. * Please notice that all Filenames coming from or going to the webdav server should be UTF-8 encoded (see RFC 2518).
  25. * This class tries to convert all you filenames into utf-8 when it's needed.
  26. *
  27. * @package moodlecore
  28. * @author Christian Juerges <christian.juerges@xwave.ch>, Xwave GmbH, Josefstr. 92, 8005 Zuerich - Switzerland
  29. * @copyright (C) 2003/2004, Christian Juerges
  30. * @license http://opensource.org/licenses/lgpl-license.php GNU Lesser General Public License
  31. * @version 0.1.5
  32. */
  33. class webdav_client {
  34. /**#@+
  35. * @access private
  36. * @var string
  37. */
  38. private $_debug = false;
  39. private $sock;
  40. private $_server;
  41. private $_protocol = 'HTTP/1.1';
  42. private $_port = 80;
  43. private $_socket = '';
  44. private $_path ='/';
  45. private $_auth = false;
  46. private $_user;
  47. private $_pass;
  48. private $_socket_timeout = 5;
  49. private $_errno;
  50. private $_errstr;
  51. private $_user_agent = 'Moodle WebDav Client';
  52. private $_crlf = "\r\n";
  53. private $_req;
  54. private $_resp_status;
  55. private $_parser;
  56. private $_parserid;
  57. private $_xmltree;
  58. private $_tree;
  59. private $_ls = array();
  60. private $_ls_ref;
  61. private $_ls_ref_cdata;
  62. private $_delete = array();
  63. private $_delete_ref;
  64. private $_delete_ref_cdata;
  65. private $_lock = array();
  66. private $_lock_ref;
  67. private $_lock_rec_cdata;
  68. private $_null = NULL;
  69. private $_header='';
  70. private $_body='';
  71. private $_connection_closed = false;
  72. private $_maxheaderlenth = 1000;
  73. private $_digestchallenge = null;
  74. private $_cnonce = '';
  75. private $_nc = 0;
  76. /**#@-*/
  77. /**
  78. * Constructor - Initialise class variables
  79. */
  80. function __construct($server = '', $user = '', $pass = '', $auth = false, $socket = '') {
  81. if (!empty($server)) {
  82. $this->_server = $server;
  83. }
  84. if (!empty($user) && !empty($pass)) {
  85. $this->user = $user;
  86. $this->pass = $pass;
  87. }
  88. $this->_auth = $auth;
  89. $this->_socket = $socket;
  90. }
  91. public function __set($key, $value) {
  92. $property = '_' . $key;
  93. $this->$property = $value;
  94. }
  95. /**
  96. * Set which HTTP protocol will be used.
  97. * Value 1 defines that HTTP/1.1 should be used (Keeps Connection to webdav server alive).
  98. * Otherwise HTTP/1.0 will be used.
  99. * @param int version
  100. */
  101. function set_protocol($version) {
  102. if ($version == 1) {
  103. $this->_protocol = 'HTTP/1.1';
  104. } else {
  105. $this->_protocol = 'HTTP/1.0';
  106. }
  107. }
  108. /**
  109. * Convert ISO 8601 Date and Time Profile used in RFC 2518 to an unix timestamp.
  110. * @access private
  111. * @param string iso8601
  112. * @return unixtimestamp on sucess. Otherwise false.
  113. */
  114. function iso8601totime($iso8601) {
  115. /*
  116. date-time = full-date "T" full-time
  117. full-date = date-fullyear "-" date-month "-" date-mday
  118. full-time = partial-time time-offset
  119. date-fullyear = 4DIGIT
  120. date-month = 2DIGIT ; 01-12
  121. date-mday = 2DIGIT ; 01-28, 01-29, 01-30, 01-31 based on
  122. month/year
  123. time-hour = 2DIGIT ; 00-23
  124. time-minute = 2DIGIT ; 00-59
  125. time-second = 2DIGIT ; 00-59, 00-60 based on leap second rules
  126. time-secfrac = "." 1*DIGIT
  127. time-numoffset = ("+" / "-") time-hour ":" time-minute
  128. time-offset = "Z" / time-numoffset
  129. partial-time = time-hour ":" time-minute ":" time-second
  130. [time-secfrac]
  131. */
  132. $regs = array();
  133. /* [1] [2] [3] [4] [5] [6] */
  134. if (preg_match('/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})Z$/', $iso8601, $regs)) {
  135. return mktime($regs[4],$regs[5], $regs[6], $regs[2], $regs[3], $regs[1]);
  136. }
  137. // to be done: regex for partial-time...apache webdav mod never returns partial-time
  138. return false;
  139. }
  140. /**
  141. * Open's a socket to a webdav server
  142. * @return bool true on success. Otherwise false.
  143. */
  144. function open() {
  145. // let's try to open a socket
  146. $this->_error_log('open a socket connection');
  147. $this->sock = fsockopen($this->_socket . $this->_server, $this->_port, $this->_errno, $this->_errstr, $this->_socket_timeout);
  148. set_time_limit(30);
  149. if (is_resource($this->sock)) {
  150. socket_set_blocking($this->sock, true);
  151. $this->_connection_closed = false;
  152. $this->_error_log('socket is open: ' . $this->sock);
  153. return true;
  154. } else {
  155. $this->_error_log("$this->_errstr ($this->_errno)\n");
  156. return false;
  157. }
  158. }
  159. /**
  160. * Closes an open socket.
  161. */
  162. function close() {
  163. $this->_error_log('closing socket ' . $this->sock);
  164. $this->_connection_closed = true;
  165. fclose($this->sock);
  166. }
  167. /**
  168. * Check's if server is a webdav compliant server.
  169. * True if server returns a DAV Element in Header and when
  170. * schema 1,2 is supported.
  171. * @return bool true if server is webdav server. Otherwise false.
  172. */
  173. function check_webdav() {
  174. $resp = $this->options();
  175. if (!$resp) {
  176. return false;
  177. }
  178. $this->_error_log($resp['header']['DAV']);
  179. // check schema
  180. if (preg_match('/1,2/', $resp['header']['DAV'])) {
  181. return true;
  182. }
  183. // otherwise return false
  184. return false;
  185. }
  186. /**
  187. * Get options from webdav server.
  188. * @return array with all header fields returned from webdav server. false if server does not speak http.
  189. */
  190. function options() {
  191. $this->header_unset();
  192. $this->create_basic_request('OPTIONS');
  193. $this->send_request();
  194. $this->get_respond();
  195. $response = $this->process_respond();
  196. // validate the response ...
  197. // check http-version
  198. if ($response['status']['http-version'] == 'HTTP/1.1' ||
  199. $response['status']['http-version'] == 'HTTP/1.0') {
  200. return $response;
  201. }
  202. $this->_error_log('Response was not even http');
  203. return false;
  204. }
  205. /**
  206. * Public method mkcol
  207. *
  208. * Creates a new collection/directory on a webdav server
  209. * @param string path
  210. * @return int status code received as reponse from webdav server (see rfc 2518)
  211. */
  212. function mkcol($path) {
  213. $this->_path = $this->translate_uri($path);
  214. $this->header_unset();
  215. $this->create_basic_request('MKCOL');
  216. $this->send_request();
  217. $this->get_respond();
  218. $response = $this->process_respond();
  219. // validate the response ...
  220. // check http-version
  221. $http_version = $response['status']['http-version'];
  222. if ($http_version == 'HTTP/1.1' || $http_version == 'HTTP/1.0') {
  223. /** seems to be http ... proceed
  224. * just return what server gave us
  225. * rfc 2518 says:
  226. * 201 (Created) - The collection or structured resource was created in its entirety.
  227. * 403 (Forbidden) - This indicates at least one of two conditions:
  228. * 1) the server does not allow the creation of collections at the given location in its namespace, or
  229. * 2) the parent collection of the Request-URI exists but cannot accept members.
  230. * 405 (Method Not Allowed) - MKCOL can only be executed on a deleted/non-existent resource.
  231. * 409 (Conflict) - A collection cannot be made at the Request-URI until one or more intermediate
  232. * collections have been created.
  233. * 415 (Unsupported Media Type)- The server does not support the request type of the body.
  234. * 507 (Insufficient Storage) - The resource does not have sufficient space to record the state of the
  235. * resource after the execution of this method.
  236. */
  237. return $response['status']['status-code'];
  238. }
  239. }
  240. /**
  241. * Public method get
  242. *
  243. * Gets a file from a webdav collection.
  244. * @param string path, string &buffer
  245. * @return status code and &$buffer (by reference) with response data from server on success. False on error.
  246. */
  247. function get($path, &$buffer) {
  248. $this->_path = $this->translate_uri($path);
  249. $this->header_unset();
  250. $this->create_basic_request('GET');
  251. $this->send_request();
  252. $this->get_respond();
  253. $response = $this->process_respond();
  254. $http_version = $response['status']['http-version'];
  255. // validate the response
  256. // check http-version
  257. if ($http_version == 'HTTP/1.1' || $http_version == 'HTTP/1.0') {
  258. // seems to be http ... proceed
  259. // We expect a 200 code
  260. if ($response['status']['status-code'] == 200 ) {
  261. $this->_error_log('returning buffer with ' . strlen($response['body']) . ' bytes.');
  262. $buffer = $response['body'];
  263. }
  264. return $response['status']['status-code'];
  265. }
  266. // ups: no http status was returned ?
  267. return false;
  268. }
  269. /**
  270. * Public method put
  271. *
  272. * Puts a file into a collection.
  273. * Data is putted as one chunk!
  274. * @param string path, string data
  275. * @return int status-code read from webdavserver. False on error.
  276. */
  277. function put($path, $data ) {
  278. $this->_path = $this->translate_uri($path);
  279. $this->header_unset();
  280. $this->create_basic_request('PUT');
  281. // add more needed header information ...
  282. $this->header_add('Content-length: ' . strlen($data));
  283. $this->header_add('Content-type: application/octet-stream');
  284. // send header
  285. $this->send_request();
  286. // send the rest (data)
  287. fputs($this->sock, $data);
  288. $this->get_respond();
  289. $response = $this->process_respond();
  290. // validate the response
  291. // check http-version
  292. if ($response['status']['http-version'] == 'HTTP/1.1' ||
  293. $response['status']['http-version'] == 'HTTP/1.0') {
  294. // seems to be http ... proceed
  295. // We expect a 200 or 204 status code
  296. // see rfc 2068 - 9.6 PUT...
  297. // print 'http ok<br>';
  298. return $response['status']['status-code'];
  299. }
  300. // ups: no http status was returned ?
  301. return false;
  302. }
  303. /**
  304. * Public method put_file
  305. *
  306. * Read a file as stream and puts it chunk by chunk into webdav server collection.
  307. *
  308. * Look at php documenation for legal filenames with fopen();
  309. * The filename will be translated into utf-8 if not allready in utf-8.
  310. *
  311. * @param string targetpath, string filename
  312. * @return int status code. False on error.
  313. */
  314. function put_file($path, $filename) {
  315. // try to open the file ...
  316. $handle = @fopen ($filename, 'r');
  317. if ($handle) {
  318. // $this->sock = pfsockopen ($this->_server, $this->_port, $this->_errno, $this->_errstr, $this->_socket_timeout);
  319. $this->_path = $this->translate_uri($path);
  320. $this->header_unset();
  321. $this->create_basic_request('PUT');
  322. // add more needed header information ...
  323. $this->header_add('Content-length: ' . filesize($filename));
  324. $this->header_add('Content-type: application/octet-stream');
  325. // send header
  326. $this->send_request();
  327. while (!feof($handle)) {
  328. fputs($this->sock,fgets($handle,4096));
  329. }
  330. fclose($handle);
  331. $this->get_respond();
  332. $response = $this->process_respond();
  333. // validate the response
  334. // check http-version
  335. if ($response['status']['http-version'] == 'HTTP/1.1' ||
  336. $response['status']['http-version'] == 'HTTP/1.0') {
  337. // seems to be http ... proceed
  338. // We expect a 200 or 204 status code
  339. // see rfc 2068 - 9.6 PUT...
  340. // print 'http ok<br>';
  341. return $response['status']['status-code'];
  342. }
  343. // ups: no http status was returned ?
  344. return false;
  345. } else {
  346. $this->_error_log('put_file: could not open ' . $filename);
  347. return false;
  348. }
  349. }
  350. /**
  351. * Public method get_file
  352. *
  353. * Gets a file from a collection into local filesystem.
  354. *
  355. * fopen() is used.
  356. * @param string srcpath, string localpath
  357. * @return true on success. false on error.
  358. */
  359. function get_file($srcpath, $localpath) {
  360. if ($this->get($srcpath, $buffer)) {
  361. // convert utf-8 filename to iso-8859-1
  362. $localpath = $this->utf_decode_path($localpath);
  363. $handle = fopen ($localpath, 'w');
  364. if ($handle) {
  365. fwrite($handle, $buffer);
  366. fclose($handle);
  367. return true;
  368. } else {
  369. return false;
  370. }
  371. } else {
  372. return false;
  373. }
  374. }
  375. /**
  376. * Public method copy_file
  377. *
  378. * Copies a file on a webdav server
  379. *
  380. * Duplicates a file on the webdav server (serverside).
  381. * All work is done on the webdav server. If you set param overwrite as true,
  382. * the target will be overwritten.
  383. *
  384. * @param string src_path, string dest_path, bool overwrite
  385. * @return int status code (look at rfc 2518). false on error.
  386. */
  387. function copy_file($src_path, $dst_path, $overwrite) {
  388. $this->_path = $this->translate_uri($src_path);
  389. $this->header_unset();
  390. $this->create_basic_request('COPY');
  391. $this->header_add(sprintf('Destination: http://%s%s', $this->_server, $this->translate_uri($dst_path)));
  392. if ($overwrite) {
  393. $this->header_add('Overwrite: T');
  394. } else {
  395. $this->header_add('Overwrite: F');
  396. }
  397. $this->header_add('');
  398. $this->send_request();
  399. $this->get_respond();
  400. $response = $this->process_respond();
  401. // validate the response ...
  402. // check http-version
  403. if ($response['status']['http-version'] == 'HTTP/1.1' ||
  404. $response['status']['http-version'] == 'HTTP/1.0') {
  405. /* seems to be http ... proceed
  406. just return what server gave us (as defined in rfc 2518) :
  407. 201 (Created) - The source resource was successfully copied. The copy operation resulted in the creation of a new resource.
  408. 204 (No Content) - The source resource was successfully copied to a pre-existing destination resource.
  409. 403 (Forbidden) - The source and destination URIs are the same.
  410. 409 (Conflict) - A resource cannot be created at the destination until one or more intermediate collections have been created.
  411. 412 (Precondition Failed) - The server was unable to maintain the liveness of the properties listed in the propertybehavior XML element
  412. or the Overwrite header is "F" and the state of the destination resource is non-null.
  413. 423 (Locked) - The destination resource was locked.
  414. 502 (Bad Gateway) - This may occur when the destination is on another server and the destination server refuses to accept the resource.
  415. 507 (Insufficient Storage) - The destination resource does not have sufficient space to record the state of the resource after the
  416. execution of this method.
  417. */
  418. return $response['status']['status-code'];
  419. }
  420. return false;
  421. }
  422. /**
  423. * Public method copy_coll
  424. *
  425. * Copies a collection on a webdav server
  426. *
  427. * Duplicates a collection on the webdav server (serverside).
  428. * All work is done on the webdav server. If you set param overwrite as true,
  429. * the target will be overwritten.
  430. *
  431. * @param string src_path, string dest_path, bool overwrite
  432. * @return int status code (look at rfc 2518). false on error.
  433. */
  434. function copy_coll($src_path, $dst_path, $overwrite) {
  435. $this->_path = $this->translate_uri($src_path);
  436. $this->header_unset();
  437. $this->create_basic_request('COPY');
  438. $this->header_add(sprintf('Destination: http://%s%s', $this->_server, $this->translate_uri($dst_path)));
  439. $this->header_add('Depth: Infinity');
  440. $xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n";
  441. $xml .= "<d:propertybehavior xmlns:d=\"DAV:\">\r\n";
  442. $xml .= " <d:keepalive>*</d:keepalive>\r\n";
  443. $xml .= "</d:propertybehavior>\r\n";
  444. $this->header_add('Content-length: ' . strlen($xml));
  445. $this->header_add('Content-type: application/xml');
  446. $this->send_request();
  447. // send also xml
  448. fputs($this->sock, $xml);
  449. $this->get_respond();
  450. $response = $this->process_respond();
  451. // validate the response ...
  452. // check http-version
  453. if ($response['status']['http-version'] == 'HTTP/1.1' ||
  454. $response['status']['http-version'] == 'HTTP/1.0') {
  455. /* seems to be http ... proceed
  456. just return what server gave us (as defined in rfc 2518) :
  457. 201 (Created) - The source resource was successfully copied. The copy operation resulted in the creation of a new resource.
  458. 204 (No Content) - The source resource was successfully copied to a pre-existing destination resource.
  459. 403 (Forbidden) - The source and destination URIs are the same.
  460. 409 (Conflict) - A resource cannot be created at the destination until one or more intermediate collections have been created.
  461. 412 (Precondition Failed) - The server was unable to maintain the liveness of the properties listed in the propertybehavior XML element
  462. or the Overwrite header is "F" and the state of the destination resource is non-null.
  463. 423 (Locked) - The destination resource was locked.
  464. 502 (Bad Gateway) - This may occur when the destination is on another server and the destination server refuses to accept the resource.
  465. 507 (Insufficient Storage) - The destination resource does not have sufficient space to record the state of the resource after the
  466. execution of this method.
  467. */
  468. return $response['status']['status-code'];
  469. }
  470. return false;
  471. }
  472. /**
  473. * Public method move
  474. *
  475. * Moves a file or collection on webdav server (serverside)
  476. *
  477. * If you set param overwrite as true, the target will be overwritten.
  478. *
  479. * @param string src_path, string dest_path, bool overwrite
  480. * @return int status code (look at rfc 2518). false on error.
  481. */
  482. // --------------------------------------------------------------------------
  483. // public method move
  484. // move/rename a file/collection on webdav server
  485. function move($src_path,$dst_path, $overwrite) {
  486. $this->_path = $this->translate_uri($src_path);
  487. $this->header_unset();
  488. $this->create_basic_request('MOVE');
  489. $this->header_add(sprintf('Destination: http://%s%s', $this->_server, $this->translate_uri($dst_path)));
  490. if ($overwrite) {
  491. $this->header_add('Overwrite: T');
  492. } else {
  493. $this->header_add('Overwrite: F');
  494. }
  495. $this->header_add('');
  496. $this->send_request();
  497. $this->get_respond();
  498. $response = $this->process_respond();
  499. // validate the response ...
  500. // check http-version
  501. if ($response['status']['http-version'] == 'HTTP/1.1' ||
  502. $response['status']['http-version'] == 'HTTP/1.0') {
  503. /* seems to be http ... proceed
  504. just return what server gave us (as defined in rfc 2518) :
  505. 201 (Created) - The source resource was successfully moved, and a new resource was created at the destination.
  506. 204 (No Content) - The source resource was successfully moved to a pre-existing destination resource.
  507. 403 (Forbidden) - The source and destination URIs are the same.
  508. 409 (Conflict) - A resource cannot be created at the destination until one or more intermediate collections have been created.
  509. 412 (Precondition Failed) - The server was unable to maintain the liveness of the properties listed in the propertybehavior XML element
  510. or the Overwrite header is "F" and the state of the destination resource is non-null.
  511. 423 (Locked) - The source or the destination resource was locked.
  512. 502 (Bad Gateway) - This may occur when the destination is on another server and the destination server refuses to accept the resource.
  513. 201 (Created) - The collection or structured resource was created in its entirety.
  514. 403 (Forbidden) - This indicates at least one of two conditions: 1) the server does not allow the creation of collections at the given
  515. location in its namespace, or 2) the parent collection of the Request-URI exists but cannot accept members.
  516. 405 (Method Not Allowed) - MKCOL can only be executed on a deleted/non-existent resource.
  517. 409 (Conflict) - A collection cannot be made at the Request-URI until one or more intermediate collections have been created.
  518. 415 (Unsupported Media Type)- The server does not support the request type of the body.
  519. 507 (Insufficient Storage) - The resource does not have sufficient space to record the state of the resource after the execution of this method.
  520. */
  521. return $response['status']['status-code'];
  522. }
  523. return false;
  524. }
  525. /**
  526. * Public method lock
  527. *
  528. * Locks a file or collection.
  529. *
  530. * Lock uses this->_user as lock owner.
  531. *
  532. * @param string path
  533. * @return int status code (look at rfc 2518). false on error.
  534. */
  535. function lock($path) {
  536. $this->_path = $this->translate_uri($path);
  537. $this->header_unset();
  538. $this->create_basic_request('LOCK');
  539. $this->header_add('Timeout: Infinite');
  540. $this->header_add('Content-type: text/xml');
  541. // create the xml request ...
  542. $xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n";
  543. $xml .= "<D:lockinfo xmlns:D='DAV:'\r\n>";
  544. $xml .= " <D:lockscope><D:exclusive/></D:lockscope>\r\n";
  545. $xml .= " <D:locktype><D:write/></D:locktype>\r\n";
  546. $xml .= " <D:owner>\r\n";
  547. $xml .= " <D:href>".($this->_user)."</D:href>\r\n";
  548. $xml .= " </D:owner>\r\n";
  549. $xml .= "</D:lockinfo>\r\n";
  550. $this->header_add('Content-length: ' . strlen($xml));
  551. $this->send_request();
  552. // send also xml
  553. fputs($this->sock, $xml);
  554. $this->get_respond();
  555. $response = $this->process_respond();
  556. // validate the response ... (only basic validation)
  557. // check http-version
  558. if ($response['status']['http-version'] == 'HTTP/1.1' ||
  559. $response['status']['http-version'] == 'HTTP/1.0') {
  560. /* seems to be http ... proceed
  561. rfc 2518 says:
  562. 200 (OK) - The lock request succeeded and the value of the lockdiscovery property is included in the body.
  563. 412 (Precondition Failed) - The included lock token was not enforceable on this resource or the server could not satisfy the
  564. request in the lockinfo XML element.
  565. 423 (Locked) - The resource is locked, so the method has been rejected.
  566. */
  567. switch($response['status']['status-code']) {
  568. case 200:
  569. // collection was successfully locked... see xml response to get lock token...
  570. if (strcmp($response['header']['Content-Type'], 'text/xml; charset="utf-8"') == 0) {
  571. // ok let's get the content of the xml stuff
  572. $this->_parser = xml_parser_create_ns();
  573. $this->_parserid = (int) $this->_parser;
  574. // forget old data...
  575. unset($this->_lock[$this->_parserid]);
  576. unset($this->_xmltree[$this->_parserid]);
  577. xml_parser_set_option($this->_parser,XML_OPTION_SKIP_WHITE,0);
  578. xml_parser_set_option($this->_parser,XML_OPTION_CASE_FOLDING,0);
  579. xml_set_object($this->_parser, $this);
  580. xml_set_element_handler($this->_parser, "_lock_startElement", "_endElement");
  581. xml_set_character_data_handler($this->_parser, "_lock_cdata");
  582. if (!xml_parse($this->_parser, $response['body'])) {
  583. die(sprintf("XML error: %s at line %d",
  584. xml_error_string(xml_get_error_code($this->_parser)),
  585. xml_get_current_line_number($this->_parser)));
  586. }
  587. // Free resources
  588. xml_parser_free($this->_parser);
  589. // add status code to array
  590. $this->_lock[$this->_parserid]['status'] = 200;
  591. return $this->_lock[$this->_parserid];
  592. } else {
  593. print 'Missing Content-Type: text/xml header in response.<br>';
  594. }
  595. return false;
  596. default:
  597. // hmm. not what we expected. Just return what we got from webdav server
  598. // someone else has to handle it.
  599. $this->_lock['status'] = $response['status']['status-code'];
  600. return $this->_lock;
  601. }
  602. }
  603. }
  604. /**
  605. * Public method unlock
  606. *
  607. * Unlocks a file or collection.
  608. *
  609. * @param string path, string locktoken
  610. * @return int status code (look at rfc 2518). false on error.
  611. */
  612. function unlock($path, $locktoken) {
  613. $this->_path = $this->translate_uri($path);
  614. $this->header_unset();
  615. $this->create_basic_request('UNLOCK');
  616. $this->header_add(sprintf('Lock-Token: <%s>', $locktoken));
  617. $this->send_request();
  618. $this->get_respond();
  619. $response = $this->process_respond();
  620. if ($response['status']['http-version'] == 'HTTP/1.1' ||
  621. $response['status']['http-version'] == 'HTTP/1.0') {
  622. /* seems to be http ... proceed
  623. rfc 2518 says:
  624. 204 (OK) - The 204 (No Content) status code is used instead of 200 (OK) because there is no response entity body.
  625. */
  626. return $response['status']['status-code'];
  627. }
  628. return false;
  629. }
  630. /**
  631. * Public method delete
  632. *
  633. * deletes a collection/directory on a webdav server
  634. * @param string path
  635. * @return int status code (look at rfc 2518). false on error.
  636. */
  637. function delete($path) {
  638. $this->_path = $this->translate_uri($path);
  639. $this->header_unset();
  640. $this->create_basic_request('DELETE');
  641. /* $this->header_add('Content-Length: 0'); */
  642. $this->header_add('');
  643. $this->send_request();
  644. $this->get_respond();
  645. $response = $this->process_respond();
  646. // validate the response ...
  647. // check http-version
  648. if ($response['status']['http-version'] == 'HTTP/1.1' ||
  649. $response['status']['http-version'] == 'HTTP/1.0') {
  650. // seems to be http ... proceed
  651. // We expect a 207 Multi-Status status code
  652. // print 'http ok<br>';
  653. switch ($response['status']['status-code']) {
  654. case 207:
  655. // collection was NOT deleted... see xml response for reason...
  656. // next there should be a Content-Type: text/xml; charset="utf-8" header line
  657. if (strcmp($response['header']['Content-Type'], 'text/xml; charset="utf-8"') == 0) {
  658. // ok let's get the content of the xml stuff
  659. $this->_parser = xml_parser_create_ns();
  660. $this->_parserid = (int) $this->_parser;
  661. // forget old data...
  662. unset($this->_delete[$this->_parserid]);
  663. unset($this->_xmltree[$this->_parserid]);
  664. xml_parser_set_option($this->_parser,XML_OPTION_SKIP_WHITE,0);
  665. xml_parser_set_option($this->_parser,XML_OPTION_CASE_FOLDING,0);
  666. xml_set_object($this->_parser, $this);
  667. xml_set_element_handler($this->_parser, "_delete_startElement", "_endElement");
  668. xml_set_character_data_handler($this->_parser, "_delete_cdata");
  669. if (!xml_parse($this->_parser, $response['body'])) {
  670. die(sprintf("XML error: %s at line %d",
  671. xml_error_string(xml_get_error_code($this->_parser)),
  672. xml_get_current_line_number($this->_parser)));
  673. }
  674. print "<br>";
  675. // Free resources
  676. xml_parser_free($this->_parser);
  677. $this->_delete[$this->_parserid]['status'] = $response['status']['status-code'];
  678. return $this->_delete[$this->_parserid];
  679. } else {
  680. print 'Missing Content-Type: text/xml header in response.<br>';
  681. }
  682. return false;
  683. default:
  684. // collection or file was successfully deleted
  685. $this->_delete['status'] = $response['status']['status-code'];
  686. return $this->_delete;
  687. }
  688. }
  689. }
  690. /**
  691. * Public method ls
  692. *
  693. * Get's directory information from webdav server into flat a array using PROPFIND
  694. *
  695. * All filenames are UTF-8 encoded.
  696. * Have a look at _propfind_startElement what keys are used in array returned.
  697. * @param string path
  698. * @return array dirinfo, false on error
  699. */
  700. function ls($path) {
  701. if (trim($path) == '') {
  702. $this->_error_log('Missing a path in method ls');
  703. return false;
  704. }
  705. $this->_path = $this->translate_uri($path);
  706. $this->header_unset();
  707. $this->create_basic_request('PROPFIND');
  708. $this->header_add('Depth: 1');
  709. $this->header_add('Content-type: application/xml');
  710. // create profind xml request...
  711. $xml = <<<EOD
  712. <?xml version="1.0" encoding="utf-8"?>
  713. <propfind xmlns="DAV:"><prop>
  714. <getcontentlength xmlns="DAV:"/>
  715. <getlastmodified xmlns="DAV:"/>
  716. <executable xmlns="http://apache.org/dav/props/"/>
  717. <resourcetype xmlns="DAV:"/>
  718. <checked-in xmlns="DAV:"/>
  719. <checked-out xmlns="DAV:"/>
  720. </prop></propfind>
  721. EOD;
  722. $this->header_add('Content-length: ' . strlen($xml));
  723. $this->send_request();
  724. $this->_error_log($xml);
  725. fputs($this->sock, $xml);
  726. $this->get_respond();
  727. $response = $this->process_respond();
  728. // validate the response ... (only basic validation)
  729. // check http-version
  730. if ($response['status']['http-version'] == 'HTTP/1.1' ||
  731. $response['status']['http-version'] == 'HTTP/1.0') {
  732. // seems to be http ... proceed
  733. // We expect a 207 Multi-Status status code
  734. // print 'http ok<br>';
  735. if (strcmp($response['status']['status-code'],'207') == 0 ) {
  736. // ok so far
  737. // next there should be a Content-Type: text/xml; charset="utf-8" header line
  738. if (preg_match('#(application|text)/xml;\s?charset=[\'\"]?utf-8[\'\"]?#i', $response['header']['Content-Type'])) {
  739. // ok let's get the content of the xml stuff
  740. $this->_parser = xml_parser_create_ns('UTF-8');
  741. $this->_parserid = (int) $this->_parser;
  742. // forget old data...
  743. unset($this->_ls[$this->_parserid]);
  744. unset($this->_xmltree[$this->_parserid]);
  745. xml_parser_set_option($this->_parser,XML_OPTION_SKIP_WHITE,0);
  746. xml_parser_set_option($this->_parser,XML_OPTION_CASE_FOLDING,0);
  747. // xml_parser_set_option($this->_parser,XML_OPTION_TARGET_ENCODING,'UTF-8');
  748. xml_set_object($this->_parser, $this);
  749. xml_set_element_handler($this->_parser, "_propfind_startElement", "_endElement");
  750. xml_set_character_data_handler($this->_parser, "_propfind_cdata");
  751. if (!xml_parse($this->_parser, $response['body'])) {
  752. die(sprintf("XML error: %s at line %d",
  753. xml_error_string(xml_get_error_code($this->_parser)),
  754. xml_get_current_line_number($this->_parser)));
  755. }
  756. // Free resources
  757. xml_parser_free($this->_parser);
  758. $arr = $this->_ls[$this->_parserid];
  759. return $arr;
  760. } else {
  761. $this->_error_log('Missing Content-Type: text/xml header in response!!');
  762. return false;
  763. }
  764. } else {
  765. // return status code ...
  766. return $response['status']['status-code'];
  767. }
  768. }
  769. // response was not http
  770. $this->_error_log('Ups in method ls: error in response from server');
  771. return false;
  772. }
  773. /**
  774. * Public method gpi
  775. *
  776. * Get's path information from webdav server for one element.
  777. *
  778. * @param string path
  779. * @return array dirinfo. false on error
  780. */
  781. function gpi($path) {
  782. // split path by last "/"
  783. $path = rtrim($path, "/");
  784. $item = basename($path);
  785. $dir = dirname($path);
  786. $list = $this->ls($dir);
  787. // be sure it is an array
  788. if (is_array($list)) {
  789. foreach($list as $e) {
  790. $fullpath = urldecode($e['href']);
  791. $filename = basename($fullpath);
  792. if ($filename == $item && $filename != "" and $fullpath != $dir."/") {
  793. return $e;
  794. }
  795. }
  796. }
  797. return false;
  798. }
  799. /**
  800. * Public method is_file
  801. *
  802. * Gathers whether a path points to a file or not.
  803. *
  804. * @param string path
  805. * @return bool true or false
  806. */
  807. function is_file($path) {
  808. $item = $this->gpi($path);
  809. if ($item === false) {
  810. return false;
  811. } else {
  812. return ($item['resourcetype'] != 'collection');
  813. }
  814. }
  815. /**
  816. * Public method is_dir
  817. *
  818. * Gather whether a path points to a directory
  819. * @param string path
  820. * return bool true or false
  821. */
  822. function is_dir($path) {
  823. // be sure path is utf-8
  824. $item = $this->gpi($path);
  825. if ($item === false) {
  826. return false;
  827. } else {
  828. return ($item['resourcetype'] == 'collection');
  829. }
  830. }
  831. /**
  832. * Public method mput
  833. *
  834. * Puts multiple files and/or directories onto a webdav server.
  835. *
  836. * Filenames should be allready UTF-8 encoded.
  837. * Param fileList must be in format array("localpath" => "destpath").
  838. *
  839. * @param array filelist
  840. * @return bool true on success. otherwise int status code on error
  841. */
  842. function mput($filelist) {
  843. $result = true;
  844. while (list($localpath, $destpath) = each($filelist)) {
  845. $localpath = rtrim($localpath, "/");
  846. $destpath = rtrim($destpath, "/");
  847. // attempt to create target path
  848. if (is_dir($localpath)) {
  849. $pathparts = explode("/", $destpath."/ "); // add one level, last level will be created as dir
  850. } else {
  851. $pathparts = explode("/", $destpath);
  852. }
  853. $checkpath = "";
  854. for ($i=1; $i<sizeof($pathparts)-1; $i++) {
  855. $checkpath .= "/" . $pathparts[$i];
  856. if (!($this->is_dir($checkpath))) {
  857. $result &= ($this->mkcol($checkpath) == 201 );
  858. }
  859. }
  860. if ($result) {
  861. // recurse directories
  862. if (is_dir($localpath)) {
  863. if (!$dp = opendir($localpath)) {
  864. $this->_error_log("Could not open localpath for reading");
  865. return false;
  866. }
  867. $fl = array();
  868. while($filename = readdir($dp)) {
  869. if ((is_file($localpath."/".$filename) || is_dir($localpath."/".$filename)) && $filename!="." && $filename != "..") {
  870. $fl[$localpath."/".$filename] = $destpath."/".$filename;
  871. }
  872. }
  873. $result &= $this->mput($fl);
  874. } else {
  875. $result &= ($this->put_file($destpath, $localpath) == 201);
  876. }
  877. }
  878. }
  879. return $result;
  880. }
  881. /**
  882. * Public method mget
  883. *
  884. * Gets multiple files and directories.
  885. *
  886. * FileList must be in format array("remotepath" => "localpath").
  887. * Filenames are UTF-8 encoded.
  888. *
  889. * @param array filelist
  890. * @return bool true on succes, other int status code on error
  891. */
  892. function mget($filelist) {
  893. $result = true;
  894. while (list($remotepath, $localpath) = each($filelist)) {
  895. $localpath = rtrim($localpath, "/");
  896. $remotepath = rtrim($remotepath, "/");
  897. // attempt to create local path
  898. if ($this->is_dir($remotepath)) {
  899. $pathparts = explode("/", $localpath."/ "); // add one level, last level will be created as dir
  900. } else {
  901. $pathparts = explode("/", $localpath);
  902. }
  903. $checkpath = "";
  904. for ($i=1; $i<sizeof($pathparts)-1; $i++) {
  905. $checkpath .= "/" . $pathparts[$i];
  906. if (!is_dir($checkpath)) {
  907. $result &= mkdir($checkpath);
  908. }
  909. }
  910. if ($result) {
  911. // recurse directories
  912. if ($this->is_dir($remotepath)) {
  913. $list = $this->ls($remotepath);
  914. $fl = array();
  915. foreach($list as $e) {
  916. $fullpath = urldecode($e['href']);
  917. $filename = basename($fullpath);
  918. if ($filename != '' and $fullpath != $remotepath . '/') {
  919. $fl[$remotepath."/".$filename] = $localpath."/".$filename;
  920. }
  921. }
  922. $result &= $this->mget($fl);
  923. } else {
  924. $result &= ($this->get_file($remotepath, $localpath));
  925. }
  926. }
  927. }
  928. return $result;
  929. }
  930. // --------------------------------------------------------------------------
  931. // private xml callback and helper functions starting here
  932. // --------------------------------------------------------------------------
  933. /**
  934. * Private method _endelement
  935. *
  936. * a generic endElement method (used for all xml callbacks).
  937. *
  938. * @param resource parser, string name
  939. * @access private
  940. */
  941. private function _endElement($parser, $name) {
  942. // end tag was found...
  943. $parserid = (int) $parser;
  944. $this->_xmltree[$parserid] = substr($this->_xmltree[$parserid],0, strlen($this->_xmltree[$parserid]) - (strlen($name) + 1));
  945. }
  946. /**
  947. * Private method _propfind_startElement
  948. *
  949. * Is needed by public method ls.
  950. *
  951. * Generic method will called by php xml_parse when a xml start element tag has been detected.
  952. * The xml tree will translated into a flat php array for easier access.
  953. * @param resource parser, string name, string attrs
  954. * @access private
  955. */
  956. private function _propfind_startElement($parser, $name, $attrs) {
  957. // lower XML Names... maybe break a RFC, don't know ...
  958. $parserid = (int) $parser;
  959. $propname = strtolower($name);
  960. if (!empty($this->_xmltree[$parserid])) {
  961. $this->_xmltree[$parserid] .= $propname . '_';
  962. } else {
  963. $this->_xmltree[$parserid] = $propname . '_';
  964. }
  965. // translate xml tree to a flat array ...
  966. switch($this->_xmltree[$parserid]) {
  967. case 'dav::multistatus_dav::response_':
  968. // new element in mu
  969. $this->_ls_ref =& $this->_ls[$parserid][];
  970. break;
  971. case 'dav::multistatus_dav::response_dav::href_':
  972. $this->_ls_ref_cdata = &$this->_ls_ref['href'];
  973. break;
  974. case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::creationdate_':
  975. $this->_ls_ref_cdata = &$this->_ls_ref['creationdate'];
  976. break;
  977. case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::getlastmodified_':
  978. $this->_ls_ref_cdata = &$this->_ls_ref['lastmodified'];
  979. break;
  980. case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::getcontenttype_':
  981. $this->_ls_ref_cdata = &$this->_ls_ref['getcontenttype'];
  982. break;
  983. case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::getcontentlength_':
  984. $this->_ls_ref_cdata = &$this->_ls_ref['getcontentlength'];
  985. break;
  986. case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::lockdiscovery_dav::activelock_dav::depth_':
  987. $this->_ls_ref_cdata = &$this->_ls_ref['activelock_depth'];
  988. break;
  989. case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::lockdiscovery_dav::activelock_dav::owner_dav::href_':
  990. $this->_ls_ref_cdata = &$this->_ls_ref['activelock_owner'];
  991. break;
  992. case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::lockdiscovery_dav::activelock_dav::owner_':
  993. $this->_ls_ref_cdata = &$this->_ls_ref['activelock_owner'];
  994. break;
  995. case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::lockdiscovery_dav::activelock_dav::timeout_':
  996. $this->_ls_ref_cdata = &$this->_ls_ref['activelock_timeout'];
  997. break;
  998. case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::lockdiscovery_dav::activelock_dav::locktoken_dav::href_':
  999. $this->_ls_ref_cdata = &$this->_ls_ref['activelock_token'];
  1000. break;
  1001. case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::lockdiscovery_dav::activelock_dav::locktype_dav::write_':
  1002. $this->_ls_ref_cdata = &$this->_ls_ref['activelock_type'];
  1003. $this->_ls_ref_cdata = 'write';
  1004. $this->_ls_ref_cdata = &$this->_null;
  1005. break;
  1006. case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::resourcetype_dav::collection_':
  1007. $this->_ls_ref_cdata = &$this->_ls_ref['resourcetype'];
  1008. $this->_ls_ref_cdata = 'collection';
  1009. $this->_ls_ref_cdata = &$this->_null;
  1010. break;
  1011. case 'dav::multistatus_dav::response_dav::propstat_dav::status_':
  1012. $this->_ls_ref_cdata = &$this->_ls_ref['status'];
  1013. break;
  1014. default:
  1015. // handle unknown xml elements...
  1016. $this->_ls_ref_cdata = &$this->_ls_ref[$this->_xmltree[$parserid]];
  1017. }
  1018. }
  1019. /**
  1020. * Private method _propfind_cData
  1021. *
  1022. * Is needed by public method ls.
  1023. *
  1024. * Will be called by php xml_set_character_data_handler() when xml data has to be handled.
  1025. * Stores data found into class var _ls_ref_cdata
  1026. * @param resource parser, string cdata
  1027. * @access private
  1028. */
  1029. private function _propfind_cData($parser, $cdata) {
  1030. if (trim($cdata) <> '') {
  1031. // cdata must be appended, because sometimes the php xml parser makes multiple calls
  1032. // to _propfind_cData before the xml end tag was reached...
  1033. $this->_ls_ref_cdata .= $cdata;
  1034. } else {
  1035. // do nothing
  1036. }
  1037. }
  1038. /**
  1039. * Private method _delete_startElement
  1040. *
  1041. * Is used by public method delete.
  1042. *
  1043. * Will be called by php xml_parse.
  1044. * @param resource parser, string name, string attrs)
  1045. * @access private
  1046. */
  1047. private function _delete_startElement($parser, $name, $attrs) {
  1048. // lower XML Names... maybe break a RFC, don't know ...
  1049. $parserid = (int) $parser;
  1050. $propname = strtolower($name);
  1051. $this->_xmltree[$parserid] .= $propname . '_';
  1052. // translate xml tree to a flat array ...
  1053. switch($this->_xmltree[$parserid]) {
  1054. case 'dav::multistatus_dav::response_':
  1055. // new element in mu
  1056. $this->_delete_ref =& $this->_delete[$parserid][];
  1057. break;
  1058. case 'dav::multistatus_dav::response_dav::href_':
  1059. $this->_delete_ref_cdata = &$this->_ls_ref['href'];
  1060. break;
  1061. default:
  1062. // handle unknown xml elements...
  1063. $this->_delete_cdata = &$this->_delete_ref[$this->_xmltree[$parserid]];
  1064. }
  1065. }
  1066. /**
  1067. * Private method _delete_cData
  1068. *
  1069. * Is used by public method delete.
  1070. *
  1071. * Will be called by php xml_set_character_data_handler() when xml data has to be handled.
  1072. * Stores data found into class var _delete_ref_cdata
  1073. * @param resource parser, string cdata
  1074. * @access private
  1075. */
  1076. private function _delete_cData($parser, $cdata) {
  1077. if (trim($cdata) <> '') {
  1078. $this->_delete_ref_cdata .= $cdata;
  1079. } else {
  1080. // do nothing
  1081. }
  1082. }
  1083. /**
  1084. * Private method _lock_startElement
  1085. *
  1086. * Is needed by public method lock.
  1087. *
  1088. * Mmethod will called by php xml_parse when a xml start element tag has been detected.
  1089. * The xml tree will translated into a flat php array for easier access.
  1090. * @param resource parser, string name, string attrs
  1091. * @access private
  1092. */
  1093. private function _lock_startElement($parser, $name, $attrs) {
  1094. // lower XML Names... maybe break a RFC, don't know ...
  1095. $parserid = (int) $parser;
  1096. $propname = strtolower($name);
  1097. $this->_xmltree[$parserid] .= $propname . '_';
  1098. // translate xml tree to a flat array ...
  1099. /*
  1100. dav::prop_dav::lockdiscovery_dav::activelock_dav::depth_=
  1101. dav::prop_dav::lockdiscovery_dav::activelock_dav::owner_dav::href_=
  1102. dav::prop_dav::lockdiscovery_dav::activelock_dav::timeout_=
  1103. dav::prop_dav::lockdiscovery_dav::activelock_dav::locktoken_dav::href_=
  1104. */
  1105. switch($this->_xmltree[$parserid]) {
  1106. case 'dav::prop_dav::lockdiscovery_dav::activelock_':
  1107. // new element
  1108. $this->_lock_ref =& $this->_lock[$parserid][];
  1109. break;
  1110. case 'dav::prop_dav::lockdiscovery_dav::activelock_dav::locktype_dav::write_':
  1111. $this->_lock_ref_cdata = &$this->_lock_ref['locktype'];
  1112. $this->_lock_cdata = 'write';
  1113. $this->_lock_cdata = &$this->_null;
  1114. break;
  1115. case 'dav::prop_dav::lockdiscovery_dav::activelock_dav::lockscope_dav::exclusive_':
  1116. $this->_lock_ref_cdata = &$this->_lock_ref['lockscope'];
  1117. $this->_lock_ref_cdata = 'exclusive';
  1118. $this->_lock_ref_cdata = &$this->_null;
  1119. break;
  1120. case 'dav::prop_dav::lockdiscovery_dav::activelock_dav::depth_':
  1121. $this->_lock_ref_cdata = &$this->_lock_ref['depth'];
  1122. break;

Large files files are truncated, but you can click here to view the full file