cr1p

File

Sep 13th, 2016
404
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 28.26 KB | None | 0 0
  1. <?php
  2. /**
  3. * Magento
  4. *
  5. * NOTICE OF LICENSE
  6. *
  7. * This source file is subject to the Open Software License (OSL 3.0)
  8. * that is bundled with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://opensource.org/licenses/osl-3.0.php
  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 [email protected] so we can send you a copy immediately.
  14. *
  15. * DISCLAIMER
  16. *
  17. * Do not edit or add to this file if you wish to upgrade Magento to newer
  18. * versions in the future. If you wish to customize Magento for your
  19. * needs please refer to http://www.magento.com for more information.
  20. *
  21. * @category Mage
  22. * @package Mage_Catalog
  23. * @copyright Copyright (c) 2006-2014 X.commerce, Inc. (http://www.magento.com)
  24. * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
  25. */
  26.  
  27. /**
  28. * Catalog product option file type
  29. *
  30. * @category Mage
  31. * @package Mage_Catalog
  32. * @author Magento Core Team <[email protected]>
  33. */
  34. class Mage_Catalog_Model_Product_Option_Type_File extends Mage_Catalog_Model_Product_Option_Type_Default
  35. {
  36. /**
  37. * Url for custom option download controller
  38. * @var string
  39. */
  40. protected $_customOptionDownloadUrl = 'sales/download/downloadCustomOption';
  41.  
  42. public function isCustomizedView()
  43. {
  44. return true;
  45. }
  46.  
  47. /**
  48. * Return option html
  49. *
  50. * @param array $optionInfo
  51. * @return string
  52. */
  53. public function getCustomizedView($optionInfo)
  54. {
  55. try {
  56. if (isset($optionInfo['option_value'])) {
  57. return $this->_getOptionHtml($optionInfo['option_value']);
  58. } elseif (isset($optionInfo['value'])) {
  59. return $optionInfo['value'];
  60. }
  61. } catch (Exception $e) {
  62. return $optionInfo['value'];
  63. }
  64. }
  65.  
  66. /**
  67. * Returns additional params for processing options
  68. *
  69. * @return Varien_Object
  70. */
  71. protected function _getProcessingParams()
  72. {
  73. $buyRequest = $this->getRequest();
  74. $params = $buyRequest->getData('_processing_params');
  75. /*
  76. * Notice check for params to be Varien_Object - by using object we protect from
  77. * params being forged and contain data from user frontend input
  78. */
  79. if ($params instanceof Varien_Object) {
  80. return $params;
  81. }
  82. return new Varien_Object();
  83. }
  84.  
  85. /**
  86. * Returns file info array if we need to get file from already existing file.
  87. * Or returns null, if we need to get file from uploaded array.
  88. *
  89. * @return null|array
  90. */
  91. protected function _getCurrentConfigFileInfo()
  92. {
  93. $option = $this->getOption();
  94. $optionId = $option->getId();
  95. $processingParams = $this->_getProcessingParams();
  96. $buyRequest = $this->getRequest();
  97.  
  98. // Check maybe restore file from config requested
  99. $optionActionKey = 'options_' . $optionId . '_file_action';
  100. if ($buyRequest->getData($optionActionKey) == 'save_old') {
  101. $fileInfo = array();
  102. $currentConfig = $processingParams->getCurrentConfig();
  103. if ($currentConfig) {
  104. $fileInfo = $currentConfig->getData('options/' . $optionId);
  105. }
  106. return $fileInfo;
  107. }
  108. return null;
  109. }
  110.  
  111. /**
  112. * Validate user input for option
  113. *
  114. * @throws Mage_Core_Exception
  115. * @param array $values All product option values, i.e. array (option_id => mixed, option_id => mixed...)
  116. * @return Mage_Catalog_Model_Product_Option_Type_File
  117. */
  118. public function validateUserValue($values)
  119. {
  120. Mage::getSingleton('checkout/session')->setUseNotice(false);
  121.  
  122. $this->setIsValid(true);
  123. $option = $this->getOption();
  124.  
  125. /*
  126. * Check whether we receive uploaded file or restore file by: reorder/edit configuration or
  127. * previous configuration with no newly uploaded file
  128. */
  129. $fileInfo = null;
  130. if (isset($values[$option->getId()]) && is_array($values[$option->getId()])) {
  131. // Legacy style, file info comes in array with option id index
  132. $fileInfo = $values[$option->getId()];
  133. } else {
  134. /*
  135. * New recommended style - file info comes in request processing parameters and we
  136. * sure that this file info originates from Magento, not from manually formed POST request
  137. */
  138. $fileInfo = $this->_getCurrentConfigFileInfo();
  139. }
  140. if ($fileInfo !== null) {
  141. if (is_array($fileInfo) && $this->_validateFile($fileInfo)) {
  142. $value = $fileInfo;
  143. } else {
  144. $value = null;
  145. }
  146. $this->setUserValue($value);
  147. return $this;
  148. }
  149.  
  150. // Process new uploaded file
  151. try {
  152. $this->_validateUploadedFile();
  153. } catch (Exception $e) {
  154. if ($this->getSkipCheckRequiredOption()) {
  155. $this->setUserValue(null);
  156. return $this;
  157. } else {
  158. Mage::throwException($e->getMessage());
  159. }
  160. }
  161. return $this;
  162. }
  163.  
  164. /**
  165. * Validate uploaded file
  166. *
  167. * @throws Mage_Core_Exception
  168. * @return Mage_Catalog_Model_Product_Option_Type_File
  169. */
  170. protected function _validateUploadedFile()
  171. {
  172. $option = $this->getOption();
  173. $processingParams = $this->_getProcessingParams();
  174.  
  175. /**
  176. * Upload init
  177. */
  178. $upload = new Zend_File_Transfer_Adapter_Http();
  179. $file = $processingParams->getFilesPrefix() . 'options_' . $option->getId() . '_file';
  180. try {
  181. $runValidation = $option->getIsRequire() || $upload->isUploaded($file);
  182. if (!$runValidation) {
  183. $this->setUserValue(null);
  184. return $this;
  185. }
  186.  
  187. $fileInfo = $upload->getFileInfo($file);
  188. $fileInfo = $fileInfo[$file];
  189. $fileInfo['title'] = $fileInfo['name'];
  190.  
  191. } catch (Exception $e) {
  192. // when file exceeds the upload_max_filesize, $_FILES is empty
  193. if (isset($_SERVER['CONTENT_LENGTH']) && $_SERVER['CONTENT_LENGTH'] > $this->_getUploadMaxFilesize()) {
  194. $this->setIsValid(false);
  195. $value = $this->_bytesToMbytes($this->_getUploadMaxFilesize());
  196. Mage::throwException(
  197. Mage::helper('catalog')->__("The file you uploaded is larger than %s Megabytes allowed by server", $value)
  198. );
  199. } else {
  200. switch($this->getProcessMode())
  201. {
  202. case Mage_Catalog_Model_Product_Type_Abstract::PROCESS_MODE_FULL:
  203. Mage::throwException(
  204. Mage::helper('catalog')->__('Please specify the product\'s required option(s).')
  205. );
  206. break;
  207. default:
  208. $this->setUserValue(null);
  209. break;
  210. }
  211. return $this;
  212. }
  213. }
  214.  
  215. /**
  216. * Option Validations
  217. */
  218.  
  219. // Image dimensions
  220. $_dimentions = array();
  221. if ($option->getImageSizeX() > 0) {
  222. $_dimentions['maxwidth'] = $option->getImageSizeX();
  223. }
  224. if ($option->getImageSizeY() > 0) {
  225. $_dimentions['maxheight'] = $option->getImageSizeY();
  226. }
  227. if (count($_dimentions) > 0) {
  228. $upload->addValidator('ImageSize', false, $_dimentions);
  229. }
  230.  
  231. // File extension
  232. $_allowed = $this->_parseExtensionsString($option->getFileExtension());
  233. if ($_allowed !== null) {
  234. $upload->addValidator('Extension', false, $_allowed);
  235. } else {
  236. $_forbidden = $this->_parseExtensionsString($this->getConfigData('forbidden_extensions'));
  237. if ($_forbidden !== null) {
  238. $upload->addValidator('ExcludeExtension', false, $_forbidden);
  239. }
  240. }
  241.  
  242. // Maximum filesize
  243. $upload->addValidator('FilesSize', false, array('max' => $this->_getUploadMaxFilesize()));
  244.  
  245. /**
  246. * Upload process
  247. */
  248.  
  249. $this->_initFilesystem();
  250.  
  251. if ($upload->isUploaded($file) && $upload->isValid($file)) {
  252.  
  253. $extension = pathinfo(strtolower($fileInfo['name']), PATHINFO_EXTENSION);
  254.  
  255. $fileName = Mage_Core_Model_File_Uploader::getCorrectFileName($fileInfo['name']);
  256. $dispersion = Mage_Core_Model_File_Uploader::getDispretionPath($fileName);
  257.  
  258. $filePath = $dispersion;
  259. $fileHash = md5(file_get_contents($fileInfo['tmp_name']));
  260. $filePath .= DS . $fileHash . '.' . $extension;
  261. $fileFullPath = $this->getQuoteTargetDir() . $filePath;
  262.  
  263. $upload->addFilter('Rename', array(
  264. 'target' => $fileFullPath,
  265. 'overwrite' => true
  266. ));
  267.  
  268. $this->getProduct()->getTypeInstance(true)->addFileQueue(array(
  269. 'operation' => 'receive_uploaded_file',
  270. 'src_name' => $file,
  271. 'dst_name' => $fileFullPath,
  272. 'uploader' => $upload,
  273. 'option' => $this,
  274. ));
  275.  
  276. $_width = 0;
  277. $_height = 0;
  278. if (is_readable($fileInfo['tmp_name'])) {
  279. $_imageSize = getimagesize($fileInfo['tmp_name']);
  280. if ($_imageSize) {
  281. $_width = $_imageSize[0];
  282. $_height = $_imageSize[1];
  283. }
  284. }
  285.  
  286. $this->setUserValue(array(
  287. 'type' => $fileInfo['type'],
  288. 'title' => $fileInfo['name'],
  289. 'quote_path' => $this->getQuoteTargetDir(true) . $filePath,
  290. 'order_path' => $this->getOrderTargetDir(true) . $filePath,
  291. 'fullpath' => $fileFullPath,
  292. 'size' => $fileInfo['size'],
  293. 'width' => $_width,
  294. 'height' => $_height,
  295. 'secret_key' => substr($fileHash, 0, 20),
  296. ));
  297.  
  298. } elseif ($upload->getErrors()) {
  299. $errors = $this->_getValidatorErrors($upload->getErrors(), $fileInfo);
  300.  
  301. if (count($errors) > 0) {
  302. $this->setIsValid(false);
  303. Mage::throwException( implode("\n", $errors) );
  304. }
  305. } else {
  306. $this->setIsValid(false);
  307. Mage::throwException(Mage::helper('catalog')->__('Please specify the product required option(s)'));
  308. }
  309. return $this;
  310. }
  311.  
  312. /**
  313. * Validate file
  314. *
  315. * @throws Mage_Core_Exception
  316. * @param array $optionValue
  317. * @return Mage_Catalog_Model_Product_Option_Type_Default
  318. */
  319. protected function _validateFile($optionValue)
  320. {
  321. $option = $this->getOption();
  322. /**
  323. * @see Mage_Catalog_Model_Product_Option_Type_File::_validateUploadFile()
  324. * There setUserValue() sets correct fileFullPath only for
  325. * quote_path. So we must form both full paths manually and
  326. * check them.
  327. */
  328. $checkPaths = array();
  329. if (isset($optionValue['quote_path'])) {
  330. $checkPaths[] = Mage::getBaseDir() . $optionValue['quote_path'];
  331. }
  332. if (isset($optionValue['order_path']) && !$this->getUseQuotePath()) {
  333. $checkPaths[] = Mage::getBaseDir() . $optionValue['order_path'];
  334. }
  335.  
  336. $fileFullPath = null;
  337. foreach ($checkPaths as $path) {
  338. if (!is_file($path)) {
  339. if (!Mage::helper('core/file_storage_database')->saveFileToFilesystem($fileFullPath)) {
  340. continue;
  341. }
  342. }
  343. $fileFullPath = $path;
  344. break;
  345. }
  346.  
  347. if ($fileFullPath === null) {
  348. return false;
  349. }
  350.  
  351. $validatorChain = new Zend_Validate();
  352.  
  353. $_dimentions = array();
  354.  
  355. if ($option->getImageSizeX() > 0) {
  356. $_dimentions['maxwidth'] = $option->getImageSizeX();
  357. }
  358. if ($option->getImageSizeY() > 0) {
  359. $_dimentions['maxheight'] = $option->getImageSizeY();
  360. }
  361. if (count($_dimentions) > 0 && !$this->_isImage($fileFullPath)) {
  362. return false;
  363. }
  364. if (count($_dimentions) > 0) {
  365. $validatorChain->addValidator(
  366. new Zend_Validate_File_ImageSize($_dimentions)
  367. );
  368. }
  369.  
  370. // File extension
  371. $_allowed = $this->_parseExtensionsString($option->getFileExtension());
  372. if ($_allowed !== null) {
  373. $validatorChain->addValidator(new Zend_Validate_File_Extension($_allowed));
  374. } else {
  375. $_forbidden = $this->_parseExtensionsString($this->getConfigData('forbidden_extensions'));
  376. if ($_forbidden !== null) {
  377. $validatorChain->addValidator(new Zend_Validate_File_ExcludeExtension($_forbidden));
  378. }
  379. }
  380.  
  381. // Maximum filesize
  382. $validatorChain->addValidator(
  383. new Zend_Validate_File_FilesSize(array('max' => $this->_getUploadMaxFilesize()))
  384. );
  385.  
  386.  
  387. if ($validatorChain->isValid($fileFullPath)) {
  388. $ok = is_readable($fileFullPath)
  389. && isset($optionValue['secret_key'])
  390. && substr(md5(file_get_contents($fileFullPath)), 0, 20) == $optionValue['secret_key'];
  391.  
  392. return $ok;
  393. } elseif ($validatorChain->getErrors()) {
  394. $errors = $this->_getValidatorErrors($validatorChain->getErrors(), $optionValue);
  395.  
  396. if (count($errors) > 0) {
  397. $this->setIsValid(false);
  398. Mage::throwException( implode("\n", $errors) );
  399. }
  400. } else {
  401. $this->setIsValid(false);
  402. Mage::throwException(Mage::helper('catalog')->__('Please specify the product required option(s)'));
  403. }
  404. }
  405.  
  406. /**
  407. * Get Error messages for validator Errors
  408. * @param array $errors Array of validation failure message codes @see Zend_Validate::getErrors()
  409. * @param array $fileInfo File info
  410. * @return array Array of error messages
  411. */
  412. protected function _getValidatorErrors($errors, $fileInfo)
  413. {
  414. $option = $this->getOption();
  415. $result = array();
  416. foreach ($errors as $errorCode) {
  417. if ($errorCode == Zend_Validate_File_ExcludeExtension::FALSE_EXTENSION) {
  418. $result[] = Mage::helper('catalog')->__("The file '%s' for '%s' has an invalid extension", $fileInfo['title'], $option->getTitle());
  419. } elseif ($errorCode == Zend_Validate_File_Extension::FALSE_EXTENSION) {
  420. $result[] = Mage::helper('catalog')->__("The file '%s' for '%s' has an invalid extension", $fileInfo['title'], $option->getTitle());
  421. } elseif ($errorCode == Zend_Validate_File_ImageSize::WIDTH_TOO_BIG
  422. || $errorCode == Zend_Validate_File_ImageSize::HEIGHT_TOO_BIG)
  423. {
  424. $result[] = Mage::helper('catalog')->__("Maximum allowed image size for '%s' is %sx%s px.", $option->getTitle(), $option->getImageSizeX(), $option->getImageSizeY());
  425. } elseif ($errorCode == Zend_Validate_File_FilesSize::TOO_BIG) {
  426. $result[] = Mage::helper('catalog')->__("The file '%s' you uploaded is larger than %s Megabytes allowed by server", $fileInfo['title'], $this->_bytesToMbytes($this->_getUploadMaxFilesize()));
  427. }
  428. }
  429. return $result;
  430. }
  431.  
  432. /**
  433. * Prepare option value for cart
  434. *
  435. * @return mixed Prepared option value
  436. */
  437. public function prepareForCart()
  438. {
  439. $option = $this->getOption();
  440. $optionId = $option->getId();
  441. $buyRequest = $this->getRequest();
  442.  
  443. // Prepare value and fill buyRequest with option
  444. $requestOptions = $buyRequest->getOptions();
  445. if ($this->getIsValid() && $this->getUserValue() !== null) {
  446. $value = $this->getUserValue();
  447.  
  448. // Save option in request, because we have no $_FILES['options']
  449. $requestOptions[$this->getOption()->getId()] = $value;
  450. $result = serialize($value);
  451. } else {
  452. /*
  453. * Clear option info from request, so it won't be stored in our db upon
  454. * unsuccessful validation. Otherwise some bad file data can happen in buyRequest
  455. * and be used later in reorders and reconfigurations.
  456. */
  457. if (is_array($requestOptions)) {
  458. unset($requestOptions[$this->getOption()->getId()]);
  459. }
  460. $result = null;
  461. }
  462. $buyRequest->setOptions($requestOptions);
  463.  
  464. // Clear action key from buy request - we won't need it anymore
  465. $optionActionKey = 'options_' . $optionId . '_file_action';
  466. $buyRequest->unsetData($optionActionKey);
  467.  
  468. return $result;
  469. }
  470.  
  471. /**
  472. * Return formatted option value for quote option
  473. *
  474. * @param string $optionValue Prepared for cart option value
  475. * @return string
  476. */
  477. public function getFormattedOptionValue($optionValue)
  478. {
  479. if ($this->_formattedOptionValue === null) {
  480. try {
  481. $value = unserialize($optionValue);
  482.  
  483. $customOptionUrlParams = $this->getCustomOptionUrlParams()
  484. ? $this->getCustomOptionUrlParams()
  485. : array(
  486. 'id' => $this->getConfigurationItemOption()->getId(),
  487. 'key' => $value['secret_key']
  488. );
  489.  
  490. $value['url'] = array('route' => $this->_customOptionDownloadUrl, 'params' => $customOptionUrlParams);
  491.  
  492. $this->_formattedOptionValue = $this->_getOptionHtml($value);
  493. $this->getConfigurationItemOption()->setValue(serialize($value));
  494. return $this->_formattedOptionValue;
  495. } catch (Exception $e) {
  496. return $optionValue;
  497. }
  498. }
  499. return $this->_formattedOptionValue;
  500. }
  501.  
  502. /**
  503. * Format File option html
  504. *
  505. * @param string|array $optionValue Serialized string of option data or its data array
  506. * @return string
  507. */
  508. protected function _getOptionHtml($optionValue)
  509. {
  510. $value = $this->_unserializeValue($optionValue);
  511. try {
  512. if (isset($value) && isset($value['width']) && isset($value['height'])
  513. && $value['width'] > 0 && $value['height'] > 0
  514. ) {
  515. $sizes = $value['width'] . ' x ' . $value['height'] . ' ' . Mage::helper('catalog')->__('px.');
  516. } else {
  517. $sizes = '';
  518. }
  519.  
  520. $urlRoute = !empty($value['url']['route']) ? $value['url']['route'] : '';
  521. $urlParams = !empty($value['url']['params']) ? $value['url']['params'] : '';
  522. $title = !empty($value['title']) ? $value['title'] : '';
  523.  
  524. return sprintf('<a href="%s" target="_blank">%s</a> %s',
  525. $this->_getOptionDownloadUrl($urlRoute, $urlParams),
  526. Mage::helper('core')->escapeHtml($title),
  527. $sizes
  528. );
  529. } catch (Exception $e) {
  530. Mage::throwException(Mage::helper('catalog')->__("File options format is not valid."));
  531. }
  532. }
  533.  
  534. /**
  535. * Create a value from a storable representation
  536. *
  537. * @param mixed $value
  538. * @return array
  539. */
  540. protected function _unserializeValue($value)
  541. {
  542. if (is_array($value)) {
  543. return $value;
  544. } elseif (is_string($value) && !empty($value)) {
  545. return unserialize($value);
  546. } else {
  547. return array();
  548. }
  549. }
  550.  
  551. /**
  552. * Return printable option value
  553. *
  554. * @param string $optionValue Prepared for cart option value
  555. * @return string
  556. */
  557. public function getPrintableOptionValue($optionValue)
  558. {
  559. return strip_tags($this->getFormattedOptionValue($optionValue));
  560. }
  561.  
  562. /**
  563. * Return formatted option value ready to edit, ready to parse
  564. *
  565. * @param string $optionValue Prepared for cart option value
  566. * @return string
  567. */
  568. public function getEditableOptionValue($optionValue)
  569. {
  570. try {
  571. $value = unserialize($optionValue);
  572. return sprintf('%s [%d]',
  573. Mage::helper('core')->escapeHtml($value['title']),
  574. $this->getConfigurationItemOption()->getId()
  575. );
  576.  
  577. } catch (Exception $e) {
  578. return $optionValue;
  579. }
  580. }
  581.  
  582. /**
  583. * Parse user input value and return cart prepared value
  584. *
  585. * @param string $optionValue
  586. * @param array $productOptionValues Values for product option
  587. * @return string|null
  588. */
  589. public function parseOptionValue($optionValue, $productOptionValues)
  590. {
  591. // search quote item option Id in option value
  592. if (preg_match('/\[([0-9]+)\]/', $optionValue, $matches)) {
  593. $confItemOptionId = $matches[1];
  594. $option = Mage::getModel('sales/quote_item_option')->load($confItemOptionId);
  595. try {
  596. unserialize($option->getValue());
  597. return $option->getValue();
  598. } catch (Exception $e) {
  599. return null;
  600. }
  601. } else {
  602. return null;
  603. }
  604. }
  605.  
  606. /**
  607. * Prepare option value for info buy request
  608. *
  609. * @param string $optionValue
  610. * @return mixed
  611. */
  612. public function prepareOptionValueForRequest($optionValue)
  613. {
  614. try {
  615. $result = unserialize($optionValue);
  616. return $result;
  617. } catch (Exception $e) {
  618. return null;
  619. }
  620. }
  621.  
  622. /**
  623. * Quote item to order item copy process
  624. *
  625. * @return Mage_Catalog_Model_Product_Option_Type_File
  626. */
  627. public function copyQuoteToOrder()
  628. {
  629. $quoteOption = $this->getQuoteItemOption();
  630. try {
  631. $value = unserialize($quoteOption->getValue());
  632. if (!isset($value['quote_path'])) {
  633. throw new Exception();
  634. }
  635. $quoteFileFullPath = Mage::getBaseDir() . $value['quote_path'];
  636. if (!is_file($quoteFileFullPath) || !is_readable($quoteFileFullPath)) {
  637. throw new Exception();
  638. }
  639. $orderFileFullPath = Mage::getBaseDir() . $value['order_path'];
  640. $dir = pathinfo($orderFileFullPath, PATHINFO_DIRNAME);
  641. $this->_createWriteableDir($dir);
  642. Mage::helper('core/file_storage_database')->copyFile($quoteFileFullPath, $orderFileFullPath);
  643. @copy($quoteFileFullPath, $orderFileFullPath);
  644. } catch (Exception $e) {
  645. return $this;
  646. }
  647. return $this;
  648. }
  649.  
  650. /**
  651. * Main Destination directory
  652. *
  653. * @param boolean $relative If true - returns relative path to the webroot
  654. * @return string
  655. */
  656. public function getTargetDir($relative = false)
  657. {
  658. $fullPath = Mage::getBaseDir('media') . DS . 'custom_options';
  659. return $relative ? str_replace(Mage::getBaseDir(), '', $fullPath) : $fullPath;
  660. }
  661.  
  662. /**
  663. * Quote items destination directory
  664. *
  665. * @param boolean $relative If true - returns relative path to the webroot
  666. * @return string
  667. */
  668. public function getQuoteTargetDir($relative = false)
  669. {
  670. return $this->getTargetDir($relative) . DS . 'quote';
  671. }
  672.  
  673. /**
  674. * Order items destination directory
  675. *
  676. * @param boolean $relative If true - returns relative path to the webroot
  677. * @return string
  678. */
  679. public function getOrderTargetDir($relative = false)
  680. {
  681. return $this->getTargetDir($relative) . DS . 'order';
  682. }
  683.  
  684. /**
  685. * Set url to custom option download controller
  686. *
  687. * @param string $url
  688. * @return Mage_Catalog_Model_Product_Option_Type_File
  689. */
  690. public function setCustomOptionDownloadUrl($url)
  691. {
  692. $this->_customOptionDownloadUrl = $url;
  693. return $this;
  694. }
  695.  
  696. /**
  697. * Directory structure initializing
  698. */
  699. protected function _initFilesystem()
  700. {
  701. $this->_createWriteableDir($this->getTargetDir());
  702. $this->_createWriteableDir($this->getQuoteTargetDir());
  703. $this->_createWriteableDir($this->getOrderTargetDir());
  704.  
  705. // Directory listing and hotlink secure
  706. $io = new Varien_Io_File();
  707. $io->cd($this->getTargetDir());
  708. if (!$io->fileExists($this->getTargetDir() . DS . '.htaccess')) {
  709. $io->streamOpen($this->getTargetDir() . DS . '.htaccess');
  710. $io->streamLock(true);
  711. $io->streamWrite("Order deny,allow\nDeny from all");
  712. $io->streamUnlock();
  713. $io->streamClose();
  714. }
  715. }
  716.  
  717. /**
  718. * Create Writeable directory if it doesn't exist
  719. *
  720. * @param string Absolute directory path
  721. * @return void
  722. */
  723. protected function _createWriteableDir($path)
  724. {
  725. $io = new Varien_Io_File();
  726. if (!$io->isWriteable($path) && !$io->mkdir($path, 0777, true)) {
  727. Mage::throwException(Mage::helper('catalog')->__("Cannot create writeable directory '%s'.", $path));
  728. }
  729. }
  730.  
  731. /**
  732. * Return URL for option file download
  733. *
  734. * @return string
  735. */
  736. protected function _getOptionDownloadUrl($route, $params)
  737. {
  738. $websites = Mage::app()->getWebsites();
  739. $code = $websites[1]->getDefaultStore()->getCode();
  740. $params['_store'] = $code;
  741. return Mage::getUrl($route, $params);
  742. }
  743.  
  744. /**
  745. * Parse file extensions string with various separators
  746. *
  747. * @param string $extensions String to parse
  748. * @return array|null
  749. */
  750. protected function _parseExtensionsString($extensions)
  751. {
  752. preg_match_all('/[a-z0-9]+/si', strtolower($extensions), $matches);
  753. if (isset($matches[0]) && is_array($matches[0]) && count($matches[0]) > 0) {
  754. return $matches[0];
  755. }
  756. return null;
  757. }
  758.  
  759. /**
  760. * Simple check if file is image
  761. *
  762. * @param array|string $fileInfo - either file data from Zend_File_Transfer or file path
  763. * @return boolean
  764. */
  765. protected function _isImage($fileInfo)
  766. {
  767. // Maybe array with file info came in
  768. if (is_array($fileInfo)) {
  769. return strstr($fileInfo['type'], 'image/');
  770. }
  771.  
  772. // File path came in - check the physical file
  773. if (!is_readable($fileInfo)) {
  774. return false;
  775. }
  776. $imageInfo = getimagesize($fileInfo);
  777. if (!$imageInfo) {
  778. return false;
  779. }
  780. return true;
  781. }
  782.  
  783. /**
  784. * Max upload filesize in bytes
  785. *
  786. * @return int
  787. */
  788. protected function _getUploadMaxFilesize()
  789. {
  790. return min($this->_getBytesIniValue('upload_max_filesize'), $this->_getBytesIniValue('post_max_size'));
  791. }
  792.  
  793. /**
  794. * Return php.ini setting value in bytes
  795. *
  796. * @param string $ini_key php.ini Var name
  797. * @return int Setting value
  798. */
  799. protected function _getBytesIniValue($ini_key)
  800. {
  801. $_bytes = @ini_get($ini_key);
  802.  
  803. // kilobytes
  804. if (stristr($_bytes, 'k')) {
  805. $_bytes = intval($_bytes) * 1024;
  806. // megabytes
  807. } elseif (stristr($_bytes, 'm')) {
  808. $_bytes = intval($_bytes) * 1024 * 1024;
  809. // gigabytes
  810. } elseif (stristr($_bytes, 'g')) {
  811. $_bytes = intval($_bytes) * 1024 * 1024 * 1024;
  812. }
  813. return (int)$_bytes;
  814. }
  815.  
  816. /**
  817. * Simple converrt bytes to Megabytes
  818. *
  819. * @param int $bytes
  820. * @return int
  821. */
  822. protected function _bytesToMbytes($bytes)
  823. {
  824. return round($bytes / (1024 * 1024));
  825. }
  826. }
Advertisement
Add Comment
Please, Sign In to add comment