PageRenderTime 123ms CodeModel.GetById 40ms app.highlight 58ms RepoModel.GetById 12ms app.codeStats 1ms

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

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