first commit

This commit is contained in:
2025-08-02 16:30:27 +02:00
commit 23646bfcee
14851 changed files with 1750626 additions and 0 deletions

View File

@@ -0,0 +1,173 @@
<?php
$main_class = 'MailerLiteWindow';
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use KupShop\MailerLiteBundle\MailerLite;
class MailerLiteWindow extends Window
{
protected $action;
protected $ID;
protected $page;
protected $template = 'window/mailerlite.tpl';
protected $title = 'MailerLite';
protected $data;
/**
* @var MailerLite
*/
protected $mailerlite;
public function __construct()
{
ini_set('memory_limit', '1G');
$this->mailerlite = ServiceContainer::getService(MailerLite::class);
$this->mailerlite->getSubscriberGroup();
}
public function get_vars()
{
if ($this->mailerlite->error) {
$vars['ErrStr'] = $this->mailerlite->error;
return $vars;
}
$this->ID = $this->getID();
$this->action = $this->getAction();
if ($this->action == 'edit') {
$this->action = 'MailerLite';
}
$this->page = getVal('page', null, 0);
$vars = parent::get_vars();
$this->data['ShopUsers'] = $this->mailerlite->getKupShopUsers();
$this->data['Unsubscribed'] = $this->mailerlite->getMailerLiteSubscribers_All('Unsubscribed');
// $this->data['Active'] = $this->mailerlite->getMailerLiteSubscribers('Active', $this->page);
$this->data['Junk'] = $this->mailerlite->getMailerLiteSubscribers('Junk');
$this->data['Bounced'] = $this->mailerlite->getMailerLiteSubscribers('Bounced');
$success = getVal('OkStr');
$error = getVal('ErrStr');
if ($success) {
$this->data[$this->ID]['success'] = $success;
}
if ($error) {
$this->data[$this->ID]['err'] = $error;
}
if ($this->ID == 'Synchronize') {
if ($success) {
if (!empty($success['success'])) {
$this->data[$this->ID]['success'] = $success['success'];
}
if (!empty($success['error'])) {
$this->data[$this->ID]['error'] = $success['error'];
}
}
$this->ID = 'Unsubscribed';
}
$this->data['id'] = $this->ID;
$this->data['page'] = $this->page;
$this->data['limit'] = $this->mailerlite->limit;
$flap = 'flap'.$this->ID;
$vars['header']['flap'] = $flap;
$pageVars['data'] = $this->data;
$vars['body'] = $pageVars;
$vars['body']['acn'] = $this->action;
$vars['body']['type'] = $this->ID;
$vars['body']['title'] = 'MailerLite Group '.$this->mailerlite->group['name'];
$vars['body']['group'] = $this->mailerlite->group;
return $vars;
}
public function handleShopUnsubscribe()
{
$this->ID = 'Unsubscribed';
$data = getVal('unsubscribe');
if (!empty($data)) {
$ids = array_keys($data);
$unsubscribe_data = $this->mailerlite->ShopUnsubscribe($ids);
if (!empty($unsubscribe_data['success'])) {
$this->returnOK($unsubscribe_data['success']);
}
}
}
public function handleShopSubscribe()
{
$this->ID = 'Active';
$data = getVal('subscribe');
if (!empty($data)) {
$ids = array_keys($data);
$subscribe_data = $this->mailerlite->ShopSubscribe($ids);
if (!empty($subscribe_data['success'])) {
$this->returnOK($subscribe_data['success']);
}
}
}
public function handleMailerliteUnsubscribe()
{
$this->ID = 'ShopUnsubscribed';
if ($this->mailerlite->error) {
return false;
}
$data = getVal('mailerlite_unsubscribe');
if (!empty($data)) {
$unsubscribe_data = $this->mailerlite->MailerliteUnsubscribe($data);
if (!empty($unsubscribe_data['err'])) {
$this->returnError($unsubscribe_data['err'], '', 'ShopUnsubscribed');
}
if (!empty($unsubscribe_data['success'])) {
$this->returnOK($unsubscribe_data['success']);
}
}
}
public function handleMailerliteSubscribe()
{
$this->ID = 'ShopUsers';
if ($this->mailerlite->error) {
return false;
}
$data = getVal('export');
if (!empty($data)) {
$users = $this->mailerlite->getKupShopUsers($data);
$subscribers = array_map([$this->mailerlite, 'prepareExportData'], $users['subscribers']);
$subscribe_data = $this->mailerlite->MailerliteSubscribe($subscribers);
if (!empty($subscribe_data['err'])) {
$this->returnError($subscribe_data['err'], '', 'ShopUsers');
}
if (!empty($subscribe_data['success'])) {
$this->returnOK($subscribe_data['success']);
}
}
}
public function handleMailerliteSynchronize()
{
$this->ID = 'Synchronize';
if ($this->mailerlite->error) {
return false;
}
$sync_data = $this->mailerlite->Synchronize();
$this->returnOK($sync_data);
}
}

View File

@@ -0,0 +1,74 @@
<?php
$main_class = 'MailerLiteActions';
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use KupShop\MailerLiteBundle\MailerLite;
class MailerLiteActions extends Window
{
protected $action;
protected $ID;
protected $template = 'window/mailerLiteActions.tpl';
protected $title = 'MailerLiteActions';
/**
* @var MailerLite
*/
protected $mailerlite;
public function __construct()
{
ini_set('memory_limit', '1G');
$this->mailerlite = ServiceContainer::getService(MailerLite::class);
$this->mailerlite->getSubscriberGroup();
}
public function get_vars()
{
if ($this->mailerlite->error) {
$vars['ErrStr'] = $this->mailerlite->error;
return $vars;
}
$vars = parent::get_vars();
$this->ID = $this->getID();
$this->action = $this->getAction();
if ($this->action == 'Upgrade') {
$this->title = 'MailerLite - Upgrade ';
$upgrade = false;
if ($this->ID == 'UpgradeCustomFields') {
$this->title .= 'Custom Fields';
$upgrade = $this->mailerlite->upgradeCustomFields();
}
if ($this->ID == 'UpgradeWebhooks') {
$this->title .= 'Webhooks';
$upgrade = $this->mailerlite->upgradeWebhooks();
}
$vars['body']['upgrade'] = ($upgrade ? 'OK' : $upgrade);
$vars['body']['upgrade_message'] = ($this->mailerlite->upgrade_message ?? []);
}
if ($this->action == 'Synchronize') {
$this->title = 'MailerLite - Synchronization';
$sync_data = null;
if ($this->ID == 'SyncEverything') {
$sync_data = $this->mailerlite->Synchronize();
}
if ($this->ID == 'Synchronize') {
$now = time();
$filter_date = date('Y-m-d', $now - 7 * 24 * 60 * 60); // -7 days
$sync_data = $this->mailerlite->Synchronize($filter_date);
$sync_data['period'] = $filter_date.' - '.date('Y-m-d', $now);
}
$vars['body']['sync_data'] = $sync_data;
}
$vars['body']['type'] = $this->getID();
$vars['body']['acn'] = $this->action;
$vars['body']['title'] = $this->title;
return $vars;
}
}

View File

@@ -0,0 +1,35 @@
<?php
namespace KupShop\MailerLiteBundle\Admin\Tabs;
use KupShop\AdminBundle\Admin\WindowTab;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use KupShop\MailerLiteBundle\MailerLite;
class MailerLiteSettings extends WindowTab
{
protected $title = 'flapMailerLite';
protected $template = 'MailerLiteSettingsWindowTab.tpl';
public static function getTypes()
{
return [
'settings' => 1,
];
}
public function getVars($smarty_tpl_vars)
{
$data = [];
$mailerlite = ServiceContainer::getService(MailerLite::class);
$mailerlite->getSubscriberGroup();
if ($mailerlite->version < MailerLite::VERSION) {
$mailerlite->upgradeCustomFields();
}
$data['mailerlite'] = $mailerlite;
return $data;
}
}

View File

@@ -0,0 +1,5 @@
<?php
$txt_str['mailerLiteSettings'] = [
'flapMailerLite' => 'MailerLite',
];

View File

@@ -0,0 +1,81 @@
<div id="flapMailerLite" class="tab-pane fade in boxFlex">
<div class="row bottom-space">
<div class="col-md-12">
<h1 class="h4 main-panel-title">MailerLite API</h1>
</div>
<div class="col-md-12">
<i class="bi bi-question-circle" style="color: #00a154;"></i> MailerLite > Integrations > Developer API (https://app.mailerlite.com/integrations/api/)<br>
</div>
</div>
<div id="mailerlite_settings">
<div class="form-group">
<div class="col-md-2 control-label"><label>API Key</label></div>
<div class="col-md-6">
<input type="text" class="form-control input-sm" name="data[mailerlite][api_key]" size="30" value="{$tab.data.mailerlite->api_key}">
</div>
</div>
<div class="form-group">
<div class="col-md-2 control-label"><label>Subscriber group</label></div>
<div class="col-md-6">
<input type="text" class="form-control input-sm" name="data[mailerlite][group]" size="30" maxlength="255" value="{$tab.data.mailerlite->groupID}">
<input type="hidden" class="form-control input-sm" name="data[mailerlite][version]" size="30" maxlength="255" value="{$tab.data.mailerlite->version}">
</div>
</div>
</div>
<div class="row bottom-space">
<div class="col-md-12">
<h1 class="h4 main-panel-title">MailerLite Forms</h1>
</div>
<div class="form-group">
<div class="col-md-2 control-label">
<label>Identifiers</label>
<a class="help-tip" data-toggle="tooltip" title="var ml_account = ml('accounts', '1099518', 'x6l9p5g0k2', 'load');"><i class="bi bi-question-circle"></i></a>
</div>
<div class="col-md-2">
<input type="text" class="form-control input-sm" name="data[mailerlite][forms][id]" size="30" maxlength="255" value="{$dbcfg.mailerlite.forms.id}">
</div>
<div class="col-md-2">
<input type="text" class="form-control input-sm" name="data[mailerlite][forms][key]" size="30" maxlength="255" value="{$dbcfg.mailerlite.forms.key}">
</div>
</div>
</div>
{if !empty($tab.data.mailerlite->error)}
<div id="mailerlite_error">
<div class="col-md-10 col-md-offset-2"><label>{$tab.data.mailerlite->error}</label></div>
</div>
{/if}
{if !empty($tab.data.mailerlite->group.id) && $tab.data.mailerlite->group.id == $tab.data.mailerlite->groupID}
<div id="mailerlite_group">
<div class="row bottom-space">
<div class="col-md-12">
<h1 class="h4 main-panel-title">{$tab.data.mailerlite->group.name}</h1>
</div>
</div>
<div class="col-md-2"><label>Group ID:</label> {$tab.data.mailerlite->group.id}</div>
<div class="col-md-3"><label>Created:</label> {$tab.data.mailerlite->group.date_created}</div>
<div class="col-md-3"><label>Updated:</label> {$tab.data.mailerlite->group.date_updated}</div>
<div class="col-md-4"><label>Active Subscribers:</label> {$tab.data.mailerlite->group.active}</div>
{if isSuperuser()}
<div class="col-md-2">
<button type="button" class="btn btn-success btn-block" name="acn" value="MailerLite" onclick="javascript:nw('MailerLite', 'Unsubscribed', 'acn=MailerLite');">Subscribers</button>
</div>
<div class="col-md-2">
<button type="submit" target="_blank" class="btn btn-danger btn-block" name="acn" value="mailerliteUpgradeCustomFields" title="Upgrade Custom Fields" onclick="javascript:nw('MailerLiteActions', 'UpgradeCustomFields', 'acn=Upgrade');">Upgrade Fields</button>
</div>
<div class="col-md-2">
<button type="submit" target="_blank" class="btn btn-danger btn-block" name="acn" value="mailerliteUpgradeWebhooks" title="Upgrade Webhooks" onclick="javascript:nw('MailerLiteActions', 'UpgradeWebhooks', 'acn=Upgrade');">Upgrade Webhooks</button>
</div>
<div class="col-md-2">
<button type="submit" target="_blank" class="btn btn-danger btn-block" name="acn" value="mailerliteSyncEverything" title="Sync everything" onclick="javascript:nw('MailerLiteActions', 'SyncEverything', 'acn=Synchronize');">Sync everything</button>
</div>
{/if}
<div class="col-md-2">
<button type="submit" target="_blank" class="btn btn-danger btn-block" name="acn" value="mailerliteSynchronize" title="Synchronize" onclick="javascript:nw('MailerLiteActions', 'Synchronize', 'acn=Synchronize');">Synchronize</button>
</div>
</div>
{/if}
</div>

View File

@@ -0,0 +1,37 @@
{extends file="[shared]/frame.tpl"}
{block title}
{$body.title}
{/block}
{block content}
<div class="form-group">
<div class="col-md-12">
<strong>{$body.title}: </strong>{$body.upgrade}
</div>
{foreach $body.upgrade_message as $message}
<div class="col-md-11 col-md-offset-1">
{$message}
</div>
{/foreach}
{if $body.sync_data}
<div class="col-md-11 col-md-offset-1">
{if !empty($body.sync_data.period)}
<b>Period:</b> {$body.sync_data.period}<br>
{/if}
{if !empty($body.sync_data.error)}
<b>Errors: </b><br>
{foreach $body.sync_data.error as $message}
{$message}<br>
{/foreach}
{/if}
{if !empty($body.sync_data.success)}
<b>Success: </b><br>
{foreach $body.sync_data.success as $message}
{$message}<br>
{/foreach}
{/if}
</div>
{/if}
</div>
{/block}

View File

@@ -0,0 +1,338 @@
{extends file="[shared]/window.tpl"}
{block js}
{$smarty.block.parent}
{/block}
{block tabs}
{windowTab id='flapUnsubscribed' label='MailerLite Unsubscribed'}
<!--{windowTab id='flapActive' label='MailerLite Active'}-->
{windowTab id='flapShopUnsubscribed' label='Shop Unsubscribed'}
{windowTab id='flapShopUsers' label='Shop Newsletter Subscribers'}
{/block}
{block title}
{if $body.title}
{$body.title}
{/if}
{/block}
{block css append}
{literal}<style>table.mailerlite{background-color:#cccccc;border-spacing:1px;border-collapse:separate;} .mailerlite td{background:white;padding:2px 5px;} .mailerlite th{background:#eeeeee;padding:2px 5px;}</style>{/literal}
{/block}
{block name=windowContent prepend}
<div id="mailerlite_group">
<div class="col-md-12">
<h1 class="h4 main-panel-title">MailerLite Group: {$body.group.name}</h1>
{if $ErrStr}<legend class="row-red">{$ErrStr}</legend>{/if}
{if $body.data.Synchronize.err}<legend class="row-red">Synchronize Errors: <br>{implode('; ', $body.data.Synchronize.err)};</legend>{/if}
{if $body.data.Synchronize.success}<legend class="row-green">Synchronize: <br>{implode('; ', $body.data.Synchronize.success)};</legend>{/if}
</div>
<div class="col-md-2 bottom-space"><label>Group ID:</label> {$body.group.id}</div>
<div class="col-md-3 bottom-space"><label>Created:</label> {$body.group.date_created}</div>
<div class="col-md-3 bottom-space"><label>Updated:</label> {$body.group.date_updated}</div>
<div class="col-md-4 bottom-space"><label>Active Subscribers:</label> {$body.group.active}</div>
</div>
{/block}
{block tabsContent}
{$shop_users = $body.data.ShopUsers.subscribers + $body.data.ShopUsers.unsubscribed}
<div id="flapUnsubscribed" class="tab-pane fade active in boxStatic">
{$type = 'Unsubscribed'}
<legend>MailerLite {$type}: {$body.data.$type.subscribers_count} {if $body.data.$type.filter_date}[date_unsubscribe >= {$body.data.$type.filter_date}]{/if}</legend>
{if $body.data.Junk.subscribers_count}
<legend>MailerLite Junk (spam complaints): {$body.data.Junk.subscribers_count}</legend>
{/if}
{if $body.data.Bounced.subscribers_count}
<legend>MailerLite Bounced (mailbox does not exists or disabled): {$body.data.Bounced.subscribers_count}</legend>
{/if}
{if $body.data.$type.err}<legend class="row-red">{$body.data.$type.err}</legend>{/if}
{if $body.data.$type.success}<legend class="row-green">{$body.data.$type.success}</legend>{/if}
{if $body.data.$type.subscribers}
<div class="form-group">
<div class="col-md-12">
<table class="mailerlite">
<tr><th></th><th colspan="2">MailerLite</th><th colspan="3">wpjshop</th></tr>
<tr>
<th>#</th>
<th>email</th>
<th>date_unsubscribe</th>
<th>exists</th>
<th>get_news</th>
<th><input type="checkbox" name="unsubscribeSelectAll" title="Select All"></th>
</tr>
{$i=1}
{foreach $body.data.Junk.subscribers as $subscriber}
{$class = 'row-red'}
{$user = null}
{if array_key_exists($subscriber['email'], $shop_users)}
{$user = $shop_users[$subscriber['email']]}
{/if}
<tr class="{$class}">
<td>{$i++}</td>
<td>{$subscriber.email}</td>
<td>{$subscriber.date_unsubscribe}</td>
{if ($user)}
<td>Y</td>
<td>{$user.get_news}</td>
<td><input type="checkbox" name="unsubscribe[{$user.id}]" {($user.get_news == 'Y')?' checked':''}></td>
{else}
<td>N</td>
<td>--</td>
<td>--</td>
{/if}
</tr>
{/foreach}
{foreach $body.data.$type.subscribers as $subscriber}
{if $i > 20000}
{break}
{/if}
{$class = ''}
{$user = null}
{if array_key_exists($subscriber['email'], $shop_users)}
{$user = $shop_users[$subscriber['email']]}
{$class = 'row-green'}
{if $user.get_news == 'Y'}
{$class = 'row-red'}
{/if}
{/if}
<tr class="{$class}">
<td>{$i++}</td>
<td>{$subscriber.email}</td>
<td>{$subscriber.date_unsubscribe}</td>
{if ($user)}
<td>Y</td>
<td>{$user.get_news}</td>
<td><input type="checkbox" name="unsubscribe[{$user.id}]" {($user.get_news == 'Y')?' checked':''}></td>
{else}
<td>N</td>
<td>--</td>
<td>--</td>
{/if}
</tr>
{/foreach}
<tr><th colspan="5">&nbsp;</th><th><button type="submit" class="btn btn-danger btn-block confirm" name="acn" value="shopUnsubscribe" title="Unsubscribe on Shop">Unsubscribe</button></th></tr>
</table>
</div>
</div>
{/if}
</div>
<div id="flapActive" class="tab-pane fade active in boxStatic">
{$type = 'Active'}
{$page = $body.data.page+1}
{$i = $body.data.limit*($page-1)+1}
<legend>MailerLite {$type}: {$i}-{$i+$body.data.$type.subscribers_count-1} (page {$page})</legend>
{if $body.data.$type.err}<legend class="row-red">{$body.data.$type.err}</legend>{/if}
{if $body.data.$type.success}<legend class="row-green">{$body.data.$type.success}</legend>{/if}
{if $body.data.$type.subscribers}
<div class="form-group">
<div class="col-md-12">
<table class="mailerlite">
<tr><th></th><th colspan="2">MailerLite</th><th colspan="3">wpjshop</th></tr>
<tr>
<th>#</th>
<th>email</th>
<th>date_subscribe</th>
<th>exists</th>
<th>get_news</th>
<th><input type="checkbox" name="subscribeSelectAll" title="Select All"></th>
</tr>
{foreach $body.data.$type.subscribers as $subscriber}
{if $i > 20000}
{break}
{/if}
{$class = ''}
{$user = null}
{if array_key_exists($subscriber['email'], $shop_users)}
{$user = $shop_users[$subscriber['email']]}
{$class = 'row-green'}
{if $user.get_news == 'N'}
{$class = 'row-red'}
{/if}
{/if}
<tr class="{$class}">
<td>{$i++}</td>
<td>{$subscriber.email}</td>
<td>{$subscriber.date_subscribe}</td>
{if ($user)}
<td>Y</td>
<td>{$user.get_news}</td>
<td><input type="checkbox" name="subscribe[{$user.id}]" {($user.get_news == 'N')?' checked':''}></td>
{else}
<td>N</td>
<td>--</td>
<td>--</td>
{/if}
</tr>
{/foreach}
<tr><th colspan="5">&nbsp;</th><th><button type="submit" class="btn btn-danger btn-block confirm" name="acn" value="shopSubscribe" title="Subscribe on Shop">Subscribe</button></th></tr>
</table>
</div>
</div>
{/if}
</div>
<div id="flapShopUnsubscribed" class="tab-pane fade active in boxStatic">
{$type = 'ShopUsers'}
<legend>Shop Unsubscribed: {$body.data.$type.unsubscribed_count}</legend>
{if $body.data.ShopUnsubscribed.err}<legend class="row-red">{$body.data.ShopUnsubscribed.err}</legend>{/if}
{if $body.data.ShopUnsubscribed.success}<legend class="row-green">{$body.data.ShopUnsubscribed.success}</legend>{/if}
{if $body.data.$type.unsubscribed}
<div class="form-group">
<div class="col-md-12">
<table class="mailerlite">
<tr><th></th><th colspan="2">wpjshop</th><th colspan="2">MailerLite</th></tr>
<tr>
<th>#</th>
<th>email</th>
<th>date_updated</th>
<th>unsubscribed</th>
<th><input type="checkbox" name="mailerlite_unsubscribeSelectAll" title="Select All"></th>
</tr>
{$i=1}
{$mailerliteUnsubscribed = array_flip(array_column($body.data.Unsubscribed.subscribers, 'email'))}
{foreach $body.data.$type.unsubscribed as $subscriber}
{$user_unsubscribed = array_key_exists($subscriber.email, $mailerliteUnsubscribed)}
{$class = ''}
{if $user_unsubscribed}
{$class = 'row-green'}
{/if}
<tr class="{$class}">
<td>{$i++}</td>
<td>{$subscriber.email}</td>
<td>{$subscriber.date_updated}</td>
{if ($user_unsubscribed)}
<td>Y</td>
<td><input type="checkbox" name="mailerlite_unsubscribe[{$subscriber.email}]"></td>
{else}
<td>N</td>
<td><input type="checkbox" name="mailerlite_unsubscribe[{$subscriber.email}]" checked></td>
{/if}
</tr>
{/foreach}
<tr><th colspan="4">&nbsp;</th><th><button type="submit" class="btn btn-danger btn-block confirm" name="acn" value="mailerliteUnsubscribe" title="Unsubscribe on Mailerlite">Unsubscribe</button></th></tr>
</table>
</div>
</div>
{/if}
</div>
<div id="flapShopUsers" class="tab-pane fade active in boxStatic">
{$type = 'ShopUsers'}
<legend>Shop Newsletter Subscribers: {$body.data.$type.subscribers_count}</legend>
{if $body.data.$type.err}<legend class="row-red">{$body.data.$type.err}</legend>{/if}
{if $body.data.$type.success}<legend class="row-green">{$body.data.$type.success}</legend>{/if}
{if $body.data.$type.subscribers}
<div class="form-group" style="margin-bottom: 100px;">
<div class="col-md-12">
<table class="mailerlite">
<tr><th></th><th colspan="4">wpjshop</th><th colspan="2">MailerLite</th></tr>
<tr>
<th>#</th>
<th>email</th>
<th>price_level</th>
<th>user_groups</th>
<th>date_updated</th>
<th>unsubscribed</th>
<th><input type="checkbox" name="exportSelectAll" title="Select All"></th>
</tr>
{$i=1}
{$mailerliteUnsubscribed = array_flip(array_column($body.data.Unsubscribed.subscribers, 'email'))}
{foreach $body.data.$type.subscribers as $subscriber}
{if $i > 20000}
{break}
{/if}
{$user_unsubscribed = array_key_exists($subscriber.email, $mailerliteUnsubscribed)}
{$class = ''}
{if $user_unsubscribed}
{$class = 'row-red'}
{/if}
<tr class="{$class}">
<td>{$i++}</td>
<td>{$subscriber.email}</td>
<td>{$subscriber.user_price_level}</td>
<td>{$subscriber.user_groups}</td>
<td>{$subscriber.date_updated}</td>
{if ($user_unsubscribed)}
<td>Y</td>
<td><input type="checkbox" name="export[{$subscriber.id}]" value='{$subscriber.id}'></td>
{else}
<td>N</td>
<td><input type="checkbox" name="export[{$subscriber.id}]" value='{$subscriber.id}' checked></td>
{/if}
</tr>
{/foreach}
<tr><th colspan="6">&nbsp;</th><th><button type="submit" class="btn btn-danger btn-block confirm" name="acn" value="mailerliteSubscribe" title="Exportovat do Mailerlite">Export</button></th></tr>
</table>
</div>
</div>
{/if}
</div>
{/block}
{block buttonsLeft}
<div class="col-md-4">
<div class="btn-group">
<button type="button" onClick="javascript:document.location='launch.php?s=MailerLite.php&acn=MailerLite&ID=Active&page={$body.data.page-1}';" data-goto="prev" class="btn">
<span class="glyphicon glyphicon-chevron-left"></span> {'prev'|translate:'button'}</button>
<button type="button" onClick="javascript:document.location='launch.php?s=MailerLite.php&acn=MailerLite&ID=Active&page={$body.data.page+1}';" data-goto="next" class="btn">{'next'|translate:'button'}
<span class="glyphicon glyphicon-chevron-right"></span>
</button>
</div>
</div>
<input type="hidden" name="page" value="{$body.data.page}">
{/block}
{block buttonsRight}
<div class="col-md-2 col-md-offset-4">
{if empty($ErrStr)}<button type="submit" class="btn btn-danger btn-block confirm" name="acn" value="mailerliteSynchronize" title="Sync everything">Synchronize</button>{/if}
</div>
<div class="col-md-2">
<input type="button" class="btn btn-primary btn-block" onClick="closeWindow();" value="{'windowCancel'|translate:'button'}"/>
</div>
{/block}
<script type="text/javascript">
{block onready prepend}
$(document).ready(function () {
{if $body.type == 'Active'}
showPrevNextButtons();
{else}
hidePrevNextButtons();
{/if}
});
$(document).on('click.bs.tab.data-api', '[data-toggle="tab"], [data-toggle="pill"]', function (e) {
if ($(this).parent().index() == 1) {
//showPrevNextButtons();
}
else {
hidePrevNextButtons();
}
});
function hidePrevNextButtons() {
$('[data-goto="prev"]').attr('style', 'display:none;');
$('[data-goto="next"]').attr('style', 'display:none;');
}
function showPrevNextButtons() {
$('[data-goto="prev"]').prop("disabled", "");
$('[data-goto="next"]').prop("disabled", "");
{if $body.data.page == 0}
$('[data-goto="prev"]').prop("disabled", "disabled");
{/if}
{if $body.data.Active.subscribers_count < $body.data.limit}
$('[data-goto="next"]').prop("disabled", "disabled");
{/if}
$('[data-goto="prev"]').attr('style', 'display:block;');
$('[data-goto="next"]').attr('style', 'display:block;');
}
$("input[type='checkbox'][name$='SelectAll']").change(function (event) {
checkboxAll = event.target;
checkbox_name = checkboxAll.name.replace('SelectAll', '');
checkbox_checked = checkboxAll.checked;
$("input[type='checkbox'][name^='" + checkbox_name + "[']").prop("checked", checkbox_checked);
})
{/block}
</script>

View File

@@ -0,0 +1,75 @@
<?php
namespace KupShop\MailerLiteBundle\Controller;
use KupShop\MailerLiteBundle\MailerLite;
use KupShop\UserBundle\Util\UserConsent;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
class MailerLiteController extends AbstractController
{
/**
* @Route(path="/_mailerlite/webhook/")
*/
public function webhookAction(Request $request, MailerLite $mailerlite, UserConsent $userConsent)
{
$data = [];
if ($mailerlite->error) {
$data['mailerlite_error'] = $mailerlite->error;
$response = new JsonResponse($data, 500);
return $response;
}
$mailerlite_signature = $request->headers->get('X-MailerLite-Signature');
if (!$mailerlite_signature) {
$data['signature_error'] = "'X-MailerLite-Signature' was not sent";
$response = new JsonResponse($data, 403);
return $response;
}
$events_json = $request->getContent();
$signature = $this->generateSignature($events_json, $mailerlite->api_key);
if ($signature != $mailerlite_signature) {
$data['signature_error'] = 'Signature mismatch';
$response = new JsonResponse($data, 403);
return $response;
}
$events = json_decode($events_json, true);
if ($events) {
$events = $events['events'];
foreach ($events as $event) {
$event_type = $event['type'];
if ($event_type == 'subscriber.unsubscribe') {
foreach ($event['data'] as $subscriber) {
$user = \User::createFromLogin($subscriber['email']);
if (!$user || ($user->get_news == 'N')) {
$update_res = 'skipped';
} else {
$update_res = ($userConsent->updateNewsletter($user->id, 'N') ? 'unsubscribed' : 'error');
}
$data[$event_type][$subscriber['email']] = $update_res;
}
}
}
}
$response = new JsonResponse($data);
return $response;
}
public function generateSignature($jsonPayload, $apiKey)
{
return base64_encode(
hash_hmac('sha256', $jsonPayload, $apiKey, true)
);
}
}

View File

@@ -0,0 +1,33 @@
<?php
namespace KupShop\MailerLiteBundle\EventListener;
use KupShop\KupShopBundle\Event\CronEvent;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use KupShop\MailerLiteBundle\MailerLite;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class CronListener implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return [
CronEvent::RUN_EXPENSIVE => [
['syncMailerLite', 200],
],
];
}
/**
* @var CronEvent
*/
public function syncMailerLite(CronEvent $cronEvent)
{
$mailerlite = ServiceContainer::getService(MailerLite::class);
if (empty($mailerlite->error)) {
$now = time();
$filter_date = date('Y-m-d', $now - 7 * 24 * 60 * 60); // -7 days
$mailerlite->Synchronize($filter_date);
}
}
}

View File

@@ -0,0 +1,619 @@
<?php
namespace KupShop\MailerLiteBundle;
use KupShop\KupShopBundle\Config;
class MailerLite
{
public $api_key;
public $groupID;
public $version;
public $group;
public $error;
public $limit = 5000;
public const VERSION = 2;
public $custom_fields = [
['Registered', 'TEXT'], ['Currency', 'TEXT'],
['User Groups', 'TEXT'], ['User Price Level', 'TEXT'],
['Greeting Name', 'TEXT'], ['Greeting Surname', 'TEXT'], ['Sex', 'TEXT'],
['Orders Count', 'NUMBER'], ['Orders Total', 'NUMBER'], ['Last Order Date', 'DATE'],
['Last Year Orders Count', 'NUMBER'], ['Last Year Orders Total', 'NUMBER'],
['Bonus Points', 'NUMBER', \Modules::BONUS_PROGRAM],
];
public $webhooks = ['subscriber.unsubscribe' => '_mailerlite/webhook/'];
public $upgrade_message;
public function __construct()
{
$settings = \Settings::getDefault();
if (isset($settings['mailerlite'])) {
$this->api_key = $settings['mailerlite']['api_key'];
$this->groupID = $settings['mailerlite']['group'];
if (isset($settings['mailerlite']['version'])) {
$this->version = $settings['mailerlite']['version'];
}
}
if ($this->api_key && $this->groupID) {
} else {
$this->error = 'MailerLite modul je špatně nastavený!';
}
}
public function getSubscriberGroup()
{
if ($this->api_key && $this->groupID) {
$response = $this->execCurl('https://api.mailerlite.com/api/v2/groups/'.$this->groupID, 5);
if (!$this->error) {
$group_response = json_decode($response, true);
if (!empty($group_response['error'])) {
$this->error = 'MailerLite: Group Error: '.$group_response['error']['message'];
} else {
$this->group = $group_response;
}
}
} else {
$this->error = 'MailerLite modul je špatně nastavený!';
}
}
public function upgradeCustomFields()
{
if ($this->error) {
$this->upgrade_message[] = $this->error;
}
if ($this->api_key) {
$response = $this->execCurl('https://api.mailerlite.com/api/v2/fields', 5);
$fields = json_decode($response, true);
if (!empty($fields['error'])) {
$this->upgrade_message[] = 'MailerLite: Fields Error: '.$fields['error']['message'];
} else {
$fields_error = false;
$fields_titles = array_flip(array_column($fields, 'title'));
foreach ($this->custom_fields as $customField) {
if (isset($customField[2]) && !findModule($customField[2])) {
$this->upgrade_message[] = 'Field skipped - '.$customField[0].' - module not found - '.$customField[2].'; ';
continue;
}
if (!array_key_exists($customField[0], $fields_titles)) {
$new_field = '{"title": "'.$customField[0].'", "type": "'.$customField[1].'"}';
$response = $this->execCurl('https://api.mailerlite.com/api/v2/fields', 5, 'POST', $new_field);
$field_response = json_decode($response, true);
if (!empty($field_response['error'])) {
$fields_error = true;
$this->upgrade_message[] = 'MailerLite: Fields Error: '.$field_response['error']['message'];
} else {
$this->upgrade_message[] = 'New field created - '.$field_response['title'].', '.$field_response['id'].', '.$field_response['key'].'; ';
}
}
}
if (!$fields_error) {
$settings = \Settings::getDefault();
if ($this->version < self::VERSION) {
$mailerlite_settings = ['version' => self::VERSION];
$settings->updateValue('mailerlite', $mailerlite_settings);
$this->version = $settings['mailerlite']['version'];
$this->upgrade_message[] = 'MailerLite: version upgraded to \''.$this->version.'\' ';
}
return true;
}
}
}
return false;
}
public function upgradeWebhooks()
{
if ($this->error) {
$this->upgrade_message[] = $this->error;
}
if ($this->api_key) {
$response = $this->execCurl('https://api.mailerlite.com/api/v2/webhooks', 5);
$webhooks = json_decode($response, true);
if (!empty($webhooks['error'])) {
$this->upgrade_message[] = 'MailerLite: Webhooks Error: '.$webhooks['error']['message'];
} else {
$webhooks_error = false;
$domain = Config::get()['Addr']['full'];
$webhooks = $webhooks['webhooks'];
foreach ($webhooks as $webhook) {
$webhook_type = $webhook['event'];
if (array_key_exists($webhook_type, $this->webhooks)) {
$url = $domain.$this->webhooks[$webhook_type];
if ($webhook['url'] != $url) {
$response = $this->execCurl('https://api.mailerlite.com/api/v2/webhooks/'.$webhook['id'], 5, 'DELETE');
$webhook_response = json_decode($response, true);
if (!empty($webhook_response['error'])) {
$webhooks_error = true;
$this->upgrade_message[] = 'MailerLite: Webhooks Error: '.$webhook_response['error']['message'];
} else {
$this->upgrade_message[] = 'Webhook deleted - '.$webhook['id'].', '.$webhook_type.', '.$webhook['url'].'; ';
}
}
}
}
foreach ($this->webhooks as $event => $url) {
$new_webhook = '{"event": "'.$event.'", "url": "'.$domain.$url.'"}';
$response = $this->execCurl('https://api.mailerlite.com/api/v2/webhooks/', 5, 'POST', $new_webhook);
$webhook_response = json_decode($response, true);
if (!empty($webhook_response['error'])) {
$webhooks_error = true;
$this->upgrade_message[] = 'MailerLite: Webhooks Error: '.$webhook_response['error']['message'];
} else {
$this->upgrade_message[] = 'New webhook created - '.$webhook_response['id'].', '.$webhook_response['event'].', '.$webhook_response['url'].'; ';
}
}
return !$webhooks_error;
}
}
return false;
}
public function execCurl($url, $timeout = 50, $http_method = 'GET', $post_data = null)
{
$curl = curl_init();
curl_setopt_array(
$curl,
[
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => $timeout,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => $http_method,
CURLOPT_HTTPHEADER => [
'content-type: application/json',
'x-mailerlite-apikey: '.$this->api_key,
],
]
);
if ($post_data) {
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
}
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
$this->error = 'MailerLite: cURL Error: '.$err;
}
return $response;
}
public function updateUser($user, $newsletter)
{
$mailerlite_data_array['email'] = $user->email;
$cur_date = date('Y-m-d H:i:s');
if ($newsletter == 'Y') {
$mailerlite_data_array['type'] = 'active';
$mailerlite_data_array['date_subscribe'] = $cur_date;
$user_data = $this->getKupShopUsers([$user->id]);
if ($user_data['subscribers_count'] == 1) {
$mailerlite_data_array += reset($user_data['subscribers']);
} elseif ($user_data['unsubscribed_count'] == 1) {
$mailerlite_data_array += reset($user_data['unsubscribed']);
}
$mailerlite_data_array['resubscribe'] = true;
} else {
$mailerlite_data_array['type'] = 'unsubscribed';
$mailerlite_data_array['date_unsubscribe'] = $cur_date;
}
$mailerlite_data = $this->prepareExportData($mailerlite_data_array);
$response = $this->execCurl('https://api.mailerlite.com/api/v2/groups/'.$this->groupID.'/subscribers', 10, 'POST', $mailerlite_data);
if ($this->error) {
return false;
}
$subscriber_response = json_decode($response, true);
if (!empty($subscriber_response['error'])) {
$this->error = 'MailerLite: updateUser Error: '.$subscriber_response['error']['message'];
return false;
}
return true;
}
public function getMailerLiteSubscribers($type = 'Unsubscribed', $page = null, $filter_date = null)
{
$data = [];
$get_params = '?limit='.$this->limit;
if ($filter_date && ($type == 'Unsubscribed')) {
$get_params .= '&filters[date_unsubscribe][$gte]='.$filter_date;
$data['filter_date'] = $filter_date;
}
if (!is_null($page)) {
if ($page > 0) {
$get_params .= '&offset='.($page * $this->limit);
}
}
$response = $this->execCurl('https://api.mailerlite.com/api/v2/groups/'.$this->groupID.'/subscribers/'.strtolower($type).$get_params);
if ($this->error) {
$data['err'] = $this->error;
} else {
$subscribers = json_decode($response, true);
if (is_null($subscribers)) {
$data['err'] = 'MailerLite: Subscribers Error: '.$response;
} else {
if (!empty($subscribers['error'])) {
$data['err'] = 'MailerLite: Subscribers Error: '.$subscribers['error']['message'];
} else {
$emails = array_column($subscribers, 'email');
$subscribers = array_combine($emails, $subscribers);
$data['subscribers_count'] = count($subscribers);
$data['subscribers'] = $subscribers;
}
}
}
return $data;
}
public function getMailerLiteSubscribers_All($type = 'Unsubscribed')
{
$data['subscribers_count'] = 0;
$data['subscribers'] = [];
$page = 0;
$next_page = $this->getMailerLiteSubscribers($type, $page);
while (!empty($next_page['subscribers_count']) && ($next_page['subscribers_count'] > 0)) {
$data['subscribers_count'] += $next_page['subscribers_count'];
$data['subscribers'] += $next_page['subscribers'];
$page++;
$next_page = $this->getMailerLiteSubscribers($type, $page);
}
if (!empty($next_page['err'])) {
$data['err'] = $next_page['err'];
}
return $data;
}
public function MailerliteUnsubscribe($users_data)
{
$data = [];
$cur_date = date('Y-m-d H:i:s');
$batch_requests['requests'] = [];
$i = 0;
foreach ($users_data as $email => $value) {
$i++;
$mailerlite_request['method'] = 'POST';
$mailerlite_request['path'] = '/api/v2/groups/'.$this->groupID.'/subscribers';
$mailerlite_request['body']['email'] = $email;
$mailerlite_request['body']['type'] = 'unsubscribed';
$mailerlite_request['body']['date_unsubscribe'] = $cur_date;
$batch_requests['requests'][] = $mailerlite_request;
// if ($i == 50) {
// break; // There is a limit of maximum 50 requests per single batch.
// }
}
/* $batch_requests_json = json_encode($batch_requests);
$response = $this->execCurl('https://api.mailerlite.com/api/v2/batch', 30, 'POST', $batch_requests_json);
if ($this->error) {
$data['err'] = $this->error;
} else {
$batch_response = json_decode($response, true);
if (!empty($batch_response['error'])) {
$data['err'] = 'MailerLite: Unsubscribe Error: '.$batch_response['error']['message'];
} else {
$data['success'] = $batch_response;
}
}
*/
// if ($data['err']) {
// if (strstr($data['err'], 'A website error has occurred.')) {
// 'batch' is not working - A website error has occurred. The website administrator has been notified of the issue. Sorry for the temporary inconvenience
// send one by one
$data['err'] = '';
$unsubscribed_count = 0;
foreach ($batch_requests['requests'] as $mailerlite_request) {
$mailerlite_request_json = json_encode($mailerlite_request['body']);
$response = $this->execCurl('https://api.mailerlite.com/api/v2/groups/'.$this->groupID.'/subscribers', 5, 'POST', $mailerlite_request_json);
if ($this->error) {
$data['err'] = $this->error;
} else {
$unsubscribe_response = json_decode($response, true);
if (!empty($unsubscribe_response['error'])) {
$data['err'] = 'MailerLite: Unsubscribe Error: '.$unsubscribe_response['error']['message'];
} else {
if ($unsubscribe_response['type'] == 'unsubscribed') {
$unsubscribed_count++;
}
}
}
if ($data['err']) {
break;
}
}
if ($unsubscribed_count > 0) {
$data['success'] = 'MailerliteUnsubscribe: '.$unsubscribed_count;
}
// }
// }
return $data;
}
public function MailerliteSubscribe($users_data)
{
$data = [];
if (!empty($users_data)) {
$subscribers = '{"subscribers":['.implode(',', $users_data).'], "resubscribe":true}';
$response = $this->execCurl('https://api.mailerlite.com/api/v2/groups/'.$this->groupID.'/subscribers/import', 300, 'POST', $subscribers);
if ($this->error) {
$data['err'] = $this->error;
} else {
$export_result = json_decode($response, true);
if (!empty($export_result['error'])) {
$data['err'] = 'MailerLite: Subscribe Error: '.$export_result['error']['message'];
} else {
$export_success_str = 'Export: imported = '.count($export_result['imported'] ?? []);
$export_success_str .= ', updated = '.count($export_result['updated'] ?? []);
$export_success_str .= ', unchanged = '.count($export_result['unchanged'] ?? []);
$export_success_str .= ', errors = '.count($export_result['errors'] ?? []);
$data['success'] = $export_success_str;
}
}
}
return $data;
}
public function getKupShopUsers($user_ids = null)
{
$data = [];
if (findModule(\Modules::CURRENCIES)) {
$currency = 'u.currency';
} else {
$currency = "NULL AS 'currency'";
}
$sql = sqlQueryBuilder()
->select('u.id', 'LOWER(u.email) as email', 'u.get_news',
'u.figure as `registered`', 'u.name', 'u.surname as `last_name`',
'u.firm as `company`', 'u.date_reg', 'u.date_updated',
'l.name as user_price_level', 'u.country', $currency,
'(SELECT CONCAT("\"", GROUP_CONCAT(ug.name SEPARATOR "\", \""), "\"")
FROM users_groups_relations ugr LEFT JOIN users_groups ug ON ugr.id_group = ug.id
WHERE ugr.id_user = u.id) AS user_groups',
'COUNT(o.id) AS orders_count',
'ROUND(SUM(o.total_price*o.currency_rate)) AS orders_total',
'MAX(o.date_created) AS last_order_date',
'SUM(o.date_created >= DATE_SUB(current_date, INTERVAL 1 YEAR)) as last_year_orders_count',
'ROUND(SUM(o.total_price*o.currency_rate*(o.date_created >= DATE_SUB(current_date, INTERVAL 1 YEAR)))) as last_year_orders_total')
->from('users', 'u')
->leftJoin('u', 'users_dealer_price_level', 'udpl', 'u.id = udpl.id_user')
->leftJoin('u', 'price_levels', 'l', 'udpl.id_price_level = l.id')
->leftJoin('u', 'orders', 'o', 'u.email = o.invoice_email AND o.status_storno=0')
->groupBy('u.id')
->orderBy('u.date_updated', 'DESC');
if (findModule(\Modules::BONUS_PROGRAM)) {
$sql->addSelect('(SELECT SUM(bp.points)
FROM bonus_points bp
WHERE bp.id_user = u.id AND bp.status = "active") AS bonus_points');
}
if (!is_null($user_ids)) {
$sql->where(\Query\Operator::inIntArray($user_ids, 'u.id'));
}
$qb = $sql->execute();
$users = $qb->fetchAll();
$users_emails = array_column($users, 'email');
$users = array_combine($users_emails, $users);
$subscribers = array_filter($users, function ($v) {return $v['get_news'] == 'Y'; });
$unsubscribed = array_filter($users, function ($v) {return $v['get_news'] == 'N'; });
$data['subscribers'] = $subscribers;
$data['unsubscribed'] = $unsubscribed;
$data['subscribers_count'] = count($data['subscribers']);
$data['unsubscribed_count'] = count($data['unsubscribed']);
return $data;
}
public function ShopUnsubscribe($users_data)
{
$data = [];
if (!empty($users_data)) {
$qb = sqlQueryBuilder()->update('users')
->set('get_news', ':news')->setParameter('news', 'N')
->set('date_unsubscribe', 'NOW()')
->set('date_updated', 'NOW()')
->where(\Query\Operator::inIntArray($users_data, 'id'))
->andWhere('get_news=\'Y\'')
->execute();
$data['success'] = 'ShopUnsubscribe: '.$qb;
}
return $data;
}
public function ShopSubscribe($users_data)
{
$data = [];
if (!empty($users_data)) {
$qb = sqlQueryBuilder()->update('users')
->set('get_news', ':news')->setParameter('news', 'Y')
->where(\Query\Operator::inIntArray($users_data, 'id'))
->execute();
$data['success'] = 'ShopSubscribe: '.$qb;
}
return $data;
}
public function Synchronize($filter_date = null)
{
$success = null;
$error = null;
if ($filter_date) {
$data['Unsubscribed'] = $this->getMailerLiteSubscribers('Unsubscribed', null, $filter_date);
} else {
$data['Unsubscribed'] = $this->getMailerLiteSubscribers_All('Unsubscribed');
}
if (array_key_exists('err', $data['Unsubscribed'])) {
$error[] = $data['Unsubscribed']['err'];
}
$data['Junk'] = $this->getMailerLiteSubscribers('Junk');
if (!empty($data['Junk']['subscribers_count'])) {
if ($error) {
$data['Unsubscribed'] = $data['Junk'];
} else {
$data['Unsubscribed']['subscribers_count'] += $data['Junk']['subscribers_count'];
$data['Unsubscribed']['subscribers'] += $data['Junk']['subscribers'];
}
}
$data['Bounced'] = $this->getMailerLiteSubscribers('Bounced');
if (!empty($data['Bounced']['subscribers_count'])) {
if ($error && empty($data['Unsubscribed'])) {
$data['Unsubscribed'] = $data['Bounced'];
} else {
$data['Unsubscribed']['subscribers_count'] += $data['Bounced']['subscribers_count'];
$data['Unsubscribed']['subscribers'] += $data['Bounced']['subscribers'];
}
}
$data['ShopUsers'] = $this->getKupShopUsers(); // all
if (!empty($data['Unsubscribed']['subscribers_count'])) {
$mailerlite_unsubscribed = $data['Unsubscribed']['subscribers'];
$shop_users_subscribers = $data['ShopUsers']['subscribers'];
$array_unsubscribe = array_intersect_key($shop_users_subscribers, $mailerlite_unsubscribed);
if ($array_unsubscribe) {
// Unsubscribe on Shop
$ids = array_column($array_unsubscribe, 'id');
$result = $this->ShopUnsubscribe($ids);
if (!empty($result['success'])) {
$success[] = $result['success'];
}
if (!empty($result['error'])) {
$error[] = $result['error'];
}
}
}
$user_ids = null;
if ($filter_date) {
$sql = sqlQueryBuilder()
->select('u.id')
->from('users', 'u')
->where('u.date_updated >= "'.$filter_date.'" ');
$qb = $sql->execute();
$user_ids = $qb->fetchAll();
$user_ids = array_column($user_ids, 'id');
$sql = sqlQueryBuilder()
->select('DISTINCT o.id_user')
->from('orders', 'o')
->where('o.id_user IS NOT NULL')
->andWhere('(o.date_created >= "'.$filter_date.'") OR (o.date_created >= DATE_SUB(current_date, INTERVAL 370 DAY) AND o.date_created < DATE_SUB(current_date, INTERVAL 1 YEAR) )');
$qb = $sql->execute();
$user_ids2 = $qb->fetchAll();
$user_ids2 = array_column($user_ids2, 'id_user');
$user_ids = array_unique(array_merge($user_ids, $user_ids2));
}
$data['ShopUsers'] = $this->getKupShopUsers($user_ids);
if ($data['ShopUsers']['subscribers_count']) {
// Subscribe on MailerLite
$shop_users_subscribers = $data['ShopUsers']['subscribers'];
foreach (array_chunk($shop_users_subscribers, 10000) as $chunk) {
$users_data = array_map([$this, 'prepareExportData'], $chunk);
$result = $this->MailerliteSubscribe($users_data);
if (!empty($result['success'])) {
$success[] = $result['success'];
}
if (!empty($result['error'])) {
$error[] = $result['error'];
}
}
}
if ($data['ShopUsers']['unsubscribed_count']) {
$shop_users_unsubscribed = $data['ShopUsers']['unsubscribed'];
$mailerlite_unsubscribed = $data['Unsubscribed']['subscribers'] ?? [];
$array_unsubscribe = array_diff_key($shop_users_unsubscribed, $mailerlite_unsubscribed);
if ($array_unsubscribe) {
// Unsubscribe on MailerLite
$result = $this->MailerliteUnsubscribe($array_unsubscribe);
if (!empty($result['success'])) {
$success[] = $result['success'];
}
if (!empty($result['error'])) {
$error[] = $result['error'];
}
}
}
$result = null;
if ($success) {
$result['success'] = $success;
}
if ($error) {
$result['error'] = $error;
}
if (empty($success) && empty($error)) {
$result['success'][] = 'Nothing to Synchronize';
}
return $result;
}
public static function prepareExportData($subscriber)
{
$export_data = null;
$export_data['email'] = $subscriber['email'];
foreach ($subscriber as $key => $value) {
if (in_array($key, ['email', 'type', 'date_subscribe', 'date_unsubscribe', 'resubscribe'])) {
$export_data[$key] = $value;
} else {
$export_data['fields'][$key] = $value;
}
}
$unsubscribed = (isset($subscriber['type']) && ($subscriber['type'] == 'unsubscribed'));
if (!$unsubscribed) {
$greeting = \Greeting::getGreeting($subscriber['name'], $subscriber['last_name'], 'name');
$export_data['fields']['greeting_name'] = $greeting['greeting'];
$export_data['fields']['sex'] = (!empty($greeting['sex']) ? $greeting['sex'] : '');
$greeting = \Greeting::getGreeting($subscriber['name'], $subscriber['last_name'], 'surname');
$export_data['fields']['greeting_surname'] = $greeting['greeting'];
}
$export_str = json_encode($export_data, 256);
return $export_str;
}
}

View File

@@ -0,0 +1,9 @@
<?php
namespace KupShop\MailerLiteBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class MailerLiteBundle extends Bundle
{
}

View File

@@ -0,0 +1,3 @@
content:
resource: "@MailerLiteBundle/Controller/"
type: annotation

View File

@@ -0,0 +1,20 @@
services:
KupShop\MailerLiteBundle\:
autowire: true
autoconfigure: true
resource: ../../{Controller}
KupShop\MailerLiteBundle\Admin\Tabs\:
resource: ../../Admin/Tabs/*.php
autoconfigure: true
KupShop\MailerLiteBundle\MailerLite:
class: KupShop\MailerLiteBundle\MailerLite
autowire: true
KupShop\MailerLiteBundle\EventListener\CronListener:
class: KupShop\MailerLiteBundle\EventListener\CronListener
autowire: true
tags:
- { name: kernel.event_subscriber }

View File

@@ -0,0 +1,34 @@
<?php
namespace KupShop\MailerLiteBundle;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
class MailerLiteUpgrade extends \UpgradeNew
{
public function check_MailerLiteVersion()
{
$settings = \Settings::getDefault();
if (isset($settings['mailerlite']) && !empty($settings['mailerlite']['api_key'])) {
$cur_version = (empty($settings['mailerlite']['version']) ? 0 : $settings['mailerlite']['version']);
if ($cur_version < MailerLite::VERSION) {
return true;
}
}
return false;
}
/** Upgrade MailerLite fields */
public function upgrade_MailerLiteVersion()
{
$mailerlite = ServiceContainer::getService(MailerLite::class);
$upgrade = $mailerlite->upgradeCustomFields();
if (isset($mailerlite->upgrade_message)) {
print_r($mailerlite->upgrade_message);
}
if ($upgrade) {
$this->upgradeOK();
}
}
}