elFinderVolumeDropbox.class.php 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464
  1. <?php
  2. elFinder::$netDrivers['dropbox'] = 'Dropbox';
  3. /**
  4. * Simple elFinder driver for FTP
  5. *
  6. * @author Dmitry (dio) Levashov
  7. * @author Cem (discofever)
  8. **/
  9. class elFinderVolumeDropbox extends elFinderVolumeDriver {
  10. /**
  11. * Driver id
  12. * Must be started from letter and contains [a-z0-9]
  13. * Used as part of volume id
  14. *
  15. * @var string
  16. **/
  17. protected $driverId = 'd';
  18. /**
  19. * OAuth object
  20. *
  21. * @var oauth
  22. **/
  23. protected $oauth = null;
  24. /**
  25. * Dropbox object
  26. *
  27. * @var dropbox
  28. **/
  29. protected $dropbox = null;
  30. /**
  31. * Directory for meta data caches
  32. * If not set driver not cache meta data
  33. *
  34. * @var string
  35. **/
  36. protected $metaCache = '';
  37. /**
  38. * Last API error message
  39. *
  40. * @var string
  41. **/
  42. protected $apiError = '';
  43. /**
  44. * Directory for tmp files
  45. * If not set driver will try to use tmbDir as tmpDir
  46. *
  47. * @var string
  48. **/
  49. protected $tmp = '';
  50. /**
  51. * Dropbox.com uid
  52. *
  53. * @var string
  54. **/
  55. protected $dropboxUid = '';
  56. /**
  57. * Dropbox download host, replaces 'www.dropbox.com' of shares URL
  58. *
  59. * @var string
  60. */
  61. private $dropbox_dlhost = 'dl.dropboxusercontent.com';
  62. private $dropbox_phpFound = false;
  63. private $DB_TableName = '';
  64. private $tmbPrefix = '';
  65. /**
  66. * Constructor
  67. * Extend options with required fields
  68. *
  69. * @author Dmitry (dio) Levashov
  70. * @author Cem (DiscoFever)
  71. */
  72. public function __construct() {
  73. // check with composer
  74. $this->dropbox_phpFound = class_exists('Dropbox_API');
  75. if (! $this->dropbox_phpFound) {
  76. // check with pear
  77. if (include_once 'Dropbox/autoload.php') {
  78. $this->dropbox_phpFound = in_array('Dropbox_autoload', spl_autoload_functions());
  79. }
  80. }
  81. $opts = array(
  82. 'consumerKey' => '',
  83. 'consumerSecret' => '',
  84. 'accessToken' => '',
  85. 'accessTokenSecret' => '',
  86. 'dropboxUid' => '',
  87. 'root' => 'dropbox',
  88. 'path' => '/',
  89. 'separator' => '/',
  90. 'PDO_DSN' => '', // if empty use 'sqlite:(metaCachePath|tmbPath)/elFinder_dropbox_db_(hash:dropboxUid+consumerSecret)'
  91. 'PDO_User' => '',
  92. 'PDO_Pass' => '',
  93. 'PDO_Options' => array(),
  94. 'PDO_DBName' => 'dropbox',
  95. 'treeDeep' => 0,
  96. 'tmbPath' => '',
  97. 'tmbURL' => '',
  98. 'tmpPath' => '',
  99. 'getTmbSize' => 'large', // small: 32x32, medium or s: 64x64, large or m: 128x128, l: 640x480, xl: 1024x768
  100. 'metaCachePath' => '',
  101. 'metaCacheTime' => '600', // 10m
  102. 'acceptedName' => '#^[^/\\?*:|"<>]*[^./\\?*:|"<>]$#',
  103. 'rootCssClass' => 'elfinder-navbar-root-dropbox'
  104. );
  105. $this->options = array_merge($this->options, $opts);
  106. $this->options['mimeDetect'] = 'internal';
  107. }
  108. /**
  109. * Prepare
  110. * Call from elFinder::netmout() before volume->mount()
  111. *
  112. * @param $options
  113. * @return Array
  114. * @author Naoki Sawada
  115. */
  116. public function netmountPrepare($options) {
  117. if (empty($options['consumerKey']) && defined('ELFINDER_DROPBOX_CONSUMERKEY')) $options['consumerKey'] = ELFINDER_DROPBOX_CONSUMERKEY;
  118. if (empty($options['consumerSecret']) && defined('ELFINDER_DROPBOX_CONSUMERSECRET')) $options['consumerSecret'] = ELFINDER_DROPBOX_CONSUMERSECRET;
  119. if ($options['user'] === 'init') {
  120. if (! $this->dropbox_phpFound || empty($options['consumerKey']) || empty($options['consumerSecret']) || !class_exists('PDO', false)) {
  121. return array('exit' => true, 'body' => '{msg:errNetMountNoDriver}');
  122. }
  123. if (defined('ELFINDER_DROPBOX_USE_CURL_PUT')) {
  124. $this->oauth = new Dropbox_OAuth_Curl($options['consumerKey'], $options['consumerSecret']);
  125. } else {
  126. if (class_exists('OAuth', false)) {
  127. $this->oauth = new Dropbox_OAuth_PHP($options['consumerKey'], $options['consumerSecret']);
  128. } else {
  129. if (! class_exists('HTTP_OAuth_Consumer')) {
  130. // We're going to try to load in manually
  131. include 'HTTP/OAuth/Consumer.php';
  132. }
  133. if (class_exists('HTTP_OAuth_Consumer', false)) {
  134. $this->oauth = new Dropbox_OAuth_PEAR($options['consumerKey'], $options['consumerSecret']);
  135. }
  136. }
  137. }
  138. if (! $this->oauth) {
  139. return array('exit' => true, 'body' => '{msg:errNetMountNoDriver}');
  140. }
  141. if ($options['pass'] === 'init') {
  142. $html = '';
  143. if ($sessionToken = $this->session->get('DropboxTokens')) {
  144. // token check
  145. try {
  146. list(, $accessToken, $accessTokenSecret) = $sessionToken;
  147. $this->oauth->setToken($accessToken, $accessTokenSecret);
  148. $this->dropbox = new Dropbox_API($this->oauth, $this->options['root']);
  149. $this->dropbox->getAccountInfo();
  150. $script = '<script>
  151. $("#'.$options['id'].'").elfinder("instance").trigger("netmount", {protocol: "dropbox", mode: "done"});
  152. </script>';
  153. $html = $script;
  154. } catch (Dropbox_Exception $e) {
  155. $this->session->remove('DropboxTokens');
  156. }
  157. }
  158. if (! $html) {
  159. // get customdata
  160. $cdata = '';
  161. $innerKeys = array('cmd', 'host', 'options', 'pass', 'protocol', 'user');
  162. $this->ARGS = $_SERVER['REQUEST_METHOD'] === 'POST'? $_POST : $_GET;
  163. foreach($this->ARGS as $k => $v) {
  164. if (! in_array($k, $innerKeys)) {
  165. $cdata .= '&' . $k . '=' . rawurlencode($v);
  166. }
  167. }
  168. if (strpos($options['url'], 'http') !== 0 ) {
  169. $options['url'] = elFinder::getConnectorUrl();
  170. }
  171. $callback = $options['url']
  172. . '?cmd=netmount&protocol=dropbox&host=dropbox.com&user=init&pass=return&node='.$options['id'].$cdata;
  173. try {
  174. $tokens = $this->oauth->getRequestToken();
  175. $url= $this->oauth->getAuthorizeUrl(rawurlencode($callback));
  176. } catch (Dropbox_Exception $e) {
  177. return array('exit' => true, 'body' => '{msg:errAccess}');
  178. }
  179. $this->session->set('DropboxAuthTokens', $tokens);
  180. $html = '<input id="elf-volumedriver-dropbox-host-btn" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" value="{msg:btnApprove}" type="button" onclick="window.open(\''.$url.'\')">';
  181. $html .= '<script>
  182. $("#'.$options['id'].'").elfinder("instance").trigger("netmount", {protocol: "dropbox", mode: "makebtn"});
  183. </script>';
  184. }
  185. return array('exit' => true, 'body' => $html);
  186. } else {
  187. $this->oauth->setToken($this->session->get('DropboxAuthTokens'));
  188. $this->session->remove('DropboxAuthTokens');
  189. $tokens = $this->oauth->getAccessToken();
  190. $this->session->set('DropboxTokens', array($_GET['uid'], $tokens['token'], $tokens['token_secret']));
  191. $out = array(
  192. 'node' => $_GET['node'],
  193. 'json' => '{"protocol": "dropbox", "mode": "done"}',
  194. 'bind' => 'netmount'
  195. );
  196. return array('exit' => 'callback', 'out' => $out);
  197. }
  198. }
  199. if ($sessionToken = $this->session->get('DropboxTokens')) {
  200. list($options['dropboxUid'], $options['accessToken'], $options['accessTokenSecret']) = $sessionToken;
  201. }
  202. unset($options['user'], $options['pass']);
  203. return $options;
  204. }
  205. /**
  206. * process of on netunmount
  207. * Drop table `dropbox` & rm thumbs
  208. *
  209. * @param $netVolumes
  210. * @param $key
  211. * @return bool
  212. * @internal param array $options
  213. */
  214. public function netunmount($netVolumes, $key) {
  215. $count = 0;
  216. $dropboxUid = '';
  217. if (isset($netVolumes[$key])) {
  218. $dropboxUid = $netVolumes[$key]['dropboxUid'];
  219. }
  220. foreach($netVolumes as $volume) {
  221. if ($volume['host'] === 'dropbox' && $volume['dropboxUid'] === $dropboxUid) {
  222. $count++;
  223. }
  224. }
  225. if ($count === 1) {
  226. $this->DB->exec('drop table '.$this->DB_TableName);
  227. foreach(glob(rtrim($this->options['tmbPath'], '\\/').DIRECTORY_SEPARATOR.$this->tmbPrefix.'*.png') as $tmb) {
  228. unlink($tmb);
  229. }
  230. }
  231. return true;
  232. }
  233. /*********************************************************************/
  234. /* INIT AND CONFIGURE */
  235. /*********************************************************************/
  236. /**
  237. * Prepare FTP connection
  238. * Connect to remote server and check if credentials are correct, if so, store the connection id in $ftp_conn
  239. *
  240. * @return bool
  241. * @author Dmitry (dio) Levashov
  242. * @author Cem (DiscoFever)
  243. **/
  244. protected function init() {
  245. if (!class_exists('PDO', false)) {
  246. return $this->setError('PHP PDO class is require.');
  247. }
  248. if (!$this->options['consumerKey']
  249. || !$this->options['consumerSecret']
  250. || !$this->options['accessToken']
  251. || !$this->options['accessTokenSecret']) {
  252. return $this->setError('Required options undefined.');
  253. }
  254. if (empty($this->options['metaCachePath']) && defined('ELFINDER_DROPBOX_META_CACHE_PATH')) {
  255. $this->options['metaCachePath'] = ELFINDER_DROPBOX_META_CACHE_PATH;
  256. }
  257. // make net mount key
  258. $this->netMountKey = md5(join('-', array('dropbox', $this->options['path'])));
  259. if (! $this->oauth) {
  260. if (defined('ELFINDER_DROPBOX_USE_CURL_PUT')) {
  261. $this->oauth = new Dropbox_OAuth_Curl($this->options['consumerKey'], $this->options['consumerSecret']);
  262. } else {
  263. if (class_exists('OAuth', false)) {
  264. $this->oauth = new Dropbox_OAuth_PHP($this->options['consumerKey'], $this->options['consumerSecret']);
  265. } else {
  266. if (! class_exists('HTTP_OAuth_Consumer')) {
  267. // We're going to try to load in manually
  268. include 'HTTP/OAuth/Consumer.php';
  269. }
  270. if (class_exists('HTTP_OAuth_Consumer', false)) {
  271. $this->oauth = new Dropbox_OAuth_PEAR($this->options['consumerKey'], $this->options['consumerSecret']);
  272. }
  273. }
  274. }
  275. }
  276. if (! $this->oauth) {
  277. return $this->setError('OAuth extension not loaded.');
  278. }
  279. // normalize root path
  280. $this->root = $this->options['path'] = $this->_normpath($this->options['path']);
  281. if (empty($this->options['alias'])) {
  282. $this->options['alias'] = ($this->options['path'] === '/')? 'Dropbox.com' : 'Dropbox'.$this->options['path'];
  283. }
  284. $this->rootName = $this->options['alias'];
  285. try {
  286. $this->oauth->setToken($this->options['accessToken'], $this->options['accessTokenSecret']);
  287. $this->dropbox = new Dropbox_API($this->oauth, $this->options['root']);
  288. } catch (Dropbox_Exception $e) {
  289. $this->session->remove('DropboxTokens');
  290. return $this->setError('Dropbox error: '.$e->getMessage());
  291. }
  292. // user
  293. if (empty($this->options['dropboxUid'])) {
  294. try {
  295. $res = $this->dropbox->getAccountInfo();
  296. $this->options['dropboxUid'] = $res['uid'];
  297. } catch (Dropbox_Exception $e) {
  298. $this->session->remove('DropboxTokens');
  299. return $this->setError('Dropbox error: '.$e->getMessage());
  300. }
  301. }
  302. $this->dropboxUid = $this->options['dropboxUid'];
  303. $this->tmbPrefix = 'dropbox'.base_convert($this->dropboxUid, 10, 32);
  304. if (!empty($this->options['tmpPath'])) {
  305. if ((is_dir($this->options['tmpPath']) || mkdir($this->options['tmpPath'])) && is_writable($this->options['tmpPath'])) {
  306. $this->tmp = $this->options['tmpPath'];
  307. }
  308. }
  309. if (!$this->tmp && is_writable($this->options['tmbPath'])) {
  310. $this->tmp = $this->options['tmbPath'];
  311. }
  312. if (!$this->tmp && ($tmp = elFinder::getStaticVar('commonTempPath'))) {
  313. $this->tmp = $tmp;
  314. }
  315. if (!empty($this->options['metaCachePath'])) {
  316. if ((is_dir($this->options['metaCachePath']) || mkdir($this->options['metaCachePath'])) && is_writable($this->options['metaCachePath'])) {
  317. $this->metaCache = $this->options['metaCachePath'];
  318. }
  319. }
  320. if (!$this->metaCache && $this->tmp) {
  321. $this->metaCache = $this->tmp;
  322. }
  323. if (!$this->metaCache) {
  324. return $this->setError('Cache dirctory (metaCachePath or tmp) is require.');
  325. }
  326. // setup PDO
  327. if (! $this->options['PDO_DSN']) {
  328. $this->options['PDO_DSN'] = 'sqlite:'.$this->metaCache.DIRECTORY_SEPARATOR.'.elFinder_dropbox_db_'.md5($this->dropboxUid.$this->options['consumerSecret']);
  329. }
  330. // DataBase table name
  331. $this->DB_TableName = $this->options['PDO_DBName'];
  332. // DataBase check or make table
  333. try {
  334. $this->DB = new PDO($this->options['PDO_DSN'], $this->options['PDO_User'], $this->options['PDO_Pass'], $this->options['PDO_Options']);
  335. if (! $this->checkDB()) {
  336. return $this->setError('Can not make DB table');
  337. }
  338. } catch (PDOException $e) {
  339. return $this->setError('PDO connection failed: '.$e->getMessage());
  340. }
  341. $res = $this->deltaCheck($this->isMyReload());
  342. if ($res !== true) {
  343. if (is_string($res)) {
  344. return $this->setError($res);
  345. } else {
  346. return $this->setError('Could not check API "delta"');
  347. }
  348. }
  349. if (is_null($this->options['syncChkAsTs'])) {
  350. $this->options['syncChkAsTs'] = true;
  351. }
  352. if ($this->options['syncChkAsTs']) {
  353. // 'tsPlSleep' minmum 5 sec
  354. $this->options['tsPlSleep'] = max(5, $this->options['tsPlSleep']);
  355. } else {
  356. // 'lsPlSleep' minmum 10 sec
  357. $this->options['lsPlSleep'] = max(10, $this->options['lsPlSleep']);
  358. }
  359. return true;
  360. }
  361. /**
  362. * Configure after successful mount.
  363. *
  364. * @return string
  365. * @author Dmitry (dio) Levashov
  366. **/
  367. protected function configure() {
  368. parent::configure();
  369. $this->disabled[] = 'archive';
  370. $this->disabled[] = 'extract';
  371. }
  372. /**
  373. * Check DB for delta cache
  374. *
  375. * @return bool
  376. */
  377. private function checkDB() {
  378. $res = $this->query('SELECT * FROM sqlite_master WHERE type=\'table\' AND name=\''.$this->DB_TableName.'\'');
  379. if ($res && isset($_REQUEST['init'])) {
  380. // check is index(nameidx) UNIQUE?
  381. $chk = $this->query('SELECT sql FROM sqlite_master WHERE type=\'index\' and name=\'nameidx\'');
  382. if (!$chk || strpos(strtoupper($chk[0]), 'UNIQUE') === false) {
  383. // remake
  384. $this->DB->exec('DROP TABLE '.$this->DB_TableName);
  385. $res = false;
  386. }
  387. }
  388. if (! $res) {
  389. try {
  390. $this->DB->exec('CREATE TABLE '.$this->DB_TableName.'(path text, fname text, dat blob, isdir integer);');
  391. $this->DB->exec('CREATE UNIQUE INDEX nameidx ON '.$this->DB_TableName.'(path, fname)');
  392. $this->DB->exec('CREATE INDEX isdiridx ON '.$this->DB_TableName.'(isdir)');
  393. } catch (PDOException $e) {
  394. return $this->setError($e->getMessage());
  395. }
  396. }
  397. return true;
  398. }
  399. /**
  400. * DB query and fetchAll
  401. *
  402. * @param string $sql
  403. * @return boolean|array
  404. */
  405. private function query($sql) {
  406. if ($sth = $this->DB->query($sql)) {
  407. $res = $sth->fetchAll(PDO::FETCH_COLUMN);
  408. } else {
  409. $res = false;
  410. }
  411. return $res;
  412. }
  413. /**
  414. * Get dat(dropbox metadata) from DB
  415. *
  416. * @param string $path
  417. * @return array dropbox metadata
  418. */
  419. private function getDBdat($path) {
  420. if ($res = $this->query('select dat from '.$this->DB_TableName.' where path='.$this->DB->quote(strtolower($this->_dirname($path))).' and fname='.$this->DB->quote(strtolower($this->_basename($path))).' limit 1')) {
  421. return unserialize($res[0]);
  422. } else {
  423. return array();
  424. }
  425. }
  426. /**
  427. * Update DB dat(dropbox metadata)
  428. *
  429. * @param string $path
  430. * @param array $dat
  431. * @return bool|array
  432. */
  433. private function updateDBdat($path, $dat) {
  434. return $this->query('update '.$this->DB_TableName.' set dat='.$this->DB->quote(serialize($dat))
  435. . ', isdir=' . ($dat['is_dir']? 1 : 0)
  436. . ' where path='.$this->DB->quote(strtolower($this->_dirname($path))).' and fname='.$this->DB->quote(strtolower($this->_basename($path))));
  437. }
  438. /*********************************************************************/
  439. /* FS API */
  440. /*********************************************************************/
  441. /**
  442. * Close opened connection
  443. *
  444. * @return void
  445. * @author Dmitry (dio) Levashov
  446. **/
  447. public function umount() {
  448. }
  449. /**
  450. * Get delta data and DB update
  451. *
  452. * @param boolean $refresh force refresh
  453. * @return true|string error message
  454. */
  455. protected function deltaCheck($refresh = true) {
  456. $chk = false;
  457. if (! $refresh && $chk = $this->query('select dat from '.$this->DB_TableName.' where path=\'\' and fname=\'\' limit 1')) {
  458. $chk = unserialize($chk[0]);
  459. }
  460. if ($chk && ($chk['mtime'] + $this->options['metaCacheTime']) > $_SERVER['REQUEST_TIME']) {
  461. return true;
  462. }
  463. try {
  464. $more = true;
  465. $this->DB->beginTransaction();
  466. if ($res = $this->query('select dat from '.$this->DB_TableName.' where path=\'\' and fname=\'\' limit 1')) {
  467. $res = unserialize($res[0]);
  468. $cursor = $res['cursor'];
  469. } else {
  470. $cursor = '';
  471. }
  472. $delete = false;
  473. $reset = false;
  474. $ptimes = array();
  475. $now = time();
  476. do {
  477. ini_set('max_execution_time', 120);
  478. $_info = $this->dropbox->delta($cursor);
  479. if (! empty($_info['reset'])) {
  480. $this->DB->exec('TRUNCATE table '.$this->DB_TableName);
  481. $this->DB->exec('insert into '.$this->DB_TableName.' values(\'\', \'\', \''.serialize(array('cursor' => '', 'mtime' => 0)).'\', 0);');
  482. $this->DB->exec('insert into '.$this->DB_TableName.' values(\'/\', \'\', \''.serialize(array(
  483. 'path' => '/',
  484. 'is_dir' => 1,
  485. 'mime_type' => '',
  486. 'bytes' => 0
  487. )).'\', 0);');
  488. $reset = true;
  489. }
  490. $cursor = $_info['cursor'];
  491. foreach($_info['entries'] as $entry) {
  492. $key = strtolower($entry[0]);
  493. $pkey = strtolower($this->_dirname($key));
  494. $path = $this->DB->quote($pkey);
  495. $fname = $this->DB->quote(strtolower($this->_basename($key)));
  496. $where = 'where path='.$path.' and fname='.$fname;
  497. if (empty($entry[1])) {
  498. $ptimes[$pkey] = isset($ptimes[$pkey])? max(array($now, $ptimes[$pkey])) : $now;
  499. $this->DB->exec('delete from '.$this->DB_TableName.' '.$where);
  500. ! $delete && $delete = true;
  501. continue;
  502. }
  503. $_itemTime = strtotime(isset($entry[1]['client_mtime'])? $entry[1]['client_mtime'] : $entry[1]['modified']);
  504. $ptimes[$pkey] = isset($ptimes[$pkey])? max(array($_itemTime, $ptimes[$pkey])) : $_itemTime;
  505. $sql = 'select path from '.$this->DB_TableName.' '.$where.' limit 1';
  506. if (! $reset && $this->query($sql)) {
  507. $this->DB->exec('update '.$this->DB_TableName.' set dat='.$this->DB->quote(serialize($entry[1])).', isdir='.($entry[1]['is_dir']? 1 : 0).' ' .$where);
  508. } else {
  509. $this->DB->exec('insert into '.$this->DB_TableName.' values ('.$path.', '.$fname.', '.$this->DB->quote(serialize($entry[1])).', '.(int)$entry[1]['is_dir'].')');
  510. }
  511. }
  512. } while (! empty($_info['has_more']));
  513. // update time stamp of parent holder
  514. foreach ($ptimes as $_p => $_t) {
  515. if ($praw = $this->getDBdat($_p)) {
  516. $_update = false;
  517. if (isset($praw['client_mtime']) && $_t > strtotime($praw['client_mtime'])) {
  518. $praw['client_mtime'] = date('r', $_t);
  519. $_update = true;
  520. }
  521. if (isset($praw['modified']) && $_t > strtotime($praw['modified'])) {
  522. $praw['modified'] = date('r', $_t);
  523. $_update = true;
  524. }
  525. if ($_update) {
  526. $pwhere = 'where path='.$this->DB->quote(strtolower($this->_dirname($_p))).' and fname='.$this->DB->quote(strtolower($this->_basename($_p)));
  527. $this->DB->exec('update '.$this->DB_TableName.' set dat='.$this->DB->quote(serialize($praw)).' '.$pwhere);
  528. }
  529. }
  530. }
  531. $this->DB->exec('update '.$this->DB_TableName.' set dat='.$this->DB->quote(serialize(array('cursor'=>$cursor, 'mtime'=>$_SERVER['REQUEST_TIME']))).' where path=\'\' and fname=\'\'');
  532. if (! $this->DB->commit()) {
  533. $e = $this->DB->errorInfo();
  534. return $e[2];
  535. }
  536. if ($delete) {
  537. $this->DB->exec('vacuum');
  538. }
  539. } catch(Dropbox_Exception $e) {
  540. return $e->getMessage();
  541. }
  542. return true;
  543. }
  544. /**
  545. * Parse line from dropbox metadata output and return file stat (array)
  546. *
  547. * @param string $raw line from ftp_rawlist() output
  548. * @return array
  549. * @author Dmitry Levashov
  550. **/
  551. protected function parseRaw($raw) {
  552. $stat = array();
  553. $stat['rev'] = isset($raw['rev'])? $raw['rev'] : 'root';
  554. $stat['name'] = $this->_basename($raw['path']);
  555. $stat['mime'] = $raw['is_dir']? 'directory' : $raw['mime_type'];
  556. $stat['size'] = $stat['mime'] == 'directory' ? 0 : $raw['bytes'];
  557. $stat['ts'] = isset($raw['client_mtime'])? strtotime($raw['client_mtime']) :
  558. (isset($raw['modified'])? strtotime($raw['modified']) : $_SERVER['REQUEST_TIME']);
  559. $stat['dirs'] = 0;
  560. if ($raw['is_dir']) {
  561. $stat['dirs'] = (int)(bool)$this->query('select path from '.$this->DB_TableName.' where isdir=1 and path='.$this->DB->quote(strtolower($raw['path'])));
  562. }
  563. if (!empty($raw['url'])) {
  564. $stat['url'] = $raw['url'];
  565. } else if (! $this->disabledGetUrl) {
  566. $stat['url'] = '1';
  567. }
  568. if (isset($raw['width'])) $stat['width'] = $raw['width'];
  569. if (isset($raw['height'])) $stat['height'] = $raw['height'];
  570. return $stat;
  571. }
  572. /**
  573. * Cache dir contents
  574. *
  575. * @param string $path dir path
  576. * @return string
  577. * @author Dmitry Levashov
  578. **/
  579. protected function cacheDir($path) {
  580. $this->dirsCache[$path] = array();
  581. $hasDir = false;
  582. $res = $this->query('select dat from '.$this->DB_TableName.' where path='.$this->DB->quote(strtolower($path)));
  583. if ($res) {
  584. foreach($res as $raw) {
  585. $raw = unserialize($raw);
  586. if ($stat = $this->parseRaw($raw)) {
  587. $stat = $this->updateCache($raw['path'], $stat);
  588. if (empty($stat['hidden']) && $path !== $raw['path']) {
  589. if (! $hasDir && $stat['mime'] === 'directory') {
  590. $hasDir = true;
  591. }
  592. $this->dirsCache[$path][] = $raw['path'];
  593. }
  594. }
  595. }
  596. }
  597. if (isset($this->sessionCache['subdirs'])) {
  598. $this->sessionCache['subdirs'][$path] = $hasDir;
  599. }
  600. return $this->dirsCache[$path];
  601. }
  602. /**
  603. * Recursive files search
  604. *
  605. * @param string $path dir path
  606. * @param string $q search string
  607. * @param array $mimes
  608. * @return array
  609. * @author Naoki Sawada
  610. **/
  611. protected function doSearch($path, $q, $mimes) {
  612. $result = array();
  613. $sth = $this->DB->prepare('select dat from '.$this->DB_TableName.' WHERE path LIKE ? AND fname LIKE ?');
  614. $sth->execute(array((($path === '/')? '' : strtolower($path)).'%', '%'.strtolower($q).'%'));
  615. $res = $sth->fetchAll(PDO::FETCH_COLUMN);
  616. $timeout = $this->options['searchTimeout']? $this->searchStart + $this->options['searchTimeout'] : 0;
  617. if ($res) {
  618. foreach($res as $raw) {
  619. if ($timeout && $timeout < time()) {
  620. $this->setError(elFinder::ERROR_SEARCH_TIMEOUT, $this->path($this->encode($path)));
  621. break;
  622. }
  623. $raw = unserialize($raw);
  624. if ($stat = $this->parseRaw($raw)) {
  625. if (!isset($this->cache[$raw['path']])) {
  626. $stat = $this->updateCache($raw['path'], $stat);
  627. }
  628. if (!empty($stat['hidden']) || ($mimes && $stat['mime'] === 'directory') || !$this->mimeAccepted($stat['mime'], $mimes)) {
  629. continue;
  630. }
  631. $stat = $this->stat($raw['path']);
  632. $stat['path'] = $this->path($stat['hash']);
  633. $result[] = $stat;
  634. }
  635. }
  636. }
  637. return $result;
  638. }
  639. /**
  640. * Copy file/recursive copy dir only in current volume.
  641. * Return new file path or false.
  642. *
  643. * @param string $src source path
  644. * @param string $dst destination dir path
  645. * @param string $name new file name (optionaly)
  646. * @return string|false
  647. * @author Dmitry (dio) Levashov
  648. * @author Naoki Sawada
  649. **/
  650. protected function copy($src, $dst, $name) {
  651. $this->clearcache();
  652. return $this->_copy($src, $dst, $name)
  653. ? $this->_joinPath($dst, $name)
  654. : $this->setError(elFinder::ERROR_COPY, $this->_path($src));
  655. }
  656. /**
  657. * Remove file/ recursive remove dir
  658. *
  659. * @param string $path file path
  660. * @param bool $force try to remove even if file locked
  661. * @param bool $recursive
  662. * @return bool
  663. * @author Dmitry (dio) Levashov
  664. * @author Naoki Sawada
  665. */
  666. protected function remove($path, $force = false, $recursive = false) {
  667. $stat = $this->stat($path);
  668. $stat['realpath'] = $path;
  669. $this->rmTmb($stat);
  670. $this->clearcache();
  671. if (empty($stat)) {
  672. return $this->setError(elFinder::ERROR_RM, $this->_path($path), elFinder::ERROR_FILE_NOT_FOUND);
  673. }
  674. if (!$force && !empty($stat['locked'])) {
  675. return $this->setError(elFinder::ERROR_LOCKED, $this->_path($path));
  676. }
  677. if ($stat['mime'] == 'directory') {
  678. if (!$recursive && !$this->_rmdir($path)) {
  679. return $this->setError(elFinder::ERROR_RM, $this->_path($path));
  680. }
  681. } else {
  682. if (!$recursive && !$this->_unlink($path)) {
  683. return $this->setError(elFinder::ERROR_RM, $this->_path($path));
  684. }
  685. }
  686. $this->removed[] = $stat;
  687. return true;
  688. }
  689. /**
  690. * Create thumnbnail and return it's URL on success
  691. *
  692. * @param string $path file path
  693. * @param $stat
  694. * @return false|string
  695. * @internal param string $mime file mime type
  696. * @author Dmitry (dio) Levashov
  697. * @author Naoki Sawada
  698. */
  699. protected function createTmb($path, $stat) {
  700. if (!$stat || !$this->canCreateTmb($path, $stat)) {
  701. return false;
  702. }
  703. $name = $this->tmbname($stat);
  704. $tmb = $this->tmbPath.DIRECTORY_SEPARATOR.$name;
  705. // copy image into tmbPath so some drivers does not store files on local fs
  706. if (! $data = $this->getThumbnail($path, $this->options['getTmbSize'])) {
  707. return false;
  708. }
  709. if (! file_put_contents($tmb, $data)) {
  710. return false;
  711. }
  712. $result = false;
  713. $tmbSize = $this->tmbSize;
  714. if (($s = getimagesize($tmb)) == false) {
  715. return false;
  716. }
  717. /* If image smaller or equal thumbnail size - just fitting to thumbnail square */
  718. if ($s[0] <= $tmbSize && $s[1] <= $tmbSize) {
  719. $result = $this->imgSquareFit($tmb, $tmbSize, $tmbSize, 'center', 'middle', $this->options['tmbBgColor'], 'png' );
  720. } else {
  721. if ($this->options['tmbCrop']) {
  722. /* Resize and crop if image bigger than thumbnail */
  723. if (!(($s[0] > $tmbSize && $s[1] <= $tmbSize) || ($s[0] <= $tmbSize && $s[1] > $tmbSize) ) || ($s[0] > $tmbSize && $s[1] > $tmbSize)) {
  724. $result = $this->imgResize($tmb, $tmbSize, $tmbSize, true, false, 'png');
  725. }
  726. if (($s = getimagesize($tmb)) != false) {
  727. $x = $s[0] > $tmbSize ? intval(($s[0] - $tmbSize)/2) : 0;
  728. $y = $s[1] > $tmbSize ? intval(($s[1] - $tmbSize)/2) : 0;
  729. $result = $this->imgCrop($tmb, $tmbSize, $tmbSize, $x, $y, 'png');
  730. }
  731. } else {
  732. $result = $this->imgResize($tmb, $tmbSize, $tmbSize, true, true, 'png');
  733. }
  734. $result = $this->imgSquareFit($tmb, $tmbSize, $tmbSize, 'center', 'middle', $this->options['tmbBgColor'], 'png' );
  735. }
  736. if (!$result) {
  737. unlink($tmb);
  738. return false;
  739. }
  740. return $name;
  741. }
  742. /**
  743. * Return thumbnail file name for required file
  744. *
  745. * @param array $stat file stat
  746. * @return string
  747. * @author Dmitry (dio) Levashov
  748. **/
  749. protected function tmbname($stat) {
  750. return $this->tmbPrefix.$stat['rev'].'.png';
  751. }
  752. /**
  753. * Get thumbnail from dropbox.com
  754. * @param string $path
  755. * @param string $size
  756. * @return string | boolean
  757. */
  758. protected function getThumbnail($path, $size = 'small') {
  759. try {
  760. return $this->dropbox->getThumbnail($path, $size);
  761. } catch (Dropbox_Exception $e) {
  762. return false;
  763. }
  764. }
  765. /**
  766. * Return content URL
  767. *
  768. * @param string $hash file hash
  769. * @param array $options options
  770. * @return array
  771. * @author Naoki Sawada
  772. **/
  773. public function getContentUrl($hash, $options = array()) {
  774. if (($file = $this->file($hash)) == false || !$file['url'] || $file['url'] == 1) {
  775. $path = $this->decode($hash);
  776. $cache = $this->getDBdat($path);
  777. $url = '';
  778. if (isset($cache['share']) && strpos($cache['share'], $this->dropbox_dlhost) !== false) {
  779. $res = $this->getHttpResponseHeader($cache['share']);
  780. if (preg_match("/^HTTP\/[01\.]+ ([0-9]{3})/", $res, $match)) {
  781. if ($match[1] < 400) {
  782. $url = $cache['share'];
  783. }
  784. }
  785. }
  786. if (! $url) {
  787. try {
  788. $res = $this->dropbox->share($path, null, false);
  789. $url = $res['url'];
  790. if (strpos($url, 'www.dropbox.com') === false) {
  791. $res = $this->getHttpResponseHeader($url);
  792. if (preg_match('/^location:\s*(http[^\s]+)/im', $res, $match)) {
  793. $url = $match[1];
  794. }
  795. }
  796. list($url) = explode('?', $url);
  797. $url = str_replace('www.dropbox.com', $this->dropbox_dlhost, $url);
  798. if (! isset($cache['share']) || $cache['share'] !== $url) {
  799. $cache['share'] = $url;
  800. $this->updateDBdat($path, $cache);
  801. }
  802. } catch (Dropbox_Exception $e) {
  803. return false;
  804. }
  805. }
  806. return $url;
  807. }
  808. return $file['url'];
  809. }
  810. /**
  811. * Get HTTP request response header string
  812. *
  813. * @param string $url target URL
  814. * @return string
  815. * @author Naoki Sawada
  816. */
  817. private function getHttpResponseHeader($url) {
  818. if (function_exists('curl_exec')) {
  819. $c = curl_init();
  820. curl_setopt( $c, CURLOPT_RETURNTRANSFER, true );
  821. curl_setopt( $c, CURLOPT_CUSTOMREQUEST, 'HEAD' );
  822. curl_setopt( $c, CURLOPT_HEADER, 1 );
  823. curl_setopt( $c, CURLOPT_NOBODY, true );
  824. curl_setopt( $c, CURLOPT_URL, $url );
  825. $res = curl_exec( $c );
  826. } else {
  827. require_once 'HTTP/Request2.php';
  828. try {
  829. $request2 = new HTTP_Request2();
  830. $request2->setConfig(array(
  831. 'ssl_verify_peer' => false,
  832. 'ssl_verify_host' => false
  833. ));
  834. $request2->setUrl($url);
  835. $request2->setMethod(HTTP_Request2::METHOD_HEAD);
  836. $result = $request2->send();
  837. $res = array();
  838. $res[] = 'HTTP/'.$result->getVersion().' '.$result->getStatus().' '.$result->getReasonPhrase();
  839. foreach($result->getHeader() as $key => $val) {
  840. $res[] = $key . ': ' . $val;
  841. }
  842. $res = join("\r\n", $res);
  843. } catch( HTTP_Request2_Exception $e ){
  844. $res = '';
  845. } catch (Exception $e){
  846. $res = '';
  847. }
  848. }
  849. return $res;
  850. }
  851. /*********************** paths/urls *************************/
  852. /**
  853. * Return parent directory path
  854. *
  855. * @param string $path file path
  856. * @return string
  857. * @author Dmitry (dio) Levashov
  858. **/
  859. protected function _dirname($path) {
  860. return $this->_normpath(substr($path, 0, strrpos($path, '/')));
  861. }
  862. /**
  863. * Return file name
  864. *
  865. * @param string $path file path
  866. * @return string
  867. * @author Dmitry (dio) Levashov
  868. **/
  869. protected function _basename($path) {
  870. return substr($path, strrpos($path, '/') + 1);
  871. }
  872. /**
  873. * Join dir name and file name and retur full path
  874. *
  875. * @param string $dir
  876. * @param string $name
  877. * @return string
  878. * @author Dmitry (dio) Levashov
  879. **/
  880. protected function _joinPath($dir, $name) {
  881. return $this->_normpath($dir.'/'.$name);
  882. }
  883. /**
  884. * Return normalized path, this works the same as os.path.normpath() in Python
  885. *
  886. * @param string $path path
  887. * @return string
  888. * @author Troex Nevelin
  889. **/
  890. protected function _normpath($path) {
  891. $path = '/' . ltrim($path, '/');
  892. return $path;
  893. }
  894. /**
  895. * Return file path related to root dir
  896. *
  897. * @param string $path file path
  898. * @return string
  899. * @author Dmitry (dio) Levashov
  900. **/
  901. protected function _relpath($path) {
  902. return $path;
  903. }
  904. /**
  905. * Convert path related to root dir into real path
  906. *
  907. * @param string $path file path
  908. * @return string
  909. * @author Dmitry (dio) Levashov
  910. **/
  911. protected function _abspath($path) {
  912. return $path;
  913. }
  914. /**
  915. * Return fake path started from root dir
  916. *
  917. * @param string $path file path
  918. * @return string
  919. * @author Dmitry (dio) Levashov
  920. **/
  921. protected function _path($path) {
  922. return $this->rootName . $this->_normpath(substr($path, strlen($this->root)));
  923. }
  924. /**
  925. * Return true if $path is children of $parent
  926. *
  927. * @param string $path path to check
  928. * @param string $parent parent path
  929. * @return bool
  930. * @author Dmitry (dio) Levashov
  931. **/
  932. protected function _inpath($path, $parent) {
  933. return $path == $parent || strpos($path, $parent.'/') === 0;
  934. }
  935. /***************** file stat ********************/
  936. /**
  937. * Return stat for given path.
  938. * Stat contains following fields:
  939. * - (int) size file size in b. required
  940. * - (int) ts file modification time in unix time. required
  941. * - (string) mime mimetype. required for folders, others - optionally
  942. * - (bool) read read permissions. required
  943. * - (bool) write write permissions. required
  944. * - (bool) locked is object locked. optionally
  945. * - (bool) hidden is object hidden. optionally
  946. * - (string) alias for symlinks - link target path relative to root path. optionally
  947. * - (string) target for symlinks - link target path. optionally
  948. *
  949. * If file does not exists - returns empty array or false.
  950. *
  951. * @param string $path file path
  952. * @return array|false
  953. * @author Dmitry (dio) Levashov
  954. **/
  955. protected function _stat($path) {
  956. //if (!empty($this->ARGS['reload']) && isset($this->ARGS['target']) && strpos($this->ARGS['target'], $this->id) === 0) {
  957. if ($this->isMyReload()) {
  958. $this->deltaCheck();
  959. }
  960. if ($raw = $this->getDBdat($path)) {
  961. return $this->parseRaw($raw);
  962. }
  963. return false;
  964. }
  965. /**
  966. * Return true if path is dir and has at least one childs directory
  967. *
  968. * @param string $path dir path
  969. * @return bool
  970. * @author Dmitry (dio) Levashov
  971. **/
  972. protected function _subdirs($path) {
  973. return ($stat = $this->stat($path)) && isset($stat['dirs']) ? $stat['dirs'] : false;
  974. }
  975. /**
  976. * Return object width and height
  977. * Ususaly used for images, but can be realize for video etc...
  978. *
  979. * @param string $path file path
  980. * @param string $mime file mime type
  981. * @return string
  982. * @author Dmitry (dio) Levashov
  983. **/
  984. protected function _dimensions($path, $mime) {
  985. if (strpos($mime, 'image') !== 0) return '';
  986. $cache = $this->getDBdat($path);
  987. if (isset($cache['width']) && isset($cache['height'])) {
  988. return $cache['width'].'x'.$cache['height'];
  989. }
  990. $ret = '';
  991. if ($work = $this->getWorkFile($path)) {
  992. if ($size = getimagesize($work)) {
  993. $cache['width'] = $size[0];
  994. $cache['height'] = $size[1];
  995. $this->updateDBdat($path, $cache);
  996. $ret = $size[0].'x'.$size[1];
  997. }
  998. }
  999. is_file($work) && unlink($work);
  1000. return $ret;
  1001. }
  1002. /******************** file/dir content *********************/
  1003. /**
  1004. * Return files list in directory.
  1005. *
  1006. * @param string $path dir path
  1007. * @return array
  1008. * @author Dmitry (dio) Levashov
  1009. * @author Cem (DiscoFever)
  1010. **/
  1011. protected function _scandir($path) {
  1012. return isset($this->dirsCache[$path])
  1013. ? $this->dirsCache[$path]
  1014. : $this->cacheDir($path);
  1015. }
  1016. /**
  1017. * Open file and return file pointer
  1018. *
  1019. * @param string $path file path
  1020. * @param string $mode
  1021. * @return false|resource
  1022. * @internal param bool $write open file for writing
  1023. * @author Dmitry (dio) Levashov
  1024. */
  1025. protected function _fopen($path, $mode='rb') {
  1026. if (($mode == 'rb' || $mode == 'r')) {
  1027. try {
  1028. $res = $this->dropbox->media($path);
  1029. $url = parse_url($res['url']);
  1030. $fp = stream_socket_client('ssl://'.$url['host'].':443');
  1031. fputs($fp, "GET {$url['path']} HTTP/1.0\r\n");
  1032. fputs($fp, "Host: {$url['host']}\r\n");
  1033. fputs($fp, "\r\n");
  1034. while(trim(fgets($fp)) !== ''){};
  1035. return $fp;
  1036. } catch (Dropbox_Exception $e) {
  1037. return false;
  1038. }
  1039. }
  1040. if ($this->tmp) {
  1041. $contents = $this->_getContents($path);
  1042. if ($contents === false) {
  1043. return false;
  1044. }
  1045. if ($local = $this->getTempFile($path)) {
  1046. if (file_put_contents($local, $contents, LOCK_EX) !== false) {
  1047. return fopen($local, $mode);
  1048. }
  1049. }
  1050. }
  1051. return false;
  1052. }
  1053. /**
  1054. * Close opened file
  1055. *
  1056. * @param resource $fp file pointer
  1057. * @param string $path
  1058. * @return bool
  1059. * @author Dmitry (dio) Levashov
  1060. */
  1061. protected function _fclose($fp, $path='') {
  1062. fclose($fp);
  1063. if ($path) {
  1064. unlink($this->getTempFile($path));
  1065. }
  1066. }
  1067. /******************** file/dir manipulations *************************/
  1068. /**
  1069. * Create dir and return created dir path or false on failed
  1070. *
  1071. * @param string $path parent dir path
  1072. * @param string $name new directory name
  1073. * @return string|bool
  1074. * @author Dmitry (dio) Levashov
  1075. **/
  1076. protected function _mkdir($path, $name) {
  1077. $path = $this->_normpath($path.'/'.$name);
  1078. try {
  1079. $this->dropbox->createFolder($path);
  1080. } catch (Dropbox_Exception $e) {
  1081. $this->deltaCheck();
  1082. if ($this->dir($this->encode($path))) {
  1083. return $path;
  1084. }
  1085. return $this->setError('Dropbox error: '.$e->getMessage());
  1086. }
  1087. $this->deltaCheck();
  1088. return $path;
  1089. }
  1090. /**
  1091. * Create file and return it's path or false on failed
  1092. *
  1093. * @param string $path parent dir path
  1094. * @param string $name new file name
  1095. * @return string|bool
  1096. * @author Dmitry (dio) Levashov
  1097. **/
  1098. protected function _mkfile($path, $name) {
  1099. return $this->_filePutContents($path.'/'.$name, '');
  1100. }
  1101. /**
  1102. * Create symlink. FTP driver does not support symlinks.
  1103. *
  1104. * @param string $target link target
  1105. * @param string $path symlink path
  1106. * @param string $name
  1107. * @return bool
  1108. * @author Dmitry (dio) Levashov
  1109. */
  1110. protected function _symlink($target, $path, $name) {
  1111. return false;
  1112. }
  1113. /**
  1114. * Copy file into another file
  1115. *
  1116. * @param string $source source file path
  1117. * @param string $targetDir target directory path
  1118. * @param string $name new file name
  1119. * @return bool
  1120. * @author Dmitry (dio) Levashov
  1121. **/
  1122. protected function _copy($source, $targetDir, $name) {
  1123. $path = $this->_normpath($targetDir.'/'.$name);
  1124. try {
  1125. $this->dropbox->copy($source, $path);
  1126. } catch (Dropbox_Exception $e) {
  1127. return $this->setError('Dropbox error: '.$e->getMessage());
  1128. }
  1129. $this->deltaCheck();
  1130. return true;
  1131. }
  1132. /**
  1133. * Move file into another parent dir.
  1134. * Return new file path or false.
  1135. *
  1136. * @param string $source source file path
  1137. * @param $targetDir
  1138. * @param string $name file name
  1139. * @return bool|string
  1140. * @internal param string $target target dir path
  1141. * @author Dmitry (dio) Levashov
  1142. */
  1143. protected function _move($source, $targetDir, $name) {
  1144. $target = $this->_normpath($targetDir.'/'.$name);
  1145. try {
  1146. $this->dropbox->move($source, $target);
  1147. } catch (Dropbox_Exception $e) {
  1148. return $this->setError('Dropbox error: '.$e->getMessage());
  1149. }
  1150. $this->deltaCheck();
  1151. return $target;
  1152. }
  1153. /**
  1154. * Remove file
  1155. *
  1156. * @param string $path file path
  1157. * @return bool
  1158. * @author Dmitry (dio) Levashov
  1159. **/
  1160. protected function _unlink($path) {
  1161. try {
  1162. $this->dropbox->delete($path);
  1163. } catch (Dropbox_Exception $e) {
  1164. return $this->setError('Dropbox error: '.$e->getMessage());
  1165. }
  1166. $this->deltaCheck();
  1167. return true;
  1168. }
  1169. /**
  1170. * Remove dir
  1171. *
  1172. * @param string $path dir path
  1173. * @return bool
  1174. * @author Dmitry (dio) Levashov
  1175. **/
  1176. protected function _rmdir($path) {
  1177. return $this->_unlink($path);
  1178. }
  1179. /**
  1180. * Create new file and write into it from file pointer.
  1181. * Return new file path or false on error.
  1182. *
  1183. * @param resource $fp file pointer
  1184. * @param string $path
  1185. * @param string $name file name
  1186. * @param array $stat file stat (required by some virtual fs)
  1187. * @return bool|string
  1188. * @internal param string $dir target dir path
  1189. * @author Dmitry (dio) Levashov
  1190. */
  1191. protected function _save($fp, $path, $name, $stat) {
  1192. if ($name) $path .= '/'.$name;
  1193. $path = $this->_normpath($path);
  1194. try {
  1195. $this->dropbox->putFile($path, $fp);
  1196. } catch (Dropbox_Exception $e) {
  1197. return $this->setError('Dropbox error: '.$e->getMessage());
  1198. }
  1199. $this->deltaCheck();
  1200. if (is_array($stat)) {
  1201. $raw = $this->getDBdat($path);
  1202. if (isset($stat['width'])) $raw['width'] = $stat['width'];
  1203. if (isset($stat['height'])) $raw['height'] = $stat['height'];
  1204. $this->updateDBdat($path, $raw);
  1205. }
  1206. return $path;
  1207. }
  1208. /**
  1209. * Get file contents
  1210. *
  1211. * @param string $path file path
  1212. * @return string|false
  1213. * @author Dmitry (dio) Levashov
  1214. **/
  1215. protected function _getContents($path) {
  1216. $contents = '';
  1217. try {
  1218. $contents = $this->dropbox->getFile($path);
  1219. } catch (Dropbox_Exception $e) {
  1220. return $this->setError('Dropbox error: '.$e->getMessage());
  1221. }
  1222. return $contents;
  1223. }
  1224. /**
  1225. * Write a string to a file
  1226. *
  1227. * @param string $path file path
  1228. * @param string $content new file content
  1229. * @return bool
  1230. * @author Dmitry (dio) Levashov
  1231. **/
  1232. protected function _filePutContents($path, $content) {
  1233. $res = false;
  1234. if ($local = $this->getTempFile($path)) {
  1235. if (file_put_contents($local, $content, LOCK_EX) !== false
  1236. && ($fp = fopen($local, 'rb'))) {
  1237. clearstatcache();
  1238. $res = $this->_save($fp, $path, '', array());
  1239. fclose($fp);
  1240. }
  1241. file_exists($local) && unlink($local);
  1242. }
  1243. return $res;
  1244. }
  1245. /**
  1246. * Detect available archivers
  1247. *
  1248. * @return array
  1249. **/
  1250. protected function _checkArchivers() {
  1251. // die('Not yet implemented. (_checkArchivers)');
  1252. return array();
  1253. }
  1254. /**
  1255. * chmod implementation
  1256. *
  1257. * @param string $path
  1258. * @param string $mode
  1259. * @return bool
  1260. */
  1261. protected function _chmod($path, $mode) {
  1262. return false;
  1263. }
  1264. /**
  1265. * Unpack archive
  1266. *
  1267. * @param string $path archive path
  1268. * @param array $arc archiver command and arguments (same as in $this->archivers)
  1269. * @return true
  1270. * @return void
  1271. * @author Dmitry (dio) Levashov
  1272. * @author Alexey Sukhotin
  1273. **/
  1274. protected function _unpack($path, $arc) {
  1275. die('Not yet implemented. (_unpack)');
  1276. }
  1277. /**
  1278. * Recursive symlinks search
  1279. *
  1280. * @param string $path file/dir path
  1281. * @return bool
  1282. * @author Dmitry (dio) Levashov
  1283. **/
  1284. protected function _findSymlinks($path) {
  1285. die('Not yet implemented. (_findSymlinks)');
  1286. }
  1287. /**
  1288. * Extract files from archive
  1289. *
  1290. * @param string $path archive path
  1291. * @param array $arc archiver command and arguments (same as in $this->archivers)
  1292. * @return true
  1293. * @author Dmitry (dio) Levashov,
  1294. * @author Alexey Sukhotin
  1295. **/
  1296. protected function _extract($path, $arc) {
  1297. die('Not yet implemented. (_extract)');
  1298. }
  1299. /**
  1300. * Create archive and return its path
  1301. *
  1302. * @param string $dir target dir
  1303. * @param array $files files names list
  1304. * @param string $name archive name
  1305. * @param array $arc archiver options
  1306. * @return string|bool
  1307. * @author Dmitry (dio) Levashov,
  1308. * @author Alexey Sukhotin
  1309. **/
  1310. protected function _archive($dir, $files, $name, $arc) {
  1311. die('Not yet implemented. (_archive)');
  1312. }
  1313. } // END class