Class-Package.php 30 KB

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