Class-Package.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038
  1. <?php
  2. /**
  3. * The xmlArray class is an xml parser.
  4. *
  5. * Simple Machines Forum (SMF)
  6. *
  7. * @package SMF
  8. * @author Simple Machines http://www.simplemachines.org
  9. * @copyright 2011 Simple Machines
  10. * @license http://www.simplemachines.org/about/smf/license.php BSD
  11. *
  12. * @version 2.1 Alpha 1
  13. */
  14. if (!defined('SMF'))
  15. die('Hacking attempt...');
  16. /**
  17. * Class representing an xml array. Reads in xml, allows you to access it simply. Version 1.1.
  18. */
  19. class xmlArray
  20. {
  21. // The array and debugging output level.
  22. public $array, $debug_level, $trim;
  23. /**
  24. * Constructor for the xml parser.
  25. * Example use:
  26. * $xml = new xmlArray(file('data.xml'));
  27. * @param string $data the xml data or an array of, unless is_clone is true.
  28. * @param bool $auto_trim, default false, used to automatically trim textual data.
  29. * @param int $level, default null, the debug level, specifies whether notices
  30. * should be generated for missing elements and attributes.
  31. * @param bool $is_clone, default false. If is_clone is true, the
  32. * xmlArray is cloned from another - used internally only.
  33. */
  34. public function __construct($data, $auto_trim = false, $level = null, $is_clone = false)
  35. {
  36. // If we're using this try to get some more memory.
  37. @ini_set('memory_limit', '32M');
  38. // Set the debug level.
  39. $this->debug_level = $level !== null ? $level : error_reporting();
  40. $this->trim = $auto_trim;
  41. // Is the data already parsed?
  42. if ($is_clone)
  43. {
  44. $this->array = $data;
  45. return;
  46. }
  47. // Is the input an array? (ie. passed from file()?)
  48. if (is_array($data))
  49. $data = implode('', $data);
  50. // Remove any xml declaration or doctype, and parse out comments and CDATA.
  51. $data = preg_replace('/<!--.*?-->/s', '', $this->_to_cdata(preg_replace(array('/^<\?xml.+?\?' . '>/is', '/<!DOCTYPE[^>]+?' . '>/s'), '', $data)));
  52. // Now parse the xml!
  53. $this->array = $this->_parse($data);
  54. }
  55. /**
  56. * Get the root element's name.
  57. * Example use:
  58. * echo $element->name();
  59. */
  60. public function name()
  61. {
  62. return isset($this->array['name']) ? $this->array['name'] : '';
  63. }
  64. /**
  65. * Get a specified element's value or attribute by path.
  66. * Children are parsed for text, but only textual data is returned
  67. * unless get_elements is true.
  68. * Example use:
  69. * $data = $xml->fetch('html/head/title');
  70. * @param string $path - the path to the element to fetch
  71. * @param bool $get_elements - whether to include elements
  72. */
  73. public function fetch($path, $get_elements = false)
  74. {
  75. // Get the element, in array form.
  76. $array = $this->path($path);
  77. if ($array === false)
  78. return false;
  79. // Getting elements into this is a bit complicated...
  80. if ($get_elements && !is_string($array))
  81. {
  82. $temp = '';
  83. // Use the _xml() function to get the xml data.
  84. foreach ($array->array as $val)
  85. {
  86. // Skip the name and any attributes.
  87. if (is_array($val))
  88. $temp .= $this->_xml($val, null);
  89. }
  90. // Just get the XML data and then take out the CDATAs.
  91. return $this->_to_cdata($temp);
  92. }
  93. // Return the value - taking care to pick out all the text values.
  94. return is_string($array) ? $array : $this->_fetch($array->array);
  95. }
  96. /** Get an element, returns a new xmlArray.
  97. * It finds any elements that match the path specified.
  98. * It will always return a set if there is more than one of the element
  99. * or return_set is true.
  100. * Example use:
  101. * $element = $xml->path('html/body');
  102. * @param $path string - the path to the element to get
  103. * @param $return_full bool - always return full result set
  104. * @return xmlArray, a new xmlArray.
  105. */
  106. public function path($path, $return_full = false)
  107. {
  108. // Split up the path.
  109. $path = explode('/', $path);
  110. // Start with a base array.
  111. $array = $this->array;
  112. // For each element in the path.
  113. foreach ($path as $el)
  114. {
  115. // Deal with sets....
  116. if (strpos($el, '[') !== false)
  117. {
  118. $lvl = (int) substr($el, strpos($el, '[') + 1);
  119. $el = substr($el, 0, strpos($el, '['));
  120. }
  121. // Find an attribute.
  122. elseif (strpos($el, '@') === 0)
  123. {
  124. // It simplifies things if the attribute is already there ;).
  125. if (isset($array[$el]))
  126. return $array[$el];
  127. else
  128. {
  129. $trace = debug_backtrace();
  130. $i = 0;
  131. while ($i < count($trace) && isset($trace[$i]['class']) && $trace[$i]['class'] == get_class($this))
  132. $i++;
  133. $debug = ' from ' . $trace[$i - 1]['file'] . ' on line ' . $trace[$i - 1]['line'];
  134. // Cause an error.
  135. if ($this->debug_level & E_NOTICE)
  136. trigger_error('Undefined XML attribute: ' . substr($el, 1) . $debug, E_USER_NOTICE);
  137. return false;
  138. }
  139. }
  140. else
  141. $lvl = null;
  142. // Find this element.
  143. $array = $this->_path($array, $el, $lvl);
  144. }
  145. // Clean up after $lvl, for $return_full.
  146. if ($return_full && (!isset($array['name']) || substr($array['name'], -1) != ']'))
  147. $array = array('name' => $el . '[]', $array);
  148. // Create the right type of class...
  149. $newClass = get_class($this);
  150. // Return a new xmlArray for the result.
  151. return $array === false ? false : new $newClass($array, $this->trim, $this->debug_level, true);
  152. }
  153. /**
  154. * Check if an element exists.
  155. * Example use,
  156. * echo $xml->exists('html/body') ? 'y' : 'n';
  157. * @param string $path - the path to the element to get.
  158. * @return bool
  159. */
  160. public function exists($path)
  161. {
  162. // Split up the path.
  163. $path = explode('/', $path);
  164. // Start with a base array.
  165. $array = $this->array;
  166. // For each element in the path.
  167. foreach ($path as $el)
  168. {
  169. // Deal with sets....
  170. if (strpos($el, '[') !== false)
  171. {
  172. $lvl = (int) substr($el, strpos($el, '[') + 1);
  173. $el = substr($el, 0, strpos($el, '['));
  174. }
  175. // Find an attribute.
  176. elseif (strpos($el, '@') === 0)
  177. return isset($array[$el]);
  178. else
  179. $lvl = null;
  180. // Find this element.
  181. $array = $this->_path($array, $el, $lvl, true);
  182. }
  183. return $array !== false;
  184. }
  185. /**
  186. * Count the number of occurences of a path.
  187. * Example use:
  188. * echo $xml->count('html/head/meta');
  189. * @param string $path - the path to search for.
  190. * @return int, the number of elements the path matches.
  191. */
  192. public function count($path)
  193. {
  194. // Get the element, always returning a full set.
  195. $temp = $this->path($path, true);
  196. // Start at zero, then count up all the numeric keys.
  197. $i = 0;
  198. foreach ($temp->array as $item)
  199. {
  200. if (is_array($item))
  201. $i++;
  202. }
  203. return $i;
  204. }
  205. /**
  206. * Get an array of xmlArray's matching the specified path.
  207. * This differs from ->path(path, true) in that instead of an xmlArray
  208. * of elements, an array of xmlArray's is returned for use with foreach.
  209. * Example use:
  210. * foreach ($xml->set('html/body/p') as $p)
  211. * @param $path string - the path to search for.
  212. * @return array, an array of xmlArray objects
  213. */
  214. public function set($path)
  215. {
  216. // None as yet, just get the path.
  217. $array = array();
  218. $xml = $this->path($path, true);
  219. foreach ($xml->array as $val)
  220. {
  221. // Skip these, they aren't elements.
  222. if (!is_array($val) || $val['name'] == '!')
  223. continue;
  224. // Create the right type of class...
  225. $newClass = get_class($this);
  226. // Create a new xmlArray and stick it in the array.
  227. $array[] = new $newClass($val, $this->trim, $this->debug_level, true);
  228. }
  229. return $array;
  230. }
  231. /**
  232. * Create an xml file from an xmlArray, the specified path if any.
  233. * Example use:
  234. * echo $this->create_xml();
  235. * @param string $path - the path to the element. (optional)
  236. * @return string, xml-formatted string.
  237. */
  238. public function create_xml($path = null)
  239. {
  240. // Was a path specified? If so, use that array.
  241. if ($path !== null)
  242. {
  243. $path = $this->path($path);
  244. // The path was not found
  245. if ($path === false)
  246. return false;
  247. $path = $path->array;
  248. }
  249. // Just use the current array.
  250. else
  251. $path = $this->array;
  252. // Add the xml declaration to the front.
  253. return '<?xml version="1.0"?' . '>' . $this->_xml($path, 0);
  254. }
  255. /**
  256. * Output the xml in an array form.
  257. * Example use:
  258. * print_r($xml->to_array());
  259. * @param string $path, the path to output.
  260. */
  261. public function to_array($path = null)
  262. {
  263. // Are we doing a specific path?
  264. if ($path !== null)
  265. {
  266. $path = $this->path($path);
  267. // The path was not found
  268. if ($path === false)
  269. return false;
  270. $path = $path->array;
  271. }
  272. // No, so just use the current array.
  273. else
  274. $path = $this->array;
  275. return $this->_array($path);
  276. }
  277. /**
  278. * Parse data into an array. (privately used...)
  279. * @param string $data to parse
  280. */
  281. protected function _parse($data)
  282. {
  283. // Start with an 'empty' array with no data.
  284. $current = array(
  285. );
  286. // Loop until we're out of data.
  287. while ($data != '')
  288. {
  289. // Find and remove the next tag.
  290. preg_match('/\A<([\w\-:]+)((?:\s+.+?)?)([\s]?\/)?' . '>/', $data, $match);
  291. if (isset($match[0]))
  292. $data = preg_replace('/' . preg_quote($match[0], '/') . '/s', '', $data, 1);
  293. // Didn't find a tag? Keep looping....
  294. if (!isset($match[1]) || $match[1] == '')
  295. {
  296. // If there's no <, the rest is data.
  297. if (strpos($data, '<') === false)
  298. {
  299. $text_value = $this->_from_cdata($data);
  300. $data = '';
  301. if ($text_value != '')
  302. $current[] = array(
  303. 'name' => '!',
  304. 'value' => $text_value
  305. );
  306. }
  307. // If the < isn't immediately next to the current position... more data.
  308. elseif (strpos($data, '<') > 0)
  309. {
  310. $text_value = $this->_from_cdata(substr($data, 0, strpos($data, '<')));
  311. $data = substr($data, strpos($data, '<'));
  312. if ($text_value != '')
  313. $current[] = array(
  314. 'name' => '!',
  315. 'value' => $text_value
  316. );
  317. }
  318. // If we're looking at a </something> with no start, kill it.
  319. elseif (strpos($data, '<') !== false && strpos($data, '<') == 0)
  320. {
  321. if (strpos($data, '<', 1) !== false)
  322. {
  323. $text_value = $this->_from_cdata(substr($data, 0, strpos($data, '<', 1)));
  324. $data = substr($data, strpos($data, '<', 1));
  325. if ($text_value != '')
  326. $current[] = array(
  327. 'name' => '!',
  328. 'value' => $text_value
  329. );
  330. }
  331. else
  332. {
  333. $text_value = $this->_from_cdata($data);
  334. $data = '';
  335. if ($text_value != '')
  336. $current[] = array(
  337. 'name' => '!',
  338. 'value' => $text_value
  339. );
  340. }
  341. }
  342. // Wait for an actual occurance of an element.
  343. continue;
  344. }
  345. // Create a new element in the array.
  346. $el = &$current[];
  347. $el['name'] = $match[1];
  348. // If this ISN'T empty, remove the close tag and parse the inner data.
  349. if ((!isset($match[3]) || trim($match[3]) != '/') && (!isset($match[2]) || trim($match[2]) != '/'))
  350. {
  351. // Because PHP 5.2.0+ seems to croak using regex, we'll have to do this the less fun way.
  352. $last_tag_end = strpos($data, '</' . $match[1]. '>');
  353. if ($last_tag_end === false)
  354. continue;
  355. $offset = 0;
  356. while (1 == 1)
  357. {
  358. // Where is the next start tag?
  359. $next_tag_start = strpos($data, '<' . $match[1], $offset);
  360. // If the next start tag is after the last end tag then we've found the right close.
  361. if ($next_tag_start === false || $next_tag_start > $last_tag_end)
  362. break;
  363. // If not then find the next ending tag.
  364. $next_tag_end = strpos($data, '</' . $match[1]. '>', $offset);
  365. // Didn't find one? Then just use the last and sod it.
  366. if ($next_tag_end === false)
  367. break;
  368. else
  369. {
  370. $last_tag_end = $next_tag_end;
  371. $offset = $next_tag_start + 1;
  372. }
  373. }
  374. // Parse the insides.
  375. $inner_match = substr($data, 0, $last_tag_end);
  376. // Data now starts from where this section ends.
  377. $data = substr($data, $last_tag_end + strlen('</' . $match[1]. '>'));
  378. if (!empty($inner_match))
  379. {
  380. // Parse the inner data.
  381. if (strpos($inner_match, '<') !== false)
  382. $el += $this->_parse($inner_match);
  383. elseif (trim($inner_match) != '')
  384. {
  385. $text_value = $this->_from_cdata($inner_match);
  386. if ($text_value != '')
  387. $el[] = array(
  388. 'name' => '!',
  389. 'value' => $text_value
  390. );
  391. }
  392. }
  393. }
  394. // If we're dealing with attributes as well, parse them out.
  395. if (isset($match[2]) && $match[2] != '')
  396. {
  397. // Find all the attribute pairs in the string.
  398. preg_match_all('/([\w:]+)="(.+?)"/', $match[2], $attr, PREG_SET_ORDER);
  399. // Set them as @attribute-name.
  400. foreach ($attr as $match_attr)
  401. $el['@' . $match_attr[1]] = $match_attr[2];
  402. }
  403. }
  404. // Return the parsed array.
  405. return $current;
  406. }
  407. /**
  408. * Get a specific element's xml. (privately used...)
  409. * @param $array
  410. * @param $indent
  411. */
  412. protected function _xml($array, $indent)
  413. {
  414. $indentation = $indent !== null ? '
  415. ' . str_repeat(' ', $indent) : '';
  416. // This is a set of elements, with no name...
  417. if (is_array($array) && !isset($array['name']))
  418. {
  419. $temp = '';
  420. foreach ($array as $val)
  421. $temp .= $this->_xml($val, $indent);
  422. return $temp;
  423. }
  424. // This is just text!
  425. if ($array['name'] == '!')
  426. return $indentation . '<![CDATA[' . $array['value'] . ']]>';
  427. elseif (substr($array['name'], -2) == '[]')
  428. $array['name'] = substr($array['name'], 0, -2);
  429. // Start the element.
  430. $output = $indentation . '<' . $array['name'];
  431. $inside_elements = false;
  432. $output_el = '';
  433. // Run through and recurively output all the elements or attrbutes inside this.
  434. foreach ($array as $k => $v)
  435. {
  436. if (strpos($k, '@') === 0)
  437. $output .= ' ' . substr($k, 1) . '="' . $v . '"';
  438. elseif (is_array($v))
  439. {
  440. $output_el .= $this->_xml($v, $indent === null ? null : $indent + 1);
  441. $inside_elements = true;
  442. }
  443. }
  444. // Indent, if necessary.... then close the tag.
  445. if ($inside_elements)
  446. $output .= '>' . $output_el . $indentation . '</' . $array['name'] . '>';
  447. else
  448. $output .= ' />';
  449. return $output;
  450. }
  451. // Return an element as an array...
  452. protected function _array($array)
  453. {
  454. $return = array();
  455. $text = '';
  456. foreach ($array as $value)
  457. {
  458. if (!is_array($value) || !isset($value['name']))
  459. continue;
  460. if ($value['name'] == '!')
  461. $text .= $value['value'];
  462. else
  463. $return[$value['name']] = $this->_array($value);
  464. }
  465. if (empty($return))
  466. return $text;
  467. else
  468. return $return;
  469. }
  470. /**
  471. * Parse out CDATA tags. (htmlspecialchars them...)
  472. * @param $data
  473. */
  474. function _to_cdata($data)
  475. {
  476. $inCdata = $inComment = false;
  477. $output = '';
  478. $parts = preg_split('~(<!\[CDATA\[|\]\]>|<!--|-->)~', $data, -1, PREG_SPLIT_DELIM_CAPTURE);
  479. foreach ($parts as $part)
  480. {
  481. // Handle XML comments.
  482. if (!$inCdata && $part === '<!--')
  483. $inComment = true;
  484. if ($inComment && $part === '-->')
  485. $inComment = false;
  486. elseif ($inComment)
  487. continue;
  488. // Handle Cdata blocks.
  489. elseif (!$inComment && $part === '<![CDATA[')
  490. $inCdata = true;
  491. elseif ($inCdata && $part === ']]>')
  492. $inCdata = false;
  493. elseif ($inCdata)
  494. $output .= htmlentities($part, ENT_QUOTES);
  495. // Everything else is kept as is.
  496. else
  497. $output .= $part;
  498. }
  499. return $output;
  500. }
  501. /**
  502. * Turn the CDATAs back to normal text.
  503. * @param $data
  504. */
  505. protected function _from_cdata($data)
  506. {
  507. // Get the HTML translation table and reverse it.
  508. $trans_tbl = array_flip(get_html_translation_table(HTML_ENTITIES, ENT_QUOTES));
  509. // Translate all the entities out.
  510. $data = strtr(preg_replace('~&#(\d{1,4});~e', "chr('\$1')", $data), $trans_tbl);
  511. return $this->trim ? trim($data) : $data;
  512. }
  513. /**
  514. * Given an array, return the text from that array. (recursive and privately used.)
  515. *
  516. * @param array $array
  517. */
  518. protected function _fetch($array)
  519. {
  520. // Don't return anything if this is just a string.
  521. if (is_string($array))
  522. return '';
  523. $temp = '';
  524. foreach ($array as $text)
  525. {
  526. // This means it's most likely an attribute or the name itself.
  527. if (!isset($text['name']))
  528. continue;
  529. // This is text!
  530. if ($text['name'] == '!')
  531. $temp .= $text['value'];
  532. // Another element - dive in ;).
  533. else
  534. $temp .= $this->_fetch($text);
  535. }
  536. // Return all the bits and pieces we've put together.
  537. return $temp;
  538. }
  539. /**
  540. * Get a specific array by path, one level down. (privately used...)
  541. * @param array $array
  542. * @param string $path
  543. * @param int $level
  544. * @param bool $no_error
  545. */
  546. protected function _path($array, $path, $level, $no_error = false)
  547. {
  548. // Is $array even an array? It might be false!
  549. if (!is_array($array))
  550. return false;
  551. // Asking for *no* path?
  552. if ($path == '' || $path == '.')
  553. return $array;
  554. $paths = explode('|', $path);
  555. // A * means all elements of any name.
  556. $show_all = in_array('*', $paths);
  557. $results = array();
  558. // Check each element.
  559. foreach ($array as $value)
  560. {
  561. if (!is_array($value) || $value['name'] === '!')
  562. continue;
  563. if ($show_all || in_array($value['name'], $paths))
  564. {
  565. // Skip elements before "the one".
  566. if ($level !== null && $level > 0)
  567. $level--;
  568. else
  569. $results[] = $value;
  570. }
  571. }
  572. // No results found...
  573. if (empty($results))
  574. {
  575. $trace = debug_backtrace();
  576. $i = 0;
  577. while ($i < count($trace) && isset($trace[$i]['class']) && $trace[$i]['class'] == get_class($this))
  578. $i++;
  579. $debug = ' from ' . $trace[$i - 1]['file'] . ' on line ' . $trace[$i - 1]['line'];
  580. // Cause an error.
  581. if ($this->debug_level & E_NOTICE && !$no_error)
  582. trigger_error('Undefined XML element: ' . $path . $debug, E_USER_NOTICE);
  583. return false;
  584. }
  585. // Only one result.
  586. elseif (count($results) == 1 || $level !== null)
  587. return $results[0];
  588. // Return the result set.
  589. else
  590. return $results + array('name' => $path . '[]');
  591. }
  592. }
  593. /**
  594. * Simple FTP protocol implementation.
  595. * http://www.faqs.org/rfcs/rfc959.html
  596. */
  597. class ftp_connection
  598. {
  599. public $connection, $error, $last_message, $pasv;
  600. // Create a new FTP connection...
  601. public function __construct($ftp_server, $ftp_port = 21, $ftp_user = 'anonymous', $ftp_pass = '[email protected]')
  602. {
  603. // Initialize variables.
  604. $this->connection = 'no_connection';
  605. $this->error = false;
  606. $this->pasv = array();
  607. if ($ftp_server !== null)
  608. $this->connect($ftp_server, $ftp_port, $ftp_user, $ftp_pass);
  609. }
  610. public function connect($ftp_server, $ftp_port = 21, $ftp_user = 'anonymous', $ftp_pass = '[email protected]')
  611. {
  612. if (strpos($ftp_server, 'ftp://') === 0)
  613. $ftp_server = substr($ftp_server, 6);
  614. elseif (strpos($ftp_server, 'ftps://') === 0)
  615. $ftp_server = 'ssl://' . substr($ftp_server, 7);
  616. if (strpos($ftp_server, 'http://') === 0)
  617. $ftp_server = substr($ftp_server, 7);
  618. $ftp_server = strtr($ftp_server, array('/' => '', ':' => '', '@' => ''));
  619. // Connect to the FTP server.
  620. $this->connection = @fsockopen($ftp_server, $ftp_port, $err, $err, 5);
  621. if (!$this->connection)
  622. {
  623. $this->error = 'bad_server';
  624. return;
  625. }
  626. // Get the welcome message...
  627. if (!$this->check_response(220))
  628. {
  629. $this->error = 'bad_response';
  630. return;
  631. }
  632. // Send the username, it should ask for a password.
  633. fwrite($this->connection, 'USER ' . $ftp_user . "\r\n");
  634. if (!$this->check_response(331))
  635. {
  636. $this->error = 'bad_username';
  637. return;
  638. }
  639. // Now send the password... and hope it goes okay.
  640. fwrite($this->connection, 'PASS ' . $ftp_pass . "\r\n");
  641. if (!$this->check_response(230))
  642. {
  643. $this->error = 'bad_password';
  644. return;
  645. }
  646. }
  647. public function chdir($ftp_path)
  648. {
  649. if (!is_resource($this->connection))
  650. return false;
  651. // No slash on the end, please...
  652. if ($ftp_path !== '/' && substr($ftp_path, -1) === '/')
  653. $ftp_path = substr($ftp_path, 0, -1);
  654. fwrite($this->connection, 'CWD ' . $ftp_path . "\r\n");
  655. if (!$this->check_response(250))
  656. {
  657. $this->error = 'bad_path';
  658. return false;
  659. }
  660. return true;
  661. }
  662. public function chmod($ftp_file, $chmod)
  663. {
  664. if (!is_resource($this->connection))
  665. return false;
  666. if ($ftp_file == '')
  667. $ftp_file = '.';
  668. // Convert the chmod value from octal (0777) to text ("777").
  669. fwrite($this->connection, 'SITE CHMOD ' . decoct($chmod) . ' ' . $ftp_file . "\r\n");
  670. if (!$this->check_response(200))
  671. {
  672. $this->error = 'bad_file';
  673. return false;
  674. }
  675. return true;
  676. }
  677. public function unlink($ftp_file)
  678. {
  679. // We are actually connected, right?
  680. if (!is_resource($this->connection))
  681. return false;
  682. // Delete file X.
  683. fwrite($this->connection, 'DELE ' . $ftp_file . "\r\n");
  684. if (!$this->check_response(250))
  685. {
  686. fwrite($this->connection, 'RMD ' . $ftp_file . "\r\n");
  687. // Still no love?
  688. if (!$this->check_response(250))
  689. {
  690. $this->error = 'bad_file';
  691. return false;
  692. }
  693. }
  694. return true;
  695. }
  696. public function check_response($desired)
  697. {
  698. // Wait for a response that isn't continued with -, but don't wait too long.
  699. $time = time();
  700. do
  701. $this->last_message = fgets($this->connection, 1024);
  702. while ((strlen($this->last_message) < 4 || strpos($this->last_message, ' ') === 0 || strpos($this->last_message, ' ', 3) !== 3) && time() - $time < 5);
  703. // Was the desired response returned?
  704. return is_array($desired) ? in_array(substr($this->last_message, 0, 3), $desired) : substr($this->last_message, 0, 3) == $desired;
  705. }
  706. public function passive()
  707. {
  708. // We can't create a passive data connection without a primary one first being there.
  709. if (!is_resource($this->connection))
  710. return false;
  711. // Request a passive connection - this means, we'll talk to you, you don't talk to us.
  712. @fwrite($this->connection, 'PASV' . "\r\n");
  713. $time = time();
  714. do
  715. $response = fgets($this->connection, 1024);
  716. while (strpos($response, ' ', 3) !== 3 && time() - $time < 5);
  717. // If it's not 227, we weren't given an IP and port, which means it failed.
  718. if (strpos($response, '227 ') !== 0)
  719. {
  720. $this->error = 'bad_response';
  721. return false;
  722. }
  723. // Snatch the IP and port information, or die horribly trying...
  724. if (preg_match('~\((\d+),\s*(\d+),\s*(\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+))\)~', $response, $match) == 0)
  725. {
  726. $this->error = 'bad_response';
  727. return false;
  728. }
  729. // This is pretty simple - store it for later use ;).
  730. $this->pasv = array('ip' => $match[1] . '.' . $match[2] . '.' . $match[3] . '.' . $match[4], 'port' => $match[5] * 256 + $match[6]);
  731. return true;
  732. }
  733. public function create_file($ftp_file)
  734. {
  735. // First, we have to be connected... very important.
  736. if (!is_resource($this->connection))
  737. return false;
  738. // I'd like one passive mode, please!
  739. if (!$this->passive())
  740. return false;
  741. // Seems logical enough, so far...
  742. fwrite($this->connection, 'STOR ' . $ftp_file . "\r\n");
  743. // Okay, now we connect to the data port. If it doesn't work out, it's probably "file already exists", etc.
  744. $fp = @fsockopen($this->pasv['ip'], $this->pasv['port'], $err, $err, 5);
  745. if (!$fp || !$this->check_response(150))
  746. {
  747. $this->error = 'bad_file';
  748. @fclose($fp);
  749. return false;
  750. }
  751. // This may look strange, but we're just closing it to indicate a zero-byte upload.
  752. fclose($fp);
  753. if (!$this->check_response(226))
  754. {
  755. $this->error = 'bad_response';
  756. return false;
  757. }
  758. return true;
  759. }
  760. public function list_dir($ftp_path = '', $search = false)
  761. {
  762. // Are we even connected...?
  763. if (!is_resource($this->connection))
  764. return false;
  765. // Passive... non-agressive...
  766. if (!$this->passive())
  767. return false;
  768. // Get the listing!
  769. fwrite($this->connection, 'LIST -1' . ($search ? 'R' : '') . ($ftp_path == '' ? '' : ' ' . $ftp_path) . "\r\n");
  770. // Connect, assuming we've got a connection.
  771. $fp = @fsockopen($this->pasv['ip'], $this->pasv['port'], $err, $err, 5);
  772. if (!$fp || !$this->check_response(array(150, 125)))
  773. {
  774. $this->error = 'bad_response';
  775. @fclose($fp);
  776. return false;
  777. }
  778. // Read in the file listing.
  779. $data = '';
  780. while (!feof($fp))
  781. $data .= fread($fp, 4096);
  782. fclose($fp);
  783. // Everything go okay?
  784. if (!$this->check_response(226))
  785. {
  786. $this->error = 'bad_response';
  787. return false;
  788. }
  789. return $data;
  790. }
  791. public function locate($file, $listing = null)
  792. {
  793. if ($listing === null)
  794. $listing = $this->list_dir('', true);
  795. $listing = explode("\n", $listing);
  796. @fwrite($this->connection, 'PWD' . "\r\n");
  797. $time = time();
  798. do
  799. $response = fgets($this->connection, 1024);
  800. while ($response[3] != ' ' && time() - $time < 5);
  801. // Check for 257!
  802. if (preg_match('~^257 "(.+?)" ~', $response, $match) != 0)
  803. $current_dir = strtr($match[1], array('""' => '"'));
  804. else
  805. $current_dir = '';
  806. for ($i = 0, $n = count($listing); $i < $n; $i++)
  807. {
  808. if (trim($listing[$i]) == '' && isset($listing[$i + 1]))
  809. {
  810. $current_dir = substr(trim($listing[++$i]), 0, -1);
  811. $i++;
  812. }
  813. // Okay, this file's name is:
  814. $listing[$i] = $current_dir . '/' . trim(strlen($listing[$i]) > 30 ? strrchr($listing[$i], ' ') : $listing[$i]);
  815. if ($file[0] == '*' && substr($listing[$i], -(strlen($file) - 1)) == substr($file, 1))
  816. return $listing[$i];
  817. if (substr($file, -1) == '*' && substr($listing[$i], 0, strlen($file) - 1) == substr($file, 0, -1))
  818. return $listing[$i];
  819. if (basename($listing[$i]) == $file || $listing[$i] == $file)
  820. return $listing[$i];
  821. }
  822. return false;
  823. }
  824. public function create_dir($ftp_dir)
  825. {
  826. // We must be connected to the server to do something.
  827. if (!is_resource($this->connection))
  828. return false;
  829. // Make this new beautiful directory!
  830. fwrite($this->connection, 'MKD ' . $ftp_dir . "\r\n");
  831. if (!$this->check_response(257))
  832. {
  833. $this->error = 'bad_file';
  834. return false;
  835. }
  836. return true;
  837. }
  838. public function detect_path($filesystem_path, $lookup_file = null)
  839. {
  840. $username = '';
  841. if (isset($_SERVER['DOCUMENT_ROOT']))
  842. {
  843. if (preg_match('~^/home[2]?/([^/]+?)/public_html~', $_SERVER['DOCUMENT_ROOT'], $match))
  844. {
  845. $username = $match[1];
  846. $path = strtr($_SERVER['DOCUMENT_ROOT'], array('/home/' . $match[1] . '/' => '', '/home2/' . $match[1] . '/' => ''));
  847. if (substr($path, -1) == '/')
  848. $path = substr($path, 0, -1);
  849. if (strlen(dirname($_SERVER['PHP_SELF'])) > 1)
  850. $path .= dirname($_SERVER['PHP_SELF']);
  851. }
  852. elseif (strpos($filesystem_path, '/var/www/') === 0)
  853. $path = substr($filesystem_path, 8);
  854. else
  855. $path = strtr(strtr($filesystem_path, array('\\' => '/')), array($_SERVER['DOCUMENT_ROOT'] => ''));
  856. }
  857. else
  858. $path = '';
  859. if (is_resource($this->connection) && $this->list_dir($path) == '')
  860. {
  861. $data = $this->list_dir('', true);
  862. if ($lookup_file === null)
  863. $lookup_file = $_SERVER['PHP_SELF'];
  864. $found_path = dirname($this->locate('*' . basename(dirname($lookup_file)) . '/' . basename($lookup_file), $data));
  865. if ($found_path == false)
  866. $found_path = dirname($this->locate(basename($lookup_file)));
  867. if ($found_path != false)
  868. $path = $found_path;
  869. }
  870. elseif (is_resource($this->connection))
  871. $found_path = true;
  872. return array($username, $path, isset($found_path));
  873. }
  874. public function close()
  875. {
  876. // Goodbye!
  877. fwrite($this->connection, 'QUIT' . "\r\n");
  878. fclose($this->connection);
  879. return true;
  880. }
  881. }
  882. ?>