Class-Package.php 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178
  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 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. $ftp_server = strtr($ftp_server, array('/' => '', ':' => '', '@' => ''));
  686. // Connect to the FTP server.
  687. $this->connection = @fsockopen($ftp_server, $ftp_port, $err, $err, 5);
  688. if (!$this->connection)
  689. {
  690. $this->error = 'bad_server';
  691. return;
  692. }
  693. // Get the welcome message...
  694. if (!$this->check_response(220))
  695. {
  696. $this->error = 'bad_response';
  697. return;
  698. }
  699. // Send the username, it should ask for a password.
  700. fwrite($this->connection, 'USER ' . $ftp_user . "\r\n");
  701. if (!$this->check_response(331))
  702. {
  703. $this->error = 'bad_username';
  704. return;
  705. }
  706. // Now send the password... and hope it goes okay.
  707. fwrite($this->connection, 'PASS ' . $ftp_pass . "\r\n");
  708. if (!$this->check_response(230))
  709. {
  710. $this->error = 'bad_password';
  711. return;
  712. }
  713. }
  714. /**
  715. * Changes to a directory (chdir) via the ftp connection
  716. *
  717. * @param string $ftp_path The path to the directory we want to change to
  718. * @return boolean Whether or not the operation was successful
  719. */
  720. public function chdir($ftp_path)
  721. {
  722. if (!is_resource($this->connection))
  723. return false;
  724. // No slash on the end, please...
  725. if ($ftp_path !== '/' && substr($ftp_path, -1) === '/')
  726. $ftp_path = substr($ftp_path, 0, -1);
  727. fwrite($this->connection, 'CWD ' . $ftp_path . "\r\n");
  728. if (!$this->check_response(250))
  729. {
  730. $this->error = 'bad_path';
  731. return false;
  732. }
  733. return true;
  734. }
  735. /**
  736. * Changes a files atrributes (chmod)
  737. *
  738. * @param string $ftp_file The file to CHMOD
  739. * @param int|string $chmod The value for the CHMOD operation
  740. * @return boolean Whether or not the operation was successful
  741. */
  742. public function chmod($ftp_file, $chmod)
  743. {
  744. if (!is_resource($this->connection))
  745. return false;
  746. if ($ftp_file == '')
  747. $ftp_file = '.';
  748. // Convert the chmod value from octal (0777) to text ("777").
  749. fwrite($this->connection, 'SITE CHMOD ' . decoct($chmod) . ' ' . $ftp_file . "\r\n");
  750. if (!$this->check_response(200))
  751. {
  752. $this->error = 'bad_file';
  753. return false;
  754. }
  755. return true;
  756. }
  757. /**
  758. * Deletes a file
  759. *
  760. * @param string $ftp_file The file to delete
  761. * @return boolean Whether or not the operation was successful
  762. */
  763. public function unlink($ftp_file)
  764. {
  765. // We are actually connected, right?
  766. if (!is_resource($this->connection))
  767. return false;
  768. // Delete file X.
  769. fwrite($this->connection, 'DELE ' . $ftp_file . "\r\n");
  770. if (!$this->check_response(250))
  771. {
  772. fwrite($this->connection, 'RMD ' . $ftp_file . "\r\n");
  773. // Still no love?
  774. if (!$this->check_response(250))
  775. {
  776. $this->error = 'bad_file';
  777. return false;
  778. }
  779. }
  780. return true;
  781. }
  782. /**
  783. * Reads the response to the command from the server
  784. *
  785. * @param string $desired The desired response
  786. * @return boolean Whether or not we got the desired response
  787. */
  788. public function check_response($desired)
  789. {
  790. // Wait for a response that isn't continued with -, but don't wait too long.
  791. $time = time();
  792. do
  793. $this->last_message = fgets($this->connection, 1024);
  794. while ((strlen($this->last_message) < 4 || strpos($this->last_message, ' ') === 0 || strpos($this->last_message, ' ', 3) !== 3) && time() - $time < 5);
  795. // Was the desired response returned?
  796. return is_array($desired) ? in_array(substr($this->last_message, 0, 3), $desired) : substr($this->last_message, 0, 3) == $desired;
  797. }
  798. /**
  799. * Used to create a passive connection
  800. *
  801. * @return boolean Whether the passive connection was created successfully
  802. */
  803. public function passive()
  804. {
  805. // We can't create a passive data connection without a primary one first being there.
  806. if (!is_resource($this->connection))
  807. return false;
  808. // Request a passive connection - this means, we'll talk to you, you don't talk to us.
  809. @fwrite($this->connection, 'PASV' . "\r\n");
  810. $time = time();
  811. do
  812. $response = fgets($this->connection, 1024);
  813. while (strpos($response, ' ', 3) !== 3 && time() - $time < 5);
  814. // If it's not 227, we weren't given an IP and port, which means it failed.
  815. if (strpos($response, '227 ') !== 0)
  816. {
  817. $this->error = 'bad_response';
  818. return false;
  819. }
  820. // Snatch the IP and port information, or die horribly trying...
  821. if (preg_match('~\((\d+),\s*(\d+),\s*(\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+))\)~', $response, $match) == 0)
  822. {
  823. $this->error = 'bad_response';
  824. return false;
  825. }
  826. // This is pretty simple - store it for later use ;).
  827. $this->pasv = array('ip' => $match[1] . '.' . $match[2] . '.' . $match[3] . '.' . $match[4], 'port' => $match[5] * 256 + $match[6]);
  828. return true;
  829. }
  830. /**
  831. * Creates a new file on the server
  832. *
  833. * @param string $ftp_file The file to create
  834. * @return boolean Whether or not the file was created successfully
  835. */
  836. public function create_file($ftp_file)
  837. {
  838. // First, we have to be connected... very important.
  839. if (!is_resource($this->connection))
  840. return false;
  841. // I'd like one passive mode, please!
  842. if (!$this->passive())
  843. return false;
  844. // Seems logical enough, so far...
  845. fwrite($this->connection, 'STOR ' . $ftp_file . "\r\n");
  846. // Okay, now we connect to the data port. If it doesn't work out, it's probably "file already exists", etc.
  847. $fp = @fsockopen($this->pasv['ip'], $this->pasv['port'], $err, $err, 5);
  848. if (!$fp || !$this->check_response(150))
  849. {
  850. $this->error = 'bad_file';
  851. @fclose($fp);
  852. return false;
  853. }
  854. // This may look strange, but we're just closing it to indicate a zero-byte upload.
  855. fclose($fp);
  856. if (!$this->check_response(226))
  857. {
  858. $this->error = 'bad_response';
  859. return false;
  860. }
  861. return true;
  862. }
  863. /**
  864. * Generates a direcotry listing for the current directory
  865. *
  866. * @param string $ftp_path The path to the directory
  867. * @param type $search Whether or not to get a recursive directory listing
  868. * @return string|boolean The results of the command or false if unsuccessful
  869. */
  870. public function list_dir($ftp_path = '', $search = false)
  871. {
  872. // Are we even connected...?
  873. if (!is_resource($this->connection))
  874. return false;
  875. // Passive... non-agressive...
  876. if (!$this->passive())
  877. return false;
  878. // Get the listing!
  879. fwrite($this->connection, 'LIST -1' . ($search ? 'R' : '') . ($ftp_path == '' ? '' : ' ' . $ftp_path) . "\r\n");
  880. // Connect, assuming we've got a connection.
  881. $fp = @fsockopen($this->pasv['ip'], $this->pasv['port'], $err, $err, 5);
  882. if (!$fp || !$this->check_response(array(150, 125)))
  883. {
  884. $this->error = 'bad_response';
  885. @fclose($fp);
  886. return false;
  887. }
  888. // Read in the file listing.
  889. $data = '';
  890. while (!feof($fp))
  891. $data .= fread($fp, 4096);
  892. fclose($fp);
  893. // Everything go okay?
  894. if (!$this->check_response(226))
  895. {
  896. $this->error = 'bad_response';
  897. return false;
  898. }
  899. return $data;
  900. }
  901. /**
  902. * Determins the current dirctory we are in
  903. *
  904. * @param string $file The name of a file
  905. * @param string $listing A directory listing or null to generate one
  906. * @return string|boolean
  907. */
  908. public function locate($file, $listing = null)
  909. {
  910. if ($listing === null)
  911. $listing = $this->list_dir('', true);
  912. $listing = explode("\n", $listing);
  913. @fwrite($this->connection, 'PWD' . "\r\n");
  914. $time = time();
  915. do
  916. $response = fgets($this->connection, 1024);
  917. while ($response[3] != ' ' && time() - $time < 5);
  918. // Check for 257!
  919. if (preg_match('~^257 "(.+?)" ~', $response, $match) != 0)
  920. $current_dir = strtr($match[1], array('""' => '"'));
  921. else
  922. $current_dir = '';
  923. for ($i = 0, $n = count($listing); $i < $n; $i++)
  924. {
  925. if (trim($listing[$i]) == '' && isset($listing[$i + 1]))
  926. {
  927. $current_dir = substr(trim($listing[++$i]), 0, -1);
  928. $i++;
  929. }
  930. // Okay, this file's name is:
  931. $listing[$i] = $current_dir . '/' . trim(strlen($listing[$i]) > 30 ? strrchr($listing[$i], ' ') : $listing[$i]);
  932. if ($file[0] == '*' && substr($listing[$i], -(strlen($file) - 1)) == substr($file, 1))
  933. return $listing[$i];
  934. if (substr($file, -1) == '*' && substr($listing[$i], 0, strlen($file) - 1) == substr($file, 0, -1))
  935. return $listing[$i];
  936. if (basename($listing[$i]) == $file || $listing[$i] == $file)
  937. return $listing[$i];
  938. }
  939. return false;
  940. }
  941. /**
  942. * Creates a new directory on the server
  943. *
  944. * @param string $ftp_dir The name of the directory to create
  945. * @return boolean Whether or not the operation was successful
  946. */
  947. public function create_dir($ftp_dir)
  948. {
  949. // We must be connected to the server to do something.
  950. if (!is_resource($this->connection))
  951. return false;
  952. // Make this new beautiful directory!
  953. fwrite($this->connection, 'MKD ' . $ftp_dir . "\r\n");
  954. if (!$this->check_response(257))
  955. {
  956. $this->error = 'bad_file';
  957. return false;
  958. }
  959. return true;
  960. }
  961. /**
  962. * Detects the current path
  963. *
  964. * @param string $filesystem_path The full path from the filesystem
  965. * @param string $lookup_file The name of a file in the specified path
  966. * @return array An array of detected info - username, path from FTP root and whether or not the current path was found
  967. */
  968. public function detect_path($filesystem_path, $lookup_file = null)
  969. {
  970. $username = '';
  971. if (isset($_SERVER['DOCUMENT_ROOT']))
  972. {
  973. if (preg_match('~^/home[2]?/([^/]+?)/public_html~', $_SERVER['DOCUMENT_ROOT'], $match))
  974. {
  975. $username = $match[1];
  976. $path = strtr($_SERVER['DOCUMENT_ROOT'], array('/home/' . $match[1] . '/' => '', '/home2/' . $match[1] . '/' => ''));
  977. if (substr($path, -1) == '/')
  978. $path = substr($path, 0, -1);
  979. if (strlen(dirname($_SERVER['PHP_SELF'])) > 1)
  980. $path .= dirname($_SERVER['PHP_SELF']);
  981. }
  982. elseif (strpos($filesystem_path, '/var/www/') === 0)
  983. $path = substr($filesystem_path, 8);
  984. else
  985. $path = strtr(strtr($filesystem_path, array('\\' => '/')), array($_SERVER['DOCUMENT_ROOT'] => ''));
  986. }
  987. else
  988. $path = '';
  989. if (is_resource($this->connection) && $this->list_dir($path) == '')
  990. {
  991. $data = $this->list_dir('', true);
  992. if ($lookup_file === null)
  993. $lookup_file = $_SERVER['PHP_SELF'];
  994. $found_path = dirname($this->locate('*' . basename(dirname($lookup_file)) . '/' . basename($lookup_file), $data));
  995. if ($found_path == false)
  996. $found_path = dirname($this->locate(basename($lookup_file)));
  997. if ($found_path != false)
  998. $path = $found_path;
  999. }
  1000. elseif (is_resource($this->connection))
  1001. $found_path = true;
  1002. return array($username, $path, isset($found_path));
  1003. }
  1004. /**
  1005. * Close the ftp connection
  1006. *
  1007. * @return boolean Always returns true
  1008. */
  1009. public function close()
  1010. {
  1011. // Goodbye!
  1012. fwrite($this->connection, 'QUIT' . "\r\n");
  1013. fclose($this->connection);
  1014. return true;
  1015. }
  1016. }
  1017. ?>