FtpClient.php 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. <?php
  2. /**
  3. * An FTP transfer wrapper using the Osinet FiniteStateMachine
  4. *
  5. * @copyright (c) 2007-2012 Ouest Systèmes Informatiques
  6. * @author Frédéric G. MARAND
  7. * @license Licensed under the CeCILL 2.0
  8. */
  9. namespace Osinet\FiniteStateMachine;
  10. /**
  11. * Save current reporting level while we set it
  12. */
  13. $_ftpEr = error_reporting(E_ALL | E_STRICT);
  14. /**
  15. * Class implements a finite-state-machine-based FTP client with *very* limited
  16. * functionality, but that can display progress information states, namely:
  17. * - init: not yet set up
  18. * - offline: no link established
  19. * - online: client connected to server
  20. * - live: client connected and logged in
  21. * - active: a data transfer operation is under way
  22. * - unsafe: something failed, disconnect can happen out of our control
  23. */
  24. class FtpClient extends Machine {
  25. /**
  26. * remote properties
  27. */
  28. private $fRemoteFile;
  29. private $fRemoteHost;
  30. private $fRemotePass;
  31. private $fRemoteUser;
  32. private $fRemoteWd;
  33. /**
  34. * local properties
  35. */
  36. private $fLocalWd;
  37. private $fLocalFile;
  38. private $fLocalFp; // file pointer to local file, used in get/put/continue
  39. /**
  40. * FTP properties
  41. */
  42. private $fFtpCallback; // name of callback function for progress information
  43. private $fFtpGoal; // bytes to be transferred
  44. private $fFtpConnection; // connection
  45. /**
  46. * @return void
  47. */
  48. public function __construct($values = array()) {
  49. if (!isset($values['source'])) {
  50. throw \Exception('Unspecified machine description.');
  51. }
  52. $this->loadFsm($values['source']);
  53. // print_r($this->fTransitions);
  54. parent::__construct();
  55. // print_r($this);die();
  56. }
  57. /**
  58. * Initialize parameters from an array
  59. *
  60. * @todo should really check names and values.
  61. *
  62. * @param array $params
  63. *
  64. * @return Result
  65. */
  66. public function setParameters($params) {
  67. $r = new \ReflectionClass(get_class($this));
  68. $dp = $r->getDefaultProperties();
  69. foreach ($params as $name => $value) {
  70. $field_name = "f$name";
  71. if (array_key_exists($field_name, $dp)) {
  72. $this->$field_name = $value;
  73. }
  74. else {
  75. echo "Skipping invalid parameter $name.\n";
  76. }
  77. }
  78. $ret = $this->applyEvent('CheckParameters');
  79. return $ret;
  80. }
  81. /**
  82. * ============ utility functions ============
  83. */
  84. /**
  85. * format a boolean value as a string
  86. *
  87. * @param boolean $val
  88. * @return string
  89. */
  90. static function stringFromBoolean($val)
  91. {
  92. return $val ? 'true' : 'false';
  93. }
  94. /**
  95. * Enter description here...
  96. *
  97. * @param unknown_type $status
  98. * @return unknown
  99. */
  100. static function stringFromFtp($status)
  101. {
  102. switch ($status)
  103. {
  104. case FTP_FINISHED: $ret = 'FTP_FINISHED'; break;
  105. case FTP_MOREDATA: $ret = 'FTP_MOREDATA'; break;
  106. case FTP_FAILED: $ret = 'FTP_MOREDATA'; break;
  107. default: $ret = 'FTP_INVALID_STATUS'; break;
  108. }
  109. return $ret;
  110. }
  111. /**
  112. * ============ event handlers ============
  113. */
  114. /**
  115. * implement change remote directory
  116. * @return string (boolean)
  117. */
  118. protected function eventChdir()
  119. {
  120. $ret = ftp_chdir($this->fFtpConnection, $this->fRemoteWd);
  121. return self::stringFromBoolean($ret);
  122. }
  123. /**
  124. * does the instance have all necessary info for a FTP transfer ?
  125. *
  126. * @return string (boolean)
  127. */
  128. public function eventCheckParameters()
  129. {
  130. $ret = isset($this->fRemoteHost)
  131. && isset($this->fRemoteUser)
  132. && isset($this->fRemotePass)
  133. && isset($this->fRemoteWd)
  134. && isset($this->fRemoteFile)
  135. && isset($this->fLocalWd)
  136. && isset($this->fLocalFile)
  137. && isset($this->fFtpCallback)
  138. ;
  139. $ret = self::stringFromBoolean($ret);
  140. // echo func_name() . ", ret = $ret\n";
  141. return $ret;
  142. }
  143. /**
  144. * implementation of Close event
  145. *
  146. * @return string (boolean)
  147. */
  148. protected function eventClose()
  149. {
  150. $ret = 'true';
  151. // echo "Trying to close socket...";
  152. if (is_resource($this->fFtpConnection))
  153. {
  154. try
  155. {
  156. // echo "Trying to close connection...";
  157. ftp_close($this->fFtpConnection);
  158. // echo "Done.";
  159. }
  160. catch (Exception $e)
  161. {
  162. print_r($e);
  163. $ret = 'false';
  164. }
  165. }
  166. // echo "Socket closed\n";
  167. return $ret;
  168. }
  169. /**
  170. * implementation of Connect event
  171. *
  172. * @return string (boolean)
  173. */
  174. protected function eventConnect()
  175. {
  176. // echo func_name() . "\n";
  177. $this->fFtpConnection = ftp_connect($this->fRemoteHost); // default port, default timeout
  178. $ret = is_resource($this->fFtpConnection);
  179. return self::stringFromBoolean($ret);
  180. }
  181. /**
  182. * implementation of continue
  183. * @return string FTP_FINISHED | FTP_MOREDATA | FTP_FAILED
  184. */
  185. protected function eventContinue()
  186. {
  187. // echo func_name();
  188. if ($this->fFtpCallback)
  189. {
  190. call_user_func($this->fFtpCallback, $this, 'pre');
  191. }
  192. $ret = ftp_nb_continue($this->fFtpConnection);
  193. if ($ret == FTP_FINISHED)
  194. {
  195. fclose($this->fLocalFp);
  196. }
  197. if ($this->fFtpCallback)
  198. call_user_func($this->fFtpCallback, $this, 'post');
  199. $ret = self::stringFromFtp($ret);
  200. return $ret;
  201. }
  202. /**
  203. * implementation of get
  204. *
  205. * @return string FTP_FINISHED | FTP_MOREDATA | FTP_FAILED
  206. * @throws Exception fail creating local file
  207. */
  208. protected function eventGet()
  209. {
  210. // echo func_name() . "\n";
  211. $this->fLocalFp = fopen($this->fLocalFile, "wb");
  212. if (!is_resource($this->fLocalFp))
  213. {
  214. $ret = self::stringFromFtp(FTP_FAILED);
  215. // throw new Exception(func_name() . ": could not create local file $this->fLocalFile");
  216. return $ret;
  217. }
  218. $this->fFtpGoal = ftp_size($this->fFtpConnection, $this->fRemoteFile);
  219. $ret = ftp_nb_fget($this->fFtpConnection, $this->fLocalFp,
  220. $this->fRemoteFile, FTP_BINARY);
  221. if ($ret == FTP_FINISHED)
  222. {
  223. fclose($this->fLocalFp);
  224. }
  225. call_user_func($this->fFtpCallback, $this, 'post');
  226. // echo func_name() . " => $ret\n"; flush();
  227. return self::stringFromFtp($ret);
  228. }
  229. /**
  230. * implementation of login
  231. * @return string (boolean)
  232. */
  233. protected function eventLogin()
  234. {
  235. // echo func_name() . "\n";
  236. $ret = ftp_login($this->fFtpConnection, $this->fRemoteUser, $this->fRemotePass);
  237. return self::stringFromBoolean($ret);
  238. }
  239. /**
  240. * handler must be implemented, but does nothing
  241. * @return void
  242. */
  243. protected function eventProgress()
  244. {
  245. return; // the FSM needs nothing for this
  246. }
  247. /**
  248. * close connection if it hasn't been done, to prevent connection
  249. * lingering on the server if avoidable
  250. * @return void
  251. */
  252. public function __destruct()
  253. {
  254. // echo func_name() . PHP_EOL;
  255. if ($this->isEventAllowed('Close'))
  256. {
  257. $this->applyEvent('Close');
  258. }
  259. if(is_resource($this->fLocalFp))
  260. try
  261. {
  262. echo "Trying to close file...";
  263. fclose($this->fLocalFp);
  264. echo "Done\n";
  265. }
  266. catch (Exception $e)
  267. {
  268. print_r($e);
  269. }
  270. // echo "End of " . func_name() . "\n";
  271. }
  272. /**
  273. * Make sure name can be resolved
  274. * ignore hosts that don't resolve in DNS or hosts file
  275. *
  276. * @param string $host
  277. * @return boolean
  278. */
  279. public function isHostValid($host = null)
  280. {
  281. $ret = is_array(gethostbynamel($host));
  282. return $ret;
  283. }
  284. /**
  285. * If a transfer is under way, return the progress percentile, otherwise 0.0
  286. *
  287. * @return float
  288. */
  289. public function getProgress()
  290. {
  291. if ((!$this->fState == 'active') || (!is_resource($this->fLocalFp)))
  292. {
  293. $ret = 0.0;
  294. }
  295. else
  296. {
  297. $pos = ftell($this->fLocalFp);
  298. $ret = $pos / $this->fFtpGoal;
  299. }
  300. return $ret;
  301. }
  302. }
  303. /**
  304. * Restore previous reporting level
  305. */
  306. error_reporting($_ftpEr);