Alex Trofimov 10 лет назад
Родитель
Сommit
47fa619b8f

+ 45 - 0
modules/boonex/mailchimp/classes/BxMailchimpAlerts.php

@@ -0,0 +1,45 @@
+<?php defined('BX_DOL') or die('hack attempt');
+/**
+ * Copyright (c) BoonEx Pty Limited - http://www.boonex.com/
+ * CC-BY License - http://creativecommons.org/licenses/by/3.0/
+ *
+ * @defgroup    Mailchimp Mailchimp integration module
+ * @ingroup     TridentModules
+ *
+ * @{
+ */
+
+class BxMailchimpAlerts extends BxDolAlertsResponse
+{
+    protected $_oModule;
+    function __construct()
+    {
+        parent::__construct();
+        $this->_oModule = BxDolModule::getInstance('bx_mailchimp');
+    }
+
+    public function response($o)
+    {
+        if ('system' == $o->sUnit && 'save_setting' == $o->sAction && 'bx_mailchimp_option_list_id' == $o->aExtras['option']) {
+            $this->_oModule->serviceUpdateMergeFields();
+        }
+        
+        if ('account' == $o->sUnit && 'delete' == $o->sAction) {
+            $this->_oModule->serviceRemoveAccount($o->iObject);
+        }
+
+        if ('account' == $o->sUnit && ('edited' == $o->sAction || 'switch_context' == $o->sAction || 'confirm' == $o->sAction || 'unconfirm' == $o->sAction)) {
+            $this->_oModule->serviceUpdateAccount($o->iObject);
+        }
+        
+        if ('profile' == $o->sUnit && ('delete' == $o->sAction || 'edit' == $o->sAction || 'add' == $o->sAction)) {
+            $oProfile = BxDolProfile::getInstanc($o->iObject);
+            $oAccount = $oProfile ? $oProfile->getAccountObject() : null;
+            
+            if ($oAccount)
+                $this->_oModule->serviceUpdateAccount($oAccount->id());
+        }
+    }    
+}
+
+/** @} */

+ 20 - 0
modules/boonex/mailchimp/classes/BxMailchimpConfig.php

@@ -0,0 +1,20 @@
+<?php defined('BX_DOL') or die('hack attempt');
+/**
+ * Copyright (c) BoonEx Pty Limited - http://www.boonex.com/
+ * CC-BY License - http://creativecommons.org/licenses/by/3.0/
+ *
+ * @defgroup    Mailchimp Mailchimp integration module
+ * @ingroup     TridentModules
+ *
+ * @{
+ */
+
+class BxMailchimpConfig extends BxDolModuleConfig
+{
+    function __construct($aModule)
+    {
+        parent::__construct($aModule);
+    }
+}
+
+/** @} */

+ 32 - 0
modules/boonex/mailchimp/classes/BxMailchimpDb.php

@@ -0,0 +1,32 @@
+<?php defined('BX_DOL') or die('hack attempt');
+/**
+ * Copyright (c) BoonEx Pty Limited - http://www.boonex.com/
+ * CC-BY License - http://creativecommons.org/licenses/by/3.0/
+ *
+ * @defgroup    Mailchimp Mailchimp integration module
+ * @ingroup     TridentModules
+ *
+ * @{
+ */
+
+class BxMailchimpDb extends BxDolModuleDb
+{
+    function __construct(&$oConfig)
+    {
+        parent::__construct($oConfig);
+    }
+
+    public function getInitialUsers($iLimit = 1000)
+    {
+        return $this->getColumn("SELECT `id` FROM `sys_accounts` ORDER BY `added` DESC LIMIT " . (int)$iLimit);
+    }
+
+    public function getSessionRowByAccountId($iAccountId)
+    {
+        return $this->getRow("SELECT * FROM `sys_sessions` WHERE `user_id` = :account ORDER BY `date` DESC LIMIT 1", array(
+            'account' => $iAccountId,
+        ));
+    }
+}
+
+/** @} */

+ 321 - 0
modules/boonex/mailchimp/classes/BxMailchimpModule.php

@@ -0,0 +1,321 @@
+<?php defined('BX_DOL') or die('hack attempt');
+/**
+ * Copyright (c) BoonEx Pty Limited - http://www.boonex.com/
+ * CC-BY License - http://creativecommons.org/licenses/by/3.0/
+ *
+ * @defgroup    Mailchimp Mailchimp integration module
+ * @ingroup     TridentModules
+ *
+ * @{
+ */
+
+define('BX_MAILCHIMP_LIMIT', 5000);
+
+class BxMailchimpModule extends BxDolModule
+{
+    protected $sHostnameAPI = 'https://{dc}.api.mailchimp.com/3.0';                
+    protected $aFields = array(
+        'ACCOUNT_ID' => 'number', 
+        'MEMBERSHIP' => 'text', 
+        'STATUS' => 'text', 
+        'TYPE' => 'text', 
+        'PROFILES' => 'text',
+        'PROFILE_URL' => 'url',
+        'IMAGE_URL' => 'imageurl',
+    );
+
+    function __construct(&$aModule)
+    {
+        parent::__construct($aModule);
+
+        if (($sKey = getParam('bx_mailchimp_option_api_key')) && ($a = explode('-', $sKey)) && !empty($a[1]))
+            $this->sHostnameAPI = str_replace('{dc}', $a[1], $this->sHostnameAPI);
+        else
+            $this->sHostnameAPI = '';
+    }
+
+    public function serviceUpdateMergeFields()
+    {
+        if (!isAdmin() || !($sListId = getParam('bx_mailchimp_option_list_id')))
+            return false;
+
+        foreach ($this->aFields as $sName => $sType) {
+            $s = $this->_request('/lists/' . $sListId . '/merge-fields', 'POST', array('name' => $sName, 'tag' => $sName, 'type' => $sType), $sErrorCurl);
+            if (!($a = $this->_checkForErrors($s, $sErrorCurl)) || isset($a['error']))
+                return false;
+        }
+
+        return true;
+    }
+
+    public function serviceGetLists($bAddEmptyValue = true)
+    {
+        if (!isAdmin())
+            return false;
+
+        $s = $this->_request('/lists', 'GET', array(), $sErrorCurl);
+        if (!($a = $this->_checkForErrors($s, $sErrorCurl)) || isset($a['error']))
+            return array();
+        
+        if (isset($a['type']) && isset($a['detail']))
+            die(json_encode(array('error' => $a['detail'])));
+
+        if (!isset($a['lists']))
+            return array();
+
+        $aRet = array();
+        foreach ($a['lists'] as $r)
+            $aRet[$r['id']] = $r['name'];
+
+        if ($bAddEmptyValue)
+            array_unshift($aRet, _t('_sys_please_select'));
+
+        return $aRet;
+    }
+
+    /**
+     * remove user from mailchimp by email or account id
+     */      
+    public function serviceRemoveAccount($mixed)
+    {
+        return $this->_accountAction($sEmail, 'DELETE');
+    }
+
+    /**
+     * update user in mailchimp by email or account id
+     */      
+    public function serviceUpdateAccount($sEmail)
+    {
+        return $this->_accountAction($sEmail, 'PUT');
+    }
+
+    protected function _accountAction($sEmail, $sMethod)
+    {
+        if (!$sEmail || !($oAccount = BxDolAccount::getInstance($sEmail)) || !($sListId = getParam('bx_mailchimp_option_list_id')))
+            return false;
+
+        $aUserInfo = $this->_prepareUser($oAccount);
+
+        $s = $this->_request('/lists/' . $sListId . '/members/' . md5(strtolower($aUserInfo['email_address'])), $sMethod, $aUserInfo, $sErrorCurl);
+        if (!($a = $this->_checkForErrors($s, $sErrorCurl)) || isset($a['error']))
+            return false;
+
+        if (isset($a['type']) && isset($a['detail']))
+            return false;
+        
+        return true;
+    }
+
+    /**
+     * remove user from mailchimp by email or account id
+     */      
+    public function actionAccountRemove($sEmail)
+    {
+        if (!isAdmin())
+            die('{}');
+
+        if (!$this->serviceRemoveAccount($sEmail))
+            die(json_encode(array('error' => true, 'message' => "Delete failed")));
+
+        echo json_encode(array('message' => "User was successfully deleted"));
+    }
+
+    /**
+     * update user by email or account id
+     */  
+    public function actionAccountUpdate($sEmail)
+    {
+        if (!isAdmin())
+            die('{}');
+
+        if (!$this->serviceUpdateAccount($sEmail))
+            die(json_encode(array('error' => true, 'message' => "Update failed")));
+
+        echo json_encode(array('message' => "User was successfully updated"));
+    }
+
+    /**
+     * Add members in bulk from local database to mailchimp
+     */      
+    public function actionBulkAdd($iLimit = BX_MAILCHIMP_LIMIT)
+    {
+        if (!isAdmin() || !($sListId = getParam('bx_mailchimp_option_list_id')))
+            die('{}');
+
+        set_time_limit(3600);
+        $aIds = $this->_oDb->getInitialUsers($iLimit);
+        $aChunks = array_chunk($aIds, 1000);
+        $iTotal = count($aIds);
+        $iCounter = 0;
+        foreach ($aChunks as $aIds) {
+            $aOperations = array();
+            $iTotal2 = 0;
+            foreach ($aIds as $iAccountId) {
+                if (!($oAccount = BxDolAccount::getInstance($iAccountId)))
+                    continue;
+                if (!($aUserInfo = $this->_prepareUser($oAccount)))
+                    continue;
+                $aOperations[] = array(
+                    'method' => 'PUT',
+                    'path' => '/lists/' . $sListId . '/members/' . md5(strtolower($aUserInfo['email_address'])),
+                    'body' => json_encode($aUserInfo),
+                );
+                ++$iTotal2;
+            }
+
+            $s = $this->_request('/batches', 'POST', array('operations' => $aOperations), $sErrorCurl);
+            if (!($a = $this->_checkForErrors($s, $sErrorCurl)) || isset($a['error']))
+                die(json_encode($a));
+
+            if (isset($a['type']) && isset($a['detail']))
+                die(json_encode(array('error' => $a['detail'])));
+        
+            $iCounter += $iTotal2;
+            sleep(1);
+        }
+        
+        echo json_encode(array('message' => _t('_bx_mailchimp_accounts_processed', $iCounter)));
+    }
+
+    /**
+     * Test query to return some stats
+     */     
+    public function actionStats()
+    {
+        if (!isAdmin() || !($sListId = getParam('bx_mailchimp_option_list_id')))
+            die('{}');
+
+        $s = $this->_request('/lists/' . $sListId, 'GET', array(), $sErrorCurl);
+        if (!($a = $this->_checkForErrors($s, $sErrorCurl)) || isset($a['error']))
+            die(json_encode($a));
+
+        if (isset($a['type']) && isset($a['detail']))
+            die(json_encode(array('error' => $a['detail'])));
+        
+        echo json_encode(array(
+            'unsubscribed' => $a['stats']['unsubscribe_count'],
+            'cleaned' => $a['stats']['cleaned_count'],
+            'total' => $a['stats']['member_count'],
+        ));
+    }
+
+    protected function _prepareUser($oAccount)
+    {
+        $oProfile = BxDolProfile::getInstanceByAccount($oAccount->id());
+        if (!$oProfile)
+            return false;
+
+        $aInfoProfile = $oProfile->getInfo();
+        $aInfoAccount = $oAccount->getInfo();
+        //$aInfoSession = $this->_oDb->getSessionRowByAccountId($oAccount->id());
+        $aProfilesIds = $oAccount->getProfilesIds();
+
+        // membership
+        $aMembership = BxDolAcl::getInstance()->getMemberMembershipInfo($oProfile->id());
+
+        // profiles
+        $sProfiles = '';
+        foreach ($aProfilesIds as $iId) {
+            if (!($o = BxDolProfile::getInstance($iId)))
+                continue;
+            $sProfiles .= $o->getDisplayName() . ', ';
+        }
+        $sProfiles = trim($sProfiles, ', ');
+
+        return array (
+            'email_address' => $oAccount->getEmail(),
+            'status' => $aInfoAccount['receive_news'] ? 'subscribed' : 'unsubscribed',
+            'timestamp_signup' => $aInfoAccount['added'], // TODO: check the date/time format
+            'merge_fields' => array(
+                'FNAME' => $oProfile->getDisplayName(),
+                'ACCOUNT_ID' => $oAccount->id(),
+                'MEMBERSHIP' => _t($aMembership['name']) . (isset($aMembership['date_expires']) && $aMembership['date_expires'] ? ' (expires:' . bx_time_utc($aMembership['date_expires']) . ')' : ''),
+                'STATUS' => $aInfoProfile['status'],
+                'TYPE' => $aInfoProfile['type'],
+                'PROFILES' => $sProfiles,
+                'PROFILE_URL' => $oProfile->getUrl(),
+                'IMAGE_URL' => $oProfile->getThumb(),
+            ),
+        );
+    }
+
+    /**
+     * @return json error object on error or empty string on success
+     */
+    protected function _checkForErrors($s, $sErrorCurl)
+    {
+        if (!$s)
+            return array('error' => 'curl error: ' . $sErrorCurl);
+
+        $a = json_decode($s, true);
+        if (null === $a)
+            return array('error' => 'json decode failed:' . htmlspecialchars($s));
+
+        return $a;
+    }
+
+    /**
+     * Perform JSON request to the API endpoint and get JSON response
+     * @return false on error
+     */
+    protected function _request($sURI, $sMethod = 'GET', $aData = array(), &$sError)
+    {
+        $sApiKey = getParam('bx_mailchimp_option_api_key');
+        if (!$sApiKey || !$this->sHostnameAPI) {
+            $sError = "No API Key or hostname isn't configured";
+            return false;
+        }
+        
+        $r = curl_init();
+    
+        $aHeaders = array(
+            'Accept: application/json',
+        );
+
+        curl_setopt($r, CURLOPT_USERPWD, "user:" . $sApiKey);
+        curl_setopt($r, CURLOPT_TIMEOUT, 30);
+        curl_setopt($r, CURLOPT_URL, $this->sHostnameAPI . $sURI);
+        curl_setopt($r, CURLOPT_HEADER, 0);
+        curl_setopt($r, CURLOPT_RETURNTRANSFER, 1);
+        curl_setopt($r, CURLOPT_FOLLOWLOCATION, 1);
+
+        if ('POST' == $sMethod || 'PUT' == $sMethod || 'PATCH' == $sMethod) {
+
+            $sDataJson = json_encode($aData); 
+
+            if ('POST' == $sMethod)
+                curl_setopt($r, CURLOPT_POST, true);
+            else
+                curl_setopt($r, CURLOPT_CUSTOMREQUEST, $sMethod);
+
+            curl_setopt($r, CURLOPT_POSTFIELDS, $sDataJson);
+
+            $aHeaders = array_merge($aHeaders, array(
+                'Content-Type: application/json',
+                'Content-Length: ' . strlen($sDataJson)
+            )); 
+
+        } elseif ('DELETE' == $sMethod) {
+
+            curl_setopt($r, CURLOPT_CUSTOMREQUEST, "DELETE");
+
+        }
+
+        // $aHeaders[] = 'X-Trigger-Error: APIKeyMissing'; // test error handling
+
+        curl_setopt($r, CURLOPT_HTTPHEADER, $aHeaders); 
+
+        $sResult = curl_exec($r);        
+
+        if (false === $sResult) {
+            $sError = curl_error ($r);
+            curl_close($r);
+            return false;
+        }
+
+        curl_close($r);
+        return $sResult;
+    }
+}
+
+/** @} */

+ 28 - 0
modules/boonex/mailchimp/classes/BxMailchimpStudioPage.php

@@ -0,0 +1,28 @@
+<?php defined('BX_DOL') or die('hack attempt');
+/**
+ * Copyright (c) BoonEx Pty Limited - http://www.boonex.com/
+ * CC-BY License - http://creativecommons.org/licenses/by/3.0/
+ *
+ * @defgroup    Mailchimp Mailchimp integration module
+ * @ingroup     TridentModules
+ *
+ * @{
+ */
+
+class BxMailchimpStudioPage extends BxTemplStudioModule
+{
+    function getHelp ()
+    {
+        $oModule = BxDolModule::getInstance('bx_mailchimp');
+        return _t('_bx_mailchimp_information_block', BX_DOL_URL_ROOT . $oModule->_oConfig->getBaseUri() . 'bulk_add', BX_MAILCHIMP_LIMIT);
+    }
+
+    protected function getPageCaptionHelp()
+    {        
+        $oTemplate = BxDolStudioTemplate::getInstance();
+        $sContent = '<a href="' . BX_DOL_URL_STUDIO . 'module.php?name=bx_mailchimp&page=help">' . _t('_bx_mailchimp_information') . "</a>";
+        return $oTemplate->parseHtmlByName('page_caption_help.html', array('content' => $sContent));
+    }
+}
+
+/** @} */

+ 20 - 0
modules/boonex/mailchimp/classes/BxMailchimpTemplate.php

@@ -0,0 +1,20 @@
+<?php defined('BX_DOL') or die('hack attempt');
+/**
+ * Copyright (c) BoonEx Pty Limited - http://www.boonex.com/
+ * CC-BY License - http://creativecommons.org/licenses/by/3.0/
+ *
+ * @defgroup    Mailchimp Mailchimp integration module
+ * @ingroup     TridentModules
+ *
+ * @{
+ */
+
+class BxMailchimpTemplate extends BxDolModuleTemplate
+{
+    function __construct(&$oConfig, &$oDb)
+    {
+        parent::__construct($oConfig, $oDb);
+    }
+}
+
+/** @} */

+ 66 - 0
modules/boonex/mailchimp/install/config.php

@@ -0,0 +1,66 @@
+<?php
+/**
+ * Copyright (c) BoonEx Pty Limited - http://www.boonex.com/
+ * CC-BY License - http://creativecommons.org/licenses/by/3.0/
+ *
+ * @defgroup    Mailchimp Mailchimp integration module
+ * @ingroup     TridentModules
+ *
+ * @{
+ */
+
+$aConfig = array(
+    /**
+     * Main Section.
+     */
+    'type' => BX_DOL_MODULE_TYPE_MODULE,
+    'name' => 'bx_mailchimp',
+    'title' => 'Mailchimp',
+    'note' => 'Mailchimp integration.',
+    'version' => '9.0.0.DEV',
+    'vendor' => 'BoonEx',
+	'help_url' => 'http://feed.boonex.com/?section={module_name}',
+
+    'compatible_with' => array(
+        '9.0.x'
+    ),
+
+    /**
+     * 'home_dir' and 'home_uri' - should be unique. Don't use spaces in 'home_uri' and the other special chars.
+     */
+    'home_dir' => 'boonex/mailchimp/',
+    'home_uri' => 'mailchimp',
+
+    'db_prefix' => 'bx_mailchimp_',
+    'class_prefix' => 'BxMailchimp',
+
+    /**
+     * Category for language keys.
+     */
+    'language_category' => 'Mailchimp',
+
+    /**
+     * Installation/Uninstallation Section.
+     */
+    'install' => array(
+        'execute_sql' => 1,
+        'update_languages' => 1,
+    ),
+    'uninstall' => array (
+        'execute_sql' => 1,
+        'update_languages' => 1,
+    ),
+    'enable' => array(
+        'execute_sql' => 1,
+        'clear_db_cache' => 1,
+    ),
+    'disable' => array(
+        'execute_sql' => 1,
+        'clear_db_cache' => 1,
+    ),
+
+    /**
+     * Dependencies Section
+     */
+    'dependencies' => array(),
+);

+ 20 - 0
modules/boonex/mailchimp/install/installer.php

@@ -0,0 +1,20 @@
+<?php defined('BX_DOL') or die('hack attempt');
+/**
+ * Copyright (c) BoonEx Pty Limited - http://www.boonex.com/
+ * CC-BY License - http://creativecommons.org/licenses/by/3.0/
+ *
+ * @defgroup    Mailchimp Mailchimp integration module
+ * @ingroup     TridentModules
+ *
+ * @{
+ */
+
+class BxMailchimpInstaller extends BxDolStudioInstaller
+{
+    function __construct($aConfig)
+    {
+        parent::__construct($aConfig);
+    }
+}
+
+/** @} */

+ 35 - 0
modules/boonex/mailchimp/install/langs/en.xml

@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources name="en" flag="gb" title="English">
+	<string name="_sys_module_mailchimp"><![CDATA[Mailchimp]]></string>
+	<string name="_bx_mailchimp"><![CDATA[Mailchimp]]></string>
+
+	<string name="_bx_mailchimp_setting"><![CDATA[Mailchimp Setting]]></string>
+    <string name="_bx_mailchimp_adm_stg_cpt_type"><![CDATA[Mailchimp]]></string>
+    <string name="_bx_mailchimp_adm_stg_cpt_category_general"><![CDATA[General]]></string>
+    <string name="_bx_mailchimp_option_api_key"><![CDATA[Mailchimp API Key]]></string>
+    <string name="_bx_mailchimp_option_list_id"><![CDATA[Mailing List]]></string>
+    <string name="_bx_mailchimp_accounts_processed"><![CDATA[{0} accounts were processed]]></string>
+
+	<string name="_bx_mailchimp_information"><![CDATA[Information]]></string>
+    <string name="_bx_mailchimp_information_block"><![CDATA[
+                <p>This module add Mailchimp services to your website.<p>
+                <p>To enable this module, you need to get Mailchimp API Key from <a target="_blank" href="http://mailchimp.com">Mailchimp</a> &gt; Account &gt; Extras &gt; API keys and specify it in this module settings.</p>
+                <p>Then you need to create the mailing list in <a target="_blank" href="http://mailchimp.com">Mailchimp</a> &gt; Lists &gt; Create List</p>
+                <p>After mailing list is created you need to select it in this module settings.</p>
+                <hr class="bx-def-hr bx-def-margin-sec-topbottom" />
+                <button class="bx-btn bx-mailchimp-bulk-add">Add or update current members in Mailchimp (limit - {1})</button>
+                <script>
+                    $(".bx-mailchimp-bulk-add").on('click', function () {
+                        var $this = this;
+                        bx_loading_btn(this, 1);
+                        $.getJSON("{0}", function(oData) {
+                            bx_loading_btn($this, 0);
+                            if ('undefined' !== typeof oData['error'])
+                                alert(oData['error']);
+                            if ('undefined' !== typeof oData['message'])
+                                alert(oData['message']);
+                        });
+                    });
+                </script>
+        ]]></string>
+</resources>

+ 11 - 0
modules/boonex/mailchimp/install/sql/disable.sql

@@ -0,0 +1,11 @@
+
+-- Settings
+
+DELETE FROM `top`, `toc`, `to` USING `sys_options_types` AS `top` LEFT JOIN `sys_options_categories` AS `toc` ON `top`.`id`=`toc`.`type_id` LEFT JOIN `sys_options` AS `to` ON `toc`.`id`=`to`.`category_id` WHERE `top`.`name` = 'bx_mailchimp';
+
+-- Alerts
+
+SET @iHandlerId := (SELECT `id` FROM `sys_alerts_handlers` WHERE `name` = 'bx_mailchimp');
+
+DELETE FROM `sys_alerts_handlers` WHERE `id`  = @iHandlerId;
+DELETE FROM `sys_alerts` WHERE `handler_id` =  @iHandlerId ;

+ 33 - 0
modules/boonex/mailchimp/install/sql/enable.sql

@@ -0,0 +1,33 @@
+
+-- Settings
+
+SET @iTypeOrder = (SELECT MAX(`order`) FROM `sys_options_types` WHERE `group` = 'modules');
+INSERT INTO `sys_options_types` (`group`, `name`, `caption`, `icon`, `order`) VALUES 
+('modules', 'bx_mailchimp', '_bx_mailchimp_adm_stg_cpt_type', 'bx_mailchimp@modules/boonex/mailchimp/|std-mi.png', IF(NOT ISNULL(@iTypeOrder), @iTypeOrder + 1, 1));
+SET @iTypeId = LAST_INSERT_ID();
+
+INSERT INTO `sys_options_categories` (`type_id`, `name`, `caption`, `order` )  
+VALUES (@iTypeId, 'bx_mailchimp_general', '_bx_mailchimp_adm_stg_cpt_category_general', 1);
+SET @iCategId = LAST_INSERT_ID();
+
+INSERT INTO `sys_options` (`name`, `value`, `category_id`, `caption`, `type`, `extra`, `check`, `check_error`, `order`) VALUES
+('bx_mailchimp_option_api_key', '', @iCategId, '_bx_mailchimp_option_api_key', 'digit', '', '', '', 10),
+('bx_mailchimp_option_list_id', '', @iCategId, '_bx_mailchimp_option_list_id', 'select', 'a:2:{s:6:"module";s:12:"bx_mailchimp";s:6:"method";s:9:"get_lists";}', '', '', 20);
+
+-- Alerts
+
+INSERT INTO `sys_alerts_handlers` SET `name` = 'bx_mailchimp', `class` = 'BxMailchimpAlerts', `file` = 'modules/boonex/mailchimp/classes/BxMailchimpAlerts.php';
+
+SET @iHandlerId := (SELECT `id` FROM `sys_alerts_handlers`  WHERE `name` = 'bx_mailchimp');
+
+INSERT INTO `sys_alerts` (`unit`, `action`, `handler_id`) VALUES
+('system', 'save_setting', @iHandlerId),
+('account', 'delete', @iHandlerId),
+('account', 'edited', @iHandlerId),
+('account', 'switch_context', @iHandlerId),
+('account', 'confirm', @iHandlerId),
+-- ('account', 'unconfirm', @iHandlerId),
+('profile', 'delete', @iHandlerId),
+('profile', 'add', @iHandlerId),
+('profile', 'edit', @iHandlerId);
+

+ 14 - 0
modules/boonex/mailchimp/install/sql/install.sql

@@ -0,0 +1,14 @@
+
+-- Studio page and widget
+
+INSERT INTO `sys_std_pages`(`index`, `name`, `header`, `caption`, `icon`) VALUES
+(3, 'bx_mailchimp', '_bx_mailchimp', '_bx_mailchimp', 'bx_mailchimp@modules/boonex/mailchimp/|std-pi.png');
+SET @iPageId = LAST_INSERT_ID();
+
+SET @iParentPageId = (SELECT `id` FROM `sys_std_pages` WHERE `name` = 'home');
+SET @iParentPageOrder = (SELECT MAX(`order`) FROM `sys_std_pages_widgets` WHERE `page_id` = @iParentPageId);
+INSERT INTO `sys_std_widgets` (`page_id`, `module`, `url`, `click`, `icon`, `caption`, `cnt_notices`, `cnt_actions`) VALUES
+(@iPageId, 'bx_mailchimp', '{url_studio}module.php?name=bx_mailchimp', '', 'bx_mailchimp@modules/boonex/mailchimp/|std-wi.png', '_bx_mailchimp', '', 'a:4:{s:6:"module";s:6:"system";s:6:"method";s:11:"get_actions";s:6:"params";a:0:{}s:5:"class";s:18:"TemplStudioModules";}');
+INSERT INTO `sys_std_pages_widgets` (`page_id`, `widget_id`, `order`) VALUES
+(@iParentPageId, LAST_INSERT_ID(), IF(ISNULL(@iParentPageOrder), 1, @iParentPageOrder + 1));
+

+ 7 - 0
modules/boonex/mailchimp/install/sql/uninstall.sql

@@ -0,0 +1,7 @@
+
+-- Studio page and widget
+
+DELETE FROM `tp`, `tw`, `tpw`
+USING `sys_std_pages` AS `tp`, `sys_std_widgets` AS `tw`, `sys_std_pages_widgets` AS `tpw`
+WHERE `tp`.`id` = `tw`.`page_id` AND `tw`.`id` = `tpw`.`widget_id` AND `tp`.`name` = 'bx_mailchimp';
+

+ 20 - 0
modules/boonex/mailchimp/request.php

@@ -0,0 +1,20 @@
+<?php
+/**
+ * Copyright (c) BoonEx Pty Limited - http://www.boonex.com/
+ * CC-BY License - http://creativecommons.org/licenses/by/3.0/
+ *
+ * @defgroup    Mailchimp Mailchimp integration module
+ * @ingroup     TridentModules
+ *
+ * @{
+ */
+
+check_logged();
+
+if ( empty($aRequest) || empty($aRequest[0]) ) {
+    BxDolRequest::processAsFile($aModule, $aRequest);
+} else {
+    BxDolRequest::processAsAction($aModule, $aRequest);
+}
+
+/** @} */

BIN
modules/boonex/mailchimp/template/images/icons/std-mi.png


BIN
modules/boonex/mailchimp/template/images/icons/std-pi.png


BIN
modules/boonex/mailchimp/template/images/icons/std-si.png


BIN
modules/boonex/mailchimp/template/images/icons/std-wi.png


+ 35 - 0
modules/boonex/russian/data/langs/bx_mailchimp/ru.xml

@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources name="ru" flag="ru" title="Russian">
+	<string name="_sys_module_mailchimp"><![CDATA[Mailchimp]]></string>
+	<string name="_bx_mailchimp"><![CDATA[Mailchimp]]></string>
+
+	<string name="_bx_mailchimp_setting"><![CDATA[Настройки Mailchimp]]></string>
+    <string name="_bx_mailchimp_adm_stg_cpt_type"><![CDATA[Mailchimp]]></string>
+    <string name="_bx_mailchimp_adm_stg_cpt_category_general"><![CDATA[Основные]]></string>
+    <string name="_bx_mailchimp_option_api_key"><![CDATA[Mailchimp API Key]]></string>
+    <string name="_bx_mailchimp_option_list_id"><![CDATA[Список для рассылки]]></string>
+    <string name="_bx_mailchimp_accounts_processed"><![CDATA[Обработано записей - {0}]]></string>
+
+	<string name="_bx_mailchimp_information"><![CDATA[Информация]]></string>
+    <string name="_bx_mailchimp_information_block"><![CDATA[
+                <p>Этот модуль добавляет Mailchimp сервис на сайт.<p>
+                <p>Что-бы этот модуль заработал, нужно получить Mailchimp API Key (это можно сделать тут - <a target="_blank" href="http://mailchimp.com">Mailchimp</a> &gt; Account &gt; Extras &gt; API keys) и указать его в настройках этого модуля.</p>
+                <p>Затем нужно создать список для рассылки (это можно сделать тут - <a target="_blank" href="http://mailchimp.com">Mailchimp</a> &gt; Lists &gt; Create List).</p>
+                <p>После создания списка, его нужно указать в настройках этого модуля.</p>
+                <hr class="bx-def-hr bx-def-margin-sec-topbottom" />
+                <button class="bx-btn bx-mailchimp-bulk-add">Добавить или обновить текущих пользователей в сервисе Mailchimp (ограничение - {1})</button>
+                <script>
+                    $(".bx-mailchimp-bulk-add").on('click', function () {
+                        var $this = this;
+                        bx_loading_btn(this, 1);
+                        $.getJSON("{0}", function(oData) {
+                            bx_loading_btn($this, 0);
+                            if ('undefined' !== typeof oData['error'])
+                                alert(oData['error']);
+                            if ('undefined' !== typeof oData['message'])
+                                alert(oData['message']);
+                        });
+                    });
+                </script>
+        ]]></string>
+</resources>