Class-Package.php 28 KB

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