Class-Package.php 27 KB

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