Admin.php 14.4 KB
<?php
namespace Tz\WordPress\Tools\Notifications\Settings;

use Tz\Common;
use Tz\WordPress\Tools;
use Tz\WordPress\Tools\Notifications;

const CAPABILITY                  = 'manage_notifications';
const MANAGE_SYSTEM_NOTIFICATIONS = 'create_system_notifications';
const SETTING_NS                  = 'canspam_settings';
const ADMIN_PAGE                  = 'canspam_admin';

call_user_func(
    function () {
        $role = get_role('administrator');
        $role->add_cap(CAPABILITY);
        $role->add_cap(MANAGE_SYSTEM_NOTIFICATIONS);

        Vars::$settings = new Tools\WP_Option(SETTING_NS);

        Tools\add_actions(__NAMESPACE__.'\Actions');
    }
);

function display_page()
{

    if (isset($_GET['action']) && $_GET['action'] == "edit") {
        /** @var \StdClass $entry */
        $entry = get_post($_GET['page_id']);

        $id = $entry->ID;

        $details = get_post_meta($id, 'details', true);
        $email   = get_post_meta($id, 'email', true);
        $system  = get_post_meta($id, 'system', true);

        $entry->details = $details;
        $entry->email   = $email;
        $entry->system  = $system;

        $validation = new Notifications\Validation;

        $validation->set_rules('type', 'Notification Type', 'required');
        $validation->set_rules('title', 'Description', 'trim|required|min_length[4]');
        $validation->set_rules('sendto', 'Send To', 'required');

        $type_val = ($_POST && $_POST['type'] == 'scheduled') ? 'required' : '';
        $validation->set_rules('execute_date', 'Execute Date', $type_val);

        $trigger_val = ($_POST && $_POST['type'] == 'triggered') ? 'required' : '';
        $validation->set_rules('trigger', 'Trigger', $trigger_val);

        $validation->set_rules('system_message_type', 'System Message Type', 'trim');

        foreach (['en', 'fr'] as $lang) {
            $validation->set_rules($lang.'_subject', 'Subject', 'trim');
            $validation->set_rules($lang.'_text', 'Text Version', 'trim|min_length[16]');
            $validation->set_rules($lang.'_html', 'HTML Version', 'trim|min_length[16]');
            $validation->set_rules($lang.'_system', 'System Message', 'trim|min_length[16]');
        }

        //details
        if ($validation->run() == true) {

            // Clean up data before saving
            Tools\tzClean($_POST);

            $type        = $_POST['type'];
            $title       = $_POST['title'];
            $sendto      = $_POST['sendto'];
            $executeDate = ($type == 'scheduled') ? $_POST['execute_date'] : '0000-00-00 00:00:00';
            $trigger     = ($type == 'scheduled') ? 'scheduled-cron-job' : $_POST['trigger'];

            $emailData         = [];
            $systemMessageData = [];

            foreach (['en', 'fr'] as $lang) {
                // email
                $subject     = $_POST[$lang.'_subject'];
                $text        = $_POST[$lang.'_text'];
                $html        = $_POST[$lang.'_html'];
                $attachments = [];
                $uploadDir   = wp_upload_dir()['basedir'].'/notifications/';

                fixFilesArray($_FILES[$lang.'_attachment']);

                foreach ($_FILES[$lang.'_attachment'] as $position => $file) {
                    // should output array with indices name, type, tmp_name, error, size
                    if ($file['name'] != '') {
                        move_uploaded_file($file['tmp_name'], $uploadDir.$file['name']);
                        $attachments[] = $file['name'];
                    }
                }

                // system
                $systemMessageType = $_POST['system_message_type'];
                $system            = $_POST[$lang.'_system'];

                if (count($entry->email[$lang.'_attachments']) > 0) {
                    $attachments = array_merge($entry->email[$lang.'_attachments'], $attachments);
                }

                $emailData         = array_merge(
                    $emailData,
                    [
                        $lang.'_subject'     => $subject,
                        $lang.'_text'        => $text,
                        $lang.'_html'        => $html,
                        $lang.'_attachments' => $attachments
                    ]
                );
                $systemMessageData = array_merge(
                    $systemMessageData,
                    [
                        'system_message_type' => $systemMessageType,
                        $lang.'_message'      => $system
                    ]
                );
            }

            update_post_meta(
                $id,
                'details',
                [
                    'type'         => $type,
                    'sendto'       => $sendto,
                    'status'       => $entry->details['status'],
                    'trigger'      => $trigger,
                    'execute_date' => $executeDate
                ]
            );
            update_post_meta($id, 'send_status', $entry->details['status']);
            update_post_meta($id, 'notif_type', $type);
            update_post_meta($id, 'execute_date', mysqldatetime_to_timestamp($executeDate));
            update_post_meta($id, 'trigger', $trigger);

            update_post_meta($id, 'email', $emailData);
            update_post_meta($id, 'system', $systemMessageData);

            $update               = [];
            $update['ID']         = $id;
            $update['post_title'] = $title;
            wp_update_post($update);

            $id = $entry->ID;

            $details = get_post_meta($id, 'details', true);
            $email   = get_post_meta($id, 'email', true);
            $system  = get_post_meta($id, 'system', true);

            $entry->details = $details;
            $entry->email   = $email;
            $entry->system  = $system;

            $flash = '<strong>Notification Saved Successfully!</strong><br /><a href=""/wp-admin/admin.php?page=notifications">Click here</a> to view all notifications.</a>';
            require_once(__DIR__.'/views/form.php');
        } else {
            require_once(__DIR__.'/views/form.php');
        }
    } else {
        if (isset($_GET['action']) && $_GET['action'] == 'delete') {
            wp_delete_post($_GET['page_id'], true);
        } elseif (isset($_GET['action']) && $_GET['action'] == 'archive') {
            $id = $_GET['page_id'];

            $postdata           = get_post_meta($id, 'details', true);
            $postdata['status'] = "archived";

            update_post_meta($id, 'details', $postdata);
            update_post_meta($id, 'send_status', $postdata['status']);
        }

        // get all the notifications that status != "archived";
        $notifications              = [];
        $notifications['triggered'] = [];
        $notifications['scheduled'] = [];

        $args = [
            'post_type'    => 'notifications',
            'numberposts'  => -1,
            'orderby'      => 'modified',
            'order'        => 'desc',
            'meta_key'     => 'send_status',
            'meta_compare' => '=',
            'meta_value'   => 'pending'
        ];

        $entries = get_posts($args);

        foreach ($entries as $entry) {
            $id = $entry->ID;

            $details = get_post_meta($id, 'details', true);
            $email   = get_post_meta($id, 'email', true);
            $system  = get_post_meta($id, 'system', true);

            $entry->trigger = $details['trigger'];
            $entry->status  = isset($details['status']) ? $details['status'] : 'active';
            $entry->type    = $details['type'];
            $entry->sendto  = $details['sendto'];

            $entry->is_email  = (($email['en_text'] != '' || $email['en_html'] != '')) ? true : false;
            $entry->is_system = (isset($system['en_message']) && $system['en_message'] != '') ? true : false;

            $entry->execute_date = $details['execute_date'];

            if ($entry->status != 'archived') {
                $notifications[$entry->type][] = $entry;
            }
        }

        require_once(__DIR__.'/views/admin.php');
    }
}

/**
 * @param string $datetime
 *
 * @return int
 */
function mysqldatetime_to_timestamp($datetime = '')
{
    // function is only applicable for valid MySQL DATETIME (19 characters) and DATE (10 characters)
    $l = strlen($datetime);
    if (!($l == 10 || $l == 19)) {
        return 0;
    }

    //
    $date    = $datetime;
    $hours   = 0;
    $minutes = 0;
    $seconds = 0;

    // DATETIME only
    if ($l == 19) {
        list($date, $time) = explode(" ", $datetime);
        list($hours, $minutes, $seconds) = explode(":", $time);
    }

    list($year, $month, $day) = explode("-", $date);

    return mktime($hours, $minutes, $seconds, $month, $day, $year);
}

/**
 * @param $files
 */
function fixFilesArray(&$files)
{
    $names = ['name' => 1, 'type' => 1, 'tmp_name' => 1, 'error' => 1, 'size' => 1];

    foreach ($files as $key => $part) {
        // only deal with valid keys and multiple files
        $key = (string)$key;
        if (isset($names[$key]) && is_array($part)) {
            foreach ($part as $position => $value) {
                $files[$position][$key] = $value;
            }
            // remove old key reference
            unset($files[$key]);
        }
    }
}

function notification_settings()
{

    require_once(__DIR__.'/views/settings.php');
}

function create_notification()
{
    $validation = new Notifications\Validation;

    $validation->set_rules('type', 'Notification Type', 'required');
    $validation->set_rules('title', 'Description', 'trim|required|min_length[4]');
    $validation->set_rules('sendto', 'Send To', 'required');

    $type_val = ($_POST && $_POST['type'] == 'scheduled') ? 'required' : '';
    $validation->set_rules('execute_date', 'Execute Date', $type_val);

    $trigger_val = ($_POST && $_POST['type'] == 'triggered') ? 'required' : '';
    $validation->set_rules('trigger', 'Trigger', $trigger_val);

    $validation->set_rules('system_message_type', 'System Message Type', 'trim');

    foreach (['en', 'fr'] as $lang) {
        $validation->set_rules($lang.'_subject', 'Subject', 'trim');
        $validation->set_rules($lang.'_text', 'Text Version', 'trim|min_length[16]');
        $validation->set_rules($lang.'_html', 'HTML Version', 'trim|min_length[16]');
        $validation->set_rules($lang.'_system', 'System Message', 'trim|min_length[16]');
    }

    if ($_POST && ($_POST['subject'] == '' && $_POST['system'] == '')) {
        $form_error = true;
        require_once(__DIR__.'/views/create.php');
    } else {
        if ($validation->run() == true) {

            // Clean up the data before saving
            Tools\tzClean($_POST);

            // ok, so now we need to create the notification.
            class PostTemplate
            {
                var $post_title = '';
                var $post_content = '';
                var $post_status = 'publish';
                var $post_type = 'notifications';
                var $comment_status = 'closed';
            }

            // details
            $type        = $_POST['type'];
            $title       = $_POST['title'];
            $sendto      = $_POST['sendto'];
            $executeDate = ($type == 'scheduled') ? $_POST['execute_date'] : '0000-00-00 00:00:00';
            $trigger     = ($type == 'scheduled') ? 'scheduled-cron-job' : $_POST['trigger'];

            $emailData         = [];
            $systemMessageData = [];

            foreach (['en', 'fr'] as $lang) {
                // email
                $subject     = $_POST[$lang.'_subject'];
                $text        = $_POST[$lang.'_text'];
                $html        = $_POST[$lang.'_html'];
                $attachments = [];
                $uploadDir = wp_upload_dir()['basedir'].'/notifications/';

                fixFilesArray($_FILES[$lang.'_attachment']);

                foreach ($_FILES[$lang.'_attachment'] as $position => $file) {
                    // should output array with indices name, type, tmp_name, error, size
                    if ($file['name'] != '') {
                        move_uploaded_file($file['tmp_name'], $uploadDir.$file['name']);
                        $attachments[] = $file['name'];
                    }
                }

                // system
                $systemMessageType = $_POST['system_message_type'];
                $system            = $_POST[$lang.'_system'];

                $emailData         = array_merge(
                    $emailData,
                    [
                        $lang.'_subject'     => $subject,
                        $lang.'_text'        => $text,
                        $lang.'_html'        => $html,
                        $lang.'_attachments' => $attachments
                    ]
                );
                $systemMessageData = array_merge(
                    $systemMessageData,
                    [
                        'system_message_type' => $systemMessageType,
                        $lang.'_message'      => $system
                    ]
                );
            }

            // make post...
            $notification                = new PostTemplate();
            $notification->post_title    = $title;
            $notification->post_content  = 'Notification created '.date(
                    'Y-m-d H:i:s'
                )." --- to be sent on $executeDate";
            $notification->post_date_gmt = date('Y-m-d H:i:s', time());

            $id = wp_insert_post((array)$notification);

            update_post_meta(
                $id,
                'details',
                [
                    'type'         => $type,
                    'sendto'       => $sendto,
                    'status'       => 'pending',
                    'trigger'      => $trigger,
                    'execute_date' => $executeDate
                ]
            );
            update_post_meta($id, 'send_status', 'pending');
            update_post_meta($id, 'notif_type', $type);
            update_post_meta($id, 'execute_date', mysqldatetime_to_timestamp($executeDate));
            update_post_meta($id, 'trigger', $trigger);

            update_post_meta($id, 'email', $emailData);
            update_post_meta($id, 'system', $systemMessageData);

            $flash = "<strong>Notification Saved Successfully!</strong><br /><a href='/wp-admin/admin.php?page=notifications'>Click here</a> to view all notifications.</a>";
            require_once(__DIR__.'/views/create.php');
        } else {
            require_once(__DIR__.DIRECTORY_SEPARATOR.'views'.DIRECTORY_SEPARATOR.'create.php');
        }
    }
}