PageRenderTime 55ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/library/Zend/File/Transfer/Adapter/Abstract.php

https://bitbucket.org/imaweda/jelly2
PHP | 1563 lines | 920 code | 179 blank | 464 comment | 185 complexity | d9fc0262452a3107fcfd043e75b69a2b MD5 | raw file
Possible License(s): BSD-3-Clause
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Zend
  16. * @package Zend_File_Transfer
  17. * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
  18. * @license http://framework.zend.com/license/new-bsd New BSD License
  19. * @version $Id: Abstract.php 23775 2011-03-01 17:25:24Z ralph $
  20. */
  21. /**
  22. * Abstract class for file transfers (Downloads and Uploads)
  23. *
  24. * @category Zend
  25. * @package Zend_File_Transfer
  26. * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
  27. * @license http://framework.zend.com/license/new-bsd New BSD License
  28. */
  29. abstract class Zend_File_Transfer_Adapter_Abstract
  30. {
  31. /**@+
  32. * Plugin loader Constants
  33. */
  34. const FILTER = 'FILTER';
  35. const VALIDATE = 'VALIDATE';
  36. /**@-*/
  37. /**
  38. * Internal list of breaks
  39. *
  40. * @var array
  41. */
  42. protected $_break = array();
  43. /**
  44. * Internal list of filters
  45. *
  46. * @var array
  47. */
  48. protected $_filters = array();
  49. /**
  50. * Plugin loaders for filter and validation chains
  51. *
  52. * @var array
  53. */
  54. protected $_loaders = array();
  55. /**
  56. * Internal list of messages
  57. *
  58. * @var array
  59. */
  60. protected $_messages = array();
  61. /**
  62. * @var Zend_Translate
  63. */
  64. protected $_translator;
  65. /**
  66. * Is translation disabled?
  67. *
  68. * @var bool
  69. */
  70. protected $_translatorDisabled = false;
  71. /**
  72. * Internal list of validators
  73. * @var array
  74. */
  75. protected $_validators = array();
  76. /**
  77. * Internal list of files
  78. * This array looks like this:
  79. * array(form => array( - Form is the name within the form or, if not set the filename
  80. * name, - Original name of this file
  81. * type, - Mime type of this file
  82. * size, - Filesize in bytes
  83. * tmp_name, - Internalally temporary filename for uploaded files
  84. * error, - Error which has occured
  85. * destination, - New destination for this file
  86. * validators, - Set validator names for this file
  87. * files - Set file names for this file
  88. * ))
  89. *
  90. * @var array
  91. */
  92. protected $_files = array();
  93. /**
  94. * TMP directory
  95. * @var string
  96. */
  97. protected $_tmpDir;
  98. /**
  99. * Available options for file transfers
  100. */
  101. protected $_options = array(
  102. 'ignoreNoFile' => false,
  103. 'useByteString' => true,
  104. 'magicFile' => null,
  105. 'detectInfos' => true,
  106. );
  107. /**
  108. * Send file
  109. *
  110. * @param mixed $options
  111. * @return bool
  112. */
  113. abstract public function send($options = null);
  114. /**
  115. * Receive file
  116. *
  117. * @param mixed $options
  118. * @return bool
  119. */
  120. abstract public function receive($options = null);
  121. /**
  122. * Is file sent?
  123. *
  124. * @param array|string|null $files
  125. * @return bool
  126. */
  127. abstract public function isSent($files = null);
  128. /**
  129. * Is file received?
  130. *
  131. * @param array|string|null $files
  132. * @return bool
  133. */
  134. abstract public function isReceived($files = null);
  135. /**
  136. * Has a file been uploaded ?
  137. *
  138. * @param array|string|null $files
  139. * @return bool
  140. */
  141. abstract public function isUploaded($files = null);
  142. /**
  143. * Has the file been filtered ?
  144. *
  145. * @param array|string|null $files
  146. * @return bool
  147. */
  148. abstract public function isFiltered($files = null);
  149. /**
  150. * Retrieve progress of transfer
  151. *
  152. * @return float
  153. */
  154. public static function getProgress()
  155. {
  156. require_once 'Zend/File/Transfer/Exception.php';
  157. throw new Zend_File_Transfer_Exception('Method must be implemented within the adapter');
  158. }
  159. /**
  160. * Set plugin loader to use for validator or filter chain
  161. *
  162. * @param Zend_Loader_PluginLoader_Interface $loader
  163. * @param string $type 'filter', or 'validate'
  164. * @return Zend_File_Transfer_Adapter_Abstract
  165. * @throws Zend_File_Transfer_Exception on invalid type
  166. */
  167. public function setPluginLoader(Zend_Loader_PluginLoader_Interface $loader, $type)
  168. {
  169. $type = strtoupper($type);
  170. switch ($type) {
  171. case self::FILTER:
  172. case self::VALIDATE:
  173. $this->_loaders[$type] = $loader;
  174. return $this;
  175. default:
  176. require_once 'Zend/File/Transfer/Exception.php';
  177. throw new Zend_File_Transfer_Exception(sprintf('Invalid type "%s" provided to setPluginLoader()', $type));
  178. }
  179. }
  180. /**
  181. * Retrieve plugin loader for validator or filter chain
  182. *
  183. * Instantiates with default rules if none available for that type. Use
  184. * 'filter' or 'validate' for $type.
  185. *
  186. * @param string $type
  187. * @return Zend_Loader_PluginLoader
  188. * @throws Zend_File_Transfer_Exception on invalid type.
  189. */
  190. public function getPluginLoader($type)
  191. {
  192. $type = strtoupper($type);
  193. switch ($type) {
  194. case self::FILTER:
  195. case self::VALIDATE:
  196. $prefixSegment = ucfirst(strtolower($type));
  197. $pathSegment = $prefixSegment;
  198. if (!isset($this->_loaders[$type])) {
  199. $paths = array(
  200. 'Zend_' . $prefixSegment . '_' => 'Zend/' . $pathSegment . '/',
  201. 'Zend_' . $prefixSegment . '_File' => 'Zend/' . $pathSegment . '/File',
  202. );
  203. require_once 'Zend/Loader/PluginLoader.php';
  204. $this->_loaders[$type] = new Zend_Loader_PluginLoader($paths);
  205. } else {
  206. $loader = $this->_loaders[$type];
  207. $prefix = 'Zend_' . $prefixSegment . '_File_';
  208. if (!$loader->getPaths($prefix)) {
  209. $loader->addPrefixPath($prefix, str_replace('_', '/', $prefix));
  210. }
  211. }
  212. return $this->_loaders[$type];
  213. default:
  214. require_once 'Zend/File/Transfer/Exception.php';
  215. throw new Zend_File_Transfer_Exception(sprintf('Invalid type "%s" provided to getPluginLoader()', $type));
  216. }
  217. }
  218. /**
  219. * Add prefix path for plugin loader
  220. *
  221. * If no $type specified, assumes it is a base path for both filters and
  222. * validators, and sets each according to the following rules:
  223. * - filters: $prefix = $prefix . '_Filter'
  224. * - validators: $prefix = $prefix . '_Validate'
  225. *
  226. * Otherwise, the path prefix is set on the appropriate plugin loader.
  227. *
  228. * @param string $prefix
  229. * @param string $path
  230. * @param string $type
  231. * @return Zend_File_Transfer_Adapter_Abstract
  232. * @throws Zend_File_Transfer_Exception for invalid type
  233. */
  234. public function addPrefixPath($prefix, $path, $type = null)
  235. {
  236. $type = strtoupper($type);
  237. switch ($type) {
  238. case self::FILTER:
  239. case self::VALIDATE:
  240. $loader = $this->getPluginLoader($type);
  241. $loader->addPrefixPath($prefix, $path);
  242. return $this;
  243. case null:
  244. $prefix = rtrim($prefix, '_');
  245. $path = rtrim($path, DIRECTORY_SEPARATOR);
  246. foreach (array(self::FILTER, self::VALIDATE) as $type) {
  247. $cType = ucfirst(strtolower($type));
  248. $pluginPath = $path . DIRECTORY_SEPARATOR . $cType . DIRECTORY_SEPARATOR;
  249. $pluginPrefix = $prefix . '_' . $cType;
  250. $loader = $this->getPluginLoader($type);
  251. $loader->addPrefixPath($pluginPrefix, $pluginPath);
  252. }
  253. return $this;
  254. default:
  255. require_once 'Zend/File/Transfer/Exception.php';
  256. throw new Zend_File_Transfer_Exception(sprintf('Invalid type "%s" provided to getPluginLoader()', $type));
  257. }
  258. }
  259. /**
  260. * Add many prefix paths at once
  261. *
  262. * @param array $spec
  263. * @return Zend_File_Transfer_Exception
  264. */
  265. public function addPrefixPaths(array $spec)
  266. {
  267. if (isset($spec['prefix']) && isset($spec['path'])) {
  268. return $this->addPrefixPath($spec['prefix'], $spec['path']);
  269. }
  270. foreach ($spec as $type => $paths) {
  271. if (is_numeric($type) && is_array($paths)) {
  272. $type = null;
  273. if (isset($paths['prefix']) && isset($paths['path'])) {
  274. if (isset($paths['type'])) {
  275. $type = $paths['type'];
  276. }
  277. $this->addPrefixPath($paths['prefix'], $paths['path'], $type);
  278. }
  279. } elseif (!is_numeric($type)) {
  280. if (!isset($paths['prefix']) || !isset($paths['path'])) {
  281. foreach ($paths as $prefix => $spec) {
  282. if (is_array($spec)) {
  283. foreach ($spec as $path) {
  284. if (!is_string($path)) {
  285. continue;
  286. }
  287. $this->addPrefixPath($prefix, $path, $type);
  288. }
  289. } elseif (is_string($spec)) {
  290. $this->addPrefixPath($prefix, $spec, $type);
  291. }
  292. }
  293. } else {
  294. $this->addPrefixPath($paths['prefix'], $paths['path'], $type);
  295. }
  296. }
  297. }
  298. return $this;
  299. }
  300. /**
  301. * Adds a new validator for this class
  302. *
  303. * @param string|array $validator Type of validator to add
  304. * @param boolean $breakChainOnFailure If the validation chain should stop an failure
  305. * @param string|array $options Options to set for the validator
  306. * @param string|array $files Files to limit this validator to
  307. * @return Zend_File_Transfer_Adapter
  308. */
  309. public function addValidator($validator, $breakChainOnFailure = false, $options = null, $files = null)
  310. {
  311. if ($validator instanceof Zend_Validate_Interface) {
  312. $name = get_class($validator);
  313. } elseif (is_string($validator)) {
  314. $name = $this->getPluginLoader(self::VALIDATE)->load($validator);
  315. $validator = new $name($options);
  316. if (is_array($options) && isset($options['messages'])) {
  317. if (is_array($options['messages'])) {
  318. $validator->setMessages($options['messages']);
  319. } elseif (is_string($options['messages'])) {
  320. $validator->setMessage($options['messages']);
  321. }
  322. unset($options['messages']);
  323. }
  324. } else {
  325. require_once 'Zend/File/Transfer/Exception.php';
  326. throw new Zend_File_Transfer_Exception('Invalid validator provided to addValidator; must be string or Zend_Validate_Interface');
  327. }
  328. $this->_validators[$name] = $validator;
  329. $this->_break[$name] = $breakChainOnFailure;
  330. $files = $this->_getFiles($files, true, true);
  331. foreach ($files as $file) {
  332. if ($name == 'NotEmpty') {
  333. $temp = $this->_files[$file]['validators'];
  334. $this->_files[$file]['validators'] = array($name);
  335. $this->_files[$file]['validators'] += $temp;
  336. } else {
  337. $this->_files[$file]['validators'][] = $name;
  338. }
  339. $this->_files[$file]['validated'] = false;
  340. }
  341. return $this;
  342. }
  343. /**
  344. * Add Multiple validators at once
  345. *
  346. * @param array $validators
  347. * @param string|array $files
  348. * @return Zend_File_Transfer_Adapter_Abstract
  349. */
  350. public function addValidators(array $validators, $files = null)
  351. {
  352. foreach ($validators as $name => $validatorInfo) {
  353. if ($validatorInfo instanceof Zend_Validate_Interface) {
  354. $this->addValidator($validatorInfo, null, null, $files);
  355. } else if (is_string($validatorInfo)) {
  356. if (!is_int($name)) {
  357. $this->addValidator($name, null, $validatorInfo, $files);
  358. } else {
  359. $this->addValidator($validatorInfo, null, null, $files);
  360. }
  361. } else if (is_array($validatorInfo)) {
  362. $argc = count($validatorInfo);
  363. $breakChainOnFailure = false;
  364. $options = array();
  365. if (isset($validatorInfo['validator'])) {
  366. $validator = $validatorInfo['validator'];
  367. if (isset($validatorInfo['breakChainOnFailure'])) {
  368. $breakChainOnFailure = $validatorInfo['breakChainOnFailure'];
  369. }
  370. if (isset($validatorInfo['options'])) {
  371. $options = $validatorInfo['options'];
  372. }
  373. $this->addValidator($validator, $breakChainOnFailure, $options, $files);
  374. } else {
  375. if (is_string($name)) {
  376. $validator = $name;
  377. $options = $validatorInfo;
  378. $this->addValidator($validator, $breakChainOnFailure, $options, $files);
  379. } else {
  380. $file = $files;
  381. switch (true) {
  382. case (0 == $argc):
  383. break;
  384. case (1 <= $argc):
  385. $validator = array_shift($validatorInfo);
  386. case (2 <= $argc):
  387. $breakChainOnFailure = array_shift($validatorInfo);
  388. case (3 <= $argc):
  389. $options = array_shift($validatorInfo);
  390. case (4 <= $argc):
  391. if (!empty($validatorInfo)) {
  392. $file = array_shift($validatorInfo);
  393. }
  394. default:
  395. $this->addValidator($validator, $breakChainOnFailure, $options, $file);
  396. break;
  397. }
  398. }
  399. }
  400. } else {
  401. require_once 'Zend/File/Transfer/Exception.php';
  402. throw new Zend_File_Transfer_Exception('Invalid validator passed to addValidators()');
  403. }
  404. }
  405. return $this;
  406. }
  407. /**
  408. * Sets a validator for the class, erasing all previous set
  409. *
  410. * @param string|array $validator Validator to set
  411. * @param string|array $files Files to limit this validator to
  412. * @return Zend_File_Transfer_Adapter
  413. */
  414. public function setValidators(array $validators, $files = null)
  415. {
  416. $this->clearValidators();
  417. return $this->addValidators($validators, $files);
  418. }
  419. /**
  420. * Determine if a given validator has already been registered
  421. *
  422. * @param string $name
  423. * @return bool
  424. */
  425. public function hasValidator($name)
  426. {
  427. return (false !== $this->_getValidatorIdentifier($name));
  428. }
  429. /**
  430. * Retrieve individual validator
  431. *
  432. * @param string $name
  433. * @return Zend_Validate_Interface|null
  434. */
  435. public function getValidator($name)
  436. {
  437. if (false === ($identifier = $this->_getValidatorIdentifier($name))) {
  438. return null;
  439. }
  440. return $this->_validators[$identifier];
  441. }
  442. /**
  443. * Returns all set validators
  444. *
  445. * @param string|array $files (Optional) Returns the validator for this files
  446. * @return null|array List of set validators
  447. */
  448. public function getValidators($files = null)
  449. {
  450. if ($files == null) {
  451. return $this->_validators;
  452. }
  453. $files = $this->_getFiles($files, true, true);
  454. $validators = array();
  455. foreach ($files as $file) {
  456. if (!empty($this->_files[$file]['validators'])) {
  457. $validators += $this->_files[$file]['validators'];
  458. }
  459. }
  460. $validators = array_unique($validators);
  461. $result = array();
  462. foreach ($validators as $validator) {
  463. $result[$validator] = $this->_validators[$validator];
  464. }
  465. return $result;
  466. }
  467. /**
  468. * Remove an individual validator
  469. *
  470. * @param string $name
  471. * @return Zend_File_Transfer_Adapter_Abstract
  472. */
  473. public function removeValidator($name)
  474. {
  475. if (false === ($key = $this->_getValidatorIdentifier($name))) {
  476. return $this;
  477. }
  478. unset($this->_validators[$key]);
  479. foreach (array_keys($this->_files) as $file) {
  480. if (empty($this->_files[$file]['validators'])) {
  481. continue;
  482. }
  483. $index = array_search($key, $this->_files[$file]['validators']);
  484. if ($index === false) {
  485. continue;
  486. }
  487. unset($this->_files[$file]['validators'][$index]);
  488. $this->_files[$file]['validated'] = false;
  489. }
  490. return $this;
  491. }
  492. /**
  493. * Remove all validators
  494. *
  495. * @return Zend_File_Transfer_Adapter_Abstract
  496. */
  497. public function clearValidators()
  498. {
  499. $this->_validators = array();
  500. foreach (array_keys($this->_files) as $file) {
  501. $this->_files[$file]['validators'] = array();
  502. $this->_files[$file]['validated'] = false;
  503. }
  504. return $this;
  505. }
  506. /**
  507. * Sets Options for adapters
  508. *
  509. * @param array $options Options to set
  510. * @param array $files (Optional) Files to set the options for
  511. */
  512. public function setOptions($options = array(), $files = null) {
  513. $file = $this->_getFiles($files, false, true);
  514. if (is_array($options)) {
  515. if (empty($file)) {
  516. $this->_options = array_merge($this->_options, $options);
  517. }
  518. foreach ($options as $name => $value) {
  519. foreach ($file as $key => $content) {
  520. switch ($name) {
  521. case 'magicFile' :
  522. $this->_files[$key]['options'][$name] = (string) $value;
  523. break;
  524. case 'ignoreNoFile' :
  525. case 'useByteString' :
  526. case 'detectInfos' :
  527. $this->_files[$key]['options'][$name] = (boolean) $value;
  528. break;
  529. default:
  530. require_once 'Zend/File/Transfer/Exception.php';
  531. throw new Zend_File_Transfer_Exception("Unknown option: $name = $value");
  532. }
  533. }
  534. }
  535. }
  536. return $this;
  537. }
  538. /**
  539. * Returns set options for adapters or files
  540. *
  541. * @param array $files (Optional) Files to return the options for
  542. * @return array Options for given files
  543. */
  544. public function getOptions($files = null) {
  545. $file = $this->_getFiles($files, false, true);
  546. foreach ($file as $key => $content) {
  547. if (isset($this->_files[$key]['options'])) {
  548. $options[$key] = $this->_files[$key]['options'];
  549. } else {
  550. $options[$key] = array();
  551. }
  552. }
  553. return $options;
  554. }
  555. /**
  556. * Checks if the files are valid
  557. *
  558. * @param string|array $files (Optional) Files to check
  559. * @return boolean True if all checks are valid
  560. */
  561. public function isValid($files = null)
  562. {
  563. $check = $this->_getFiles($files, false, true);
  564. if (empty($check)) {
  565. return false;
  566. }
  567. $translator = $this->getTranslator();
  568. $this->_messages = array();
  569. $break = false;
  570. foreach($check as $key => $content) {
  571. if (array_key_exists('validators', $content) &&
  572. in_array('Zend_Validate_File_Count', $content['validators'])) {
  573. $validator = $this->_validators['Zend_Validate_File_Count'];
  574. $count = $content;
  575. if (empty($content['tmp_name'])) {
  576. continue;
  577. }
  578. if (array_key_exists('destination', $content)) {
  579. $checkit = $content['destination'];
  580. } else {
  581. $checkit = dirname($content['tmp_name']);
  582. }
  583. $checkit .= DIRECTORY_SEPARATOR . $content['name'];
  584. $validator->addFile($checkit);
  585. }
  586. }
  587. if (isset($count)) {
  588. if (!$validator->isValid($count['tmp_name'], $count)) {
  589. $this->_messages += $validator->getMessages();
  590. }
  591. }
  592. foreach ($check as $key => $content) {
  593. $fileerrors = array();
  594. if (array_key_exists('validators', $content) && $content['validated']) {
  595. continue;
  596. }
  597. if (array_key_exists('validators', $content)) {
  598. foreach ($content['validators'] as $class) {
  599. $validator = $this->_validators[$class];
  600. if (method_exists($validator, 'setTranslator')) {
  601. $validator->setTranslator($translator);
  602. }
  603. if (($class === 'Zend_Validate_File_Upload') and (empty($content['tmp_name']))) {
  604. $tocheck = $key;
  605. } else {
  606. $tocheck = $content['tmp_name'];
  607. }
  608. if (!$validator->isValid($tocheck, $content)) {
  609. $fileerrors += $validator->getMessages();
  610. }
  611. if (!empty($content['options']['ignoreNoFile']) and (isset($fileerrors['fileUploadErrorNoFile']))) {
  612. unset($fileerrors['fileUploadErrorNoFile']);
  613. break;
  614. }
  615. if (($class === 'Zend_Validate_File_Upload') and (count($fileerrors) > 0)) {
  616. break;
  617. }
  618. if (($this->_break[$class]) and (count($fileerrors) > 0)) {
  619. $break = true;
  620. break;
  621. }
  622. }
  623. }
  624. if (count($fileerrors) > 0) {
  625. $this->_files[$key]['validated'] = false;
  626. } else {
  627. $this->_files[$key]['validated'] = true;
  628. }
  629. $this->_messages += $fileerrors;
  630. if ($break) {
  631. break;
  632. }
  633. }
  634. if (count($this->_messages) > 0) {
  635. return false;
  636. }
  637. return true;
  638. }
  639. /**
  640. * Returns found validation messages
  641. *
  642. * @return array
  643. */
  644. public function getMessages()
  645. {
  646. return $this->_messages;
  647. }
  648. /**
  649. * Retrieve error codes
  650. *
  651. * @return array
  652. */
  653. public function getErrors()
  654. {
  655. return array_keys($this->_messages);
  656. }
  657. /**
  658. * Are there errors registered?
  659. *
  660. * @return boolean
  661. */
  662. public function hasErrors()
  663. {
  664. return (!empty($this->_messages));
  665. }
  666. /**
  667. * Adds a new filter for this class
  668. *
  669. * @param string|array $filter Type of filter to add
  670. * @param string|array $options Options to set for the filter
  671. * @param string|array $files Files to limit this filter to
  672. * @return Zend_File_Transfer_Adapter
  673. */
  674. public function addFilter($filter, $options = null, $files = null)
  675. {
  676. if ($filter instanceof Zend_Filter_Interface) {
  677. $class = get_class($filter);
  678. } elseif (is_string($filter)) {
  679. $class = $this->getPluginLoader(self::FILTER)->load($filter);
  680. $filter = new $class($options);
  681. } else {
  682. require_once 'Zend/File/Transfer/Exception.php';
  683. throw new Zend_File_Transfer_Exception('Invalid filter specified');
  684. }
  685. $this->_filters[$class] = $filter;
  686. $files = $this->_getFiles($files, true, true);
  687. foreach ($files as $file) {
  688. $this->_files[$file]['filters'][] = $class;
  689. }
  690. return $this;
  691. }
  692. /**
  693. * Add Multiple filters at once
  694. *
  695. * @param array $filters
  696. * @param string|array $files
  697. * @return Zend_File_Transfer_Adapter_Abstract
  698. */
  699. public function addFilters(array $filters, $files = null)
  700. {
  701. foreach ($filters as $key => $spec) {
  702. if ($spec instanceof Zend_Filter_Interface) {
  703. $this->addFilter($spec, null, $files);
  704. continue;
  705. }
  706. if (is_string($key)) {
  707. $this->addFilter($key, $spec, $files);
  708. continue;
  709. }
  710. if (is_int($key)) {
  711. if (is_string($spec)) {
  712. $this->addFilter($spec, null, $files);
  713. continue;
  714. }
  715. if (is_array($spec)) {
  716. if (!array_key_exists('filter', $spec)) {
  717. continue;
  718. }
  719. $filter = $spec['filter'];
  720. unset($spec['filter']);
  721. $this->addFilter($filter, $spec, $files);
  722. continue;
  723. }
  724. continue;
  725. }
  726. }
  727. return $this;
  728. }
  729. /**
  730. * Sets a filter for the class, erasing all previous set
  731. *
  732. * @param string|array $filter Filter to set
  733. * @param string|array $files Files to limit this filter to
  734. * @return Zend_File_Transfer_Adapter
  735. */
  736. public function setFilters(array $filters, $files = null)
  737. {
  738. $this->clearFilters();
  739. return $this->addFilters($filters, $files);
  740. }
  741. /**
  742. * Determine if a given filter has already been registered
  743. *
  744. * @param string $name
  745. * @return bool
  746. */
  747. public function hasFilter($name)
  748. {
  749. return (false !== $this->_getFilterIdentifier($name));
  750. }
  751. /**
  752. * Retrieve individual filter
  753. *
  754. * @param string $name
  755. * @return Zend_Filter_Interface|null
  756. */
  757. public function getFilter($name)
  758. {
  759. if (false === ($identifier = $this->_getFilterIdentifier($name))) {
  760. return null;
  761. }
  762. return $this->_filters[$identifier];
  763. }
  764. /**
  765. * Returns all set filters
  766. *
  767. * @param string|array $files (Optional) Returns the filter for this files
  768. * @return array List of set filters
  769. * @throws Zend_File_Transfer_Exception When file not found
  770. */
  771. public function getFilters($files = null)
  772. {
  773. if ($files === null) {
  774. return $this->_filters;
  775. }
  776. $files = $this->_getFiles($files, true, true);
  777. $filters = array();
  778. foreach ($files as $file) {
  779. if (!empty($this->_files[$file]['filters'])) {
  780. $filters += $this->_files[$file]['filters'];
  781. }
  782. }
  783. $filters = array_unique($filters);
  784. $result = array();
  785. foreach ($filters as $filter) {
  786. $result[] = $this->_filters[$filter];
  787. }
  788. return $result;
  789. }
  790. /**
  791. * Remove an individual filter
  792. *
  793. * @param string $name
  794. * @return Zend_File_Transfer_Adapter_Abstract
  795. */
  796. public function removeFilter($name)
  797. {
  798. if (false === ($key = $this->_getFilterIdentifier($name))) {
  799. return $this;
  800. }
  801. unset($this->_filters[$key]);
  802. foreach (array_keys($this->_files) as $file) {
  803. if (empty($this->_files[$file]['filters'])) {
  804. continue;
  805. }
  806. $index = array_search($key, $this->_files[$file]['filters']);
  807. if ($index === false) {
  808. continue;
  809. }
  810. unset($this->_files[$file]['filters'][$index]);
  811. }
  812. return $this;
  813. }
  814. /**
  815. * Remove all filters
  816. *
  817. * @return Zend_File_Transfer_Adapter_Abstract
  818. */
  819. public function clearFilters()
  820. {
  821. $this->_filters = array();
  822. foreach (array_keys($this->_files) as $file) {
  823. $this->_files[$file]['filters'] = array();
  824. }
  825. return $this;
  826. }
  827. /**
  828. * Returns all set files
  829. *
  830. * @return array List of set files
  831. * @throws Zend_File_Transfer_Exception Not implemented
  832. */
  833. public function getFile()
  834. {
  835. require_once 'Zend/File/Transfer/Exception.php';
  836. throw new Zend_File_Transfer_Exception('Method not implemented');
  837. }
  838. /**
  839. * Retrieves the filename of transferred files.
  840. *
  841. * @param string $fileelement (Optional) Element to return the filename for
  842. * @param boolean $path (Optional) Should the path also be returned ?
  843. * @return string|array
  844. */
  845. public function getFileName($file = null, $path = true)
  846. {
  847. $files = $this->_getFiles($file, true, true);
  848. $result = array();
  849. $directory = "";
  850. foreach($files as $file) {
  851. if (empty($this->_files[$file]['name'])) {
  852. continue;
  853. }
  854. if ($path === true) {
  855. $directory = $this->getDestination($file) . DIRECTORY_SEPARATOR;
  856. }
  857. $result[$file] = $directory . $this->_files[$file]['name'];
  858. }
  859. if (count($result) == 1) {
  860. return current($result);
  861. }
  862. return $result;
  863. }
  864. /**
  865. * Retrieve additional internal file informations for files
  866. *
  867. * @param string $file (Optional) File to get informations for
  868. * @return array
  869. */
  870. public function getFileInfo($file = null)
  871. {
  872. return $this->_getFiles($file);
  873. }
  874. /**
  875. * Adds one or more files
  876. *
  877. * @param string|array $file File to add
  878. * @param string|array $validator Validators to use for this file, must be set before
  879. * @param string|array $filter Filters to use for this file, must be set before
  880. * @return Zend_File_Transfer_Adapter_Abstract
  881. * @throws Zend_File_Transfer_Exception Not implemented
  882. */
  883. public function addFile($file, $validator = null, $filter = null)
  884. {
  885. require_once 'Zend/File/Transfer/Exception.php';
  886. throw new Zend_File_Transfer_Exception('Method not implemented');
  887. }
  888. /**
  889. * Returns all set types
  890. *
  891. * @return array List of set types
  892. * @throws Zend_File_Transfer_Exception Not implemented
  893. */
  894. public function getType()
  895. {
  896. require_once 'Zend/File/Transfer/Exception.php';
  897. throw new Zend_File_Transfer_Exception('Method not implemented');
  898. }
  899. /**
  900. * Adds one or more type of files
  901. *
  902. * @param string|array $type Type of files to add
  903. * @param string|array $validator Validators to use for this file, must be set before
  904. * @param string|array $filter Filters to use for this file, must be set before
  905. * @return Zend_File_Transfer_Adapter_Abstract
  906. * @throws Zend_File_Transfer_Exception Not implemented
  907. */
  908. public function addType($type, $validator = null, $filter = null)
  909. {
  910. require_once 'Zend/File/Transfer/Exception.php';
  911. throw new Zend_File_Transfer_Exception('Method not implemented');
  912. }
  913. /**
  914. * Sets a new destination for the given files
  915. *
  916. * @deprecated Will be changed to be a filter!!!
  917. * @param string $destination New destination directory
  918. * @param string|array $files Files to set the new destination for
  919. * @return Zend_File_Transfer_Abstract
  920. * @throws Zend_File_Transfer_Exception when the given destination is not a directory or does not exist
  921. */
  922. public function setDestination($destination, $files = null)
  923. {
  924. $orig = $files;
  925. $destination = rtrim($destination, "/\\");
  926. if (!is_dir($destination)) {
  927. require_once 'Zend/File/Transfer/Exception.php';
  928. throw new Zend_File_Transfer_Exception('The given destination is not a directory or does not exist');
  929. }
  930. if (!is_writable($destination)) {
  931. require_once 'Zend/File/Transfer/Exception.php';
  932. throw new Zend_File_Transfer_Exception('The given destination is not writeable');
  933. }
  934. if ($files === null) {
  935. foreach ($this->_files as $file => $content) {
  936. $this->_files[$file]['destination'] = $destination;
  937. }
  938. } else {
  939. $files = $this->_getFiles($files, true, true);
  940. if (empty($files) and is_string($orig)) {
  941. $this->_files[$orig]['destination'] = $destination;
  942. }
  943. foreach ($files as $file) {
  944. $this->_files[$file]['destination'] = $destination;
  945. }
  946. }
  947. return $this;
  948. }
  949. /**
  950. * Retrieve destination directory value
  951. *
  952. * @param null|string|array $files
  953. * @return null|string|array
  954. */
  955. public function getDestination($files = null)
  956. {
  957. $orig = $files;
  958. $files = $this->_getFiles($files, false, true);
  959. $destinations = array();
  960. if (empty($files) and is_string($orig)) {
  961. if (isset($this->_files[$orig]['destination'])) {
  962. $destinations[$orig] = $this->_files[$orig]['destination'];
  963. } else {
  964. require_once 'Zend/File/Transfer/Exception.php';
  965. throw new Zend_File_Transfer_Exception(sprintf('The file transfer adapter can not find "%s"', $orig));
  966. }
  967. }
  968. foreach ($files as $key => $content) {
  969. if (isset($this->_files[$key]['destination'])) {
  970. $destinations[$key] = $this->_files[$key]['destination'];
  971. } else {
  972. $tmpdir = $this->_getTmpDir();
  973. $this->setDestination($tmpdir, $key);
  974. $destinations[$key] = $tmpdir;
  975. }
  976. }
  977. if (empty($destinations)) {
  978. $destinations = $this->_getTmpDir();
  979. } else if (count($destinations) == 1) {
  980. $destinations = current($destinations);
  981. }
  982. return $destinations;
  983. }
  984. /**
  985. * Set translator object for localization
  986. *
  987. * @param Zend_Translate|null $translator
  988. * @return Zend_File_Transfer_Abstract
  989. */
  990. public function setTranslator($translator = null)
  991. {
  992. if (null === $translator) {
  993. $this->_translator = null;
  994. } elseif ($translator instanceof Zend_Translate_Adapter) {
  995. $this->_translator = $translator;
  996. } elseif ($translator instanceof Zend_Translate) {
  997. $this->_translator = $translator->getAdapter();
  998. } else {
  999. require_once 'Zend/File/Transfer/Exception.php';
  1000. throw new Zend_File_Transfer_Exception('Invalid translator specified');
  1001. }
  1002. return $this;
  1003. }
  1004. /**
  1005. * Retrieve localization translator object
  1006. *
  1007. * @return Zend_Translate_Adapter|null
  1008. */
  1009. public function getTranslator()
  1010. {
  1011. if ($this->translatorIsDisabled()) {
  1012. return null;
  1013. }
  1014. return $this->_translator;
  1015. }
  1016. /**
  1017. * Indicate whether or not translation should be disabled
  1018. *
  1019. * @param bool $flag
  1020. * @return Zend_File_Transfer_Abstract
  1021. */
  1022. public function setDisableTranslator($flag)
  1023. {
  1024. $this->_translatorDisabled = (bool) $flag;
  1025. return $this;
  1026. }
  1027. /**
  1028. * Is translation disabled?
  1029. *
  1030. * @return bool
  1031. */
  1032. public function translatorIsDisabled()
  1033. {
  1034. return $this->_translatorDisabled;
  1035. }
  1036. /**
  1037. * Returns the hash for a given file
  1038. *
  1039. * @param string $hash Hash algorithm to use
  1040. * @param string|array $files Files to return the hash for
  1041. * @return string|array Hashstring
  1042. * @throws Zend_File_Transfer_Exception On unknown hash algorithm
  1043. */
  1044. public function getHash($hash = 'crc32', $files = null)
  1045. {
  1046. if (!in_array($hash, hash_algos())) {
  1047. require_once 'Zend/File/Transfer/Exception.php';
  1048. throw new Zend_File_Transfer_Exception('Unknown hash algorithm');
  1049. }
  1050. $files = $this->_getFiles($files);
  1051. $result = array();
  1052. foreach($files as $key => $value) {
  1053. if (file_exists($value['name'])) {
  1054. $result[$key] = hash_file($hash, $value['name']);
  1055. } else if (file_exists($value['tmp_name'])) {
  1056. $result[$key] = hash_file($hash, $value['tmp_name']);
  1057. } else if (empty($value['options']['ignoreNoFile'])) {
  1058. require_once 'Zend/File/Transfer/Exception.php';
  1059. throw new Zend_File_Transfer_Exception("The file '{$value['name']}' does not exist");
  1060. }
  1061. }
  1062. if (count($result) == 1) {
  1063. return current($result);
  1064. }
  1065. return $result;
  1066. }
  1067. /**
  1068. * Returns the real filesize of the file
  1069. *
  1070. * @param string|array $files Files to get the filesize from
  1071. * @throws Zend_File_Transfer_Exception When the file does not exist
  1072. * @return string|array Filesize
  1073. */
  1074. public function getFileSize($files = null)
  1075. {
  1076. $files = $this->_getFiles($files);
  1077. $result = array();
  1078. foreach($files as $key => $value) {
  1079. if (file_exists($value['name']) || file_exists($value['tmp_name'])) {
  1080. if ($value['options']['useByteString']) {
  1081. $result[$key] = self::_toByteString($value['size']);
  1082. } else {
  1083. $result[$key] = $value['size'];
  1084. }
  1085. } else if (empty($value['options']['ignoreNoFile'])) {
  1086. require_once 'Zend/File/Transfer/Exception.php';
  1087. throw new Zend_File_Transfer_Exception("The file '{$value['name']}' does not exist");
  1088. } else {
  1089. continue;
  1090. }
  1091. }
  1092. if (count($result) == 1) {
  1093. return current($result);
  1094. }
  1095. return $result;
  1096. }
  1097. /**
  1098. * Internal method to detect the size of a file
  1099. *
  1100. * @param array $value File infos
  1101. * @return string Filesize of given file
  1102. */
  1103. protected function _detectFileSize($value)
  1104. {
  1105. if (file_exists($value['name'])) {
  1106. $result = sprintf("%u", @filesize($value['name']));
  1107. } else if (file_exists($value['tmp_name'])) {
  1108. $result = sprintf("%u", @filesize($value['tmp_name']));
  1109. } else {
  1110. return null;
  1111. }
  1112. return $result;
  1113. }
  1114. /**
  1115. * Returns the real mimetype of the file
  1116. * Uses fileinfo, when not available mime_magic and as last fallback a manual given mimetype
  1117. *
  1118. * @param string|array $files Files to get the mimetype from
  1119. * @throws Zend_File_Transfer_Exception When the file does not exist
  1120. * @return string|array MimeType
  1121. */
  1122. public function getMimeType($files = null)
  1123. {
  1124. $files = $this->_getFiles($files);
  1125. $result = array();
  1126. foreach($files as $key => $value) {
  1127. if (file_exists($value['name']) || file_exists($value['tmp_name'])) {
  1128. $result[$key] = $value['type'];
  1129. } else if (empty($value['options']['ignoreNoFile'])) {
  1130. require_once 'Zend/File/Transfer/Exception.php';
  1131. throw new Zend_File_Transfer_Exception("The file '{$value['name']}' does not exist");
  1132. } else {
  1133. continue;
  1134. }
  1135. }
  1136. if (count($result) == 1) {
  1137. return current($result);
  1138. }
  1139. return $result;
  1140. }
  1141. /**
  1142. * Internal method to detect the mime type of a file
  1143. *
  1144. * @param array $value File infos
  1145. * @return string Mimetype of given file
  1146. */
  1147. protected function _detectMimeType($value)
  1148. {
  1149. if (file_exists($value['name'])) {
  1150. $file = $value['name'];
  1151. } else if (file_exists($value['tmp_name'])) {
  1152. $file = $value['tmp_name'];
  1153. } else {
  1154. return null;
  1155. }
  1156. if (class_exists('finfo', false)) {
  1157. $const = defined('FILEINFO_MIME_TYPE') ? FILEINFO_MIME_TYPE : FILEINFO_MIME;
  1158. if (!empty($value['options']['magicFile'])) {
  1159. $mime = @finfo_open($const, $value['options']['magicFile']);
  1160. }
  1161. if (empty($mime)) {
  1162. $mime = @finfo_open($const);
  1163. }
  1164. if (!empty($mime)) {
  1165. $result = finfo_file($mime, $file);
  1166. }
  1167. unset($mime);
  1168. }
  1169. if (empty($result) && (function_exists('mime_content_type')
  1170. && ini_get('mime_magic.magicfile'))) {
  1171. $result = mime_content_type($file);
  1172. }
  1173. if (empty($result)) {
  1174. $result = 'application/octet-stream';
  1175. }
  1176. return $result;
  1177. }
  1178. /**
  1179. * Returns the formatted size
  1180. *
  1181. * @param integer $size
  1182. * @return string
  1183. */
  1184. protected static function _toByteString($size)
  1185. {
  1186. $sizes = array('B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
  1187. for ($i=0; $size >= 1024 && $i < 9; $i++) {
  1188. $size /= 1024;
  1189. }
  1190. return round($size, 2) . $sizes[$i];
  1191. }
  1192. /**
  1193. * Internal function to filter all given files
  1194. *
  1195. * @param string|array $files (Optional) Files to check
  1196. * @return boolean False on error
  1197. */
  1198. protected function _filter($files = null)
  1199. {
  1200. $check = $this->_getFiles($files);
  1201. foreach ($check as $name => $content) {
  1202. if (array_key_exists('filters', $content)) {
  1203. foreach ($content['filters'] as $class) {
  1204. $filter = $this->_filters[$class];
  1205. try {
  1206. $result = $filter->filter($this->getFileName($name));
  1207. $this->_files[$name]['destination'] = dirname($result);
  1208. $this->_files[$name]['name'] = basename($result);
  1209. } catch (Zend_Filter_Exception $e) {
  1210. $this->_messages += array($e->getMessage());
  1211. }
  1212. }
  1213. }
  1214. }
  1215. if (count($this->_messages) > 0) {
  1216. return false;
  1217. }
  1218. return true;
  1219. }
  1220. /**
  1221. * Determine system TMP directory and detect if we have read access
  1222. *
  1223. * @return string
  1224. * @throws Zend_File_Transfer_Exception if unable to determine directory
  1225. */
  1226. protected function _getTmpDir()
  1227. {
  1228. if (null === $this->_tmpDir) {
  1229. $tmpdir = array();
  1230. if (function_exists('sys_get_temp_dir')) {
  1231. $tmpdir[] = sys_get_temp_dir();
  1232. }
  1233. if (!empty($_ENV['TMP'])) {
  1234. $tmpdir[] = realpath($_ENV['TMP']);
  1235. }
  1236. if (!empty($_ENV['TMPDIR'])) {
  1237. $tmpdir[] = realpath($_ENV['TMPDIR']);
  1238. }
  1239. if (!empty($_ENV['TEMP'])) {
  1240. $tmpdir[] = realpath($_ENV['TEMP']);
  1241. }
  1242. $upload = ini_get('upload_tmp_dir');
  1243. if ($upload) {
  1244. $tmpdir[] = realpath($upload);
  1245. }
  1246. foreach($tmpdir as $directory) {
  1247. if ($this->_isPathWriteable($directory)) {
  1248. $this->_tmpDir = $directory;
  1249. }
  1250. }
  1251. if (empty($this->_tmpDir)) {
  1252. // Attemp to detect by creating a temporary file
  1253. $tempFile = tempnam(md5(uniqid(rand(), TRUE)), '');
  1254. if ($tempFile) {
  1255. $this->_tmpDir = realpath(dirname($tempFile));
  1256. unlink($tempFile);
  1257. } else {
  1258. require_once 'Zend/File/Transfer/Exception.php';
  1259. throw new Zend_File_Transfer_Exception('Could not determine a temporary directory');
  1260. }
  1261. }
  1262. $this->_tmpDir = rtrim($this->_tmpDir, "/\\");
  1263. }
  1264. return $this->_tmpDir;
  1265. }
  1266. /**
  1267. * Tries to detect if we can read and write to the given path
  1268. *
  1269. * @param string $path
  1270. */
  1271. protected function _isPathWriteable($path)
  1272. {
  1273. $tempFile = rtrim($path, "/\\");
  1274. $tempFile .= '/' . 'test.1';
  1275. $result = @file_put_contents($tempFile, 'TEST');
  1276. if ($result == false) {
  1277. return false;
  1278. }
  1279. $result = @unlink($tempFile);
  1280. if ($result == false) {
  1281. return false;
  1282. }
  1283. return true;
  1284. }
  1285. /**
  1286. * Returns found files based on internal file array and given files
  1287. *
  1288. * @param string|array $files (Optional) Files to return
  1289. * @param boolean $names (Optional) Returns only names on true, else complete info
  1290. * @param boolean $noexception (Optional) Allows throwing an exception, otherwise returns an empty array
  1291. * @return array Found files
  1292. * @throws Zend_File_Transfer_Exception On false filename
  1293. */
  1294. protected function _getFiles($files, $names = false, $noexception = false)
  1295. {
  1296. $check = array();
  1297. if (is_string($files)) {
  1298. $files = array($files);
  1299. }
  1300. if (is_array($files)) {
  1301. foreach ($files as $find) {
  1302. $found = array();
  1303. foreach ($this->_files as $file => $content) {
  1304. if (!isset($content['name'])) {
  1305. continue;
  1306. }
  1307. if (($content['name'] === $find) && isset($content['multifiles'])) {
  1308. foreach ($content['multifiles'] as $multifile) {
  1309. $found[] = $multifile;
  1310. }
  1311. break;
  1312. }
  1313. if ($file === $find) {
  1314. $found[] = $file;
  1315. break;
  1316. }
  1317. if ($content['name'] === $find) {
  1318. $found[] = $file;
  1319. break;
  1320. }
  1321. }
  1322. if (empty($found)) {
  1323. if ($noexception !== false) {
  1324. return array();
  1325. }
  1326. require_once 'Zend/File/Transfer/Exception.php';
  1327. throw new Zend_File_Transfer_Exception(sprintf('The file transfer adapter can not find "%s"', $find));
  1328. }
  1329. foreach ($found as $checked) {
  1330. $check[$checked] = $this->_files[$checked];
  1331. }
  1332. }
  1333. }
  1334. if ($files === null) {
  1335. $check = $this->_files;
  1336. $keys = array_keys($check);
  1337. foreach ($keys as $key) {
  1338. if (isset($check[$key]['multifiles'])) {
  1339. unset($check[$key]);
  1340. }
  1341. }
  1342. }
  1343. if ($names) {
  1344. $check = array_keys($check);
  1345. }
  1346. return $check;
  1347. }
  1348. /**
  1349. * Retrieve internal identifier for a named validator
  1350. *
  1351. * @param string $name
  1352. * @return string
  1353. */
  1354. protected function _getValidatorIdentifier($name)
  1355. {
  1356. if (array_key_exists($name, $this->_validators)) {
  1357. return $name;
  1358. }
  1359. foreach (array_keys($this->_validators) as $test) {
  1360. if (preg_match('/' . preg_quote($name) . '$/i', $test)) {
  1361. return $test;
  1362. }
  1363. }
  1364. return false;
  1365. }
  1366. /**
  1367. * Retrieve internal identifier for a named filter
  1368. *
  1369. * @param string $name
  1370. * @return string
  1371. */
  1372. protected function _getFilterIdentifier($name)
  1373. {
  1374. if (array_key_exists($name, $this->_filters)) {
  1375. return $name;
  1376. }
  1377. foreach (array_keys($this->_filters) as $test) {
  1378. if (preg_match('/' . preg_quote($name) . '$/i', $test)) {
  1379. return $test;
  1380. }
  1381. }
  1382. return false;
  1383. }
  1384. }