PageRenderTime 129ms CodeModel.GetById 40ms app.highlight 46ms RepoModel.GetById 34ms app.codeStats 1ms

/app/code/core/Mage/XmlConnect/Model/Application.php

https://bitbucket.org/claudiu_marginean/magento-hg-mirror
PHP | 948 lines | 485 code | 83 blank | 380 comment | 91 complexity | c7d8a2fda02474a04cdffdde80b16428 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 * @method Mage_XmlConnect_Model_Mysql4_Application _getResource()
 29 * @method Mage_XmlConnect_Model_Mysql4_Application getResource()
 30 * @method string getName()
 31 * @method Mage_XmlConnect_Model_Application setName(string $value)
 32 * @method string getCode()
 33 * @method Mage_XmlConnect_Model_Application setCode(string $value)
 34 * @method string getType()
 35 * @method Mage_XmlConnect_Model_Application setType(string $value)
 36 * @method Mage_XmlConnect_Model_Application setStoreId(int $value)
 37 * @method string getActiveFrom()
 38 * @method Mage_XmlConnect_Model_Application setActiveFrom(string $value)
 39 * @method string getActiveTo()
 40 * @method Mage_XmlConnect_Model_Application setActiveTo(string $value)
 41 * @method string getUpdatedAt()
 42 * @method Mage_XmlConnect_Model_Application setUpdatedAt(string $value)
 43 * @method string getConfiguration()
 44 * @method Mage_XmlConnect_Model_Application setConfiguration(string $value)
 45 * @method int getStatus()
 46 * @method Mage_XmlConnect_Model_Application setStatus(int $value)
 47 * @method int getBrowsingMode()
 48 * @method Mage_XmlConnect_Model_Application setBrowsingMode(int $value)
 49 *
 50 * @category    Mage
 51 * @package     Mage_XmlConnect
 52 * @author      Magento Core Team <core@magentocommerce.com>
 53 */
 54class Mage_XmlConnect_Model_Application extends Mage_Core_Model_Abstract
 55{
 56    /**
 57     * Application code cookie name
 58     *
 59     * @var string
 60     */
 61    const APP_CODE_COOKIE_NAME = 'app_code';
 62
 63    /**
 64     * Device screen size name
 65     *
 66     * @var string
 67     */
 68    const APP_SCREEN_SIZE_NAME = 'screen_size';
 69
 70    /**
 71     * Device screen size name
 72     *
 73     * @var string
 74     */
 75    const APP_SCREEN_SIZE_DEFAULT = '320x480';
 76
 77    /**
 78     * Device screen size source name
 79     *
 80     * @var string
 81     */
 82    const APP_SCREEN_SOURCE_DEFAULT = 'default';
 83
 84    /**
 85     * Application status "submitted" value
 86     *
 87     * @var int
 88     */
 89    const APP_STATUS_SUCCESS = 1;
 90
 91    /**
 92     * Application status "not submitted" value
 93     *
 94     * @var int
 95     */
 96    const APP_STATUS_INACTIVE = 0;
 97
 98    /**
 99     * Application prefix length of cutted part of deviceType and storeCode
100     *
101     * @var int
102     */
103    const APP_PREFIX_CUT_LENGTH = 3;
104
105    /**
106     * Last submitted data from history table
107     *
108     * @var null|array
109     */
110    protected $_lastParams;
111
112    /**
113     * Application submit info
114     *
115     * @var array
116     */
117    protected $submit_params = array();
118
119    /**
120     * Application submit action type
121     *
122     * @var bool
123     */
124    protected $is_resubmit_action = false;
125
126    /**
127     * Full application code
128     *
129     * @var null|string
130     */
131    protected $code;
132
133    /**
134     * Main configuration of current application
135     *
136     * @var null|array
137     */
138    protected $conf;
139
140    /**
141     * Social networking validation array
142     *
143     * Social networking validation array specified as
144     *      array (
145     *          network id => API key string length
146     *      )
147     *
148     * @var array
149     */
150    protected $_socialNetValidationArray = array(
151        Mage_XmlConnect_Helper_Data::SOCIAL_NETWORK_TWITTER,
152        Mage_XmlConnect_Helper_Data::SOCIAL_NETWORK_FACEBOOK,
153        Mage_XmlConnect_Helper_Data::SOCIAL_NETWORK_LINKEDIN,
154    );
155
156    /**
157     * Submission/Resubmission key max length
158     *
159     * @var int
160     */
161    const APP_MAX_KEY_LENGTH = 40;
162
163    /**
164     * XML path to config with an email address
165     * for contact to receive credentials
166     * of Urban Airship notifications
167     *
168     * @var string
169     */
170    const XML_PATH_CONTACT_CREDENTIALS_EMAIL = 'xmlconnect/mobile_application/urbanairship_credentials_email';
171
172    /**
173     * XML path to config with Urban Airship Terms of Service URL
174     *
175     * @var string
176     */
177    const XML_PATH_URBAN_AIRSHIP_TOS_URL = 'xmlconnect/mobile_application/urbanairship_terms_of_service_url';
178
179    /**
180     * XML path to config copyright data
181     *
182     * @var string
183     */
184    const XML_PATH_DESIGN_FOOTER_COPYRIGHT = 'design/footer/copyright';
185
186    /**
187     * XML path to config restriction status
188     * (EE module)
189     *
190     * @var string
191     */
192    const XML_PATH_GENERAL_RESTRICTION_IS_ACTIVE = 'general/restriction/is_active';
193
194    /**
195     * XML path to config restriction mode
196     * (EE module)
197     *
198     * @var string
199     */
200    const XML_PATH_GENERAL_RESTRICTION_MODE = 'general/restriction/mode';
201
202    /**
203     * XML path to config secure base link URL
204     *
205     * @var string
206     */
207    const XML_PATH_SECURE_BASE_LINK_URL = 'web/secure/base_link_url';
208
209    /**
210     * XML path to config for paypal business account
211     *
212     * @var string
213     */
214    const XML_PATH_PAYPAL_BUSINESS_ACCOUNT = 'paypal/general/business_account';
215
216    /**
217     * XML path to config for default cache time
218     *
219     * @var string
220     */
221    const XML_PATH_DEFAULT_CACHE_LIFETIME = 'xmlconnect/mobile_application/cache_lifetime';
222
223    /**
224     * Initialize application
225     *
226     * @return void
227     */
228    protected function _construct()
229    {
230        $this->_init('xmlconnect/application');
231    }
232
233    /**
234     * Checks is it app is submitted
235     * (edit is premitted only before submission)
236     *
237     * @return bool
238     */
239    public function getIsSubmitted()
240    {
241        return $this->getStatus() == Mage_XmlConnect_Model_Application::APP_STATUS_SUCCESS;
242    }
243
244    /**
245     * Load data (flat array) for Varien_Data_Form
246     *
247     * @return array
248     */
249    public function getFormData()
250    {
251        $data = $this->getData();
252        $data = Mage::helper('xmlconnect')->getDeviceHelper()->checkImages($data);
253        return $this->_flatArray($data);
254    }
255
256    /**
257     * Load data (flat array) for Varien_Data_Form
258     *
259     * @param array $subtree
260     * @param string $prefix
261     * @return array
262     */
263    protected function _flatArray($subtree, $prefix=null)
264    {
265        $result = array();
266        foreach ($subtree as $key => $value) {
267            if (is_null($prefix)) {
268                $name = $key;
269            } else {
270                $name = $prefix . '[' . $key . ']';
271            }
272
273            if (is_array($value)) {
274                $result = array_merge($result, $this->_flatArray($value, $name));
275            } else {
276                $result[$name] = $value;
277            }
278        }
279        return $result;
280    }
281
282    /**
283     * Like array_merge_recursive(), but string values is replaced
284     *
285     * @param array $a
286     * @param array $b
287     * @return array
288     */
289    protected function _configMerge(array $a, array $b)
290    {
291        $result = array();
292        $keys = array_unique(array_merge(array_keys($a), array_keys($b)));
293        foreach ($keys as $key) {
294            if (!isset($a[$key])) {
295                $result[$key] = $b[$key];
296            } elseif (!isset($b[$key])) {
297                $result[$key] = $a[$key];
298            } elseif (is_scalar($a[$key]) || is_scalar($b[$key])) {
299                $result[$key] = $b[$key];
300            } else {
301                $result[$key] = $this->_configMerge($a[$key], $b[$key]);
302            }
303        }
304        return $result;
305    }
306
307    /**
308     * Set default configuration data
309     *
310     * @return void
311     */
312    public function loadDefaultConfiguration()
313    {
314        $this->setCode($this->getCodePrefix());
315        $this->setConf(Mage::helper('xmlconnect')->getDeviceHelper()->getDefaultConfiguration());
316    }
317
318    /**
319     * Return first part for application code field
320     *
321     * @return string
322     */
323    public function getCodePrefix()
324    {
325        return substr(Mage::app()->getStore($this->getStoreId())->getCode(), 0, self::APP_PREFIX_CUT_LENGTH)
326            . substr($this->getType(), 0, self::APP_PREFIX_CUT_LENGTH);
327    }
328
329    /**
330     * Checks if application code field has autoincrement
331     *
332     * @return bool
333     */
334    public function isCodePrefixed()
335    {
336        $suffix = substr($this->getCode(), self::APP_PREFIX_CUT_LENGTH * 2);
337        return !empty($suffix);
338    }
339
340    /**
341     * Load application configuration
342     *
343     * @return array
344     */
345    public function prepareConfiguration()
346    {
347        return $this->getData('conf');
348    }
349
350    /**
351     * Get config formatted for rendering
352     *
353     * @return array
354     */
355    public function getRenderConf()
356    {
357        $result = Mage::helper('xmlconnect')->getDeviceHelper()->getDefaultConfiguration();
358        $result = $result['native'];
359        $extra = array();
360        if (isset($this->_data['conf'])) {
361            if (isset($this->_data['conf']['native'])) {
362                $result = $this->_configMerge($result, $this->_data['conf']['native']);
363            }
364            if (isset($this->_data['conf']['extra'])) {
365                $extra = $this->_data['conf']['extra'];
366                if (isset($extra['tabs'])) {
367                    $tabs = Mage::getModel('xmlconnect/tabs', $extra['tabs']);
368                    $result['tabBar']['tabs'] = $tabs;
369                }
370                if (isset($extra['fontColors'])) {
371                    if (!empty($extra['fontColors']['header'])) {
372                        $result['fonts']['Title1']['color'] = $extra['fontColors']['header'];
373                    }
374                    if (!empty($extra['fontColors']['primary'])) {
375                        $result['fonts']['Title2']['color'] = $extra['fontColors']['primary'];
376                        $result['fonts']['Title3']['color'] = $extra['fontColors']['primary'];
377                        $result['fonts']['Text1']['color'] = $extra['fontColors']['primary'];
378                        $result['fonts']['Text2']['color'] = $extra['fontColors']['primary'];
379                        $result['fonts']['Title7']['color'] = $extra['fontColors']['primary'];
380                    }
381                    if (!empty($extra['fontColors']['secondary'])) {
382                        $result['fonts']['Title4']['color'] = $extra['fontColors']['secondary'];
383                        $result['fonts']['Title6']['color'] = $extra['fontColors']['secondary'];
384                        $result['fonts']['Title8']['color'] = $extra['fontColors']['secondary'];
385                        $result['fonts']['Title9']['color'] = $extra['fontColors']['secondary'];
386                    }
387                    if (!empty($extra['fontColors']['price'])) {
388                        $result['fonts']['Title5']['color'] = $extra['fontColors']['price'];
389                    }
390                }
391            }
392        }
393        /** @var $helperImage Mage_XmlConnect_Helper_Image */
394        $helperImage = Mage::helper('xmlconnect/image');
395        $paths = $helperImage->getInterfaceImagesPathsConf();
396        foreach ($paths as $confPath => $dataPath) {
397            $imageNodeValue =& $helperImage->findPath($result, $dataPath);
398            if ($imageNodeValue) {
399                if (!file_exists($imageNodeValue)) {
400                    /**
401                     * We set empty string to get default image if original was missing in some reason
402                     */
403                    $imageNodeValue = '';
404                } else {
405                    /**
406                     * Creating file ending (some_inner/some_dir/filename.png) For url
407                     */
408                    $imageNodeValue = $helperImage->getFileCustomDirSuffixAsUrl($confPath, $imageNodeValue);
409                }
410            }
411        }
412        $result = $this->_absPath($result);
413
414        /**
415         * General configuration
416	 $resulI = $this->_absPath($result);
417         */
418        $result['general']['updateTimeUTC'] = strtotime($this->getUpdatedAt());
419        $result['general']['browsingMode'] = $this->getBrowsingMode();
420        $result['general']['currencyCode'] = Mage::app()->getStore($this->getStoreId())->getDefaultCurrencyCode();
421        $result['general']['secureBaseUrl'] = Mage::getStoreConfig(
422            self::XML_PATH_SECURE_BASE_LINK_URL,
423            $this->getStoreId()
424        );
425
426        $maxRecipients  = 0;
427        $allowGuest     = 0;
428        if (Mage::getStoreConfig(Mage_Sendfriend_Helper_Data::XML_PATH_ENABLED)) {
429            $maxRecipients = Mage::getStoreConfig(Mage_Sendfriend_Helper_Data::XML_PATH_MAX_RECIPIENTS);
430            $allowGuest = Mage::getStoreConfig(Mage_Sendfriend_Helper_Data::XML_PATH_ALLOW_FOR_GUEST);
431        }
432        $result['general']['emailToFriendMaxRecepients'] = $maxRecipients;
433        $result['general']['emailAllowGuest'] = $allowGuest;
434        $result['general']['primaryStoreLang'] = Mage::app()
435            ->getStore($this->getStoreId())->getConfig(Mage_Core_Model_Locale::XML_PATH_DEFAULT_LOCALE);
436        $result['general']['magentoVersion'] = Mage::getVersion();
437        $result['general']['copyright'] = Mage::getStoreConfig(
438            self::XML_PATH_DESIGN_FOOTER_COPYRIGHT,
439            $this->getStoreId()
440        );
441
442        $result['general']['isAllowedGuestCheckout'] = Mage::getSingleton('checkout/session')
443            ->getQuote()->isAllowedGuestCheckout();
444
445        /**
446         * Check is guest can post product reviews
447         */
448        if (Mage::helper('review')->getIsGuestAllowToWrite()) {
449            $result['general']['isAllowedGuestReview'] = '1';
450        } else {
451            $result['general']['isAllowedGuestReview'] = '0';
452        }
453
454        /**
455        * Check is wishlist enabled in a config
456        */
457        if (Mage::getStoreConfigFlag('wishlist/general/active')) {
458            $result['general']['wishlistEnable'] = '1';
459        } else {
460            $result['general']['wishlistEnable'] = '0';
461        }
462
463        /**
464         * "Use Secure URLs in Frontend" flag
465         */
466        $result['general']['useSecureURLInFrontend'] = (int)Mage::getStoreConfigFlag(
467            Mage_Core_Model_Store::XML_PATH_SECURE_IN_FRONTEND
468        );
469
470        /**
471         * PayPal configuration
472         */
473        $result['paypal']['businessAccount'] = Mage::getModel('paypal/config')->businessAccount;
474        $result['paypal']['merchantLabel'] = $this->getData('conf/special/merchantLabel');
475
476        $isActive = 0;
477        if (isset($result['paypal']) && isset($result['paypal']['isActive'])) {
478            $paypalMep = Mage::getModel('xmlconnect/payment_method_paypal_mep');
479            $isActive = (int)($result['paypal']['isActive'] && $paypalMep->isAvailable(null));
480        }
481        $result['paypal']['isActive'] = $isActive;
482
483        if ((int)Mage::getStoreConfig(self::XML_PATH_GENERAL_RESTRICTION_IS_ACTIVE)) {
484            $result['website_restrictions']['mode'] = (int)Mage::getStoreConfig(
485                self::XML_PATH_GENERAL_RESTRICTION_MODE
486            );
487        }
488
489        return $result;
490    }
491
492    /**
493     * Return current screen_size parameter
494     *
495     * @return string
496     */
497    public function getScreenSize()
498    {
499        if (!isset($this->_data['screen_size'])) {
500            $this->_data['screen_size'] = self::APP_SCREEN_SIZE_DEFAULT;
501        }
502        return $this->_data['screen_size'];
503    }
504
505    /**
506     * Setter
507     * for current screen_size parameter
508     *
509     * @param string $screenSize
510     * @return this
511     */
512    public function setScreenSize($screenSize)
513    {
514        $this->_data['screen_size'] = Mage::helper('xmlconnect/image')->filterScreenSize((string) $screenSize);
515        return $this;
516    }
517
518    /**
519     * Return Enabled Tabs array from actual config
520     *
521     * @return array:
522     */
523    public function getEnabledTabsArray()
524    {
525        if ($this->getData('conf/extra/tabs')) {
526            return Mage::getModel('xmlconnect/tabs', $this->getData('conf/extra/tabs'))->getRenderTabs();
527        }
528        return array();
529    }
530
531    /**
532     * Change URLs to absolute
533     *
534     * @param array $subtree
535     * @return array
536     */
537    protected function _absPath($subtree)
538    {
539        foreach ($subtree as $key => $value) {
540            if (!empty($value)) {
541                if (is_array($value)) {
542                    $subtree[$key] = $this->_absPath($value);
543                } elseif ((substr($key, -4) == 'icon') ||
544                    (substr($key, -4) == 'Icon') ||
545                    (substr($key, -5) == 'Image')) {
546                    $subtree[$key] = Mage::getBaseUrl('media') . 'xmlconnect/' . $value;
547                }
548            }
549        }
550        return $subtree;
551    }
552
553    /**
554     * Return content pages
555     *
556     * @return array
557     */
558    public function getPages()
559    {
560        if (isset($this->_data['conf']['native']['pages'])) {
561            return $this->_data['conf']['native']['pages'];
562        }
563        return array();
564    }
565
566    /**
567     * Processing object before save data
568     *
569     * @return Mage_XmlConnect_Model_Application
570     */
571    protected function _beforeSave()
572    {
573        $conf = serialize($this->prepareConfiguration());
574        $this->setConfiguration($conf);
575        $this->setUpdatedAt(date('Y-m-d H:i:s', time()));
576        return $this;
577    }
578
579    /**
580     * Load configuration data (from serialized blob)
581     *
582     * @return Mage_XmlConnect_Model_Application
583     */
584    public function loadConfiguration()
585    {
586        static $isConfigurationLoaded = null;
587
588        if (is_null($isConfigurationLoaded)) {
589            $configuration = $this->getConfiguration();
590            if (!empty($configuration)) {
591                $configuration = unserialize($configuration);
592                $this->setData('conf', $configuration);
593                $isConfigurationLoaded = true;
594            }
595        }
596        return $this;
597    }
598
599    /**
600     * Load application by code
601     *
602     * @param string $code
603     * @return Mage_XmlConnect_Model_Application
604     */
605    public function loadByCode($code)
606    {
607        $this->_getResource()->load($this, $code, 'code');
608        return $this;
609    }
610
611    /**
612     * Loads submit tab data from xmlconnect/history table
613     *
614     * @return bool
615     */
616    public function loadSubmit()
617    {
618        $isResubmitAction = false;
619        if ($this->getId()) {
620            $params = $this->getLastParams();
621            if (!empty($params)) {
622                // Using Pointer !
623                $conf = &$this->_data['conf'];
624                if (!isset($conf['submit_text']) || !is_array($conf['submit_text'])) {
625                    $conf['submit_text'] = array();
626                }
627                if (!isset($conf['submit_restore']) || !is_array($conf['submit_restore'])) {
628                    $conf['submit_restore'] = array();
629                }
630                foreach ($params as $id => $value) {
631                    $deviceImages = Mage::helper('xmlconnect')
632                        ->getDeviceHelper()
633                        ->getSubmitImages();
634
635                    if (!in_array($id, $deviceImages)) {
636                        $conf['submit_text'][$id] = $value;
637                    } else {
638                        $conf['submit_restore'][$id] = $value;
639                    }
640                    $isResubmitAction = true;
641                }
642            }
643        }
644        $this->setIsResubmitAction($isResubmitAction);
645        return $isResubmitAction;
646    }
647
648    /**
649     * Returns ( image[ ID ] => "SRC" )  array
650     *
651     * @return array
652     */
653    public function getImages()
654    {
655        $images = array();
656        $params = $this->getLastParams();
657        $deviceImages = Mage::helper('xmlconnect')
658            ->getDeviceHelper()
659            ->getSubmitImages();
660
661        foreach ($deviceImages as $id) {
662            $path = $this->getData('conf/submit/'.$id);
663            $basename = null;
664            if (!empty($path)) {
665                /**
666                 * Fetching data from session restored array
667                 */
668                 $basename = basename($path);
669            } else if (isset($params[$id])) {
670               /**
671                * Fetching data from submission history table record
672                *
673                * converting :  "@\var\somedir\media\xmlconnect\form_icon_6.png"
674                * to "\var\somedir\media\xmlconnect\forn_icon_6.png"
675                */
676                $basename = basename($params[$id]);
677            }
678            if (!empty($basename)) {
679                $images['conf/submit/'.$id] = Mage::getBaseUrl('media').'xmlconnect/'
680                    . Mage::helper('xmlconnect/image')->getFileDefaultSizeSuffixAsUrl($basename);
681            }
682        }
683        return $images;
684    }
685
686    /**
687     * Return last submitted data from history table
688     *
689     * @return array
690     */
691    public function getLastParams()
692    {
693        if (!isset($this->_lastParams)) {
694            $this->_lastParams = Mage::getModel('xmlconnect/history')->getLastParams($this->getId());
695        }
696        return $this->_lastParams;
697    }
698
699    /**
700     * Validate application data
701     *
702     * @return array|bool
703     */
704    public function validate()
705    {
706        $errors = array();
707
708        $validateConf = $this->_validateConf();
709        if ($validateConf !== true) {
710            $errors = $validateConf;
711        }
712
713        if (!Zend_Validate::is($this->getName(), 'NotEmpty')) {
714            $errors[] = Mage::helper('xmlconnect')->__('Please enter "App Title".');
715        }
716
717        if (empty($errors)) {
718            return true;
719        }
720        return $errors;
721    }
722
723    /**
724     * Validate submit application data
725     *
726     * @param array $params
727     * @return array|bool
728     */
729    public function validateSubmit($params)
730    {
731        $errors = array();
732        $validateConf = $this->_validateConf();
733        if ($validateConf !== true) {
734            $errors = $validateConf;
735        }
736
737        $submitErrors = Mage::helper('xmlconnect')->getDeviceHelper($this)->validateSubmit($params);
738
739        if (count($submitErrors)) {
740            $errors = array_merge($errors, $submitErrors);
741        }
742        if (empty($errors)) {
743            return true;
744        }
745        return $errors;
746    }
747
748    /**
749     * Check config for valid values
750     *
751     * @return bool|array
752     */
753    protected function _validateConf()
754    {
755        $conf = $this->getConf();
756        $native = isset($conf['native']) && is_array($conf['native']) ? $conf['native'] : false;
757        $errors = Mage::helper('xmlconnect')->getDeviceHelper($this)->validateConfig($native);
758
759        foreach ($this->_socialNetValidationArray as $networkKey) {
760            if (isset($native['socialNetworking'][$networkKey]['isActive'])
761                && $native['socialNetworking'][$networkKey]['isActive']
762            ) {
763                if ($networkKey !== Mage_XmlConnect_Helper_Data::SOCIAL_NETWORK_FACEBOOK) {
764                    $networkName = ucfirst($networkKey);
765                    if (!isset($native['socialNetworking'][$networkKey]['apiKey'])
766                        || !Zend_Validate::is($native['socialNetworking'][$networkKey]['apiKey'], 'NotEmpty')
767                    ) {
768                        $errors[] = Mage::helper('xmlconnect')->__('%s API Key required.', $networkName);
769                    }
770                    if (!isset($native['socialNetworking'][$networkKey]['secretKey'])
771                        || !Zend_Validate::is($native['socialNetworking'][$networkKey]['secretKey'], 'NotEmpty')
772                    ) {
773                        $errors[] = Mage::helper('xmlconnect')->__('%s Secret Key required.', $networkName);
774                    }
775                } else {
776                    $networkName = ucfirst($networkKey);
777                    if (!isset($native['socialNetworking'][$networkKey]['appID'])
778                        || !Zend_Validate::is($native['socialNetworking'][$networkKey]['appID'], 'NotEmpty')
779                    ) {
780                        $errors[] = Mage::helper('xmlconnect')->__('%s Application ID required.', $networkName);
781                    }
782                }
783            }
784        }
785
786        if (empty($errors)) {
787            return true;
788        }
789        return $errors;
790    }
791
792    /**
793     * Imports post/get data into the model
794     *
795     * @param array $data - $_REQUEST[]
796     * @return array
797     */
798    public function prepareSubmitParams($data)
799    {
800        $params = array();
801        if (isset($data['conf']) && is_array($data['conf'])) {
802
803            if (isset($data['conf']['submit_text']) && is_array($data['conf']['submit_text'])) {
804                $params = $data['conf']['submit_text'];
805            }
806
807            $params['name'] = $this->getName();
808            $params['code'] = $this->getCode();
809            $params['type'] = $this->getType();
810            $params['url'] = Mage::getUrl('xmlconnect/configuration/index', array(
811                '_store' => $this->getStoreId(),
812                '_nosid' => true,
813                'app_code' => $this->getCode()
814            ));
815
816            $params['magentoversion'] = Mage::getVersion();
817
818            if (isset($params['country']) && is_array($params['country'])) {
819                $params['country'] = implode(',', $params['country']);
820            }
821            if ($this->getIsResubmitAction()) {
822                if (isset($params['resubmission_activation_key'])) {
823                    $params['resubmission_activation_key'] = trim($params['resubmission_activation_key']);
824                    $params['key'] = $params['resubmission_activation_key'];
825                } else {
826                    $params['key'] = '';
827                }
828            } else {
829                $params['key'] = isset($params['key']) ? trim($params['key']) : '';
830            }
831            // processing files :
832            $submit = array();
833            if (isset($this->_data['conf']['submit']) && is_array($this->_data['conf']['submit'])) {
834                 $submit = $this->_data['conf']['submit'];
835            }
836
837            $submitRestore  = array();
838            if (isset($this->_data['conf']['submit_restore']) && is_array($this->_data['conf']['submit_restore'])) {
839                $submitRestore = $this->_data['conf']['submit_restore'];
840            }
841
842            $deviceImages = Mage::helper('xmlconnect')
843                ->getDeviceHelper()
844                ->getSubmitImages();
845
846            foreach ($deviceImages as $id) {
847                if (isset($submit[$id])) {
848                    $params[$id] = '@' . $submit[$id];
849                } else if (isset($submitRestore[$id])) {
850                    $params[$id] = $submitRestore[$id];
851                }
852            }
853        }
854        $this->setSubmitParams($params);
855        return $params;
856    }
857
858    /**
859     * Retrieve Store Id
860     *
861     * @return int
862     */
863    public function getStoreId()
864    {
865        if ($this->hasData('store_id')) {
866            return $this->getData('store_id');
867        }
868        return Mage::app()->getStore()->getId();
869    }
870
871    /**
872     * Getter, returns activation key for current application
873     *
874     * @return string|null
875     */
876    public function getActivationKey()
877    {
878        $key = null;
879        if (isset($this->_data['conf']) && is_array($this->_data['conf']) &&
880            isset($this->_data['conf']['submit_text']) && is_array($this->_data['conf']['submit_text']) &&
881            isset($this->_data['conf']['submit_text']['key'])) {
882            $key = $this->_data['conf']['submit_text']['key'];
883        }
884        return $key;
885    }
886
887    /**
888     * Perform update for all applications "updated at" parameter with current date
889     *
890     * @return Mage_XmlConnect_Model_Application
891     */
892    public function updateAllAppsUpdatedAtParameter()
893    {
894        $this->_getResource()->updateAllAppsUpdatedAtParameter();
895        return $this;
896    }
897
898    /**
899     * Getter return concatenated user and password
900     *
901     * @return string
902     */
903    public function getUserpwd()
904    {
905        return $this->loadConfiguration()->getAppKey() . ':' . $this->getAppMasterSecret();
906    }
907
908    /**
909     * Getter for Application Key
910     *
911     * @return string
912     */
913    public function getAppKey()
914    {
915        return $this->getData('conf/native/notifications/applicationKey');
916    }
917
918    /**
919     * Getter for Application Secret
920     *
921     * @return string
922     */
923    public function getAppSecret()
924    {
925        return $this->getData('conf/native/notifications/applicationSecret');
926    }
927
928    /**
929     * Getter for Application Master Secret
930     *
931     * @return string
932     */
933    public function getAppMasterSecret()
934    {
935        return $this->getData('conf/native/notifications/applicationMasterSecret');
936    }
937
938    /**
939     * Getter for Application Cache Lifetime
940     *
941     * @return int|string
942     */
943    public function getCacheLifetime()
944    {
945        $lifetime = (int)$this->loadConfiguration()->getData('conf/native/cacheLifetime');
946        return $lifetime <= 0 ? '' : $lifetime;
947    }
948}