PageRenderTime 65ms CodeModel.GetById 33ms RepoModel.GetById 0ms app.codeStats 1ms

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

https://bitbucket.org/mayorbrain/precurio-v2
PHP | 1551 lines | 909 code | 178 blank | 464 comment | 181 complexity | 21d80a0a5795b9ff9fb5af0be5c7f422 MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, LGPL-2.1, BSD-3-Clause, LGPL-2.0, CC-BY-SA-3.0, MIT
  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-2010 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 20911 2010-02-04 19:40:57Z thomas $
  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-2010 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. $this->_files[$file]['validators'][] = $name;
  333. $this->_files[$file]['validated'] = false;
  334. }
  335. return $this;
  336. }
  337. /**
  338. * Add Multiple validators at once
  339. *
  340. * @param array $validators
  341. * @param string|array $files
  342. * @return Zend_File_Transfer_Adapter_Abstract
  343. */
  344. public function addValidators(array $validators, $files = null)
  345. {
  346. foreach ($validators as $name => $validatorInfo) {
  347. if ($validatorInfo instanceof Zend_Validate_Interface) {
  348. $this->addValidator($validatorInfo, null, null, $files);
  349. } else if (is_string($validatorInfo)) {
  350. if (!is_int($name)) {
  351. $this->addValidator($name, null, $validatorInfo, $files);
  352. } else {
  353. $this->addValidator($validatorInfo, null, null, $files);
  354. }
  355. } else if (is_array($validatorInfo)) {
  356. $argc = count($validatorInfo);
  357. $breakChainOnFailure = false;
  358. $options = array();
  359. if (isset($validatorInfo['validator'])) {
  360. $validator = $validatorInfo['validator'];
  361. if (isset($validatorInfo['breakChainOnFailure'])) {
  362. $breakChainOnFailure = $validatorInfo['breakChainOnFailure'];
  363. }
  364. if (isset($validatorInfo['options'])) {
  365. $options = $validatorInfo['options'];
  366. }
  367. $this->addValidator($validator, $breakChainOnFailure, $options, $files);
  368. } else {
  369. if (is_string($name)) {
  370. $validator = $name;
  371. $options = $validatorInfo;
  372. $this->addValidator($validator, $breakChainOnFailure, $options, $files);
  373. } else {
  374. $file = $files;
  375. switch (true) {
  376. case (0 == $argc):
  377. break;
  378. case (1 <= $argc):
  379. $validator = array_shift($validatorInfo);
  380. case (2 <= $argc):
  381. $breakChainOnFailure = array_shift($validatorInfo);
  382. case (3 <= $argc):
  383. $options = array_shift($validatorInfo);
  384. case (4 <= $argc):
  385. if (!empty($validatorInfo)) {
  386. $file = array_shift($validatorInfo);
  387. }
  388. default:
  389. $this->addValidator($validator, $breakChainOnFailure, $options, $file);
  390. break;
  391. }
  392. }
  393. }
  394. } else {
  395. require_once 'Zend/File/Transfer/Exception.php';
  396. throw new Zend_File_Transfer_Exception('Invalid validator passed to addValidators()');
  397. }
  398. }
  399. return $this;
  400. }
  401. /**
  402. * Sets a validator for the class, erasing all previous set
  403. *
  404. * @param string|array $validator Validator to set
  405. * @param string|array $files Files to limit this validator to
  406. * @return Zend_File_Transfer_Adapter
  407. */
  408. public function setValidators(array $validators, $files = null)
  409. {
  410. $this->clearValidators();
  411. return $this->addValidators($validators, $files);
  412. }
  413. /**
  414. * Determine if a given validator has already been registered
  415. *
  416. * @param string $name
  417. * @return bool
  418. */
  419. public function hasValidator($name)
  420. {
  421. return (false !== $this->_getValidatorIdentifier($name));
  422. }
  423. /**
  424. * Retrieve individual validator
  425. *
  426. * @param string $name
  427. * @return Zend_Validate_Interface|null
  428. */
  429. public function getValidator($name)
  430. {
  431. if (false === ($identifier = $this->_getValidatorIdentifier($name))) {
  432. return null;
  433. }
  434. return $this->_validators[$identifier];
  435. }
  436. /**
  437. * Returns all set validators
  438. *
  439. * @param string|array $files (Optional) Returns the validator for this files
  440. * @return null|array List of set validators
  441. */
  442. public function getValidators($files = null)
  443. {
  444. if ($files == null) {
  445. return $this->_validators;
  446. }
  447. $files = $this->_getFiles($files, true, true);
  448. $validators = array();
  449. foreach ($files as $file) {
  450. if (!empty($this->_files[$file]['validators'])) {
  451. $validators += $this->_files[$file]['validators'];
  452. }
  453. }
  454. $validators = array_unique($validators);
  455. $result = array();
  456. foreach ($validators as $validator) {
  457. $result[$validator] = $this->_validators[$validator];
  458. }
  459. return $result;
  460. }
  461. /**
  462. * Remove an individual validator
  463. *
  464. * @param string $name
  465. * @return Zend_File_Transfer_Adapter_Abstract
  466. */
  467. public function removeValidator($name)
  468. {
  469. if (false === ($key = $this->_getValidatorIdentifier($name))) {
  470. return $this;
  471. }
  472. unset($this->_validators[$key]);
  473. foreach (array_keys($this->_files) as $file) {
  474. if (empty($this->_files[$file]['validators'])) {
  475. continue;
  476. }
  477. $index = array_search($key, $this->_files[$file]['validators']);
  478. if ($index === false) {
  479. continue;
  480. }
  481. unset($this->_files[$file]['validators'][$index]);
  482. $this->_files[$file]['validated'] = false;
  483. }
  484. return $this;
  485. }
  486. /**
  487. * Remove all validators
  488. *
  489. * @return Zend_File_Transfer_Adapter_Abstract
  490. */
  491. public function clearValidators()
  492. {
  493. $this->_validators = array();
  494. foreach (array_keys($this->_files) as $file) {
  495. $this->_files[$file]['validators'] = array();
  496. $this->_files[$file]['validated'] = false;
  497. }
  498. return $this;
  499. }
  500. /**
  501. * Sets Options for adapters
  502. *
  503. * @param array $options Options to set
  504. * @param array $files (Optional) Files to set the options for
  505. */
  506. public function setOptions($options = array(), $files = null) {
  507. $file = $this->_getFiles($files, false, true);
  508. if (is_array($options)) {
  509. if ($file === null) {
  510. $this->_options = array_merge($this->_options, $options);
  511. }
  512. foreach ($options as $name => $value) {
  513. foreach ($file as $key => $content) {
  514. switch ($name) {
  515. case 'magicFile' :
  516. $this->_files[$key]['options'][$name] = (string) $value;
  517. break;
  518. case 'ignoreNoFile' :
  519. case 'useByteString' :
  520. $this->_files[$key]['options'][$name] = (boolean) $value;
  521. break;
  522. default:
  523. require_once 'Zend/File/Transfer/Exception.php';
  524. throw new Zend_File_Transfer_Exception("Unknown option: $name = $value");
  525. }
  526. }
  527. }
  528. }
  529. return $this;
  530. }
  531. /**
  532. * Returns set options for adapters or files
  533. *
  534. * @param array $files (Optional) Files to return the options for
  535. * @return array Options for given files
  536. */
  537. public function getOptions($files = null) {
  538. $file = $this->_getFiles($files, false, true);
  539. foreach ($file as $key => $content) {
  540. if (isset($this->_files[$key]['options'])) {
  541. $options[$key] = $this->_files[$key]['options'];
  542. } else {
  543. $options[$key] = array();
  544. }
  545. }
  546. return $options;
  547. }
  548. /**
  549. * Checks if the files are valid
  550. *
  551. * @param string|array $files (Optional) Files to check
  552. * @return boolean True if all checks are valid
  553. */
  554. public function isValid($files = null)
  555. {
  556. $check = $this->_getFiles($files, false, true);
  557. if (empty($check)) {
  558. return false;
  559. }
  560. $translator = $this->getTranslator();
  561. $this->_messages = array();
  562. $break = false;
  563. foreach($check as $key => $content) {
  564. if (array_key_exists('validators', $content) &&
  565. in_array('Zend_Validate_File_Count', $content['validators'])) {
  566. $validator = $this->_validators['Zend_Validate_File_Count'];
  567. if (array_key_exists('destination', $content)) {
  568. $checkit = $content['destination'];
  569. } else {
  570. $checkit = dirname($content['tmp_name']);
  571. }
  572. $checkit .= DIRECTORY_SEPARATOR . $content['name'];
  573. $validator->addFile($checkit);
  574. $count = $content;
  575. }
  576. }
  577. if (isset($count)) {
  578. if (!$validator->isValid($count['tmp_name'], $count)) {
  579. $this->_messages += $validator->getMessages();
  580. }
  581. }
  582. foreach ($check as $key => $content) {
  583. $fileerrors = array();
  584. if (array_key_exists('validators', $content) && $content['validated']) {
  585. continue;
  586. }
  587. if (array_key_exists('validators', $content)) {
  588. foreach ($content['validators'] as $class) {
  589. $validator = $this->_validators[$class];
  590. if (method_exists($validator, 'setTranslator')) {
  591. $validator->setTranslator($translator);
  592. }
  593. if (($class === 'Zend_Validate_File_Upload') and (empty($content['tmp_name']))) {
  594. $tocheck = $key;
  595. } else {
  596. $tocheck = $content['tmp_name'];
  597. }
  598. if (!$validator->isValid($tocheck, $content)) {
  599. $fileerrors += $validator->getMessages();
  600. }
  601. if (!empty($content['options']['ignoreNoFile']) and (isset($fileerrors['fileUploadErrorNoFile']))) {
  602. unset($fileerrors['fileUploadErrorNoFile']);
  603. break;
  604. }
  605. if (($class === 'Zend_Validate_File_Upload') and (count($fileerrors) > 0)) {
  606. break;
  607. }
  608. if (($this->_break[$class]) and (count($fileerrors) > 0)) {
  609. $break = true;
  610. break;
  611. }
  612. }
  613. }
  614. if (count($fileerrors) > 0) {
  615. $this->_files[$key]['validated'] = false;
  616. } else {
  617. $this->_files[$key]['validated'] = true;
  618. }
  619. $this->_messages += $fileerrors;
  620. if ($break) {
  621. break;
  622. }
  623. }
  624. if (count($this->_messages) > 0) {
  625. return false;
  626. }
  627. return true;
  628. }
  629. /**
  630. * Returns found validation messages
  631. *
  632. * @return array
  633. */
  634. public function getMessages()
  635. {
  636. return $this->_messages;
  637. }
  638. /**
  639. * Retrieve error codes
  640. *
  641. * @return array
  642. */
  643. public function getErrors()
  644. {
  645. return array_keys($this->_messages);
  646. }
  647. /**
  648. * Are there errors registered?
  649. *
  650. * @return boolean
  651. */
  652. public function hasErrors()
  653. {
  654. return (!empty($this->_messages));
  655. }
  656. /**
  657. * Adds a new filter for this class
  658. *
  659. * @param string|array $filter Type of filter to add
  660. * @param string|array $options Options to set for the filter
  661. * @param string|array $files Files to limit this filter to
  662. * @return Zend_File_Transfer_Adapter
  663. */
  664. public function addFilter($filter, $options = null, $files = null)
  665. {
  666. if ($filter instanceof Zend_Filter_Interface) {
  667. $class = get_class($filter);
  668. } elseif (is_string($filter)) {
  669. $class = $this->getPluginLoader(self::FILTER)->load($filter);
  670. $filter = new $class($options);
  671. } else {
  672. require_once 'Zend/File/Transfer/Exception.php';
  673. throw new Zend_File_Transfer_Exception('Invalid filter specified');
  674. }
  675. $this->_filters[$class] = $filter;
  676. $files = $this->_getFiles($files, true, true);
  677. foreach ($files as $file) {
  678. $this->_files[$file]['filters'][] = $class;
  679. }
  680. return $this;
  681. }
  682. /**
  683. * Add Multiple filters at once
  684. *
  685. * @param array $filters
  686. * @param string|array $files
  687. * @return Zend_File_Transfer_Adapter_Abstract
  688. */
  689. public function addFilters(array $filters, $files = null)
  690. {
  691. foreach ($filters as $key => $spec) {
  692. if ($spec instanceof Zend_Filter_Interface) {
  693. $this->addFilter($spec, null, $files);
  694. continue;
  695. }
  696. if (is_string($key)) {
  697. $this->addFilter($key, $spec, $files);
  698. continue;
  699. }
  700. if (is_int($key)) {
  701. if (is_string($spec)) {
  702. $this->addFilter($spec, null, $files);
  703. continue;
  704. }
  705. if (is_array($spec)) {
  706. if (!array_key_exists('filter', $spec)) {
  707. continue;
  708. }
  709. $filter = $spec['filter'];
  710. unset($spec['filter']);
  711. $this->addFilter($filter, $spec, $files);
  712. continue;
  713. }
  714. continue;
  715. }
  716. }
  717. return $this;
  718. }
  719. /**
  720. * Sets a filter for the class, erasing all previous set
  721. *
  722. * @param string|array $filter Filter to set
  723. * @param string|array $files Files to limit this filter to
  724. * @return Zend_File_Transfer_Adapter
  725. */
  726. public function setFilters(array $filters, $files = null)
  727. {
  728. $this->clearFilters();
  729. return $this->addFilters($filters, $files);
  730. }
  731. /**
  732. * Determine if a given filter has already been registered
  733. *
  734. * @param string $name
  735. * @return bool
  736. */
  737. public function hasFilter($name)
  738. {
  739. return (false !== $this->_getFilterIdentifier($name));
  740. }
  741. /**
  742. * Retrieve individual filter
  743. *
  744. * @param string $name
  745. * @return Zend_Filter_Interface|null
  746. */
  747. public function getFilter($name)
  748. {
  749. if (false === ($identifier = $this->_getFilterIdentifier($name))) {
  750. return null;
  751. }
  752. return $this->_filters[$identifier];
  753. }
  754. /**
  755. * Returns all set filters
  756. *
  757. * @param string|array $files (Optional) Returns the filter for this files
  758. * @return array List of set filters
  759. * @throws Zend_File_Transfer_Exception When file not found
  760. */
  761. public function getFilters($files = null)
  762. {
  763. if ($files === null) {
  764. return $this->_filters;
  765. }
  766. $files = $this->_getFiles($files, true, true);
  767. $filters = array();
  768. foreach ($files as $file) {
  769. if (!empty($this->_files[$file]['filters'])) {
  770. $filters += $this->_files[$file]['filters'];
  771. }
  772. }
  773. $filters = array_unique($filters);
  774. $result = array();
  775. foreach ($filters as $filter) {
  776. $result[] = $this->_filters[$filter];
  777. }
  778. return $result;
  779. }
  780. /**
  781. * Remove an individual filter
  782. *
  783. * @param string $name
  784. * @return Zend_File_Transfer_Adapter_Abstract
  785. */
  786. public function removeFilter($name)
  787. {
  788. if (false === ($key = $this->_getFilterIdentifier($name))) {
  789. return $this;
  790. }
  791. unset($this->_filters[$key]);
  792. foreach (array_keys($this->_files) as $file) {
  793. if (empty($this->_files[$file]['filters'])) {
  794. continue;
  795. }
  796. $index = array_search($key, $this->_files[$file]['filters']);
  797. if ($index === false) {
  798. continue;
  799. }
  800. unset($this->_files[$file]['filters'][$index]);
  801. }
  802. return $this;
  803. }
  804. /**
  805. * Remove all filters
  806. *
  807. * @return Zend_File_Transfer_Adapter_Abstract
  808. */
  809. public function clearFilters()
  810. {
  811. $this->_filters = array();
  812. foreach (array_keys($this->_files) as $file) {
  813. $this->_files[$file]['filters'] = array();
  814. }
  815. return $this;
  816. }
  817. /**
  818. * Returns all set files
  819. *
  820. * @return array List of set files
  821. * @throws Zend_File_Transfer_Exception Not implemented
  822. */
  823. public function getFile()
  824. {
  825. require_once 'Zend/File/Transfer/Exception.php';
  826. throw new Zend_File_Transfer_Exception('Method not implemented');
  827. }
  828. /**
  829. * Retrieves the filename of transferred files.
  830. *
  831. * @param string $fileelement (Optional) Element to return the filename for
  832. * @param boolean $path (Optional) Should the path also be returned ?
  833. * @return string|array
  834. */
  835. public function getFileName($file = null, $path = true)
  836. {
  837. $files = $this->_getFiles($file, true, true);
  838. $result = array();
  839. $directory = "";
  840. foreach($files as $file) {
  841. if (empty($this->_files[$file]['name'])) {
  842. continue;
  843. }
  844. if ($path === true) {
  845. $directory = $this->getDestination($file) . DIRECTORY_SEPARATOR;
  846. }
  847. $result[$file] = $directory . $this->_files[$file]['name'];
  848. }
  849. if (count($result) == 1) {
  850. return current($result);
  851. }
  852. return $result;
  853. }
  854. /**
  855. * Retrieve additional internal file informations for files
  856. *
  857. * @param string $file (Optional) File to get informations for
  858. * @return array
  859. */
  860. public function getFileInfo($file = null)
  861. {
  862. return $this->_getFiles($file);
  863. }
  864. /**
  865. * Adds one or more files
  866. *
  867. * @param string|array $file File to add
  868. * @param string|array $validator Validators to use for this file, must be set before
  869. * @param string|array $filter Filters to use for this file, must be set before
  870. * @return Zend_File_Transfer_Adapter_Abstract
  871. * @throws Zend_File_Transfer_Exception Not implemented
  872. */
  873. public function addFile($file, $validator = null, $filter = null)
  874. {
  875. require_once 'Zend/File/Transfer/Exception.php';
  876. throw new Zend_File_Transfer_Exception('Method not implemented');
  877. }
  878. /**
  879. * Returns all set types
  880. *
  881. * @return array List of set types
  882. * @throws Zend_File_Transfer_Exception Not implemented
  883. */
  884. public function getType()
  885. {
  886. require_once 'Zend/File/Transfer/Exception.php';
  887. throw new Zend_File_Transfer_Exception('Method not implemented');
  888. }
  889. /**
  890. * Adds one or more type of files
  891. *
  892. * @param string|array $type Type of files to add
  893. * @param string|array $validator Validators to use for this file, must be set before
  894. * @param string|array $filter Filters to use for this file, must be set before
  895. * @return Zend_File_Transfer_Adapter_Abstract
  896. * @throws Zend_File_Transfer_Exception Not implemented
  897. */
  898. public function addType($type, $validator = null, $filter = null)
  899. {
  900. require_once 'Zend/File/Transfer/Exception.php';
  901. throw new Zend_File_Transfer_Exception('Method not implemented');
  902. }
  903. /**
  904. * Sets a new destination for the given files
  905. *
  906. * @deprecated Will be changed to be a filter!!!
  907. * @param string $destination New destination directory
  908. * @param string|array $files Files to set the new destination for
  909. * @return Zend_File_Transfer_Abstract
  910. * @throws Zend_File_Transfer_Exception when the given destination is not a directory or does not exist
  911. */
  912. public function setDestination($destination, $files = null)
  913. {
  914. $orig = $files;
  915. $destination = rtrim($destination, "/\\");
  916. if (!is_dir($destination)) {
  917. require_once 'Zend/File/Transfer/Exception.php';
  918. throw new Zend_File_Transfer_Exception('The given destination is no directory or does not exist');
  919. }
  920. if (!is_writable($destination)) {
  921. require_once 'Zend/File/Transfer/Exception.php';
  922. throw new Zend_File_Transfer_Exception('The given destination is not writeable');
  923. }
  924. if ($files === null) {
  925. foreach ($this->_files as $file => $content) {
  926. $this->_files[$file]['destination'] = $destination;
  927. }
  928. } else {
  929. $files = $this->_getFiles($files, true, true);
  930. if (empty($files) and is_string($orig)) {
  931. $this->_files[$orig]['destination'] = $destination;
  932. }
  933. foreach ($files as $file) {
  934. $this->_files[$file]['destination'] = $destination;
  935. }
  936. }
  937. return $this;
  938. }
  939. /**
  940. * Retrieve destination directory value
  941. *
  942. * @param null|string|array $files
  943. * @return null|string|array
  944. */
  945. public function getDestination($files = null)
  946. {
  947. $orig = $files;
  948. $files = $this->_getFiles($files, false, true);
  949. $destinations = array();
  950. if (empty($files) and is_string($orig)) {
  951. if (isset($this->_files[$orig]['destination'])) {
  952. $destinations[$orig] = $this->_files[$orig]['destination'];
  953. } else {
  954. require_once 'Zend/File/Transfer/Exception.php';
  955. throw new Zend_File_Transfer_Exception(sprintf('"%s" not found by file transfer adapter', $orig));
  956. }
  957. }
  958. foreach ($files as $key => $content) {
  959. if (isset($this->_files[$key]['destination'])) {
  960. $destinations[$key] = $this->_files[$key]['destination'];
  961. } else {
  962. $tmpdir = $this->_getTmpDir();
  963. $this->setDestination($tmpdir, $key);
  964. $destinations[$key] = $tmpdir;
  965. }
  966. }
  967. if (empty($destinations)) {
  968. $destinations = $this->_getTmpDir();
  969. } else if (count($destinations) == 1) {
  970. $destinations = current($destinations);
  971. }
  972. return $destinations;
  973. }
  974. /**
  975. * Set translator object for localization
  976. *
  977. * @param Zend_Translate|null $translator
  978. * @return Zend_File_Transfer_Abstract
  979. */
  980. public function setTranslator($translator = null)
  981. {
  982. if (null === $translator) {
  983. $this->_translator = null;
  984. } elseif ($translator instanceof Zend_Translate_Adapter) {
  985. $this->_translator = $translator;
  986. } elseif ($translator instanceof Zend_Translate) {
  987. $this->_translator = $translator->getAdapter();
  988. } else {
  989. require_once 'Zend/File/Transfer/Exception.php';
  990. throw new Zend_File_Transfer_Exception('Invalid translator specified');
  991. }
  992. return $this;
  993. }
  994. /**
  995. * Retrieve localization translator object
  996. *
  997. * @return Zend_Translate_Adapter|null
  998. */
  999. public function getTranslator()
  1000. {
  1001. if ($this->translatorIsDisabled()) {
  1002. return null;
  1003. }
  1004. return $this->_translator;
  1005. }
  1006. /**
  1007. * Indicate whether or not translation should be disabled
  1008. *
  1009. * @param bool $flag
  1010. * @return Zend_File_Transfer_Abstract
  1011. */
  1012. public function setDisableTranslator($flag)
  1013. {
  1014. $this->_translatorDisabled = (bool) $flag;
  1015. return $this;
  1016. }
  1017. /**
  1018. * Is translation disabled?
  1019. *
  1020. * @return bool
  1021. */
  1022. public function translatorIsDisabled()
  1023. {
  1024. return $this->_translatorDisabled;
  1025. }
  1026. /**
  1027. * Returns the hash for a given file
  1028. *
  1029. * @param string $hash Hash algorithm to use
  1030. * @param string|array $files Files to return the hash for
  1031. * @return string|array Hashstring
  1032. * @throws Zend_File_Transfer_Exception On unknown hash algorithm
  1033. */
  1034. public function getHash($hash = 'crc32', $files = null)
  1035. {
  1036. if (!in_array($hash, hash_algos())) {
  1037. require_once 'Zend/File/Transfer/Exception.php';
  1038. throw new Zend_File_Transfer_Exception('Unknown hash algorithm');
  1039. }
  1040. $files = $this->_getFiles($files);
  1041. $result = array();
  1042. foreach($files as $key => $value) {
  1043. if (file_exists($value['name'])) {
  1044. $result[$key] = hash_file($hash, $value['name']);
  1045. } else if (file_exists($value['tmp_name'])) {
  1046. $result[$key] = hash_file($hash, $value['tmp_name']);
  1047. } else if (empty($value['options']['ignoreNoFile'])) {
  1048. require_once 'Zend/File/Transfer/Exception.php';
  1049. throw new Zend_File_Transfer_Exception("File '{$value['name']}' does not exist");
  1050. }
  1051. }
  1052. if (count($result) == 1) {
  1053. return current($result);
  1054. }
  1055. return $result;
  1056. }
  1057. /**
  1058. * Returns the real filesize of the file
  1059. *
  1060. * @param string|array $files Files to get the filesize from
  1061. * @throws Zend_File_Transfer_Exception When the file does not exist
  1062. * @return string|array Filesize
  1063. */
  1064. public function getFileSize($files = null)
  1065. {
  1066. $files = $this->_getFiles($files);
  1067. $result = array();
  1068. foreach($files as $key => $value) {
  1069. if (file_exists($value['name']) || file_exists($value['tmp_name'])) {
  1070. if ($value['options']['useByteString']) {
  1071. $result[$key] = self::_toByteString($value['size']);
  1072. } else {
  1073. $result[$key] = $value['size'];
  1074. }
  1075. } else if (empty($value['options']['ignoreNoFile'])) {
  1076. require_once 'Zend/File/Transfer/Exception.php';
  1077. throw new Zend_File_Transfer_Exception("File '{$value['name']}' does not exist");
  1078. } else {
  1079. continue;
  1080. }
  1081. }
  1082. if (count($result) == 1) {
  1083. return current($result);
  1084. }
  1085. return $result;
  1086. }
  1087. /**
  1088. * Internal method to detect the size of a file
  1089. *
  1090. * @param array $value File infos
  1091. * @return string Filesize of given file
  1092. */
  1093. protected function _detectFileSize($value)
  1094. {
  1095. if (file_exists($value['name'])) {
  1096. $result = sprintf("%u", @filesize($value['name']));
  1097. } else if (file_exists($value['tmp_name'])) {
  1098. $result = sprintf("%u", @filesize($value['tmp_name']));
  1099. } else {
  1100. return null;
  1101. }
  1102. return $result;
  1103. }
  1104. /**
  1105. * Returns the real mimetype of the file
  1106. * Uses fileinfo, when not available mime_magic and as last fallback a manual given mimetype
  1107. *
  1108. * @param string|array $files Files to get the mimetype from
  1109. * @throws Zend_File_Transfer_Exception When the file does not exist
  1110. * @return string|array MimeType
  1111. */
  1112. public function getMimeType($files = null)
  1113. {
  1114. $files = $this->_getFiles($files);
  1115. $result = array();
  1116. foreach($files as $key => $value) {
  1117. if (file_exists($value['name']) || file_exists($value['tmp_name'])) {
  1118. $result[$key] = $value['type'];
  1119. } else if (empty($value['options']['ignoreNoFile'])) {
  1120. require_once 'Zend/File/Transfer/Exception.php';
  1121. throw new Zend_File_Transfer_Exception("File '{$value['name']}' does not exist");
  1122. } else {
  1123. continue;
  1124. }
  1125. }
  1126. if (count($result) == 1) {
  1127. return current($result);
  1128. }
  1129. return $result;
  1130. }
  1131. /**
  1132. * Internal method to detect the mime type of a file
  1133. *
  1134. * @param array $value File infos
  1135. * @return string Mimetype of given file
  1136. */
  1137. protected function _detectMimeType($value)
  1138. {
  1139. if (file_exists($value['name'])) {
  1140. $file = $value['name'];
  1141. } else if (file_exists($value['tmp_name'])) {
  1142. $file = $value['tmp_name'];
  1143. } else {
  1144. return null;
  1145. }
  1146. if (class_exists('finfo', false)) {
  1147. $const = defined('FILEINFO_MIME_TYPE') ? FILEINFO_MIME_TYPE : FILEINFO_MIME;
  1148. if (!empty($value['options']['magicFile'])) {
  1149. $mime = new finfo($const, $value['options']['magicFile']);
  1150. } else {
  1151. $mime = new finfo($const);
  1152. }
  1153. if ($mime !== false) {
  1154. $result = $mime->file($file);
  1155. }
  1156. unset($mime);
  1157. }
  1158. if (empty($result) && (function_exists('mime_content_type')
  1159. && ini_get('mime_magic.magicfile'))) {
  1160. $result = mime_content_type($file);
  1161. }
  1162. if (empty($result)) {
  1163. $result = 'application/octet-stream';
  1164. }
  1165. return $result;
  1166. }
  1167. /**
  1168. * Returns the formatted size
  1169. *
  1170. * @param integer $size
  1171. * @return string
  1172. */
  1173. protected static function _toByteString($size)
  1174. {
  1175. $sizes = array('B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
  1176. for ($i=0; $size >= 1024 && $i < 9; $i++) {
  1177. $size /= 1024;
  1178. }
  1179. return round($size, 2) . $sizes[$i];
  1180. }
  1181. /**
  1182. * Internal function to filter all given files
  1183. *
  1184. * @param string|array $files (Optional) Files to check
  1185. * @return boolean False on error
  1186. */
  1187. protected function _filter($files = null)
  1188. {
  1189. $check = $this->_getFiles($files);
  1190. foreach ($check as $name => $content) {
  1191. if (array_key_exists('filters', $content)) {
  1192. foreach ($content['filters'] as $class) {
  1193. $filter = $this->_filters[$class];
  1194. try {
  1195. $result = $filter->filter($this->getFileName($name));
  1196. $this->_files[$name]['destination'] = dirname($result);
  1197. $this->_files[$name]['name'] = basename($result);
  1198. } catch (Zend_Filter_Exception $e) {
  1199. $this->_messages += array($e->getMessage());
  1200. }
  1201. }
  1202. }
  1203. }
  1204. if (count($this->_messages) > 0) {
  1205. return false;
  1206. }
  1207. return true;
  1208. }
  1209. /**
  1210. * Determine system TMP directory and detect if we have read access
  1211. *
  1212. * @return string
  1213. * @throws Zend_File_Transfer_Exception if unable to determine directory
  1214. */
  1215. protected function _getTmpDir()
  1216. {
  1217. if (null === $this->_tmpDir) {
  1218. $tmpdir = array();
  1219. if (function_exists('sys_get_temp_dir')) {
  1220. $tmpdir[] = sys_get_temp_dir();
  1221. }
  1222. if (!empty($_ENV['TMP'])) {
  1223. $tmpdir[] = realpath($_ENV['TMP']);
  1224. }
  1225. if (!empty($_ENV['TMPDIR'])) {
  1226. $tmpdir[] = realpath($_ENV['TMPDIR']);
  1227. }
  1228. if (!empty($_ENV['TEMP'])) {
  1229. $tmpdir[] = realpath($_ENV['TEMP']);
  1230. }
  1231. $upload = ini_get('upload_tmp_dir');
  1232. if ($upload) {
  1233. $tmpdir[] = realpath($upload);
  1234. }
  1235. foreach($tmpdir as $directory) {
  1236. if ($this->_isPathWriteable($directory)) {
  1237. $this->_tmpDir = $directory;
  1238. }
  1239. }
  1240. if (empty($this->_tmpDir)) {
  1241. // Attemp to detect by creating a temporary file
  1242. $tempFile = tempnam(md5(uniqid(rand(), TRUE)), '');
  1243. if ($tempFile) {
  1244. $this->_tmpDir = realpath(dirname($tempFile));
  1245. unlink($tempFile);
  1246. } else {
  1247. require_once 'Zend/File/Transfer/Exception.php';
  1248. throw new Zend_File_Transfer_Exception('Could not determine temp directory');
  1249. }
  1250. }
  1251. $this->_tmpDir = rtrim($this->_tmpDir, "/\\");
  1252. }
  1253. return $this->_tmpDir;
  1254. }
  1255. /**
  1256. * Tries to detect if we can read and write to the given path
  1257. *
  1258. * @param string $path
  1259. */
  1260. protected function _isPathWriteable($path)
  1261. {
  1262. $tempFile = rtrim($path, "/\\");
  1263. $tempFile .= '/' . 'test.1';
  1264. $result = @file_put_contents($tempFile, 'TEST');
  1265. if ($result == false) {
  1266. return false;
  1267. }
  1268. $result = @unlink($tempFile);
  1269. if ($result == false) {
  1270. return false;
  1271. }
  1272. return true;
  1273. }
  1274. /**
  1275. * Returns found files based on internal file array and given files
  1276. *
  1277. * @param string|array $files (Optional) Files to return
  1278. * @param boolean $names (Optional) Returns only names on true, else complete info
  1279. * @param boolean $noexception (Optional) Allows throwing an exception, otherwise returns an empty array
  1280. * @return array Found files
  1281. * @throws Zend_File_Transfer_Exception On false filename
  1282. */
  1283. protected function _getFiles($files, $names = false, $noexception = false)
  1284. {
  1285. $check = array();
  1286. if (is_string($files)) {
  1287. $files = array($files);
  1288. }
  1289. if (is_array($files)) {
  1290. foreach ($files as $find) {
  1291. $found = array();
  1292. foreach ($this->_files as $file => $content) {
  1293. if (!isset($content['name'])) {
  1294. continue;
  1295. }
  1296. if (($content['name'] === $find) && isset($content['multifiles'])) {
  1297. foreach ($content['multifiles'] as $multifile) {
  1298. $found[] = $multifile;
  1299. }
  1300. break;
  1301. }
  1302. if ($file === $find) {
  1303. $found[] = $file;
  1304. break;
  1305. }
  1306. if ($content['name'] === $find) {
  1307. $found[] = $file;
  1308. break;
  1309. }
  1310. }
  1311. if (empty($found)) {
  1312. if ($noexception !== false) {
  1313. return array();
  1314. }
  1315. require_once 'Zend/File/Transfer/Exception.php';
  1316. throw new Zend_File_Transfer_Exception(sprintf('"%s" not found by file transfer adapter', $find));
  1317. }
  1318. foreach ($found as $checked) {
  1319. $check[$checked] = $this->_files[$checked];
  1320. }
  1321. }
  1322. }
  1323. if ($files === null) {
  1324. $check = $this->_files;
  1325. $keys = array_keys($check);
  1326. foreach ($keys as $key) {
  1327. if (isset($check[$key]['multifiles'])) {
  1328. unset($check[$key]);
  1329. }
  1330. }
  1331. }
  1332. if ($names) {
  1333. $check = array_keys($check);
  1334. }
  1335. return $check;
  1336. }
  1337. /**
  1338. * Retrieve internal identifier for a named validator
  1339. *
  1340. * @param string $name
  1341. * @return string
  1342. */
  1343. protected function _getValidatorIdentifier($name)
  1344. {
  1345. if (array_key_exists($name, $this->_validators)) {
  1346. return $name;
  1347. }
  1348. foreach (array_keys($this->_validators) as $test) {
  1349. if (preg_match('/' . preg_quote($name) . '$/i', $test)) {
  1350. return $test;
  1351. }
  1352. }
  1353. return false;
  1354. }
  1355. /**
  1356. * Retrieve internal identifier for a named filter
  1357. *
  1358. * @param string $name
  1359. * @return string
  1360. */
  1361. protected function _getFilterIdentifier($name)
  1362. {
  1363. if (array_key_exists($name, $this->_filters)) {
  1364. return $name;
  1365. }
  1366. foreach (array_keys($this->_filters) as $test) {
  1367. if (preg_match('/' . preg_quote($name) . '$/i', $test)) {
  1368. return $test;
  1369. }
  1370. }
  1371. return false;
  1372. }
  1373. }