tenzing-compaign-monitor.php 13.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
<?php
/*
Plugin Name: Tenzing Campaign Monitor
Plugin URI: http://gotenzing.com/wordpress-plugins/tenzing-campaign-monitor
Description: For campaign monitor
Version: 1.0
Author: Tenzing Communications Inc.
License: GPLv2
*/




require_once plugin_dir_path(__FILE__) . 'vendor/autoload.php';
require_once plugin_dir_path(__FILE__) . 'class/class-campaign-handler.php';
require_once plugin_dir_path(__FILE__) . 'class/class-campaign-item.php';

register_activation_hook(__FILE__, 'tz_campaign_monitor_install');
register_deactivation_hook(__FILE__, 'tz_campaign_monitor_remove');

add_action('plugins_loaded', 'init');

function init() {
    wp_enqueue_style('tzcm_style', plugin_dir_url(__FILE__) . 'css/tzcm.css', [], false);
    wp_enqueue_script('tzcm_script', plugin_dir_url(__FILE__) . 'js/tzcm.js', [], false, true);
}

// Set up our WordPress Plugin
function tz_campaign_monitor_install()
{
    date_default_timezone_set('America/Toronto');

    $campaignItemArray = campaign_Monitor_GetData('DESC');

    /** @var campaignItemClass $campaignItemObject */
    foreach ($campaignItemArray as $campaignItemObject) {
        $cm_post = [
            'post_title'  => $campaignItemObject->getItemURL(),
            'post_type'   => 'campaign',
            'post_status' => 'publish',
        ];

        wp_insert_post($cm_post);
    }
}

add_action(
    'init',
    function () {
        register_post_type(
            'campaign',
            [
                'labels'              => [
                    'name'              => __('campaign'),
                    'singular_name'     => __('campaign'),
                    'parent_item_colon' => ''
                ],
                'public'              => true,
                'publicly_queryable'  => true,
                'query_var'           => false,
                'exclude_from_search' => false,
                'show_ui'             => false,
                //'menu_position' => 23,
                'supports'            => [
                    'title'
                ],
                //'taxonomies' => array('post_tag'),
                'show_in_nav_menus'   => false,
                'rewrite'             => [
                    'pages'     => false,
                    'slug'      => 'app/wp-content/plugins/tenzing-campaign-monitor/campaignRetriever.php?campaignURL=http://eblast.gotenzing.com/t/ViewEmailArchive/r',
                    'with_frot' => false
                ],
                'hierarchical'        => true,
                'capability_type'     => 'post',
                'has_archive'         => true
            ]
        );

    }
);

function tz_campaign_monitor_remove()
{
    // Delete transient
    delete_transient('cm_' . get_option('cm_client_id'));

    //delete wp_options
    delete_option('cm_client_id');
    delete_option('cm_api_key');

    //delete all cm posts
    $args    = [
        'post_type'      => 'campaign', /* Change with your custom post type name */
        'posts_per_page' => -1,
    ];
    $results = get_posts($args);
    foreach ($results as $post) : setup_postdata($post);
        wp_delete_post($post->ID, true);
    endforeach;
    wp_reset_postdata();
}


if (is_admin()) {
    add_action('admin_menu', 'display_cm_menu');
}

function display_cm_menu()
{
    add_submenu_page(
        'options-general.php',
        'Set Campaign Monitor',
        'Campaign Monitor Menu',
        'manage_options',
        'display_cm',
        'display_cm_html_page'
    );
}

add_action('admin_post_cm_actid_save_hook', 'process_cm_options');

function process_cm_options()
{
    if (!current_user_can('manage_options')) {
        wp_die('You are not allowed to be on this page.');
    }
    // Check that nonce field
    check_admin_referer('cm_actid_verify');

    if (isset($_POST['cm_client_id']) && isset($_POST['cm_api_key'])) {
        if (!empty($_POST['cm_client_id']) && !empty($_POST['cm_api_key'])) {
            update_option('cm_client_id', $_POST['cm_client_id']);
            update_option('cm_api_key', $_POST['cm_api_key']);

//            campaign_Monitor_LoadData();
            wp_redirect(admin_url('options-general.php?page=display_cm&m=1'));
            exit;
        } else {
            wp_redirect(admin_url('options-general.php?page=display_cm&m=2'));
            exit;
        }
    }
}

function display_cm_html_page()
{
    if (isset($_GET['m'])) {
        switch ($_GET['m']) {
            case '1':
                echo '<div id="message" class="updated fade"><p><strong style="font-size:15px;">You have successfully updated your Campaign Monitor Client ID & API Key.</strong></p></div>';
                break;
            case '2':
                echo '<div id="message" class="error fade"><p><strong style="font-size:15px;">You must enter your Campaign Monitor Client ID & API Key.</strong></p></div>';
                break;
        }
    }
    ?>
    <div class="wrap">
        <h2>Set Campaign Monitor Client ID & API Key</h2>
        <form method="post" action="admin-post.php">
            <input type="hidden" name="action" value="cm_actid_save_hook" />
            <?php wp_nonce_field('cm_actid_verify'); ?>
            <p>
                <label for="cm_client_id">Campaign Monitor Client ID: </label>
                <input type="text" name="cm_client_id" id="cm_client_id"
                       value="<?php echo get_option('cm_client_id'); ?>"
                       style="width:500px" />
            </p>
            <p>
                <label for="cm_api_key">Campaign Monitor API Key: </label>
                <input type="text" name="cm_api_key" id="cm_api_key" value="<?php echo get_option('cm_api_key'); ?>" style="width:500px" />
            </p>
            <p>
                <?php

                $campaignItemArray = campaign_Monitor_GetData('DESC');
                $campaignHandler = new campaignHandlerClass($campaignItemArray);
                $yearArray = $campaignHandler->getCampaignYears();
                // getCampaignYears not working
                $yearArray = array('2018','2019','2020','2021', '2022');
                echo 'Please click a year to sync: ';
                foreach($yearArray as $year) : ?>
                    <?php
                        $syncTime = get_option('tcm_sync_time_' . $year);
                        $syncTime = $syncTime == false ? 'N/A' : date('Y-m-d G:i', $syncTime);
                    ?>
                    <br>
                    <button type="button" class="year-sync" data-value="<?php echo $year;?>">
                        <img src="/wp-admin/images/wpspin_light.gif" alt="loader icon" class="ajax-loader" style="display: none;"/>
                        <?php echo $year;?><br>Last sync: <span class="sync-time"><?php echo $syncTime;?></span>
                    </button>
                    <br>
                <?php endforeach;?>
            </p>
            <p>
                <input type="submit" value="Save" class="button-primary" />
            </p>
        </form>
    </div>
    <?php
}

if (!wp_next_scheduled('wpjam_daily_function_hook')) {
    wp_schedule_event(time(), 'daily', 'wpjam_daily_function_hook');
}

add_action('wpjam_daily_function_hook', 'campaign_Monitor_LoadData');

add_action('wp_ajax_load_campaign_data', 'campaign_Monitor_LoadData');

function campaign_Monitor_LoadData()
{
    $action = $_POST['action'];
    $year = $_POST['year'];

    if(empty($year)) {
        $year = date('Y');
    }

    // Check if there is cached data
    $clientID = get_option('cm_client_id');
    $apiKey   = get_option('cm_api_key');

    if ($clientID !== false && $apiKey !== false) {
        $auth   = array('api_key' => $apiKey);
        $wrap   = new CS_REST_Clients(
            $clientID,
            $auth
        );
        $result = $wrap->get_campaigns();
        if ($result->was_successful()) {
            set_transient('cm_' . $clientID, serialize($result->response), DAY_IN_SECONDS);
        } else {
            echo 'Failed with code '.$result->http_status_code."\n<br /><pre>";
            var_dump($result->response);
            echo '</pre>';
        }

        //delete all cm posts

        if(get_option('tcm_clean_up')) {
            $args    = [
                'post_type'      => 'campaign', /* Change with your custom post type name */
                'posts_per_page' => -1,
                'meta_query' => array(
                    array(
                        'key' => 'sent_year',
                        'value' => $year
                    )
                )
            ];
        } else {
            $args    = [
                'post_type'      => 'campaign', /* Change with your custom post type name */
                'posts_per_page' => -1
            ];

            update_option('tcm_clean_up', true);
        }

        $results = get_posts($args);
        foreach ($results as $post) : setup_postdata($post);
            wp_delete_post($post->ID, true);
        endforeach;
        wp_reset_postdata();

        $campaignItemArray = campaign_Monitor_GetData('DESC');
        /** @var campaignItemClass $campaignItemObject */
        foreach ($campaignItemArray as $campaignItemObject) {
            $itemYear = (int)date("Y", strtotime($campaignItemObject->getItemDate()));
            if($itemYear == $year) {
                $dom = new DOMDocument;
                // We don't want to bother with white spaces
                $dom->preserveWhiteSpace = false;

                // Most HTML Developers are chimps and produce invalid markup...
                $dom->strictErrorChecking = false;
                $dom->recover = true;

                libxml_use_internal_errors(true);  //hides errors from invalid tags
                $dom->loadHTMLFile($campaignItemObject->getItemTextURL());

                $DOMxpath = new DOMXPath($dom);
                $DivContent = $DOMxpath->query("//div");
                $postContent = $DivContent->item(0)->textContent;
                $cm_post = [
                    'post_title'  => $campaignItemObject->getItemName(),
                    'post_type'   => 'campaign',
                    'post_status' => 'publish',
                    'post_content' => utf8_decode($postContent),
                    'meta_input' => array(
                        'sent_year' => $year,
                        'item_url' => $campaignItemObject->getItemURL()
                    )
                ];

                wp_insert_post($cm_post);
            }
        }

        update_option('tcm_sync_time_' . $year, time());

        wp_send_json_success(['sync_time'=>time()]);
    }
}
function getUrlContent($url){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    $data = curl_exec($ch);
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    return ($httpcode>=200 && $httpcode<300) ? $data : false;
}


function campaign_Monitor_GetData($order)
{
    $clientID          = get_option('cm_client_id');
    $apiKey            = get_option('cm_api_key');
    $cachedResult      = get_transient('cm_' . $clientID);
    $campaignItemArray = [];  //no file found, return a empty array

    if ($cachedResult) {
        $cachedResultArray = is_serialized($cachedResult) ? unserialize($cachedResult) : $cachedResult;

        foreach($cachedResultArray as $campaignItem) {
            $campaignItemObject = new campaignItemClass($campaignItem);
            array_push($campaignItemArray, $campaignItemObject);
        }

        if ($order == 'DESC') {
            usort($campaignItemArray, 'descDate');
        } else {
            if ($order == 'ASC') {
                usort($campaignItemArray, 'ascDate');
            }
        }
        return $campaignItemArray;
    } else {
        return $campaignItemArray;
    }

}


function descDate($a, $b)
{
    return -(strtotime($a->getItemDate()) - strtotime($b->getItemDate()));
}


function ascDate($a, $b)
{
    return strtotime($a->getItemDate()) - strtotime($b->getItemDate());
}


function campaign_Monitor_CreateHTML($atts)
{

    $atts
        = shortcode_atts(
        [
            'newsletter_name'  => '',
            'orderby'          => 'date',
            'order'            => 'DESC',
            'number_posts'     => -1,
            'template'         => 'table',
            'is_pop_up_window' => 'false',
        ],
        $atts
    );

    if (preg_replace("/\s| /", "", $atts['newsletter_name']) != '') {
        $newsletter_name = is_string($atts['newsletter_name']) ? array_map(
            'trim',
            explode(',', strtolower($atts['newsletter_name']))
        )
            : $atts['newsletter_name'];
    } else {
        $newsletter_name = '';
    }

    $orderBy          = $atts['orderby'];
    $order            = $atts['order'];
    $number_posts     = $atts['number_posts'];
    $template         = $atts['template'];
    $is_pop_up_window = $atts['is_pop_up_window'];

    $output = "";

    $campaignItemArray = campaign_Monitor_GetData($order);
    if (count($campaignItemArray) > 0) {
        $campaignHandlerObject = new campaignHandlerClass($campaignItemArray);
        $output .= ($newsletter_name == '') ? $campaignHandlerObject->displayAllItem($number_posts, $is_pop_up_window)
            : $campaignHandlerObject->displayMatchItems($newsletter_name, $number_posts, $is_pop_up_window);
    } else {
        campaign_Monitor_LoadData();
        wp_redirect('../broker-landing-page/circulars/');
        exit;
        $output .= '<h2>No Newsletters found under this client.</h2>';
    }

    return $output;

}

add_shortcode('campaign_monitor', 'campaign_Monitor_CreateHTML');

?>