init();
}
public function init()
{
add_action('init', array($this, 'wpInit'), 9999999999);
add_action('init', array($this, 'postTypeInit'), 9999);
add_action('init', array($this, 'updatesInit'), 9999);
add_action('admin_menu', array($this, 'addSubMenu'));
add_action('admin_menu', array($this, 'supportLinks'), 999);
add_action('admin_head', array($this, 'showPreviewButtonAfterPopupPublish'));
add_action('admin_head', array($this, 'custom_admin_js'));
add_action('admin_enqueue_scripts', array($this, 'adminLoadPopups'));
add_action('admin_action_popupSaveAsNew', array($this, 'popupSaveAsNew'));
add_action('admin_post_csv_file', array($this, 'getSubscribersCsvFile'));
add_action('admin_post_sgpb_system_info', array($this, 'getSystemInfoFile'));
add_action('admin_post_sgpbSaveSettings', array($this, 'saveSettings'), 10, 1);
add_action('admin_init', array($this, 'userRolesCaps'));
add_action('admin_notices', array($this, 'pluginNotices'));
add_action('admin_init', array($this, 'pluginLoaded'));
add_action('transition_post_status', array($this, 'deletePopup'), 100, 3);
// activate extensions
add_action('wp_before_admin_bar_render', array($this, 'pluginActivated'), 10, 2);
add_action('admin_head', array($this, 'hidePageBuilderEditButtons'));
add_action('admin_head', array($this, 'hidePublishingActions'));
add_action('add_meta_boxes', array($this, 'popupMetaboxes'), 100);
add_filter('post_updated_messages', array($this, 'popupPublishedMessage'), 1, 1);
add_action('before_delete_post', array($this, 'deleteSubscribersWithPopup'), 1, 1);
add_action('sgpb_duplicate_post', array($this, 'popupCopyPostMetaInfo'), 10, 2);
add_filter('get_sample_permalink_html', array($this, 'removePostPermalink'), 1, 1);
add_action('manage_'.SG_POPUP_POST_TYPE.'_posts_custom_column' , array($this, 'popupsTableColumnsValues'), 10, 2);
add_action('media_buttons', array($this, 'popupMediaButton'));
add_filter('mce_external_plugins', array($this, 'editorButton'), 1, 1);
add_action('admin_enqueue_scripts', array('sgpb\Style', 'enqueueStyles'));
add_action('admin_enqueue_scripts', array('sgpb\Javascript', 'enqueueScripts'));
// this action for popup options saving and popup builder classes save ex from post and page
add_action('save_post', array($this, 'savePost'), 100, 3);
add_action('wp_enqueue_scripts', array($this, 'enqueuePopupBuilderScripts'));
add_filter('sgpbOtherConditions', array($this ,'conditionsSatisfy'), 11, 1);
add_shortcode('sg_popup', array($this, 'popupShortcode'));
add_filter('cron_schedules', array($this, 'cronAddMinutes'), 10, 1);
add_action('sgpb_send_newsletter', array($this, 'newsletterSendEmail'), 10, 1);
add_action('sgpbGetBannerContentOnce', array($this, 'getBannerContent'), 10, 1);
add_action('plugins_loaded', array($this, 'loadTextDomain'));
// for change admin popup list order
add_action('pre_get_posts', array($this, 'preGetPosts'));
add_action('template_redirect', array($this, 'redirectFromPopupPage'));
add_filter('views_edit-popupbuilder', array($this, 'mainActionButtons'), 10, 1);
add_action('wpml_loaded', array($this, 'wpmlRelatedActions'));
add_filter('get_user_option_screen_layout_'.SG_POPUP_POST_TYPE, array($this, 'screenLayoutSetOneColumn'));
new SGPBFeedback();
new SGPBReports();
new SGPBMenu();
new Ajax();
}
private function checkIfLicenseIsActive($license, $itemId, $storeURL, $key) {
$transient = 'sgpb-license-key-'.$key.'-requested';
if ( false !== ( $value = get_transient( $transient ) ) ) {
return;
}
$apiParams = array(
'edd_action' => 'activate_license',
'license' => $license,
'item_id' => $itemId, // The ID of the item in EDD
'url' => home_url()
);
$response = wp_remote_post($storeURL, array('timeout' => 15, 'sslverify' => false, 'body' => $apiParams));
if (!is_wp_error($response) || 200 == wp_remote_retrieve_response_code($response)) {
$licenseData = json_decode(wp_remote_retrieve_body($response));
update_option('sgpb-license-status-'.$key, $licenseData->license);
set_transient($transient, $licenseData->item_name, WEEK_IN_SECONDS);
}
}
public function updatesInit()
{
if (!class_exists('sgpb\EDD_SL_Plugin_Updater')) {
// load our custom updater if it doesn't already exist
require_once(SG_POPUP_LIBS_PATH .'EDD_SL_Plugin_Updater.php');
}
$licenses = (new License())->getLicenses();
foreach ($licenses as $license) {
$key = @$license['key'];
$storeURL = @$license['storeURL'];
$itemId = @$license['itemId'];
$filePath = @$license['file'];
$pluginMainFilePath = strpos($filePath, SG_POPUP_PLUGIN_PATH) !== 0 ? SG_POPUP_PLUGIN_PATH.$filePath : $filePath;
$licenseKey = trim(get_option('sgpb-license-key-'.$key));
$status = get_option('sgpb-license-status-'.$key);
if ($status == false || $status != 'valid') {
continue;
}
$this->checkIfLicenseIsActive($licenseKey, $itemId, $storeURL, $key);
switch($key) {
case 'POPUP_SOCIAL':
if (defined('SGPB_SOCIAL_POPUP_VERSION')) {
$version = @constant('SGPB_SOCIAL_POPUP_VERSION');
} else {
$version = @constant('SG_VERSION_'.$key);
}
break;
case 'POPUP_AGE_VERIFICATION':
if (defined('SGPB_AGE_VERIFICATION_POPUP_VERSION')) {
$version = @constant('SGPB_AGE_VERIFICATION_POPUP_VERSION');
} else{
$version = @constant('SG_VERSION_'.$key);
}
break;
case 'POPUP_GAMIFICATION':
if (defined('POPUP_GAMIFICATION')) {
$version = @constant('POPUP_GAMIFICATION');
} else {
$version = @constant('SG_VERSION_'.$key);
}
break;
default :
$version = @constant('SG_VERSION_'.$key);
break;
}
// If the version of the extension is not found, update will not possibly be shown
if(empty($version)) {
continue;
}
$sgpbUpdater = new EDD_SL_Plugin_Updater($storeURL, $pluginMainFilePath, array(
'version' => $version, // current version number
'license' => $licenseKey, // license key (used get_option above to retrieve from DB)
'item_id' => $license['itemId'], // id of this plugin
'author' => $license['autor'], // author of this plugin
'beta' => false // set to true if you wish customers to receive update notifications of beta releases
));
}
}
public function custom_admin_js()
{
$currentPostType = AdminHelper::getCurrentPostType();
if (!empty($currentPostType) && ($currentPostType == SG_POPUP_POST_TYPE || $currentPostType == SG_POPUP_AUTORESPONDER_POST_TYPE || $currentPostType == SG_POPUP_TEMPLATE_POST_TYPE)) {
?>
#save-post {
display:none !important;
}
.subsubsub {
display:none !important;
}
.subsubsub.show {
display:block !important;
}
.search-box {
display:none !important;
}
.search-box.show {
display:block !important;
}
.tablenav-pages.no-pages {
display: block;
}
.tablenav-pages *:not(.subsubsub, .subsubsub *),
.tablenav-pages.no-pages *:not(.subsubsub, .subsubsub *),
.tablenav-pages.one-page *:not(.subsubsub, .subsubsub *) {
display: none;
}
';
}
}
public function inactiveExtensionNotice()
{
$screen = '';
$dontShowLicenseBanner = get_option('sgpb-hide-license-notice-banner');
if ($dontShowLicenseBanner) {
return $screen;
}
$inactive = AdminHelper::getOption('SGPB_INACTIVE_EXTENSIONS');
$hasInactiveExtensions = AdminHelper::hasInactiveExtensions();
if (!$inactive) {
AdminHelper::updateOption('SGPB_INACTIVE_EXTENSIONS', 1);
if ($hasInactiveExtensions) {
AdminHelper::updateOption('SGPB_INACTIVE_EXTENSIONS', 'inactive');
$inactive = 'inactive';
}
}
$licenseSectionUrl = menu_page_url(SGPB_POPUP_LICENSE, false);
$partOfContent = '
'.__('Follow the link to finalize the activation.', SG_POPUP_TEXT_DOMAIN);
if (function_exists('get_current_screen')) {
$screen = get_current_screen();
$screenId = $screen->id;
if ($screenId == SGPB_POPUP_LICENSE_SCREEN) {
$partOfContent = '';
}
}
if ($hasInactiveExtensions && $inactive == 'inactive') {
$content = '';
ob_start();
?>
#misc-publishing-actions .edit-post-status,
#misc-publishing-actions .edit-timestamp,
#misc-publishing-actions .edit-visibility {
display:none !important;
}
';
}
public function hidePageBuilderEditButtons($postId = 0, $post = array())
{
$currentPostType = AdminHelper::getCurrentPostType();
if (empty($currentPostType) || $currentPostType != SG_POPUP_POST_TYPE) {
return false;
}
$excludedPopupTypesFromPageBuildersFunctionality = array(
'image'
);
$excludedPopupTypesFromPageBuildersFunctionality = apply_filters('sgpbHidePageBuilderEditButtons', $excludedPopupTypesFromPageBuildersFunctionality);
$popupType = AdminHelper::getCurrentPopupType();
if (in_array($popupType, $excludedPopupTypesFromPageBuildersFunctionality)) {
echo '';
}
}
public function getBannerContent()
{
// right metabox banner content
$metaboxBannerContent = AdminHelper::getFileFromURL(SGPB_METABOX_BANNER_CRON_TEXT_URL);
update_option('sgpb-metabox-banner-remote-get', $metaboxBannerContent);
return true;
}
public function wpInit()
{
}
public function mainActionButtons($views)
{
require_once(SG_POPUP_VIEWS_PATH.'mainActionButtons.php');
return $views;
}
/**
* Loads the plugin language files
*/
public function loadTextDomain()
{
$popupBuilderLangDir = SG_POPUP_BUILDER_PATH.'/languages/';
$popupBuilderLangDir = apply_filters('popupBuilderLanguagesDirectory', $popupBuilderLangDir);
$locale = apply_filters('sgpbPluginLocale', get_locale(), SG_POPUP_TEXT_DOMAIN);
$mofile = sprintf('%1$s-%2$s.mo', SG_POPUP_TEXT_DOMAIN, $locale);
$mofileLocal = $popupBuilderLangDir.$mofile;
if (file_exists($mofileLocal)) {
// Look in local /wp-content/plugins/popup-builder/languages/ folder
load_textdomain(SG_POPUP_TEXT_DOMAIN, $mofileLocal);
}
else {
// Load the default language files
load_plugin_textdomain(SG_POPUP_TEXT_DOMAIN, false, $popupBuilderLangDir);
}
}
public function redirectFromPopupPage()
{
global $post;
$currentPostType = '';
if (is_object($post)) {
$currentPostType = @$post->post_type;
}
// in some themes global $post returns null
if (empty($currentPostType)) {
global $post_type;
$currentPostType = $post_type;
}
// for editing popup content via page builders on backend
if (!isset($_GET) || empty($_GET)) {
if (!is_admin() && SG_POPUP_POST_TYPE == $currentPostType && !is_preview()) {
// it's for seo optimization
status_header(301);
$homeURL = home_url();
wp_redirect($homeURL);
exit();
}
}
}
public function preGetPosts($query)
{
if (!is_admin() || !isset($_GET['post_type']) || $_GET['post_type'] != SG_POPUP_POST_TYPE) {
return false;
}
// change default order by id and desc
if (!isset($_GET['orderby'])) {
$query->set('orderby', 'ID');
$query->set('order', 'desc');
}
$query = apply_filters('sgpbPreGetPosts', $query);
return true;
}
public function pluginNotices()
{
if (function_exists('get_current_screen')) {
$screen = get_current_screen();
$screenId = $screen->id;
if ($screenId == 'edit-popupbuilder') {
$notificationsObj = new SGPBNotificationCenter();
echo $notificationsObj->displayNotifications();
}
}
$extensions = AdminHelper::getAllActiveExtensions();
$updated = get_option('sgpb_extensions_updated');
$content = '';
// if popup builder has the old version
if (!get_option('SG_POPUP_VERSION')) {
return $content;
}
$alertProblem = get_option('sgpb_alert_problems');
// for old users show alert about problems
if (!$alertProblem) {
echo AdminHelper::renderAlertProblem();
}
// Don't show the banner if there's not any extension of Popup Builder or if the user has clicked "don't show"
if (empty($extensions) || $updated) {
return $content;
}
ob_start();
?>
registerImporter();
$versionPopup = get_option('SG_POPUP_VERSION');
$convert = get_option('sgpbConvertToNewVersion');
$unsubscribeColumnFixed = get_option('sgpbUnsubscribeColumnFixed');
AdminHelper::makeRegisteredPluginsStaticPathsToDynamic();
if (!$unsubscribeColumnFixed) {
AdminHelper::addUnsubscribeColumn();
update_option('sgpbUnsubscribeColumnFixed', 1);
delete_option('sgpbUnsubscribeColumn');
}
if ($versionPopup && !$convert) {
update_option('sgpbConvertToNewVersion', 1);
ConvertToNewVersion::convert();
Installer::registerPlugin();
}
}
public function popupMediaButton()
{
if (!$this->mediaButton) {
$this->mediaButton = true;
self::enqueueScriptsForPageBuilders();
if (function_exists('get_current_screen')) {
$screen = get_current_screen();
if (!empty($screen)) {
echo new MediaButton();
}
}
}
}
public function editorButton($plugins)
{
if (empty($this->mediaButton)) {
$this->mediaButton = true;
add_action('admin_footer', function() {
self::enqueueScriptsForPageBuilders();
echo new MediaButton(false);
});
}
return $plugins;
}
public static function enqueueScriptsForPageBuilders()
{
require_once(ABSPATH.'wp-admin/includes/screen.php');
global $post;
if (function_exists('get_current_screen')) {
$screen = get_current_screen();
if ((!empty($screen->id) && $screen->id == SG_POPUP_POST_TYPE) || !empty($post)) {
if (!isset($_GET['fl_builder'])) {
Javascript::enqueueScripts('post-new.php');
Style::enqueueStyles('post-new.php');
}
}
}
else if (isset($_GET['fl_builder'])) {
Javascript::enqueueScripts('post-new.php');
Style::enqueueStyles('post-new.php');
}
}
public function userRolesCaps()
{
$userSavedRoles = get_option('sgpb-user-roles');
if (!$userSavedRoles) {
$userSavedRoles = array('administrator');
}
else {
array_push($userSavedRoles, 'administrator');
}
foreach ($userSavedRoles as $theRole) {
$role = get_role($theRole);
if (empty($role)) {
continue;
}
$role->add_cap('read');
$role->add_cap('read_post');
$role->add_cap('read_private_sgpb_popups');
$role->add_cap('edit_sgpb_popup');
$role->add_cap('edit_sgpb_popups');
$role->add_cap('edit_others_sgpb_popups');
$role->add_cap('edit_published_sgpb_popups');
$role->add_cap('publish_sgpb_popups');
$role->add_cap('delete_sgpb_popups');
$role->add_cap('delete_published_posts');
$role->add_cap('delete_others_sgpb_popups');
$role->add_cap('delete_private_sgpb_popups');
$role->add_cap('delete_private_sgpb_popup');
$role->add_cap('delete_published_sgpb_popups');
// For popup builder sub-menus and terms
$role->add_cap('sgpb_manage_options');
$role->add_cap('manage_popup_terms');
$role->add_cap('manage_popup_categories_terms');
$role = apply_filters('sgpbUserRoleCap', $role);
}
return true;
}
public function pluginActivated()
{
if (!get_option('sgpbActivateExtensions') && SGPB_POPUP_PKG != SGPB_POPUP_PKG_FREE) {
$obj = new PopupExtensionActivator();
$obj->activate();
update_option('sgpbActivateExtensions', 1);
}
}
public function popupShortcode($args, $content)
{
if (empty($args) || empty($args['id'])) {
return $content;
}
$oldShortcode = isset($args['event']) && $args['event'] === 'onload';
$isInherit = isset($args['event']) && $args['event'] == 'inherit';
$event = '';
$shortcodeContent = '';
$argsId = $popupId = (int)$args['id'];
// for old popups
if (function_exists('sgpb\sgpGetCorrectPopupId')) {
$popupId = sgpGetCorrectPopupId($popupId);
}
$popup = SGPopup::find($popupId);
$popup = apply_filters('sgpbShortCodePopupObj', $popup);
$event = preg_replace('/on/', '', @$args['event']);
// when popup does not exists or popup post status it's not publish ex when popup in trash
if (empty($popup) || (!is_object($popup) && $popup != 'publish')) {
return $content;
}
$isActive = $popup->isActive();
if (!$isActive) {
return $content;
}
$alreadySavedEvents = $popup->getEvents();
$loadableMode = $popup->getLoadableModes();
if (!isset($args['event']) && isset($args['insidepopup'])) {
unset($args['insidepopup']);
$event = 'insideclick';
$insideShortcodeKey = $popupId.$event;
// for prevent infinity chain
if (is_array($this->insideShortcodes) && in_array($insideShortcodeKey, $this->insideShortcodes)) {
$shortcodeContent = SGPopup::renderPopupContentShortcode($content, $argsId, $event, $args);
return $shortcodeContent;
}
$this->insideShortcodes[] = $insideShortcodeKey;
}
// if no event attribute is set, or old shortcode
if (!isset($args['event']) || $oldShortcode || $isInherit) {
$loadableMode = $popup->getLoadableModes();
if (!empty($content)) {
$alreadySavedEvents = false;
}
// for old popup, after the update, there aren't any events
if (empty($alreadySavedEvents)) {
$event = '';
if (!empty($content)) {
$event = 'click';
}
if (!empty($args['event'])) {
$event = $args['event'];
}
$event = preg_replace('/on/', '', $event);
$popup->setEvents(array($event));
}
if (empty($loadableMode)) {
$loadableMode = array();
}
$loadableMode['option_event'] = true;
}
else {
$event = $args['event'];
$event = preg_replace('/on/', '', $event);
$popup->setEvents(array($event));
}
$popup->setLoadableModes($loadableMode);
$scriptsLoader = new ScriptsLoader();
$loadablePopups = array($popup);
$groupObj = new PopupGroupFilter();
$groupObj->setPopups(array($popup));
$loadablePopups = $groupObj->filter();
$scriptsLoader->setLoadablePopups($loadablePopups);
$scriptsLoader->loadToFooter();
if (!empty($content)) {
$matches = SGPopup::getPopupShortcodeMatchesFromContent($content);
if (!empty($matches)) {
foreach ($matches[0] as $key => $value) {
$attrs = shortcode_parse_atts($matches[3][$key]);
if (empty($attrs['id'])) {
continue;
}
$shortcodeContent = SGPopup::renderPopupContentShortcode($content, $attrs['id'], $attrs['event'], $attrs);
break;
}
}
}
if (isset($event) && $event != 'onload' && !empty($content)) {
$shortcodeContent = SGPopup::renderPopupContentShortcode($content, $argsId, $event, $args);
}
$shortcodeContent = apply_filters('sgpbPopupShortCodeContent', $shortcodeContent);
return do_shortcode($shortcodeContent);
}
public function deleteSubscribersWithPopup($postId)
{
global $post_type;
if ($post_type == SG_POPUP_POST_TYPE) {
AdminHelper::deleteSubscriptionPopupSubscribers($postId);
}
}
public function cronAddMinutes($schedules)
{
$schedules['sgpb_newsletter_send_every_minute'] = array(
'interval' => SGPB_CRON_REPEAT_INTERVAL * 60,
'display' => __('Once Every Minute', SG_POPUP_TEXT_DOMAIN)
);
$schedules['sgpb_banners'] = array(
'interval' => SGPB_TRANSIENT_TIMEOUT_WEEK,
'display' => __('Once Every Week', SG_POPUP_TEXT_DOMAIN)
);
$schedules = apply_filters('sgpbCronTimeoutSettings', $schedules);
return $schedules;
}
public function newsletterSendEmail()
{
global $wpdb;
$newsletterOptions = get_option('SGPB_NEWSLETTER_DATA');
if (empty($newsletterOptions)) {
wp_clear_scheduled_hook('sgpb_send_newsletter');
}
$subscriptionFormId = (int)$newsletterOptions['subscriptionFormId'];
$subscriptionFormTitle = get_the_title($subscriptionFormId);
$emailsInFlow = (int)$newsletterOptions['emailsInFlow'];
$mailSubject = $newsletterOptions['newsletterSubject'];
$fromEmail = $newsletterOptions['fromEmail'];
$emailMessage = $newsletterOptions['messageBody'];
$allAvailableShortcodes = array();
$allAvailableShortcodes['patternFirstName'] = '/\[First name]/';
$allAvailableShortcodes['patternLastName'] = '/\[Last name]/';
$allAvailableShortcodes['patternBlogName'] = '/\[Blog name]/';
$allAvailableShortcodes['patternUserName'] = '/\[User name]/';
$allAvailableShortcodes['patternUnsubscribe'] = '';
$pattern = "/\[(\[?)(Unsubscribe)(?![\w-])([^\]\/]*(?:\/(?!\])[^\]\/]*)*?)(?:(\/)\]|\](?:([^\[]\*+(?:\[(?!\/\2\])[^\[]\*+)\*+)\[\/\2\])?)(\]?)/";
preg_match($pattern, $emailMessage, $matches);
$title = __('Unsubscribe', SG_POPUP_TEXT_DOMAIN);
if ($matches) {
$patternUnsubscribe = $matches[0];
// If user didn't change anything inside the [unsubscribe] shortcode $matches[2] will be equal to 'Unsubscribe'
if ($matches[2] == 'Unsubscribe') {
$pattern = '/\s(\w+?)="(.+?)"]/';
preg_match($pattern, $matches[0], $matchesTitle);
if (!empty($matchesTitle[2])) {
$title = AdminHelper::removeAllNonPrintableCharacters($matchesTitle[2], 'Unsubscribe');
}
}
$allAvailableShortcodes['patternUnsubscribe'] = $patternUnsubscribe;
}
// When email is not valid we don't continue
if (!preg_match('/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$/', $fromEmail)) {
wp_clear_scheduled_hook('sgpb_send_newsletter');
return false;
}
$selectionQuery = 'SELECT id FROM '.$wpdb->prefix.SGPB_SUBSCRIBERS_TABLE_NAME.' WHERE';
$selectionQuery = apply_filters('sgpbUserSelectionQuery', $selectionQuery);
$sql = $wpdb->prepare($selectionQuery .' and subscriptionType = %d limit 1', $subscriptionFormId);
$result = $wpdb->get_row($sql, ARRAY_A);
$currentStateEmailId = (int)$result['id'];
$getTotalSql = $wpdb->prepare('SELECT count(*) FROM '.$wpdb->prefix.SGPB_SUBSCRIBERS_TABLE_NAME.' WHERE unsubscribed = 0 and subscriptionType = %d', $subscriptionFormId);
$totalSubscribers = $wpdb->get_var($getTotalSql);
// $currentStateEmailId == 0 when all emails status = 1
if ($currentStateEmailId == 0) {
// Clear schedule hook
$headers = 'MIME-Version: 1.0'."\r\n";
$headers .= 'Content-type: text/html; charset=UTF-8'."\r\n";
$successTotal = get_option('SGPB_NEWSLETTER_'.$subscriptionFormId);
if (!$successTotal) {
$successTotal = 0;
}
$failedTotal = $totalSubscribers - $successTotal;
$emailMessageCustom = __('Your mail list %s delivered successfully!
%d of the %d emails succeeded, %d failed.
For more details, please download log file inside the plugin.
This email was generated via Popup Builder plugin.', SG_POPUP_TEXT_DOMAIN);
$emailMessageCustom = sprintf($emailMessageCustom, $subscriptionFormTitle, $successTotal, $totalSubscribers, $failedTotal);
wp_mail($fromEmail, $subscriptionFormTitle.' list has been successfully delivered!', $emailMessageCustom, $headers);
delete_option('SGPB_NEWSLETTER_'.$subscriptionFormId);
wp_clear_scheduled_hook('sgpb_send_newsletter');
return;
}
$getAllDataSql = 'SELECT id, firstName, lastName, email FROM '.$wpdb->prefix.SGPB_SUBSCRIBERS_TABLE_NAME.' WHERE';
$getAllDataSql = apply_filters('sgpbUserSelectionQuery', $getAllDataSql);
$getAllDataSql = $wpdb->prepare($getAllDataSql .' and id >= %d and subscriptionType = %s limit %d', $currentStateEmailId, $subscriptionFormId, $emailsInFlow);
$subscribers = $wpdb->get_results($getAllDataSql, ARRAY_A);
$subscribers = apply_filters('sgpNewsletterSendingSubscribers', $subscribers);
$blogInfo = get_bloginfo();
$headers = array(
'From: "'.$blogInfo.'" <'.$fromEmail.'>' ,
'MIME-Version: 1.0' ,
'Content-type: text/html; charset=UTF-8'
);
foreach ($subscribers as $subscriber) {
$replacementId = $subscriber['id'];
$allAvailableShortcodes = apply_filters('sgpbNewsletterShortcodes', $allAvailableShortcodes, $subscriptionFormId, $replacementId);
$replacementFirstName = $subscriber['firstName'];
$replacementLastName = $subscriber['lastName'];
$replacementBlogName = $newsletterOptions['blogname'];
$replacementUserName = $newsletterOptions['username'];
$replacementEmail = $subscriber['email'];
$replacementUnsubscribe = get_home_url();
$replacementUnsubscribe .= '?sgpbUnsubscribe='.md5($replacementId.$replacementEmail);
$replacementUnsubscribe .= '&email='.$subscriber['email'];
$replacementUnsubscribe .= '&popup='.$subscriptionFormId;
$replacementUnsubscribe = ' '.$title.'';
// Replace First name and Last name from email message
$emailMessageCustom = preg_replace($allAvailableShortcodes['patternFirstName'], $replacementFirstName, $emailMessage);
$emailMessageCustom = preg_replace($allAvailableShortcodes['patternLastName'], $replacementLastName, $emailMessageCustom);
$emailMessageCustom = preg_replace($allAvailableShortcodes['patternBlogName'], $replacementBlogName, $emailMessageCustom);
$emailMessageCustom = preg_replace($allAvailableShortcodes['patternUserName'], $replacementUserName, $emailMessageCustom);
$emailMessageCustom = str_replace($allAvailableShortcodes['patternUnsubscribe'], $replacementUnsubscribe, $emailMessageCustom);
if (!empty($allAvailableShortcodes['extraShortcodesWithValues'])) {
$customFields = $allAvailableShortcodes['extraShortcodesWithValues'];
foreach ($customFields as $customFieldKey => $customFieldValue) {
$finalShortcode = '/\['.$customFieldKey.']/';
$emailMessageCustom = preg_replace($finalShortcode, $customFieldValue, $emailMessageCustom);
}
}
$emailMessageCustom = stripslashes($emailMessageCustom);
$emailMessageCustom = apply_filters('sgpNewsletterSendingMessage', $emailMessageCustom);
$mailStatus = wp_mail($subscriber['email'], $mailSubject, $emailMessageCustom, $headers);
if (!$mailStatus) {
$errorLogSql = $wpdb->prepare('INSERT INTO '. $wpdb->prefix .SGPB_SUBSCRIBERS_ERROR_TABLE_NAME.' (`popupType`, `email`, `date`) VALUES (%s, %s, %s)', $subscriptionFormId, $subscriber['email'], date('Y-m-d H:i'));
$wpdb->query($errorLogSql);
continue;
}
$successCount = get_option('SGPB_NEWSLETTER_'.$subscriptionFormId);
if (!$successCount) {
update_option('SGPB_NEWSLETTER_'.$subscriptionFormId, 1);
}
else {
update_option('SGPB_NEWSLETTER_'.$subscriptionFormId, ++$successCount);
}
}
// Update the status of all the sent mails
$updateStatusQuery = $wpdb->prepare('UPDATE '.$wpdb->prefix.SGPB_SUBSCRIBERS_TABLE_NAME.' SET status = 1 where id >= %d and subscriptionType = %d limit %d', $currentStateEmailId, $subscriptionFormId, $emailsInFlow);
$wpdb->query($updateStatusQuery);
}
private function unsubscribe($params = array())
{
AdminHelper::deleteUserFromSubscribers($params);
}
public function enqueuePopupBuilderScripts()
{
// for old popups
if (get_option('SG_POPUP_VERSION')) {
ConvertToNewVersion::saveCustomInserted();
}
$popupLoaderObj = PopupLoader::instance();
if (is_object($popupLoaderObj)) {
$popupLoaderObj->loadPopups();
}
}
public function adminLoadPopups($hook)
{
$allowedPages = array();
$allowedPages = apply_filters('sgpbAdminLoadedPages', $allowedPages);
if (!empty($allowedPages) && is_array($allowedPages) && in_array($hook, $allowedPages)) {
$scriptsLoader = new ScriptsLoader();
$scriptsLoader->setIsAdmin(true);
$scriptsLoader->loadToFooter();
}
}
public function postTypeInit()
{
if (isset($_POST['sgpb-is-preview']) && $_POST['sgpb-is-preview'] == 1) {
$postId = $_POST['post_ID'];
$post = get_post($postId);
$this->savePost($postId, $post, false);
}
$adminUrl = admin_url();
if (isset($_GET['page']) && $_GET['page'] == 'PopupBuilder') {
_e('Popup Builder plugin has been successfully updated. Please click here to go to the new Dashboard of the plugin.', SG_POPUP_TEXT_DOMAIN);
wp_die();
}
$unsubscribeArgs = $this->collectUnsubscriberArgs();
if (!empty($unsubscribeArgs)) {
$this->unsubscribe($unsubscribeArgs);
}
AdminHelper::removeUnnecessaryCodeFromPopups();
$this->customPostTypeObj = new RegisterPostType();
}
public function collectUnsubscriberArgs()
{
if (!isset($_GET['sgpbUnsubscribe'])) {
return false;
}
$args = array();
if (isset($_GET['sgpbUnsubscribe'])) {
$args['token'] = $_GET['sgpbUnsubscribe'];
}
if (isset($_GET['email'])) {
$args['email'] = $_GET['email'];
}
if (isset($_GET['popup'])) {
$args['popup'] = $_GET['popup'];
}
return $args;
}
public function addSubMenu()
{
// We need to check license keys and statuses before adding new menu "License" item
new Updates();
$this->customPostTypeObj->addSubMenu();
}
public function supportLinks()
{
if (SGPB_POPUP_PKG == SGPB_POPUP_PKG_FREE) {
if (method_exists($this->customPostTypeObj, 'supportLinks')) {
$this->customPostTypeObj->supportLinks();
}
}
}
public function popupMetaboxes()
{
$this->customPostTypeObj->addPopupMetaboxes();
}
public function savePost($postId = 0, $post = array(), $update = false)
{
if ($post->post_type !== SG_POPUP_POST_TYPE) {
return;
}
$allowToAction = AdminHelper::userCanAccessTo();
Functions::clearAllTransients();
$postData = SGPopup::parsePopupDataFromData($_POST);
$saveMode = '';
$postData['sgpb-post-id'] = $postId;
// If preview mode
if (isset($postData['sgpb-is-preview']) && $postData['sgpb-is-preview'] == 1) {
$saveMode = '_preview';
SgpbPopupConfig::popupTypesInit();
SgpbDataConfig::init();
// published popup
if (empty($post)) {
global $post;
$postId = $post->ID;
}
if ($post->post_status != 'draft') {
$posts = array();
$popupContent = $post->post_content;
$query = new WP_Query(
array(
'post_parent' => $postId,
'posts_per_page' => - 1,
'post_type' => 'revision',
'post_status' => 'inherit'
)
);
$query = apply_filters('sgpbSavePostQuery', $query);
while ($query->have_posts()) {
$query->the_post();
if (empty($posts)) {
$posts[] = $post;
}
}
if (!empty($posts[0])) {
$popup = $posts[0];
$popupContent = $popup->post_content;
}
}
}
if (empty($post)) {
$saveMode = '';
}
if ($post->post_status == 'draft') {
$saveMode = '_preview';
}
/* In preview mode saveMode should be true*/
if ((!empty($post) && $post->post_type == SG_POPUP_POST_TYPE) || $saveMode || (empty($post) && !$saveMode)) {
if (!$allowToAction) {
wp_redirect(get_home_url());
exit();
}
if (!empty($postData['sgpb-type'])) {
$popupType = $postData['sgpb-type'];
$popupClassName = SGPopup::getPopupClassNameFormType($popupType);
$popupClassPath = SGPopup::getPopupTypeClassPath($popupType);
require_once($popupClassPath.$popupClassName.'.php');
$popupClassName = __NAMESPACE__.'\\'.$popupClassName;
$popupClassName::create($postData, $saveMode, 1);
}
}
else {
$content = get_post_field('post_content', $postId);
SGPopup::deletePostCustomInsertedData($postId);
SGPopup::deletePostCustomInsertedEvents($postId);
/*We detect all the popups that were inserted as a custom ones, in the content.*/
SGPopup::savePopupsFromContentClasses($content, $post);
}
}
/**
* Check Popup is satisfy for popup condition
*
* @param array $args
*
* @return array
*
*@since 1.0.0
*
*/
public function conditionsSatisfy($args = array())
{
if (isset($args['status']) && $args['status'] === false) {
return $args;
}
$args['status'] = PopupChecker::checkOtherConditionsActions($args);
return $args;
}
public function popupsTableColumnsValues($column, $postId)
{
$postId = (int)$postId;// Convert to int for security reasons
global $post_type;
if ($postId) {
$args['status'] = array('publish', 'draft', 'pending', 'private', 'trash');
$popup = SGPopup::find($postId, $args);
}
if (empty($popup) && $post_type == SG_POPUP_POST_TYPE) {
return false;
}
if ($column == 'shortcode') {
echo '';
}
if ($column == 'className') {
echo '';
}
else if ($column == 'counter') {
$count = $popup->getPopupOpeningCountById($postId);
echo '