PageRenderTime 30ms CodeModel.GetById 17ms RepoModel.GetById 0ms 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
  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::lockscope_dav::exclusive_':
  1121. $this->_lock_ref_cdata = &$this->_lock_ref['lockscope'];
  1122. $this->_lock_ref_cdata = 'exclusive';
  1123. $this->_lock_ref_cdata = &$this->_null;
  1124. break;
  1125. case 'dav::prop_dav::lockdiscovery_dav::activelock_dav::depth_':
  1126. $this->_lock_ref_cdata = &$this->_lock_ref['depth'];
  1127. break;
  1128. case 'dav::prop_dav::lockdiscovery_dav::activelock_dav::owner_dav::href_':
  1129. $this->_lock_ref_cdata = &$this->_lock_ref['owner'];
  1130. break;
  1131. case 'dav::prop_dav::lockdiscovery_dav::activelock_dav::timeout_':
  1132. $this->_lock_ref_cdata = &$this->_lock_ref['timeout'];
  1133. break;
  1134. case 'dav::prop_dav::lockdiscovery_dav::activelock_dav::locktoken_dav::href_':
  1135. $this->_lock_ref_cdata = &$this->_lock_ref['locktoken'];
  1136. break;
  1137. default:
  1138. // handle unknown xml elements...
  1139. $this->_lock_cdata = &$this->_lock_ref[$this->_xmltree[$parserid]];
  1140. }
  1141. }
  1142. /**
  1143. * Private method _lock_cData
  1144. *
  1145. * Is used by public method lock.
  1146. *
  1147. * Will be called by php xml_set_character_data_handler() when xml data has to be handled.
  1148. * Stores data found into class var _lock_ref_cdata
  1149. * @param resource parser, string cdata
  1150. * @access private
  1151. */
  1152. private function _lock_cData($parser, $cdata) {
  1153. $parserid = (int) $parser;
  1154. if (trim($cdata) <> '') {
  1155. // $this->_error_log(($this->_xmltree[$parserid]) . '='. htmlentities($cdata));
  1156. $this->_lock_ref_cdata .= $cdata;
  1157. } else {
  1158. // do nothing
  1159. }
  1160. }
  1161. /**
  1162. * Private method header_add
  1163. *
  1164. * extends class var array _req
  1165. * @param string string
  1166. * @access private
  1167. */
  1168. private function header_add($string) {
  1169. $this->_req[] = $string;
  1170. }
  1171. /**
  1172. * Private method header_unset
  1173. *
  1174. * unsets class var array _req
  1175. * @access private
  1176. */
  1177. private function header_unset() {
  1178. unset($this->_req);
  1179. }
  1180. /**
  1181. * Private method create_basic_request
  1182. *
  1183. * creates by using private method header_add an general request header.
  1184. * @param string method
  1185. * @access private
  1186. */
  1187. private function create_basic_request($method) {
  1188. $this->header_add(sprintf('%s %s %s', $method, $this->_path, $this->_protocol));
  1189. $this->header_add(sprintf('Host: %s:%s', $this->_server, $this->_port));
  1190. //$request .= sprintf('Connection: Keep-Alive');
  1191. $this->header_add(sprintf('User-Agent: %s', $this->_user_agent));
  1192. $this->header_add('Connection: TE');
  1193. $this->header_add('TE: Trailers');
  1194. if ($this->_auth == 'basic') {
  1195. $this->header_add(sprintf('Authorization: Basic %s', base64_encode("$this->_user:$this->_pass")));
  1196. } else if ($this->_auth == 'digest') {
  1197. if ($signature = $this->digest_signature($method)){
  1198. $this->header_add($signature);
  1199. }
  1200. }
  1201. }
  1202. /**
  1203. * Reads the header, stores the challenge information
  1204. *
  1205. * @return void
  1206. */
  1207. private function digest_auth() {
  1208. $headers = array();
  1209. $headers[] = sprintf('%s %s %s', 'HEAD', $this->_path, $this->_protocol);
  1210. $headers[] = sprintf('Host: %s:%s', $this->_server, $this->_port);
  1211. $headers[] = sprintf('User-Agent: %s', $this->_user_agent);
  1212. $headers = implode("\r\n", $headers);
  1213. $headers .= "\r\n\r\n";
  1214. fputs($this->sock, $headers);
  1215. // Reads the headers.
  1216. $i = 0;
  1217. $header = '';
  1218. do {
  1219. $header .= fread($this->sock, 1);
  1220. $i++;
  1221. } while (!preg_match('/\\r\\n\\r\\n$/', $header, $matches) && $i < $this->_maxheaderlenth);
  1222. // Analyse the headers.
  1223. $digest = array();
  1224. $splitheaders = explode("\r\n", $header);
  1225. foreach ($splitheaders as $line) {
  1226. if (!preg_match('/^WWW-Authenticate: Digest/', $line)) {
  1227. continue;
  1228. }
  1229. $line = substr($line, strlen('WWW-Authenticate: Digest '));
  1230. $params = explode(',', $line);
  1231. foreach ($params as $param) {
  1232. list($key, $value) = explode('=', trim($param), 2);
  1233. $digest[$key] = trim($value, '"');
  1234. }
  1235. break;
  1236. }
  1237. $this->_digestchallenge = $digest;
  1238. }
  1239. /**
  1240. * Generates the digest signature
  1241. *
  1242. * @return string signature to add to the headers
  1243. * @access private
  1244. */
  1245. private function digest_signature($method) {
  1246. if (!$this->_digestchallenge) {
  1247. $this->digest_auth();
  1248. }
  1249. $signature = array();
  1250. $signature['username'] = '"' . $this->_user . '"';
  1251. $signature['realm'] = '"' . $this->_digestchallenge['realm'] . '"';
  1252. $signature['nonce'] = '"' . $this->_digestchallenge['nonce'] . '"';
  1253. $signature['uri'] = '"' . $this->_path . '"';
  1254. if (isset($this->_digestchallenge['algorithm']) && $this->_digestchallenge['algorithm'] != 'MD5') {
  1255. $this->_error_log('Algorithm other than MD5 are not supported');
  1256. return false;
  1257. }
  1258. $a1 = $this->_user . ':' . $this->_digestchallenge['realm'] . ':' . $this->_pass;
  1259. $a2 = $method . ':' . $this->_path;
  1260. if (!isset($this->_digestchallenge['qop'])) {
  1261. $signature['response'] = '"' . md5(md5($a1) . ':' . $this->_digestchallenge['nonce'] . ':' . md5($a2)) . '"';
  1262. } else {
  1263. // Assume QOP is auth
  1264. if (empty($this->_cnonce)) {
  1265. $this->_cnonce = random_string();
  1266. $this->_nc = 0;
  1267. }
  1268. $this->_nc++;
  1269. $nc = sprintf('%08d', $this->_nc);
  1270. $signature['cnonce'] = '"' . $this->_cnonce . '"';
  1271. $signature['nc'] = '"' . $nc . '"';
  1272. $signature['qop'] = '"' . $this->_digestchallenge['qop'] . '"';
  1273. $signature['response'] = '"' . md5(md5($a1) . ':' . $this->_digestchallenge['nonce'] . ':' .
  1274. $nc . ':' . $this->_cnonce . ':' . $this->_digestchallenge['qop'] . ':' . md5($a2)) . '"';
  1275. }
  1276. $response = array();
  1277. foreach ($signature as $key => $value) {
  1278. $response[] = "$key=$value";
  1279. }
  1280. return 'Authorization: Digest ' . implode(', ', $response);
  1281. }
  1282. /**
  1283. * Private method send_request
  1284. *
  1285. * Sends a ready formed http/webdav request to webdav server.
  1286. *
  1287. * @access private
  1288. */
  1289. private function send_request() {
  1290. // check if stream is declared to be open
  1291. // only logical check we are not sure if socket is really still open ...
  1292. if ($this->_connection_closed) {
  1293. // reopen it
  1294. // be sure to close the open socket.
  1295. $this->close();
  1296. $this->reopen();
  1297. }
  1298. // convert array to string
  1299. $buffer = implode("\r\n", $this->_req);
  1300. $buffer .= "\r\n\r\n";
  1301. $this->_error_log($buffer);
  1302. fputs($this->sock, $buffer);
  1303. }
  1304. /**
  1305. * Private method get_respond
  1306. *
  1307. * Reads the response from the webdav server.
  1308. *
  1309. * Stores data into class vars _header for the header data and
  1310. * _body for the rest of the response.
  1311. * This routine is the weakest part of this class, because it very depends how php does handle a socket stream.
  1312. * If the stream is blocked for some reason php is blocked as well.
  1313. * @access private
  1314. * @param resource $fp optional the file handle to write the body content to (stored internally in the '_body' if not set)
  1315. */
  1316. private function get_respond($fp = null) {
  1317. $this->_error_log('get_respond()');
  1318. // init vars (good coding style ;-)
  1319. $buffer = '';
  1320. $header = '';
  1321. // attention: do not make max_chunk_size to big....
  1322. $max_chunk_size = 8192;
  1323. // be sure we got a open ressource
  1324. if (! $this->sock) {
  1325. $this->_error_log('socket is not open. Can not process response');
  1326. return false;
  1327. }
  1328. // following code maybe helps to improve socket behaviour ... more testing needed
  1329. // disabled at the moment ...
  1330. // socket_set_timeout($this->sock,1 );
  1331. // $socket_state = socket_get_status($this->sock);
  1332. // read stream one byte by another until http header ends
  1333. $i = 0;
  1334. $matches = array();
  1335. do {
  1336. $header.=fread($this->sock, 1);
  1337. $i++;
  1338. } while (!preg_match('/\\r\\n\\r\\n$/',$header, $matches) && $i < $this->_maxheaderlenth);
  1339. $this->_error_log($header);
  1340. if (preg_match('/Connection: close\\r\\n/', $header)) {
  1341. // This says that the server will close connection at the end of this stream.
  1342. // Therefore we need to reopen the socket, before are sending the next request...
  1343. $this->_error_log('Connection: close found');
  1344. $this->_connection_closed = true;
  1345. } else if (preg_match('@^HTTP/1\.(1|0) 401 @', $header)) {
  1346. $this->_error_log('The server requires an authentication');
  1347. }
  1348. // check how to get the data on socket stream
  1349. // chunked or content-length (HTTP/1.1) or
  1350. // one block until feof is received (HTTP/1.0)
  1351. switch(true) {
  1352. case (preg_match('/Transfer\\-Encoding:\\s+chunked\\r\\n/',$header)):
  1353. $this->_error_log('Getting HTTP/1.1 chunked data...');
  1354. do {
  1355. $byte = '';
  1356. $chunk_size='';
  1357. do {
  1358. $chunk_size.=$byte;
  1359. $byte=fread($this->sock,1);
  1360. // check what happens while reading, because I do not really understand how php reads the socketstream...
  1361. // but so far - it seems to work here - tested with php v4.3.1 on apache 1.3.27 and Debian Linux 3.0 ...
  1362. if (strlen($byte) == 0) {
  1363. $this->_error_log('get_respond: warning --> read zero bytes');
  1364. }
  1365. } while ($byte!="\r" and strlen($byte)>0); // till we match the Carriage Return
  1366. fread($this->sock, 1); // also drop off the Line Feed
  1367. $chunk_size=hexdec($chunk_size); // convert to a number in decimal system
  1368. if ($chunk_size > 0) {
  1369. $read = 0;
  1370. // Reading the chunk in one bite is not secure, we read it byte by byte.
  1371. while ($read < $chunk_size) {
  1372. $chunk = fread($this->sock, 1);
  1373. self::update_file_or_buffer($chunk, $fp, $buffer);
  1374. $read++;
  1375. }
  1376. }
  1377. fread($this->sock, 2); // ditch the CRLF that trails the chunk
  1378. } while ($chunk_size); // till we reach the 0 length chunk (end marker)
  1379. break;
  1380. // check for a specified content-length
  1381. case preg_match('/Content\\-Length:\\s+([0-9]*)\\r\\n/',$header,$matches):
  1382. $this->_error_log('Getting data using Content-Length '. $matches[1]);
  1383. // check if we the content data size is small enough to get it as one block
  1384. if ($matches[1] <= $max_chunk_size ) {
  1385. // only read something if Content-Length is bigger than 0
  1386. if ($matches[1] > 0 ) {
  1387. $chunk = fread($this->sock, $matches[1]);
  1388. $loadsize = strlen($chunk);
  1389. //did we realy get the full length?
  1390. if ($loadsize < $matches[1]) {
  1391. $max_chunk_size = $loadsize;
  1392. do {
  1393. $mod = $max_chunk_size % ($matches[1] - strlen($chunk));
  1394. $chunk_size = ($mod == $max_chunk_size ? $max_chunk_size : $matches[1] - strlen($chunk));
  1395. $chunk .= fread($this->sock, $chunk_size);
  1396. $this->_error_log('mod: ' . $mod . ' chunk: ' . $chunk_size . ' total: ' . strlen($chunk));
  1397. } while ($mod == $max_chunk_size);
  1398. }
  1399. self::update_file_or_buffer($chunk, $fp, $buffer);
  1400. break;
  1401. } else {
  1402. $buffer = '';
  1403. break;
  1404. }
  1405. }
  1406. // data is to big to handle it as one. Get it chunk per chunk...
  1407. //trying to get the full length of max_chunk_size
  1408. $chunk = fread($this->sock, $max_chunk_size);
  1409. $loadsize = strlen($chunk);
  1410. self::update_file_or_buffer($chunk, $fp, $buffer);
  1411. if ($loadsize < $max_chunk_size) {
  1412. $max_chunk_size = $loadsize;
  1413. }
  1414. do {
  1415. $mod = $max_chunk_size % ($matches[1] - $loadsize);
  1416. $chunk_size = ($mod == $max_chunk_size ? $max_chunk_size : $matches[1] - $loadsize);
  1417. $chunk = fread($this->sock, $chunk_size);
  1418. self::update_file_or_buffer($chunk, $fp, $buffer);
  1419. $loadsize += strlen($chunk);
  1420. $this->_error_log('mod: ' . $mod . ' chunk: ' . $chunk_size . ' total: ' . $loadsize);
  1421. } while ($mod == $max_chunk_size);
  1422. if ($loadsize < $matches[1]) {
  1423. $chunk = fread($this->sock, $matches[1] - $loadsize);
  1424. self::update_file_or_buffer($chunk, $fp, $buffer);
  1425. }
  1426. break;
  1427. // check for 204 No Content
  1428. // 204 responds have no body.
  1429. // Therefore we do not need to read any data from socket stream.
  1430. case preg_match('/HTTP\/1\.1\ 204/',$header):
  1431. // nothing to do, just proceed
  1432. $this->_error_log('204 No Content found. No further data to read..');
  1433. break;
  1434. default:
  1435. // just get the data until foef appears...
  1436. $this->_error_log('reading until feof...' . $header);
  1437. socket_set_timeout($this->sock, 0, 0);
  1438. while (!feof($this->sock)) {
  1439. $chunk = fread($this->sock, 4096);
  1440. self::update_file_or_buffer($chunk, $fp, $buffer);
  1441. }
  1442. // renew the socket timeout...does it do something ???? Is it needed. More debugging needed...
  1443. socket_set_timeout($this->sock, $this->_socket_timeout, 0);
  1444. }
  1445. $this->_header = $header;
  1446. $this->_body = $buffer;
  1447. // $this->_buffer = $header . "\r\n\r\n" . $buffer;
  1448. $this->_error_log($this->_header);
  1449. $this->_error_log($this->_body);
  1450. }
  1451. /**
  1452. * Write the chunk to the file if $fp is set, otherwise append the data to the buffer
  1453. * @param string $chunk the data to add
  1454. * @param resource $fp the file handle to write to (or null)
  1455. * @param string &$buffer the buffer to append to (if $fp is null)
  1456. */
  1457. static private function update_file_or_buffer($chunk, $fp, &$buffer) {
  1458. if ($fp) {
  1459. fwrite($fp, $chunk);
  1460. } else {
  1461. $buffer .= $chunk;
  1462. }
  1463. }
  1464. /**
  1465. * Private method process_respond
  1466. *
  1467. * Processes the webdav server respond and detects its components (header, body).
  1468. * and returns data array structure.
  1469. * @return array ret_struct
  1470. * @access private
  1471. */
  1472. private function process_respond() {
  1473. $lines = explode("\r\n", $this->_header);
  1474. $header_done = false;
  1475. // $this->_error_log($this->_buffer);
  1476. // First line should be a HTTP status line (see http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html#sec6)
  1477. // Format is: HTTP-Version SP Status-Code SP Reason-Phrase CRLF
  1478. list($ret_struct['status']['http-version'],
  1479. $ret_struct['status']['status-code'],
  1480. $ret_struct['status']['reason-phrase']) = explode(' ', $lines[0],3);
  1481. // print "HTTP Version: '$http_version' Status-Code: '$status_code' Reason Phrase: '$reason_phrase'<br>";
  1482. // get the response header fields
  1483. // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html#sec6
  1484. for($i=1; $i<count($lines); $i++) {
  1485. if (rtrim($lines[$i]) == '' && !$header_done) {
  1486. $header_done = true;
  1487. // print "--- response header end ---<br>";
  1488. }
  1489. if (!$header_done ) {
  1490. // store all found headers in array ...
  1491. list($fieldname, $fieldvalue) = explode(':', $lines[$i]);
  1492. // check if this header was allready set (apache 2.0 webdav module does this....).
  1493. // If so we add the the value to the end the fieldvalue, separated by comma...
  1494. if (empty($ret_struct['header'])) {
  1495. $ret_struct['header'] = array();
  1496. }
  1497. if (empty($ret_struct['header'][$fieldname])) {
  1498. $ret_struct['header'][$fieldname] = trim($fieldvalue);
  1499. } else {
  1500. $ret_struct['header'][$fieldname] .= ',' . trim($fieldvalue);
  1501. }
  1502. }
  1503. }
  1504. // print 'string len of response_body:'. strlen($response_body);
  1505. // print '[' . htmlentities($response_body) . ']';
  1506. $ret_struct['body'] = $this->_body;
  1507. $this->_error_log('process_respond: ' . var_export($ret_struct,true));
  1508. return $ret_struct;
  1509. }
  1510. /**
  1511. * Private method reopen
  1512. *
  1513. * Reopens a socket, if 'connection: closed'-header was received from server.
  1514. *
  1515. * Uses public method open.
  1516. * @access private
  1517. */
  1518. private function reopen() {
  1519. // let's try to reopen a socket
  1520. $this->_error_log('reopen a socket connection');
  1521. return $this->open();
  1522. }
  1523. /**
  1524. * Private method translate_uri
  1525. *
  1526. * translates an uri to raw url encoded string.
  1527. * Removes any html entity in uri
  1528. * @param string uri
  1529. * @return string translated_uri
  1530. * @access private
  1531. */
  1532. private function translate_uri($uri) {
  1533. // remove all html entities...
  1534. $native_path = html_entity_decode($uri);
  1535. $parts = explode('/', $native_path);
  1536. for ($i = 0; $i < count($parts); $i++) {
  1537. // check if part is allready utf8
  1538. if (iconv('UTF-8', 'UTF-8', $parts[$i]) == $parts[$i]) {
  1539. $parts[$i] = rawurlencode($parts[$i]);
  1540. } else {
  1541. $parts[$i] = rawurlencode(utf8_encode($parts[$i]));
  1542. }
  1543. }
  1544. return implode('/', $parts);
  1545. }
  1546. /**
  1547. * Private method utf_decode_path
  1548. *
  1549. * decodes a UTF-8 encoded string
  1550. * @return string decodedstring
  1551. * @access private
  1552. */
  1553. private function utf_decode_path($path) {
  1554. $fullpath = $path;
  1555. if (iconv('UTF-8', 'UTF-8', $fullpath) == $fullpath) {
  1556. $this->_error_log("filename is utf-8. Needs conversion...");
  1557. $fullpath = utf8_decode($fullpath);
  1558. }
  1559. return $fullpath;
  1560. }
  1561. /**
  1562. * Private method _error_log
  1563. *
  1564. * a simple php error_log wrapper.
  1565. * @param string err_string
  1566. * @access private
  1567. */
  1568. private function _error_log($err_string) {
  1569. if ($this->_debug) {
  1570. error_log($err_string);
  1571. }
  1572. }
  1573. }