PageRenderTime 59ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/webdavlib.php

https://bitbucket.org/synergylearning/campusconnect
PHP | 1734 lines | 928 code | 156 blank | 650 comment | 186 complexity | 75d8311bea9cd2b9db795a48bc71ad47 MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, LGPL-3.0, GPL-3.0, LGPL-2.1, Apache-2.0, BSD-3-Clause, AGPL-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 response 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 the path to the file on the webdav server
  245. * @param string &$buffer the buffer to store the data in
  246. * @param resource $fp optional if included, the data is written directly to this resource and not to the buffer
  247. * @return string|bool status code and &$buffer (by reference) with response data from server on success. False on error.
  248. */
  249. function get($path, &$buffer, $fp = null) {
  250. $this->_path = $this->translate_uri($path);
  251. $this->header_unset();
  252. $this->create_basic_request('GET');
  253. $this->send_request();
  254. $this->get_respond($fp);
  255. $response = $this->process_respond();
  256. $http_version = $response['status']['http-version'];
  257. // validate the response
  258. // check http-version
  259. if ($http_version == 'HTTP/1.1' || $http_version == 'HTTP/1.0') {
  260. // seems to be http ... proceed
  261. // We expect a 200 code
  262. if ($response['status']['status-code'] == 200 ) {
  263. if (!is_null($fp)) {
  264. $stat = fstat($fp);
  265. $this->_error_log('file created with ' . $stat['size'] . ' bytes.');
  266. } else {
  267. $this->_error_log('returning buffer with ' . strlen($response['body']) . ' bytes.');
  268. $buffer = $response['body'];
  269. }
  270. }
  271. return $response['status']['status-code'];
  272. }
  273. // ups: no http status was returned ?
  274. return false;
  275. }
  276. /**
  277. * Public method put
  278. *
  279. * Puts a file into a collection.
  280. * Data is putted as one chunk!
  281. * @param string path, string data
  282. * @return int status-code read from webdavserver. False on error.
  283. */
  284. function put($path, $data ) {
  285. $this->_path = $this->translate_uri($path);
  286. $this->header_unset();
  287. $this->create_basic_request('PUT');
  288. // add more needed header information ...
  289. $this->header_add('Content-length: ' . strlen($data));
  290. $this->header_add('Content-type: application/octet-stream');
  291. // send header
  292. $this->send_request();
  293. // send the rest (data)
  294. fputs($this->sock, $data);
  295. $this->get_respond();
  296. $response = $this->process_respond();
  297. // validate the response
  298. // check http-version
  299. if ($response['status']['http-version'] == 'HTTP/1.1' ||
  300. $response['status']['http-version'] == 'HTTP/1.0') {
  301. // seems to be http ... proceed
  302. // We expect a 200 or 204 status code
  303. // see rfc 2068 - 9.6 PUT...
  304. // print 'http ok<br>';
  305. return $response['status']['status-code'];
  306. }
  307. // ups: no http status was returned ?
  308. return false;
  309. }
  310. /**
  311. * Public method put_file
  312. *
  313. * Read a file as stream and puts it chunk by chunk into webdav server collection.
  314. *
  315. * Look at php documenation for legal filenames with fopen();
  316. * The filename will be translated into utf-8 if not allready in utf-8.
  317. *
  318. * @param string targetpath, string filename
  319. * @return int status code. False on error.
  320. */
  321. function put_file($path, $filename) {
  322. // try to open the file ...
  323. $handle = @fopen ($filename, 'r');
  324. if ($handle) {
  325. // $this->sock = pfsockopen ($this->_server, $this->_port, $this->_errno, $this->_errstr, $this->_socket_timeout);
  326. $this->_path = $this->translate_uri($path);
  327. $this->header_unset();
  328. $this->create_basic_request('PUT');
  329. // add more needed header information ...
  330. $this->header_add('Content-length: ' . filesize($filename));
  331. $this->header_add('Content-type: application/octet-stream');
  332. // send header
  333. $this->send_request();
  334. while (!feof($handle)) {
  335. fputs($this->sock,fgets($handle,4096));
  336. }
  337. fclose($handle);
  338. $this->get_respond();
  339. $response = $this->process_respond();
  340. // validate the response
  341. // check http-version
  342. if ($response['status']['http-version'] == 'HTTP/1.1' ||
  343. $response['status']['http-version'] == 'HTTP/1.0') {
  344. // seems to be http ... proceed
  345. // We expect a 200 or 204 status code
  346. // see rfc 2068 - 9.6 PUT...
  347. // print 'http ok<br>';
  348. return $response['status']['status-code'];
  349. }
  350. // ups: no http status was returned ?
  351. return false;
  352. } else {
  353. $this->_error_log('put_file: could not open ' . $filename);
  354. return false;
  355. }
  356. }
  357. /**
  358. * Public method get_file
  359. *
  360. * Gets a file from a collection into local filesystem.
  361. *
  362. * fopen() is used.
  363. * @param string $srcpath
  364. * @param string $localpath
  365. * @return bool true on success. false on error.
  366. */
  367. function get_file($srcpath, $localpath) {
  368. $localpath = $this->utf_decode_path($localpath);
  369. $handle = fopen($localpath, 'wb');
  370. if ($handle) {
  371. $unused = '';
  372. $ret = $this->get($srcpath, $unused, $handle);
  373. fclose($handle);
  374. if ($ret) {
  375. return true;
  376. }
  377. }
  378. return false;
  379. }
  380. /**
  381. * Public method copy_file
  382. *
  383. * Copies a file on a webdav server
  384. *
  385. * Duplicates a file on the webdav server (serverside).
  386. * All work is done on the webdav server. If you set param overwrite as true,
  387. * the target will be overwritten.
  388. *
  389. * @param string src_path, string dest_path, bool overwrite
  390. * @return int status code (look at rfc 2518). false on error.
  391. */
  392. function copy_file($src_path, $dst_path, $overwrite) {
  393. $this->_path = $this->translate_uri($src_path);
  394. $this->header_unset();
  395. $this->create_basic_request('COPY');
  396. $this->header_add(sprintf('Destination: http://%s%s', $this->_server, $this->translate_uri($dst_path)));
  397. if ($overwrite) {
  398. $this->header_add('Overwrite: T');
  399. } else {
  400. $this->header_add('Overwrite: F');
  401. }
  402. $this->header_add('');
  403. $this->send_request();
  404. $this->get_respond();
  405. $response = $this->process_respond();
  406. // validate the response ...
  407. // check http-version
  408. if ($response['status']['http-version'] == 'HTTP/1.1' ||
  409. $response['status']['http-version'] == 'HTTP/1.0') {
  410. /* seems to be http ... proceed
  411. just return what server gave us (as defined in rfc 2518) :
  412. 201 (Created) - The source resource was successfully copied. The copy operation resulted in the creation of a new resource.
  413. 204 (No Content) - The source resource was successfully copied to a pre-existing destination resource.
  414. 403 (Forbidden) - The source and destination URIs are the same.
  415. 409 (Conflict) - A resource cannot be created at the destination until one or more intermediate collections have been created.
  416. 412 (Precondition Failed) - The server was unable to maintain the liveness of the properties listed in the propertybehavior XML element
  417. or the Overwrite header is "F" and the state of the destination resource is non-null.
  418. 423 (Locked) - The destination resource was locked.
  419. 502 (Bad Gateway) - This may occur when the destination is on another server and the destination server refuses to accept the resource.
  420. 507 (Insufficient Storage) - The destination resource does not have sufficient space to record the state of the resource after the
  421. execution of this method.
  422. */
  423. return $response['status']['status-code'];
  424. }
  425. return false;
  426. }
  427. /**
  428. * Public method copy_coll
  429. *
  430. * Copies a collection on a webdav server
  431. *
  432. * Duplicates a collection on the webdav server (serverside).
  433. * All work is done on the webdav server. If you set param overwrite as true,
  434. * the target will be overwritten.
  435. *
  436. * @param string src_path, string dest_path, bool overwrite
  437. * @return int status code (look at rfc 2518). false on error.
  438. */
  439. function copy_coll($src_path, $dst_path, $overwrite) {
  440. $this->_path = $this->translate_uri($src_path);
  441. $this->header_unset();
  442. $this->create_basic_request('COPY');
  443. $this->header_add(sprintf('Destination: http://%s%s', $this->_server, $this->translate_uri($dst_path)));
  444. $this->header_add('Depth: Infinity');
  445. $xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n";
  446. $xml .= "<d:propertybehavior xmlns:d=\"DAV:\">\r\n";
  447. $xml .= " <d:keepalive>*</d:keepalive>\r\n";
  448. $xml .= "</d:propertybehavior>\r\n";
  449. $this->header_add('Content-length: ' . strlen($xml));
  450. $this->header_add('Content-type: application/xml');
  451. $this->send_request();
  452. // send also xml
  453. fputs($this->sock, $xml);
  454. $this->get_respond();
  455. $response = $this->process_respond();
  456. // validate the response ...
  457. // check http-version
  458. if ($response['status']['http-version'] == 'HTTP/1.1' ||
  459. $response['status']['http-version'] == 'HTTP/1.0') {
  460. /* seems to be http ... proceed
  461. just return what server gave us (as defined in rfc 2518) :
  462. 201 (Created) - The source resource was successfully copied. The copy operation resulted in the creation of a new resource.
  463. 204 (No Content) - The source resource was successfully copied to a pre-existing destination resource.
  464. 403 (Forbidden) - The source and destination URIs are the same.
  465. 409 (Conflict) - A resource cannot be created at the destination until one or more intermediate collections have been created.
  466. 412 (Precondition Failed) - The server was unable to maintain the liveness of the properties listed in the propertybehavior XML element
  467. or the Overwrite header is "F" and the state of the destination resource is non-null.
  468. 423 (Locked) - The destination resource was locked.
  469. 502 (Bad Gateway) - This may occur when the destination is on another server and the destination server refuses to accept the resource.
  470. 507 (Insufficient Storage) - The destination resource does not have sufficient space to record the state of the resource after the
  471. execution of this method.
  472. */
  473. return $response['status']['status-code'];
  474. }
  475. return false;
  476. }
  477. /**
  478. * Public method move
  479. *
  480. * Moves a file or collection on webdav server (serverside)
  481. *
  482. * If you set param overwrite as true, the target will be overwritten.
  483. *
  484. * @param string src_path, string dest_path, bool overwrite
  485. * @return int status code (look at rfc 2518). false on error.
  486. */
  487. // --------------------------------------------------------------------------
  488. // public method move
  489. // move/rename a file/collection on webdav server
  490. function move($src_path,$dst_path, $overwrite) {
  491. $this->_path = $this->translate_uri($src_path);
  492. $this->header_unset();
  493. $this->create_basic_request('MOVE');
  494. $this->header_add(sprintf('Destination: http://%s%s', $this->_server, $this->translate_uri($dst_path)));
  495. if ($overwrite) {
  496. $this->header_add('Overwrite: T');
  497. } else {
  498. $this->header_add('Overwrite: F');
  499. }
  500. $this->header_add('');
  501. $this->send_request();
  502. $this->get_respond();
  503. $response = $this->process_respond();
  504. // validate the response ...
  505. // check http-version
  506. if ($response['status']['http-version'] == 'HTTP/1.1' ||
  507. $response['status']['http-version'] == 'HTTP/1.0') {
  508. /* seems to be http ... proceed
  509. just return what server gave us (as defined in rfc 2518) :
  510. 201 (Created) - The source resource was successfully moved, and a new resource was created at the destination.
  511. 204 (No Content) - The source resource was successfully moved to a pre-existing destination resource.
  512. 403 (Forbidden) - The source and destination URIs are the same.
  513. 409 (Conflict) - A resource cannot be created at the destination until one or more intermediate collections have been created.
  514. 412 (Precondition Failed) - The server was unable to maintain the liveness of the properties listed in the propertybehavior XML element
  515. or the Overwrite header is "F" and the state of the destination resource is non-null.
  516. 423 (Locked) - The source or the destination resource was locked.
  517. 502 (Bad Gateway) - This may occur when the destination is on another server and the destination server refuses to accept the resource.
  518. 201 (Created) - The collection or structured resource was created in its entirety.
  519. 403 (Forbidden) - This indicates at least one of two conditions: 1) the server does not allow the creation of collections at the given
  520. location in its namespace, or 2) the parent collection of the Request-URI exists but cannot accept members.
  521. 405 (Method Not Allowed) - MKCOL can only be executed on a deleted/non-existent resource.
  522. 409 (Conflict) - A collection cannot be made at the Request-URI until one or more intermediate collections have been created.
  523. 415 (Unsupported Media Type)- The server does not support the request type of the body.
  524. 507 (Insufficient Storage) - The resource does not have sufficient space to record the state of the resource after the execution of this method.
  525. */
  526. return $response['status']['status-code'];
  527. }
  528. return false;
  529. }
  530. /**
  531. * Public method lock
  532. *
  533. * Locks a file or collection.
  534. *
  535. * Lock uses this->_user as lock owner.
  536. *
  537. * @param string path
  538. * @return int status code (look at rfc 2518). false on error.
  539. */
  540. function lock($path) {
  541. $this->_path = $this->translate_uri($path);
  542. $this->header_unset();
  543. $this->create_basic_request('LOCK');
  544. $this->header_add('Timeout: Infinite');
  545. $this->header_add('Content-type: text/xml');
  546. // create the xml request ...
  547. $xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n";
  548. $xml .= "<D:lockinfo xmlns:D='DAV:'\r\n>";
  549. $xml .= " <D:lockscope><D:exclusive/></D:lockscope>\r\n";
  550. $xml .= " <D:locktype><D:write/></D:locktype>\r\n";
  551. $xml .= " <D:owner>\r\n";
  552. $xml .= " <D:href>".($this->_user)."</D:href>\r\n";
  553. $xml .= " </D:owner>\r\n";
  554. $xml .= "</D:lockinfo>\r\n";
  555. $this->header_add('Content-length: ' . strlen($xml));
  556. $this->send_request();
  557. // send also xml
  558. fputs($this->sock, $xml);
  559. $this->get_respond();
  560. $response = $this->process_respond();
  561. // validate the response ... (only basic validation)
  562. // check http-version
  563. if ($response['status']['http-version'] == 'HTTP/1.1' ||
  564. $response['status']['http-version'] == 'HTTP/1.0') {
  565. /* seems to be http ... proceed
  566. rfc 2518 says:
  567. 200 (OK) - The lock request succeeded and the value of the lockdiscovery property is included in the body.
  568. 412 (Precondition Failed) - The included lock token was not enforceable on this resource or the server could not satisfy the
  569. request in the lockinfo XML element.
  570. 423 (Locked) - The resource is locked, so the method has been rejected.
  571. */
  572. switch($response['status']['status-code']) {
  573. case 200:
  574. // collection was successfully locked... see xml response to get lock token...
  575. if (strcmp($response['header']['Content-Type'], 'text/xml; charset="utf-8"') == 0) {
  576. // ok let's get the content of the xml stuff
  577. $this->_parser = xml_parser_create_ns();
  578. $this->_parserid = (int) $this->_parser;
  579. // forget old data...
  580. unset($this->_lock[$this->_parserid]);
  581. unset($this->_xmltree[$this->_parserid]);
  582. xml_parser_set_option($this->_parser,XML_OPTION_SKIP_WHITE,0);
  583. xml_parser_set_option($this->_parser,XML_OPTION_CASE_FOLDING,0);
  584. xml_set_object($this->_parser, $this);
  585. xml_set_element_handler($this->_parser, "_lock_startElement", "_endElement");
  586. xml_set_character_data_handler($this->_parser, "_lock_cdata");
  587. if (!xml_parse($this->_parser, $response['body'])) {
  588. die(sprintf("XML error: %s at line %d",
  589. xml_error_string(xml_get_error_code($this->_parser)),
  590. xml_get_current_line_number($this->_parser)));
  591. }
  592. // Free resources
  593. xml_parser_free($this->_parser);
  594. // add status code to array
  595. $this->_lock[$this->_parserid]['status'] = 200;
  596. return $this->_lock[$this->_parserid];
  597. } else {
  598. print 'Missing Content-Type: text/xml header in response.<br>';
  599. }
  600. return false;
  601. default:
  602. // hmm. not what we expected. Just return what we got from webdav server
  603. // someone else has to handle it.
  604. $this->_lock['status'] = $response['status']['status-code'];
  605. return $this->_lock;
  606. }
  607. }
  608. }
  609. /**
  610. * Public method unlock
  611. *
  612. * Unlocks a file or collection.
  613. *
  614. * @param string path, string locktoken
  615. * @return int status code (look at rfc 2518). false on error.
  616. */
  617. function unlock($path, $locktoken) {
  618. $this->_path = $this->translate_uri($path);
  619. $this->header_unset();
  620. $this->create_basic_request('UNLOCK');
  621. $this->header_add(sprintf('Lock-Token: <%s>', $locktoken));
  622. $this->send_request();
  623. $this->get_respond();
  624. $response = $this->process_respond();
  625. if ($response['status']['http-version'] == 'HTTP/1.1' ||
  626. $response['status']['http-version'] == 'HTTP/1.0') {
  627. /* seems to be http ... proceed
  628. rfc 2518 says:
  629. 204 (OK) - The 204 (No Content) status code is used instead of 200 (OK) because there is no response entity body.
  630. */
  631. return $response['status']['status-code'];
  632. }
  633. return false;
  634. }
  635. /**
  636. * Public method delete
  637. *
  638. * deletes a collection/directory on a webdav server
  639. * @param string path
  640. * @return int status code (look at rfc 2518). false on error.
  641. */
  642. function delete($path) {
  643. $this->_path = $this->translate_uri($path);
  644. $this->header_unset();
  645. $this->create_basic_request('DELETE');
  646. /* $this->header_add('Content-Length: 0'); */
  647. $this->header_add('');
  648. $this->send_request();
  649. $this->get_respond();
  650. $response = $this->process_respond();
  651. // validate the response ...
  652. // check http-version
  653. if ($response['status']['http-version'] == 'HTTP/1.1' ||
  654. $response['status']['http-version'] == 'HTTP/1.0') {
  655. // seems to be http ... proceed
  656. // We expect a 207 Multi-Status status code
  657. // print 'http ok<br>';
  658. switch ($response['status']['status-code']) {
  659. case 207:
  660. // collection was NOT deleted... see xml response for reason...
  661. // next there should be a Content-Type: text/xml; charset="utf-8" header line
  662. if (strcmp($response['header']['Content-Type'], 'text/xml; charset="utf-8"') == 0) {
  663. // ok let's get the content of the xml stuff
  664. $this->_parser = xml_parser_create_ns();
  665. $this->_parserid = (int) $this->_parser;
  666. // forget old data...
  667. unset($this->_delete[$this->_parserid]);
  668. unset($this->_xmltree[$this->_parserid]);
  669. xml_parser_set_option($this->_parser,XML_OPTION_SKIP_WHITE,0);
  670. xml_parser_set_option($this->_parser,XML_OPTION_CASE_FOLDING,0);
  671. xml_set_object($this->_parser, $this);
  672. xml_set_element_handler($this->_parser, "_delete_startElement", "_endElement");
  673. xml_set_character_data_handler($this->_parser, "_delete_cdata");
  674. if (!xml_parse($this->_parser, $response['body'])) {
  675. die(sprintf("XML error: %s at line %d",
  676. xml_error_string(xml_get_error_code($this->_parser)),
  677. xml_get_current_line_number($this->_parser)));
  678. }
  679. print "<br>";
  680. // Free resources
  681. xml_parser_free($this->_parser);
  682. $this->_delete[$this->_parserid]['status'] = $response['status']['status-code'];
  683. return $this->_delete[$this->_parserid];
  684. } else {
  685. print 'Missing Content-Type: text/xml header in response.<br>';
  686. }
  687. return false;
  688. default:
  689. // collection or file was successfully deleted
  690. $this->_delete['status'] = $response['status']['status-code'];
  691. return $this->_delete;
  692. }
  693. }
  694. }
  695. /**
  696. * Public method ls
  697. *
  698. * Get's directory information from webdav server into flat a array using PROPFIND
  699. *
  700. * All filenames are UTF-8 encoded.
  701. * Have a look at _propfind_startElement what keys are used in array returned.
  702. * @param string path
  703. * @return array dirinfo, false on error
  704. */
  705. function ls($path) {
  706. if (trim($path) == '') {
  707. $this->_error_log('Missing a path in method ls');
  708. return false;
  709. }
  710. $this->_path = $this->translate_uri($path);
  711. $this->header_unset();
  712. $this->create_basic_request('PROPFIND');
  713. $this->header_add('Depth: 1');
  714. $this->header_add('Content-type: application/xml');
  715. // create profind xml request...
  716. $xml = <<<EOD
  717. <?xml version="1.0" encoding="utf-8"?>
  718. <propfind xmlns="DAV:"><prop>
  719. <getcontentlength xmlns="DAV:"/>
  720. <getlastmodified xmlns="DAV:"/>
  721. <executable xmlns="http://apache.org/dav/props/"/>
  722. <resourcetype xmlns="DAV:"/>
  723. <checked-in xmlns="DAV:"/>
  724. <checked-out xmlns="DAV:"/>
  725. </prop></propfind>
  726. EOD;
  727. $this->header_add('Content-length: ' . strlen($xml));
  728. $this->send_request();
  729. $this->_error_log($xml);
  730. fputs($this->sock, $xml);
  731. $this->get_respond();
  732. $response = $this->process_respond();
  733. // validate the response ... (only basic validation)
  734. // check http-version
  735. if ($response['status']['http-version'] == 'HTTP/1.1' ||
  736. $response['status']['http-version'] == 'HTTP/1.0') {
  737. // seems to be http ... proceed
  738. // We expect a 207 Multi-Status status code
  739. // print 'http ok<br>';
  740. if (strcmp($response['status']['status-code'],'207') == 0 ) {
  741. // ok so far
  742. // next there should be a Content-Type: text/xml; charset="utf-8" header line
  743. if (preg_match('#(application|text)/xml;\s?charset=[\'\"]?utf-8[\'\"]?#i', $response['header']['Content-Type'])) {
  744. // ok let's get the content of the xml stuff
  745. $this->_parser = xml_parser_create_ns('UTF-8');
  746. $this->_parserid = (int) $this->_parser;
  747. // forget old data...
  748. unset($this->_ls[$this->_parserid]);
  749. unset($this->_xmltree[$this->_parserid]);
  750. xml_parser_set_option($this->_parser,XML_OPTION_SKIP_WHITE,0);
  751. xml_parser_set_option($this->_parser,XML_OPTION_CASE_FOLDING,0);
  752. // xml_parser_set_option($this->_parser,XML_OPTION_TARGET_ENCODING,'UTF-8');
  753. xml_set_object($this->_parser, $this);
  754. xml_set_element_handler($this->_parser, "_propfind_startElement", "_endElement");
  755. xml_set_character_data_handler($this->_parser, "_propfind_cdata");
  756. if (!xml_parse($this->_parser, $response['body'])) {
  757. die(sprintf("XML error: %s at line %d",
  758. xml_error_string(xml_get_error_code($this->_parser)),
  759. xml_get_current_line_number($this->_parser)));
  760. }
  761. // Free resources
  762. xml_parser_free($this->_parser);
  763. $arr = $this->_ls[$this->_parserid];
  764. return $arr;
  765. } else {
  766. $this->_error_log('Missing Content-Type: text/xml header in response!!');
  767. return false;
  768. }
  769. } else {
  770. // return status code ...
  771. return $response['status']['status-code'];
  772. }
  773. }
  774. // response was not http
  775. $this->_error_log('Ups in method ls: error in response from server');
  776. return false;
  777. }
  778. /**
  779. * Public method gpi
  780. *
  781. * Get's path information from webdav server for one element.
  782. *
  783. * @param string path
  784. * @return array dirinfo. false on error
  785. */
  786. function gpi($path) {
  787. // split path by last "/"
  788. $path = rtrim($path, "/");
  789. $item = basename($path);
  790. $dir = dirname($path);
  791. $list = $this->ls($dir);
  792. // be sure it is an array
  793. if (is_array($list)) {
  794. foreach($list as $e) {
  795. $fullpath = urldecode($e['href']);
  796. $filename = basename($fullpath);
  797. if ($filename == $item && $filename != "" and $fullpath != $dir."/") {
  798. return $e;
  799. }
  800. }
  801. }
  802. return false;
  803. }
  804. /**
  805. * Public method is_file
  806. *
  807. * Gathers whether a path points to a file or not.
  808. *
  809. * @param string path
  810. * @return bool true or false
  811. */
  812. function is_file($path) {
  813. $item = $this->gpi($path);
  814. if ($item === false) {
  815. return false;
  816. } else {
  817. return ($item['resourcetype'] != 'collection');
  818. }
  819. }
  820. /**
  821. * Public method is_dir
  822. *
  823. * Gather whether a path points to a directory
  824. * @param string path
  825. * return bool true or false
  826. */
  827. function is_dir($path) {
  828. // be sure path is utf-8
  829. $item = $this->gpi($path);
  830. if ($item === false) {
  831. return false;
  832. } else {
  833. return ($item['resourcetype'] == 'collection');
  834. }
  835. }
  836. /**
  837. * Public method mput
  838. *
  839. * Puts multiple files and/or directories onto a webdav server.
  840. *
  841. * Filenames should be allready UTF-8 encoded.
  842. * Param fileList must be in format array("localpath" => "destpath").
  843. *
  844. * @param array filelist
  845. * @return bool true on success. otherwise int status code on error
  846. */
  847. function mput($filelist) {
  848. $result = true;
  849. while (list($localpath, $destpath) = each($filelist)) {
  850. $localpath = rtrim($localpath, "/");
  851. $destpath = rtrim($destpath, "/");
  852. // attempt to create target path
  853. if (is_dir($localpath)) {
  854. $pathparts = explode("/", $destpath."/ "); // add one level, last level will be created as dir
  855. } else {
  856. $pathparts = explode("/", $destpath);
  857. }
  858. $checkpath = "";
  859. for ($i=1; $i<sizeof($pathparts)-1; $i++) {
  860. $checkpath .= "/" . $pathparts[$i];
  861. if (!($this->is_dir($checkpath))) {
  862. $result &= ($this->mkcol($checkpath) == 201 );
  863. }
  864. }
  865. if ($result) {
  866. // recurse directories
  867. if (is_dir($localpath)) {
  868. if (!$dp = opendir($localpath)) {
  869. $this->_error_log("Could not open localpath for reading");
  870. return false;
  871. }
  872. $fl = array();
  873. while($filename = readdir($dp)) {
  874. if ((is_file($localpath."/".$filename) || is_dir($localpath."/".$filename)) && $filename!="." && $filename != "..") {
  875. $fl[$localpath."/".$filename] = $destpath."/".$filename;
  876. }
  877. }
  878. $result &= $this->mput($fl);
  879. } else {
  880. $result &= ($this->put_file($destpath, $localpath) == 201);
  881. }
  882. }
  883. }
  884. return $result;
  885. }
  886. /**
  887. * Public method mget
  888. *
  889. * Gets multiple files and directories.
  890. *
  891. * FileList must be in format array("remotepath" => "localpath").
  892. * Filenames are UTF-8 encoded.
  893. *
  894. * @param array filelist
  895. * @return bool true on succes, other int status code on error
  896. */
  897. function mget($filelist) {
  898. $result = true;
  899. while (list($remotepath, $localpath) = each($filelist)) {
  900. $localpath = rtrim($localpath, "/");
  901. $remotepath = rtrim($remotepath, "/");
  902. // attempt to create local path
  903. if ($this->is_dir($remotepath)) {
  904. $pathparts = explode("/", $localpath."/ "); // add one level, last level will be created as dir
  905. } else {
  906. $pathparts = explode("/", $localpath);
  907. }
  908. $checkpath = "";
  909. for ($i=1; $i<sizeof($pathparts)-1; $i++) {
  910. $checkpath .= "/" . $pathparts[$i];
  911. if (!is_dir($checkpath)) {
  912. $result &= mkdir($checkpath);
  913. }
  914. }
  915. if ($result) {
  916. // recurse directories
  917. if ($this->is_dir($remotepath)) {
  918. $list = $this->ls($remotepath);
  919. $fl = array();
  920. foreach($list as $e) {
  921. $fullpath = urldecode($e['href']);
  922. $filename = basename($fullpath);
  923. if ($filename != '' and $fullpath != $remotepath . '/') {
  924. $fl[$remotepath."/".$filename] = $localpath."/".$filename;
  925. }
  926. }
  927. $result &= $this->mget($fl);
  928. } else {
  929. $result &= ($this->get_file($remotepath, $localpath));
  930. }
  931. }
  932. }
  933. return $result;
  934. }
  935. // --------------------------------------------------------------------------
  936. // private xml callback and helper functions starting here
  937. // --------------------------------------------------------------------------
  938. /**
  939. * Private method _endelement
  940. *
  941. * a generic endElement method (used for all xml callbacks).
  942. *
  943. * @param resource parser, string name
  944. * @access private
  945. */
  946. private function _endElement($parser, $name) {
  947. // end tag was found...
  948. $parserid = (int) $parser;
  949. $this->_xmltree[$parserid] = substr($this->_xmltree[$parserid],0, strlen($this->_xmltree[$parserid]) - (strlen($name) + 1));
  950. }
  951. /**
  952. * Private method _propfind_startElement
  953. *
  954. * Is needed by public method ls.
  955. *
  956. * Generic method will called by php xml_parse when a xml start element tag has been detected.
  957. * The xml tree will translated into a flat php array for easier access.
  958. * @param resource parser, string name, string attrs
  959. * @access private
  960. */
  961. private function _propfind_startElement($parser, $name, $attrs) {
  962. // lower XML Names... maybe break a RFC, don't know ...
  963. $parserid = (int) $parser;
  964. $propname = strtolower($name);
  965. if (!empty($this->_xmltree[$parserid])) {
  966. $this->_xmltree[$parserid] .= $propname . '_';
  967. } else {
  968. $this->_xmltree[$parserid] = $propname . '_';
  969. }
  970. // translate xml tree to a flat array ...
  971. switch($this->_xmltree[$parserid]) {
  972. case 'dav::multistatus_dav::response_':
  973. // new element in mu
  974. $this->_ls_ref =& $this->_ls[$parserid][];
  975. break;
  976. case 'dav::multistatus_dav::response_dav::href_':
  977. $this->_ls_ref_cdata = &$this->_ls_ref['href'];
  978. break;
  979. case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::creationdate_':
  980. $this->_ls_ref_cdata = &$this->_ls_ref['creationdate'];
  981. break;
  982. case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::getlastmodified_':
  983. $this->_ls_ref_cdata = &$this->_ls_ref['lastmodified'];
  984. break;
  985. case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::getcontenttype_':
  986. $this->_ls_ref_cdata = &$this->_ls_ref['getcontenttype'];
  987. break;
  988. case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::getcontentlength_':
  989. $this->_ls_ref_cdata = &$this->_ls_ref['getcontentlength'];
  990. break;
  991. case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::lockdiscovery_dav::activelock_dav::depth_':
  992. $this->_ls_ref_cdata = &$this->_ls_ref['activelock_depth'];
  993. break;
  994. case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::lockdiscovery_dav::activelock_dav::owner_dav::href_':
  995. $this->_ls_ref_cdata = &$this->_ls_ref['activelock_owner'];
  996. break;
  997. case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::lockdiscovery_dav::activelock_dav::owner_':
  998. $this->_ls_ref_cdata = &$this->_ls_ref['activelock_owner'];
  999. break;
  1000. case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::lockdiscovery_dav::activelock_dav::timeout_':
  1001. $this->_ls_ref_cdata = &$this->_ls_ref['activelock_timeout'];
  1002. break;
  1003. case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::lockdiscovery_dav::activelock_dav::locktoken_dav::href_':
  1004. $this->_ls_ref_cdata = &$this->_ls_ref['activelock_token'];
  1005. break;
  1006. case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::lockdiscovery_dav::activelock_dav::locktype_dav::write_':
  1007. $this->_ls_ref_cdata = &$this->_ls_ref['activelock_type'];
  1008. $this->_ls_ref_cdata = 'write';
  1009. $this->_ls_ref_cdata = &$this->_null;
  1010. break;
  1011. case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::resourcetype_dav::collection_':
  1012. $this->_ls_ref_cdata = &$this->_ls_ref['resourcetype'];
  1013. $this->_ls_ref_cdata = 'collection';
  1014. $this->_ls_ref_cdata = &$this->_null;
  1015. break;
  1016. case 'dav::multistatus_dav::response_dav::propstat_dav::status_':
  1017. $this->_ls_ref_cdata = &$this->_ls_ref['status'];
  1018. break;
  1019. default:
  1020. // handle unknown xml elements...
  1021. $this->_ls_ref_cdata = &$this->_ls_ref[$this->_xmltree[$parserid]];
  1022. }
  1023. }
  1024. /**
  1025. * Private method _propfind_cData
  1026. *
  1027. * Is needed by public method ls.
  1028. *
  1029. * Will be called by php xml_set_character_data_handler() when xml data has to be handled.
  1030. * Stores data found into class var _ls_ref_cdata
  1031. * @param resource parser, string cdata
  1032. * @access private
  1033. */
  1034. private function _propfind_cData($parser, $cdata) {
  1035. if (trim($cdata) <> '') {
  1036. // cdata must be appended, because sometimes the php xml parser makes multiple calls
  1037. // to _propfind_cData before the xml end tag was reached...
  1038. $this->_ls_ref_cdata .= $cdata;
  1039. } else {
  1040. // do nothing
  1041. }
  1042. }
  1043. /**
  1044. * Private method _delete_startElement
  1045. *
  1046. * Is used by public method delete.
  1047. *
  1048. * Will be called by php xml_parse.
  1049. * @param resource parser, string name, string attrs)
  1050. * @access private
  1051. */
  1052. private function _delete_startElement($parser, $name, $attrs) {
  1053. // lower XML Names... maybe break a RFC, don't know ...
  1054. $parserid = (int) $parser;
  1055. $propname = strtolower($name);
  1056. $this->_xmltree[$parserid] .= $propname . '_';
  1057. // translate xml tree to a flat array ...
  1058. switch($this->_xmltree[$parserid]) {
  1059. case 'dav::multistatus_dav::response_':
  1060. // new element in mu
  1061. $this->_delete_ref =& $this->_delete[$parserid][];
  1062. break;
  1063. case 'dav::multistatus_dav::response_dav::href_':
  1064. $this->_delete_ref_cdata = &$this->_ls_ref['href'];
  1065. break;
  1066. default:
  1067. // handle unknown xml elements...
  1068. $this->_delete_cdata = &$this->_delete_ref[$this->_xmltree[$parserid]];
  1069. }
  1070. }
  1071. /**
  1072. * Private method _delete_cData
  1073. *
  1074. * Is used by public method delete.
  1075. *
  1076. * Will be called by php xml_set_character_data_handler() when xml data has to be handled.
  1077. * Stores data found into class var _delete_ref_cdata
  1078. * @param resource parser, string cdata
  1079. * @access private
  1080. */
  1081. private function _delete_cData($parser, $cdata) {
  1082. if (trim($cdata) <> '') {
  1083. $this->_delete_ref_cdata .= $cdata;
  1084. } else {
  1085. // do nothing
  1086. }
  1087. }
  1088. /**
  1089. * Private method _lock_startElement
  1090. *
  1091. * Is needed by public method lock.
  1092. *
  1093. * Mmethod will called by php xml_parse when a xml start element tag has been detected.
  1094. * The xml tree will translated into a flat php array for easier access.
  1095. * @param resource parser, string name, string attrs
  1096. * @access private
  1097. */
  1098. private function _lock_startElement($parser, $name, $attrs) {
  1099. // lower XML Names... maybe break a RFC, don't know ...
  1100. $parserid = (int) $parser;
  1101. $propname = strtolower($name);
  1102. $this->_xmltree[$parserid] .= $propname . '_';
  1103. // translate xml tree to a flat array ...
  1104. /*
  1105. dav::prop_dav::lockdiscovery_dav::activelock_dav::depth_=
  1106. dav::prop_dav::lockdiscovery_dav::activelock_dav::owner_dav::href_=
  1107. dav::prop_dav::lockdiscovery_dav::activelock_dav::timeout_=
  1108. dav::prop_dav::lockdiscovery_dav::activelock_dav::locktoken_dav::href_=
  1109. */
  1110. switch($this->_xmltree[$parserid]) {
  1111. case 'dav::prop_dav::lockdiscovery_dav::activelock_':
  1112. // new element
  1113. $this->_lock_ref =& $this->_lock[$parserid][];
  1114. break;
  1115. case 'dav::prop_dav::lockdiscovery_dav::activelock_dav::locktype_dav::write_':
  1116. $this->_lock_ref_cdata = &$this->_lock_ref['locktype'];
  1117. $this->_lock_cdata = 'write';
  1118. $this->_lock_cdata = &$this->_null;
  1119. break;
  1120. case 'dav::prop_dav::lockdiscovery_dav::activelock_dav::lockā€¦

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