PageRenderTime 65ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/app/code/core/Mage/XmlConnect/controllers/Adminhtml/MobileController.php

https://bitbucket.org/andrewjleavitt/magestudy
PHP | 1290 lines | 906 code | 90 blank | 294 comment | 156 complexity | 472918160c408c2ff48ea90d0a8619fe MD5 | raw file
Possible License(s): CC-BY-SA-3.0, LGPL-2.1, GPL-2.0, WTFPL
  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 license@magentocommerce.com 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.magentocommerce.com for more information.
  20. *
  21. * @category Mage
  22. * @package Mage_XmlConnect
  23. * @copyright Copyright (c) 2010 Magento Inc. (http://www.magentocommerce.com)
  24. * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
  25. */
  26. /**
  27. * XmlConnect Adminhtml mobile controller
  28. *
  29. * @category Mage
  30. * @package Mage_XmlConnect
  31. * @author Magento Core Team <core@magentocommerce.com>
  32. */
  33. class Mage_XmlConnect_Adminhtml_MobileController extends Mage_Adminhtml_Controller_Action
  34. {
  35. /**
  36. * Initialize application
  37. *
  38. * @param string $paramName
  39. * @param string $type
  40. * @return Mage_XmlConnect_Model_Application
  41. */
  42. protected function _initApp($paramName = 'application_id', $type = false)
  43. {
  44. $id = (int) $this->getRequest()->getParam($paramName);
  45. $app = Mage::getModel('xmlconnect/application');
  46. if ($id) {
  47. $app->load($id);
  48. if ($app->getId()) {
  49. $app->loadConfiguration();
  50. }
  51. } else {
  52. $app->setType($type);
  53. Mage::register('current_app', $app);
  54. $app->loadDefaultConfiguration();
  55. Mage::unregister('current_app');
  56. }
  57. Mage::register('current_app', $app);
  58. return $app;
  59. }
  60. /**
  61. * Restore data from session $_POST and $_FILES (processed)
  62. *
  63. * @param array $data
  64. * @return array|null
  65. */
  66. protected function _restoreSessionFilesFormData($data)
  67. {
  68. $filesData = Mage::getSingleton('adminhtml/session')->getUploadedFilesFormData(true);
  69. if (!empty($filesData) && is_array($filesData)) {
  70. if (!is_array($data)) {
  71. $data = array();
  72. }
  73. foreach ($filesData as $filePath => $fileName) {
  74. $target =& $data;
  75. Mage::helper('xmlconnect')->_injectFieldToArray($target, $filePath, $fileName);
  76. }
  77. }
  78. return $data;
  79. }
  80. /**
  81. * Mobile applications management
  82. *
  83. * @return void
  84. */
  85. public function indexAction()
  86. {
  87. $this->loadLayout();
  88. $this->_setActiveMenu('xmlconnect/mobile');
  89. $this->renderLayout();
  90. }
  91. /**
  92. * Create new app
  93. *
  94. * @return void
  95. */
  96. public function newAction()
  97. {
  98. Mage::getSingleton('adminhtml/session')->setData('new_application', true);
  99. $this->loadLayout();
  100. $this->_setActiveMenu('xmlconnect/mobile');
  101. $this->renderLayout();
  102. }
  103. /**
  104. * Submission Action, loads application data
  105. *
  106. * @return void
  107. */
  108. public function submissionAction()
  109. {
  110. try {
  111. $app = $this->_initApp();
  112. if (!$app->getId()) {
  113. $this->_getSession()->addError($this->__('App does not exist.'));
  114. $this->_redirect('*/*/');
  115. return;
  116. }
  117. $app->loadSubmit();
  118. if ((bool) Mage::getSingleton('adminhtml/session')->getLoadSessionFlag(true)) {
  119. $data = $this->_restoreSessionFilesFormData(
  120. Mage::getSingleton('adminhtml/session')->getFormSubmissionData(true)
  121. );
  122. if (!empty($data)) {
  123. $app->setData(Mage::helper('xmlconnect')->arrayMergeRecursive($app->getData(), $data));
  124. }
  125. }
  126. $this->loadLayout();
  127. $this->_setActiveMenu('xmlconnect/mobile');
  128. $this->renderLayout();
  129. } catch (Mage_Core_Exception $e) {
  130. $this->_getSession()->addError($e->getMessage());
  131. if (isset($app)) {
  132. $this->_redirect('*/*/edit', array('application_id' => $app->getId()));
  133. } else {
  134. $this->_redirect('*/*/');
  135. }
  136. } catch (Exception $e) {
  137. $this->_getSession()->addException($e, $this->__('Can\'t open submission form.'));
  138. if (isset($app)) {
  139. $this->_redirect('*/*/edit', array('application_id' => $app->getId()));
  140. } else {
  141. $this->_redirect('*/*/');
  142. }
  143. }
  144. }
  145. /**
  146. * Edit app form
  147. *
  148. * @return void
  149. */
  150. public function editAction()
  151. {
  152. $redirectBack = false;
  153. try {
  154. $id = (int) $this->getRequest()->getParam('application_id');
  155. $type = $this->getRequest()->getParam('type');
  156. $app = $this->_initApp('application_id', $type);
  157. if (!$app->getId() && $id) {
  158. $this->_getSession()->addError($this->__('App does not exist.'));
  159. $this->_redirect('*/*/');
  160. return;
  161. }
  162. $newAppData = $this->_restoreSessionFilesFormData(
  163. Mage::getSingleton('adminhtml/session')->getFormData(true)
  164. );
  165. if (!empty($newAppData)) {
  166. $app->setData(Mage::helper('xmlconnect')->arrayMergeRecursive($app->getData(), $newAppData));
  167. }
  168. if ($app->getId() || $app->getType()) {
  169. Mage::getSingleton('adminhtml/session')->setData('new_application', false);
  170. } else {
  171. $this->_redirect('*/*/new');
  172. }
  173. $devArray = Mage::helper('xmlconnect')->getSupportedDevices();
  174. if (array_key_exists($app->getType(), $devArray)) {
  175. $deviceTitle = $devArray[$app->getType()];
  176. }
  177. $deviceTitle = isset($deviceTitle) ? $deviceTitle : $app->getType();
  178. $app->setDevtype($deviceTitle);
  179. $app->loadSubmit();
  180. $this->loadLayout();
  181. $this->_setActiveMenu('xmlconnect/mobile');
  182. $this->renderLayout();
  183. } catch (Mage_Core_Exception $e) {
  184. $this->_getSession()->addError($e->getMessage());
  185. $redirectBack = true;
  186. } catch (Exception $e) {
  187. $this->_getSession()->addError($this->__('Unable to load application form.'));
  188. $redirectBack = true;
  189. Mage::logException($e);
  190. }
  191. if ($redirectBack) {
  192. $this->_redirect('*/*/');
  193. return;
  194. }
  195. }
  196. /**
  197. * Submit POST application action
  198. *
  199. * @return void
  200. */
  201. public function submissionPostAction()
  202. {
  203. $data = $this->getRequest()->getPost();
  204. try {
  205. $isError = false;
  206. if (!empty($data)) {
  207. Mage::getSingleton('adminhtml/session')->setFormSubmissionData($this->_filterFormDataForSession($data));
  208. }
  209. /** @var $app Mage_XmlConnect_Model_Application */
  210. $app = $this->_initApp('key');
  211. $app->loadSubmit();
  212. $newAppData = $this->_processUploadedFiles($app->getData(), true);
  213. if (!empty($newAppData)) {
  214. $app->setData(Mage::helper('xmlconnect')->arrayMergeRecursive($app->getData(), $newAppData));
  215. }
  216. $params = $app->prepareSubmitParams($data);
  217. $errors = $app->validateSubmit($params);
  218. if ($errors !== true) {
  219. foreach ($errors as $err) {
  220. $this->_getSession()->addError($err);
  221. }
  222. $isError = true;
  223. }
  224. if (!$isError) {
  225. $this->_processPostRequest();
  226. $history = Mage::getModel('xmlconnect/history');
  227. $history->setData(array(
  228. 'params' => $params,
  229. 'application_id' => $app->getId(),
  230. 'created_at' => Mage::getModel('core/date')->date(),
  231. 'store_id' => $app->getStoreId(),
  232. 'title' => isset($params['title']) ? $params['title'] : '',
  233. 'name' => $app->getName(),
  234. 'code' => $app->getCode(),
  235. 'activation_key' => isset($params['resubmission_activation_key'])
  236. ? $params['resubmission_activation_key']
  237. : $params['key'],
  238. ));
  239. $history->save();
  240. $app->getResource()->updateApplicationStatus($app->getId(),
  241. Mage_XmlConnect_Model_Application::APP_STATUS_SUCCESS);
  242. $this->_getSession()->addSuccess($this->__('App has been submitted.'));
  243. $this->_clearSessionData();
  244. $this->_redirect('*/*/edit', array('application_id' => $app->getId()));
  245. } else {
  246. Mage::getSingleton('adminhtml/session')->setLoadSessionFlag(true);
  247. $this->_redirect('*/*/submission', array('application_id' => $app->getId()));
  248. }
  249. } catch (Mage_Core_Exception $e) {
  250. $this->_getSession()->addError($e->getMessage());
  251. if (isset($app)) {
  252. Mage::getSingleton('adminhtml/session')->setLoadSessionFlag(true);
  253. $this->_redirect('*/*/submission', array('application_id' => $app->getId()));
  254. } else {
  255. $this->_redirect('*/*/');
  256. }
  257. } catch (Exception $e) {
  258. $this->_getSession()->addException($e, $this->__('Can\'t submit application.'));
  259. Mage::logException($e);
  260. if (isset($app)) {
  261. Mage::getSingleton('adminhtml/session')->setLoadSessionFlag(true);
  262. $this->_redirect('*/*/submission', array('application_id' => $app->getId()));
  263. } else {
  264. $this->_redirect('*/*/');
  265. }
  266. }
  267. }
  268. /**
  269. * Format post/get data for session storage
  270. *
  271. * @param array $data - $_REQUEST[]
  272. * @return array
  273. */
  274. protected function _filterFormDataForSession($data)
  275. {
  276. $params = null;
  277. if (isset($data['conf']) && is_array($data['conf'])) {
  278. if (isset($data['conf']['submit_text']) && is_array($data['conf']['submit_text'])) {
  279. $params = &$data['conf']['submit_text'];
  280. }
  281. }
  282. if (isset($params['country']) && is_array($params['country'])) {
  283. $data['conf']['submit_text']['country'] = implode(',', $params['country']);
  284. }
  285. return $data;
  286. }
  287. /**
  288. * Clear session data
  289. * Used after successful save/submit action
  290. *
  291. * @return this
  292. */
  293. protected function _clearSessionData()
  294. {
  295. Mage::getSingleton('adminhtml/session')->unsFormData();
  296. Mage::getSingleton('adminhtml/session')->unsFormSubmissionData();
  297. Mage::getSingleton('adminhtml/session')->unsUploadedFilesFormData();
  298. return $this;
  299. }
  300. /**
  301. * Send HTTP POST request to magentocommerce.com
  302. *
  303. * @return void
  304. */
  305. protected function _processPostRequest()
  306. {
  307. try {
  308. $app = Mage::helper('xmlconnect')->getApplication();
  309. $params = $app->getSubmitParams();
  310. $appConnectorUrl = Mage::getStoreConfig('xmlconnect/mobile_application/magentocommerce_url');
  311. $ch = curl_init($appConnectorUrl . $params['key']);
  312. // set URL and other appropriate options
  313. curl_setopt($ch, CURLOPT_POST, 1);
  314. curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
  315. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
  316. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  317. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  318. curl_setopt($ch, CURLOPT_TIMEOUT, 60);
  319. // Execute the request.
  320. $result = curl_exec($ch);
  321. $succeeded = curl_errno($ch) == 0 ? true : false;
  322. // close cURL resource, and free up system resources
  323. curl_close($ch);
  324. // Assert that we received an expected message in reponse.
  325. $resultArray = json_decode($result, true);
  326. $app->setResult($result);
  327. $success = (isset($resultArray['success'])) && ($resultArray['success'] === true);
  328. $app->setSuccess($success);
  329. if (!$app->getSuccess()) {
  330. $message = '';
  331. $message = isset($resultArray['message']) ? $resultArray['message']: '';
  332. if (is_array($message)) {
  333. $message = implode(' ,', $message);
  334. }
  335. Mage::throwException($this->__('Submit App failure. %s', $message));
  336. }
  337. } catch (Exception $e) {
  338. throw $e;
  339. }
  340. }
  341. /**
  342. * Save action
  343. *
  344. * @return void
  345. */
  346. public function saveAction()
  347. {
  348. $data = $this->getRequest()->getPost();
  349. $redirectSubmit = $this->getRequest()->getParam('submitapp', false);
  350. $app = false;
  351. $isError = false;
  352. if ($data) {
  353. Mage::getSingleton('adminhtml/session')->setFormData($data);
  354. try {
  355. $id = $this->getRequest()->getParam('application_id');
  356. if (!$id && isset($data['devtype'])) {
  357. $devArray = Mage::helper('xmlconnect')->getSupportedDevices();
  358. if (!array_key_exists($data['devtype'], $devArray)) {
  359. $this->_getSession()->addError($this->__('Wrong device type.'));
  360. $isError = true;
  361. }
  362. }
  363. $app = $this->_initApp('application_id', $data['devtype']);
  364. if (!$app->getId() && $id) {
  365. $this->_getSession()->addError($this->__('App does not exist.'));
  366. $this->_redirect('*/*/');
  367. return;
  368. }
  369. $app->addData($this->_preparePostData($data));
  370. $app->addData($this->_processUploadedFiles($app->getData()));
  371. $errors = $app->validate();
  372. if ($errors !== true) {
  373. foreach ($errors as $err) {
  374. $this->_getSession()->addError($err);
  375. }
  376. $isError = true;
  377. }
  378. if (!$isError) {
  379. $this->_saveThemeAction($data, 'current_theme');
  380. $app->save();
  381. $this->_getSession()->addSuccess($this->__('App has been saved.'));
  382. $this->_clearSessionData();
  383. }
  384. } catch (Mage_Core_Exception $e) {
  385. $this->_getSession()->addException($e, $e->getMessage());
  386. $isError = true;
  387. } catch (Exception $e) {
  388. $this->_getSession()->addException($e, $this->__('Unable to save app.'));
  389. $isError = true;
  390. Mage::logException($e);
  391. }
  392. }
  393. $isApplication = $app instanceof Mage_XmlConnect_Model_Application;
  394. if (!$isError && $isApplication && $app->getId() && $redirectSubmit) {
  395. $this->_redirect('*/*/submission', array('application_id' => $app->getId()));
  396. } else if ($isError && $isApplication && $app->getId()) {
  397. Mage::getSingleton('adminhtml/session')->setLoadSessionFlag(true);
  398. $this->_redirect('*/*/edit', array('application_id' => $app->getId()));
  399. } else if ($isError && $isApplication && !$app->getId() && $app->getType()) {
  400. $this->_redirect('*/*/edit', array('type' => $app->getType()));
  401. } else if ($this->getRequest()->getParam('back') && $isApplication) {
  402. $this->_redirect('*/*/edit', array('application_id' => $app->getId()));
  403. } else {
  404. $this->_redirect('*/*/');
  405. }
  406. }
  407. /**
  408. * Save changes to theme
  409. *
  410. * @param array $data
  411. * @param string $paramId
  412. */
  413. protected function _saveThemeAction($data, $paramId = 'saveTheme')
  414. {
  415. try {
  416. $themeName = $this->getRequest()->getParam($paramId, false);
  417. if ($themeName) {
  418. if ($themeName == Mage::helper('xmlconnect/theme')->getCustomThemeName()) {
  419. $theme = Mage::helper('xmlconnect/theme')->getThemeByName($themeName);
  420. if ($theme instanceof Mage_XmlConnect_Model_Theme) {
  421. if ($paramId == 'saveTheme') {
  422. $convertedConf = $this->_convertPost($data);
  423. } else {
  424. if (isset($data['conf'])) {
  425. $convertedConf = $data['conf'];
  426. } else {
  427. $response = array(
  428. 'error' => true,
  429. 'message' => $this->__('Cannot save theme "%s". Incorrect data received', $themeName)
  430. );
  431. }
  432. }
  433. if (!isset($response)) {
  434. $theme->importAndSaveData($convertedConf);
  435. $response = Mage::helper('xmlconnect/theme')->getAllThemesArray(true);
  436. }
  437. } else {
  438. $response = array('error' => true, 'message' => $this->__('Cannot load theme "%s".', $themeName));
  439. }
  440. } else {
  441. $response = Mage::helper('xmlconnect/theme')->getAllThemesArray(true);
  442. }
  443. } else {
  444. $response = array('error' => true, 'message' => $this->__('Theme name is not set.'));
  445. }
  446. } catch (Mage_Core_Exception $e) {
  447. $response = array(
  448. 'error' => true,
  449. 'message' => $e->getMessage(),
  450. );
  451. } catch (Exception $e) {
  452. $response = array(
  453. 'error' => true,
  454. 'message' => $this->__('Can\'t save theme.')
  455. );
  456. }
  457. if (is_array($response)) {
  458. $response = Mage::helper('core')->jsonEncode($response);
  459. $this->getResponse()->setBody($response);
  460. }
  461. }
  462. /**
  463. * Converts native Ajax data from flat to real array
  464. * Convert array key->value pairs inside array like:
  465. * "conf_native_bar_tintcolor" => $val to $conf['native']['bar']['tintcolor'] => $val
  466. *
  467. * @param array $data $_POST
  468. * @return array
  469. */
  470. protected function _convertPost($data)
  471. {
  472. $conf = array();
  473. foreach ($data as $key => $val) {
  474. $parts = explode('_', $key);
  475. // "4" - is number of expected params conf_native_bar_tintcolor in correct data
  476. if (is_array($parts) && (count($parts) == 4)) {
  477. @list($key0, $key1, $key2, $key3) = $parts;
  478. if (!isset($conf[$key1])) {
  479. $conf[$key1] = array();
  480. }
  481. if (!isset($conf[$key1][$key2])) {
  482. $conf[$key1][$key2] = array();
  483. }
  484. $conf[$key1][$key2][$key3] = $val;
  485. }
  486. }
  487. return $conf;
  488. }
  489. /**
  490. * Save Theme action
  491. *
  492. * @return void
  493. */
  494. public function saveThemeAction()
  495. {
  496. $data = $this->getRequest()->getPost();
  497. $this->_saveThemeAction($data);
  498. }
  499. /**
  500. * Save Theme action
  501. *
  502. * @return void
  503. */
  504. public function resetThemeAction()
  505. {
  506. try {
  507. $theme = $this->getRequest()->getPost('theme', null);
  508. Mage::helper('xmlconnect/theme')->resetTheme($theme);
  509. $response = Mage::helper('xmlconnect/theme')->getAllThemesArray(true);
  510. } catch (Mage_Core_Exception $e) {
  511. $response = array(
  512. 'error' => true,
  513. 'message' => $e->getMessage(),
  514. );
  515. } catch (Exception $e) {
  516. $response = array(
  517. 'error' => true,
  518. 'message' => $this->__('Can\'t reset theme.')
  519. );
  520. }
  521. if (is_array($response)) {
  522. $response = Mage::helper('core')->jsonEncode($response);
  523. $this->getResponse()->setBody($response);
  524. }
  525. }
  526. /**
  527. * Preview Home action handler
  528. *
  529. * @return void
  530. */
  531. public function previewHomeAction()
  532. {
  533. $this->_previewAction('preview_home_content');
  534. }
  535. /**
  536. * Preview Home landscape mode action handler
  537. */
  538. public function previewHomeHorAction()
  539. {
  540. $this->_previewAction('preview_home_hor_content');
  541. }
  542. /**
  543. * Preview Catalog action handler
  544. *
  545. * @return void
  546. */
  547. public function previewCatalogAction()
  548. {
  549. $this->_previewAction('preview_catalog_content');
  550. }
  551. /**
  552. * Preview Catalog landscape mode action handler
  553. */
  554. public function previewCatalogHorAction()
  555. {
  556. $this->_previewAction('preview_catalog_hor_content');
  557. }
  558. /**
  559. * Preview Product Info action handler
  560. */
  561. public function previewProductinfoAction()
  562. {
  563. $this->_previewAction('preview_productinfo_content');
  564. }
  565. /**
  566. * Preview AirMail Queue Template action handler
  567. */
  568. public function previewQueueAction()
  569. {
  570. $message = $this->_initMessage();
  571. if ($message->getId()) {
  572. $this->getRequest()->setParam('queue_preview', $message->getId());
  573. }
  574. $this->_forward('previewTemplate');
  575. }
  576. /**
  577. * Preview AirMail Template action handler
  578. */
  579. public function previewTemplateAction()
  580. {
  581. $this->loadLayout('adminhtml_mobile_template_preview');
  582. $this->renderLayout();
  583. }
  584. /**
  585. * Preview action implementation
  586. *
  587. * @param string $block
  588. */
  589. protected function _previewAction($block)
  590. {
  591. $redirectBack = false;
  592. try {
  593. $deviceType = $this->getRequest()->getParam('devtype');
  594. $app = $this->_initApp('application_id', $deviceType);
  595. if (!$this->getRequest()->getParam('submission_action')) {
  596. $app->addData($this->_preparePostData($this->getRequest()->getPost()));
  597. }
  598. /** render base configuration of application */
  599. $appConf = $app->getRenderConf();
  600. try {
  601. /** try to upload files */
  602. $dataUploaded = $this->_processUploadedFiles($app->getData());
  603. $app->addData($dataUploaded);
  604. /** render configuration with just uploaded images */
  605. $appConf = $app->getRenderConf();
  606. } catch (Exception $e) {
  607. /** when cannot upload - just tell user what is happen */
  608. $jsErrorMessage = addslashes($e->getMessage());
  609. }
  610. $this->loadLayout(false);
  611. $preview = $this->getLayout()->getBlock($block);
  612. if (isset($jsErrorMessage)) {
  613. $preview->setJsErrorMessage($jsErrorMessage);
  614. }
  615. $preview->setConf($appConf);
  616. Mage::helper('xmlconnect')->getPreviewModel()->setConf($appConf);
  617. $this->renderLayout();
  618. return;
  619. } catch (Mage_Core_Exception $e) {
  620. $this->_getSession()->addException($e, $e->getMessage());
  621. $redirectBack = true;
  622. } catch (Exception $e) {
  623. $this->_getSession()->addException($e, $this->__('Unable to process preview.'));
  624. $redirectBack = true;
  625. }
  626. if (isset($app) && $app instanceof Mage_XmlConnect_Model_Application && $redirectBack) {
  627. $this->_redirect('*/*/edit', array('application_id' => $app->getId()));
  628. } else {
  629. $this->_redirect('*/*/');
  630. }
  631. }
  632. /**
  633. * Delete app action
  634. *
  635. * @return void
  636. */
  637. public function deleteAction()
  638. {
  639. try {
  640. $app = $this->_initApp();
  641. if (!$app->getIsSubmitted()) {
  642. $app->delete();
  643. $this->_getSession()->addSuccess($this->__('App has been deleted.'));
  644. } else {
  645. Mage::throwException($this->__('It\'s not allowed to delete submitted application.'));
  646. }
  647. } catch (Mage_Core_Exception $e) {
  648. $this->_getSession()->addException($e, $e->getMessage());
  649. } catch (Exception $e) {
  650. $this->_getSession()->addException($e, $this->__('Unable to find an app to delete.'));
  651. }
  652. $this->_redirect('*/*/');
  653. }
  654. /**
  655. * Delete template action
  656. */
  657. public function deleteTemplateAction()
  658. {
  659. // check if we know what should be deleted
  660. if ($id = $this->getRequest()->getParam('id')) {
  661. try {
  662. // init template and delete
  663. Mage::getModel('xmlconnect/template')->load($id)->delete();
  664. // display success message
  665. Mage::getSingleton('adminhtml/session')->addSuccess(
  666. $this->__('Template has been deleted.')
  667. );
  668. // go to grid
  669. $this->_redirect('*/*/template');
  670. return;
  671. } catch (Exception $e) {
  672. // display error message
  673. Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
  674. // go back to edit form
  675. $this->_redirect('*/*/template', array('id' => $id));
  676. return;
  677. }
  678. }
  679. // display error message
  680. Mage::getSingleton('adminhtml/session')->addError(
  681. $this->__('Unable to find template to delete.')
  682. );
  683. }
  684. /**
  685. * Check the permission to run it
  686. *
  687. * @return boolean
  688. */
  689. protected function _isAllowed()
  690. {
  691. return Mage::getSingleton('admin/session')->isAllowed('xmlconnect');
  692. }
  693. /**
  694. * List application submit history
  695. */
  696. public function historyAction()
  697. {
  698. $this->loadLayout();
  699. $this->_setActiveMenu('xmlconnect/history');
  700. $this->renderLayout();
  701. }
  702. /**
  703. * Render apps grid
  704. *
  705. * @return void
  706. */
  707. public function gridAction()
  708. {
  709. $this->loadLayout(false);
  710. $this->_setActiveMenu('xmlconnect/mobile');
  711. $this->renderLayout();
  712. }
  713. /**
  714. * Process all uploaded files
  715. * setup filenames to the configuration return array
  716. *
  717. * @param array $data
  718. * @param bool $restore
  719. * @return array
  720. */
  721. protected function _processUploadedFiles($data, $restore = false)
  722. {
  723. if ($restore === true) {
  724. $this->_uploadedFiles = Mage::getSingleton('adminhtml/session')->getUploadedFilesFormDataSubmit();
  725. }
  726. if (!isset($this->_uploadedFiles) || !is_array($this->_uploadedFiles)) {
  727. $this->_uploadedFiles = array();
  728. }
  729. if (!empty($_FILES)) {
  730. foreach ($_FILES as $field => $file) {
  731. if (!empty($file['name']) && is_scalar($file['name'])) {
  732. $uploadedFileName = Mage::helper('xmlconnect/image')->handleUpload($field, $data);
  733. if (!empty($uploadedFileName)) {
  734. $this->_uploadedFiles[$field] = $uploadedFileName;
  735. }
  736. }
  737. }
  738. }
  739. foreach ($this->_uploadedFiles as $fieldPath => $fileName) {
  740. Mage::helper('xmlconnect')->_injectFieldToArray($data, $fieldPath, $fileName);
  741. }
  742. Mage::getSingleton('adminhtml/session')->setUploadedFilesFormData($this->_uploadedFiles);
  743. if ($restore === true) {
  744. Mage::getSingleton('adminhtml/session')->setUploadedFilesFormDataSubmit($this->_uploadedFiles);
  745. }
  746. return $data;
  747. }
  748. /**
  749. * Prepare post data
  750. * Retains previous data in the object.
  751. *
  752. * @param array $arr
  753. * @return array
  754. */
  755. public function _preparePostData(array $arr)
  756. {
  757. unset($arr['code']);
  758. if (!empty($arr['conf']['native']['pages'])) {
  759. /**
  760. * Remove emptied pages
  761. */
  762. $pages = array();
  763. foreach ($arr['conf']['native']['pages'] as $_page) {
  764. if (!empty($_page['id']) && !empty($_page['label'])) {
  765. $pages[] = $_page;
  766. }
  767. }
  768. $arr['conf']['native']['pages'] = $pages;
  769. }
  770. if (isset($arr['conf']['new_pages']['ids']) && isset($arr['conf']['new_pages']['labels'])) {
  771. $newPages = array();
  772. $cmsPages = &$arr['conf']['new_pages'];
  773. $idx = 0;
  774. foreach ($cmsPages['ids'] as $key => $value) {
  775. if (!empty($value) && !empty($cmsPages['labels'][$key])) {
  776. $newPages[$idx]['id'] = trim($value);
  777. $newPages[$idx++]['label'] = trim($cmsPages['labels'][$key]);
  778. }
  779. }
  780. if (!isset($arr['conf']['native']['pages'])) {
  781. $arr['conf']['native']['pages'] = array();
  782. }
  783. if (!empty($newPages)) {
  784. $arr['conf']['native']['pages'] = array_merge($arr['conf']['native']['pages'], $newPages);
  785. }
  786. unset($arr['conf']['new_pages']);
  787. }
  788. /**
  789. * Check cache settings
  790. */
  791. $lifetime = &$arr['conf']['native']['cacheLifetime'];
  792. $lifetime = $lifetime <= 0 ? '' : (int)$lifetime;
  793. /**
  794. * Restoring current_theme over selected but not applied theme
  795. */
  796. if (isset($arr['current_theme'])) {
  797. $arr['conf']['extra']['theme'] = $arr['current_theme'];
  798. }
  799. if (!isset($arr['conf']['defaultCheckout'])) {
  800. $arr['conf']['defaultCheckout'] = array();
  801. }
  802. if (!isset($arr['conf']['defaultCheckout']['isActive'])) {
  803. $arr['conf']['defaultCheckout']['isActive'] = 0;
  804. }
  805. if (!isset($arr['conf']['paypal'])) {
  806. $arr['conf']['paypal'] = array();
  807. }
  808. if (!isset($arr['conf']['paypal']['isActive'])) {
  809. $arr['conf']['paypal']['isActive'] = 0;
  810. }
  811. return $arr;
  812. }
  813. /**
  814. * Submission history grid action on submission history tab
  815. */
  816. public function submissionHistoryGridAction()
  817. {
  818. $this->_initApp();
  819. $this->loadLayout();
  820. $this->renderLayout();
  821. }
  822. /**
  823. * Initialize message queue
  824. *
  825. * @param string $paramName
  826. * @return Mage_XmlConnect_Model_Queue
  827. */
  828. protected function _initMessage($paramName = 'id')
  829. {
  830. $id = (int) $this->getRequest()->getParam($paramName);
  831. $message = Mage::getModel('xmlconnect/queue')->load($id);
  832. Mage::unregister('current_message');
  833. Mage::register('current_message', $message);
  834. return $message;
  835. }
  836. /**
  837. * Initialize Template object
  838. *
  839. * @param string $paramName
  840. * @return Mage_XmlConnect_Model_Template
  841. */
  842. protected function _initTemplate($paramName = 'id')
  843. {
  844. $id = (int) $this->getRequest()->getParam($paramName);
  845. $template = Mage::getModel('xmlconnect/template')->load($id);
  846. Mage::unregister('current_template');
  847. Mage::register('current_template', $template);
  848. return $template;
  849. }
  850. /**
  851. * List AirMail message queue grid
  852. *
  853. * @return void
  854. */
  855. public function queueAction()
  856. {
  857. $this->loadLayout();
  858. $this->_setActiveMenu('xmlconnect/queue');
  859. $this->renderLayout();
  860. }
  861. /**
  862. * Edit message action
  863. *
  864. * @return void
  865. */
  866. public function editQueueAction()
  867. {
  868. $message = $this->_initMessage();
  869. if ($message->getId()) {
  870. $this->getRequest()->setParam('template_id', $message->getTemplateId());
  871. $this->_initTemplate('template_id');
  872. }
  873. $this->_forward('queueMessage');
  874. }
  875. /**
  876. * Filtering posted data. Converting localized data if needed
  877. *
  878. * @param array
  879. * @return array
  880. */
  881. protected function _filterPostData($data)
  882. {
  883. $data = $this->_filterDateTime($data, array('exec_time'));
  884. return $data;
  885. }
  886. /**
  887. * Cancel queue action
  888. *
  889. * @return void
  890. */
  891. public function cancelQueueAction()
  892. {
  893. try {
  894. $id = $this->getRequest()->getParam('id');
  895. $message = $this->_initMessage();
  896. if (!$message->getId() && $id) {
  897. $this->_getSession()->addError($this->__('Queue does not exist.'));
  898. $this->_redirect('*/*/');
  899. return;
  900. }
  901. $message->setStatus(Mage_XmlConnect_Model_Queue::STATUS_CANCELED);
  902. $message->save();
  903. } catch (Mage_Core_Exception $e) {
  904. $this->_getSession()->addException($e, $e->getMessage());
  905. } catch (Exception $e) {
  906. $this->_getSession()->addException($e, $this->__('Unable to cancel queue.'));
  907. Mage::logException($e);
  908. }
  909. $this->_redirect('*/*/queue');
  910. }
  911. /**
  912. * Delete queue action
  913. *
  914. * @return void
  915. */
  916. public function deleteQueueAction()
  917. {
  918. try {
  919. $id = $this->getRequest()->getParam('id');
  920. $message = $this->_initMessage();
  921. if (!$message->getId() && $id) {
  922. $this->_getSession()->addError($this->__('Queue does not exist.'));
  923. $this->_redirect('*/*/');
  924. return;
  925. }
  926. $message->setStatus(Mage_XmlConnect_Model_Queue::STATUS_DELETED);
  927. $message->save();
  928. } catch (Mage_Core_Exception $e) {
  929. $this->_getSession()->addException($e, $e->getMessage());
  930. } catch (Exception $e) {
  931. $this->_getSession()->addException($e, $this->__('Unable to delete queue.'));
  932. Mage::logException($e);
  933. }
  934. $this->_redirect('*/*/queue');
  935. }
  936. /**
  937. * Cancel selected queue action
  938. *
  939. * @return void
  940. */
  941. public function massCancelQueueAction()
  942. {
  943. $queueIds = $this->getRequest()->getParam('queue');
  944. if(!is_array($queueIds)) {
  945. Mage::getSingleton('adminhtml/session')->addError(Mage::helper('adminhtml')->__('Please select message(s).'));
  946. } else {
  947. try {
  948. $queue = Mage::getModel('xmlconnect/queue');
  949. foreach ($queueIds as $queueId) {
  950. $queue->reset()
  951. ->load((int)$queueId)
  952. ->setStatus(Mage_XmlConnect_Model_Queue::STATUS_CANCELED)
  953. ->save();
  954. }
  955. Mage::getSingleton('adminhtml/session')->addSuccess(
  956. Mage::helper('adminhtml')->__('Total of %d record(s) were canceled.', count($queueIds))
  957. );
  958. } catch (Exception $e) {
  959. Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
  960. }
  961. }
  962. $this->_redirect('*/*/queue');
  963. }
  964. /**
  965. * Delete selected queue action
  966. *
  967. * @return void
  968. */
  969. public function massDeleteQueueAction()
  970. {
  971. $queueIds = $this->getRequest()->getParam('queue');
  972. if(!is_array($queueIds)) {
  973. Mage::getSingleton('adminhtml/session')->addError(Mage::helper('adminhtml')->__('Please select message(s).'));
  974. } else {
  975. try {
  976. $queue = Mage::getModel('xmlconnect/queue');
  977. foreach ($queueIds as $queueId) {
  978. $queue->reset()
  979. ->load($queueId)
  980. ->setStatus(Mage_XmlConnect_Model_Queue::STATUS_DELETED)
  981. ->save();
  982. }
  983. Mage::getSingleton('adminhtml/session')->addSuccess(
  984. Mage::helper('adminhtml')->__(
  985. 'Total of %d record(s) were deleted.', count($queueIds)
  986. )
  987. );
  988. } catch (Exception $e) {
  989. Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
  990. }
  991. }
  992. $this->_redirect('*/*/queue');
  993. }
  994. /**
  995. * Save AirMail message action
  996. *
  997. * @return void
  998. */
  999. public function saveMessageAction()
  1000. {
  1001. $data = $this->_filterPostData($this->getRequest()->getPost());
  1002. $isError = false;
  1003. $message = false;
  1004. if ($data) {
  1005. try {
  1006. $data = Mage::getModel('core/input_filter_maliciousCode')->filter($data);
  1007. $template = $this->_initTemplate('template_id');
  1008. $message = $this->_initMessage();
  1009. if (!$template->getId() && !$message->getTemplateId()) {
  1010. $this->_getSession()->addError(
  1011. $this->__('Template for new AirMail Message does not exist.')
  1012. );
  1013. $this->_redirect('*/*/queue');
  1014. return;
  1015. }
  1016. $temporaryObject = new Varien_Object();
  1017. $temporaryObject->setData($data);
  1018. if ($temporaryObject->getTemplateId()) {
  1019. $message->setTemplateId($temporaryObject->getTemplateId());
  1020. } else {
  1021. $message->setTemplateId($template->getId());
  1022. }
  1023. if (!$message->getId()) {
  1024. // set status for new messages only
  1025. $message->setStatus(Mage_XmlConnect_Model_Queue::STATUS_IN_QUEUE);
  1026. } elseif ($message->getStatus() != Mage_XmlConnect_Model_Queue::STATUS_IN_QUEUE) {
  1027. $this->_getSession()->addError(
  1028. $this->__('Message can be edited when status of the message is "IN QUEUE" only.')
  1029. );
  1030. $this->_redirect('*/*/queue');
  1031. return;
  1032. }
  1033. switch ($temporaryObject->getType()) {
  1034. case Mage_XmlConnect_Model_Queue::MESSAGE_TYPE_AIRMAIL:
  1035. $message->setData('type', Mage_XmlConnect_Model_Queue::MESSAGE_TYPE_AIRMAIL);
  1036. break;
  1037. case Mage_XmlConnect_Model_Queue::MESSAGE_TYPE_PUSH:
  1038. default:
  1039. $message->setData('type', Mage_XmlConnect_Model_Queue::MESSAGE_TYPE_PUSH);
  1040. break;
  1041. }
  1042. if ($temporaryObject->getExecTime()) {
  1043. $message->setExecTime(
  1044. Mage::getSingleton('core/date')->gmtDate(null, $temporaryObject->getExecTime())
  1045. );
  1046. } else {
  1047. $message->setExecTime(new Zend_Db_Expr('NULL'));
  1048. }
  1049. if ($template->getId()) {
  1050. $message->setAppCode($template->getAppCode());
  1051. }
  1052. $message->setPushTitle($temporaryObject->getPushTitle());
  1053. $message->setMessageTitle($temporaryObject->getMessageTitle());
  1054. $message->setContent($temporaryObject->getContent());
  1055. $message->save();
  1056. } catch (Mage_Core_Exception $e) {
  1057. $this->_getSession()->addException($e, $e->getMessage());
  1058. $isError = true;
  1059. } catch (Exception $e) {
  1060. $this->_getSession()->addException($e, $this->__('Unable to save message.'));
  1061. $isError = true;
  1062. Mage::logException($e);
  1063. }
  1064. }
  1065. if ($isError) {
  1066. if ($isError) {
  1067. Mage::getSingleton('adminhtml/session')->setLoadSessionFlag(true);
  1068. }
  1069. $redirectParams = array();
  1070. if ($message && $message->getId()) {
  1071. $redirectParams['id'] = $message->getId();
  1072. } else {
  1073. $redirectParams['template_id'] = (int) $this->getRequest()->getParam('template_id');
  1074. }
  1075. $this->_redirect('*/*/queueMessage', $redirectParams);
  1076. } else {
  1077. $this->_redirect('*/*/queue');
  1078. }
  1079. }
  1080. /**
  1081. * Temlate grid
  1082. *
  1083. * @return void
  1084. */
  1085. public function templateAction()
  1086. {
  1087. $this->loadLayout();
  1088. $this->_setActiveMenu('xmlconnect/template');
  1089. $this->renderLayout();
  1090. }
  1091. /**
  1092. * Create new template action
  1093. *
  1094. * @return void
  1095. */
  1096. public function newTemplateAction()
  1097. {
  1098. $this->_forward('editTemplate');
  1099. }
  1100. /**
  1101. * Edit template action
  1102. *
  1103. * @return void
  1104. */
  1105. public function editTemplateAction()
  1106. {
  1107. $template = $this->_initTemplate();
  1108. $applicationsFound = Mage::helper('xmlconnect')->getApplicationOptions();
  1109. if (!$template->getId() && empty($applicationsFound)) {
  1110. $this->_getSession()->addError(
  1111. $this->__('Template creation is allowed only for applications which have device type iPhone, but this kind of applications has not been found.')
  1112. );
  1113. $this->_redirect('*/*/template');
  1114. return;
  1115. }
  1116. $this->loadLayout();
  1117. $this->_setActiveMenu('xmlconnect/templates');
  1118. $this->renderLayout();
  1119. }
  1120. /**
  1121. * Save template action
  1122. *
  1123. * @return void
  1124. */
  1125. public function saveTemplateAction()
  1126. {
  1127. $data = $this->getRequest()->getPost();
  1128. $template = false;
  1129. $isError = false;
  1130. if ($data) {
  1131. $data = Mage::getModel('core/input_filter_maliciousCode')->filter($data);
  1132. Mage::getSingleton('adminhtml/session')->setFormData($data);
  1133. try {
  1134. $id = $this->getRequest()->getParam('id');
  1135. $template = $this->_initTemplate();
  1136. if (!$template->getId() && $id) {
  1137. $this->_getSession()->addError($this->__('Template does not exist.'));
  1138. $this->_redirect('*/*/');
  1139. return;
  1140. }
  1141. $template->setModifiedAt(Mage::getSingleton('core/date')->gmtDate())->addData($data);
  1142. $template->save();
  1143. } catch (Mage_Core_Exception $e) {
  1144. $this->_getSession()->addException($e, $e->getMessage());
  1145. $isError = true;
  1146. } catch (Exception $e) {
  1147. $this->_getSession()->addException($e, $this->__('Unable to save template.'));
  1148. $isError = true;
  1149. Mage::logException($e);
  1150. }
  1151. }
  1152. if ($isError && ($template && $template->getId())) {
  1153. Mage::getSingleton('adminhtml/session')->setLoadSessionFlag(true);
  1154. $this->_redirect('*/*/editTemplate', array('id' => $template->getId()));
  1155. } else {
  1156. $this->_redirect('*/*/template');
  1157. }
  1158. }
  1159. /**
  1160. * Add message to queue action
  1161. *
  1162. * @return void
  1163. */
  1164. public function queueMessageAction()
  1165. {
  1166. $message = $this->_initMessage();
  1167. if (!$message->getId()) {
  1168. $template = $this->_initTemplate('template_id');
  1169. if (!$template->getId()) {
  1170. $this->_getSession()->addError(
  1171. $this->__('Template for new AirMail Message does not exist.')
  1172. );
  1173. $this->_redirect('*/*/template');
  1174. }
  1175. }
  1176. $this->loadLayout();
  1177. if ($message->getId()) {
  1178. $title = $this->__('Edit AirMail Message');
  1179. } else {
  1180. $title = $this->__('New AirMail Message');
  1181. }
  1182. $this->_addBreadcrumb(
  1183. $this->__('AirMail Message Queue'),
  1184. $this->__('AirMail Message Queue'),
  1185. $this->getUrl('*/*/queue')
  1186. );
  1187. $this->_addBreadcrumb($title, $title);
  1188. $this->_setActiveMenu('xmlconnect/queue');
  1189. $this->renderLayout();
  1190. }
  1191. /**
  1192. * Edit queue message action
  1193. *
  1194. * @return void
  1195. */
  1196. public function editMessageAction()
  1197. {
  1198. $this->_forward('queueMessage');
  1199. }
  1200. }