Setting process of the email queue
authorSteve Sutton <steve@gaslightmedia.com>
Fri, 31 May 2019 17:46:19 +0000 (13:46 -0400)
committerSteve Sutton <steve@gaslightmedia.com>
Fri, 31 May 2019 17:46:19 +0000 (13:46 -0400)
Setting up cron task to run the email queue ever hour.

classes/data/dataEmailMessages.php
index.php
models/admin/messages/index.php
models/admin/messages/sendMessagesEmails.php [new file with mode: 0644]
setup/adminHooks.php
setup/validActions.php
views/admin/messages/list.html

index f56c241..86291dd 100644 (file)
@@ -74,6 +74,7 @@ class GlmDataEmailMessages extends GlmDataAbstract
     public $fields = false;
 
     public $postStats = false;
+    public $postSent = false;
 
     /**
      * Constructor
@@ -188,13 +189,25 @@ class GlmDataEmailMessages extends GlmDataAbstract
             // get number of queued emails for this message.
             $queued = $this->wpdb->get_var(
                 $this->wpdb->prepare(
-                    "SELECT count(*)
+                    "SELECT max( queue_date )
                        FROM " . GLM_MEMBERS_MESSAGES_PLUGIN_DB_PREFIX . "email_queue
                       WHERE message_id = %d",
                     $r['id']
                 )
             );
-            $r['stats'] = $queued;
+            $r['stats'] = ( $queued ) ? strtotime( $queued ) : '';
+        }
+        if ( $this->postSent ) {
+            // get number of queued emails for this message.
+            $queued = $this->wpdb->get_var(
+                $this->wpdb->prepare(
+                    "SELECT max( send_date )
+                       FROM " . GLM_MEMBERS_MESSAGES_PLUGIN_DB_PREFIX . "email_logs
+                      WHERE message_id = %d",
+                    $r['id']
+                )
+            );
+            $r['sent'] = ( $queued ) ? strtotime( $queued ) : '';
         }
         return $r;
     }
index be26c59..d0e47bf 100644 (file)
--- a/index.php
+++ b/index.php
@@ -165,27 +165,27 @@ function glmMembersMessagesRegisterAddOn($addOns) {
 
     // Add this add-on to the add-ons array
     $addOns[GLM_MEMBERS_MESSAGES_PLUGIN_SLUG] =  array(
-        'dir' => GLM_MEMBERS_MESSAGES_PLUGIN_PATH,
-        'name' =>  GLM_MEMBERS_MESSAGES_PLUGIN_NAME,
-        'short_name' => GLM_MEMBERS_MESSAGES_PLUGIN_SHORT_NAME,
-        'slug' => GLM_MEMBERS_MESSAGES_PLUGIN_SLUG,
-        'actions' => $GLOBALS['glmMembersMessagesAddOnValidActions'],
-        'config' => array(
+        'dir'                   => GLM_MEMBERS_MESSAGES_PLUGIN_PATH,
+        'name'                  => GLM_MEMBERS_MESSAGES_PLUGIN_NAME,
+        'short_name'            => GLM_MEMBERS_MESSAGES_PLUGIN_SHORT_NAME,
+        'slug'                  => GLM_MEMBERS_MESSAGES_PLUGIN_SLUG,
+        'actions'               => $GLOBALS['glmMembersMessagesAddOnValidActions'],
+        'config'                => array(
 //            'settings' => $GLOBALS['glmMembersMessagesManagementSettings'],
 //            'terms' => $GLOBALS['glmMembersMessagesSettingsTerms']
         ),
-        'shortcodes' => $GLOBALS['glmMembersMessagesShortcodes'],
+        'shortcodes'            => $GLOBALS['glmMembersMessagesShortcodes'],
         'shortcodesDescription' => $GLOBALS['glmMembersMessagesShortcodesDescription']
     );
 
     // If we have database tables for this plugin/addon, provide that data also
     if (isset($GLOBALS['glmMembersMessagesDbVersions'])) {
         $addOns[GLM_MEMBERS_MESSAGES_PLUGIN_SLUG]['database'] = array(
-            'dbPrefix' => GLM_MEMBERS_MESSAGES_PLUGIN_DB_PREFIX,
-            'dbCurrentVersion' => GLM_MEMBERS_MESSAGES_PLUGIN_DB_VERSION,
+            'dbPrefix'              => GLM_MEMBERS_MESSAGES_PLUGIN_DB_PREFIX,
+            'dbCurrentVersion'      => GLM_MEMBERS_MESSAGES_PLUGIN_DB_VERSION,
             'dbActiveVersionOption' => GLM_MEMBERS_MESSAGES_PLUGIN_ACTIVE_DB_OPTION,
-            'dbScriptPath' => GLM_MEMBERS_MESSAGES_PLUGIN_DB_SCRIPTS,
-            'dbVersions' => $GLOBALS['glmMembersMessagesDbVersions']
+            'dbScriptPath'          => GLM_MEMBERS_MESSAGES_PLUGIN_DB_SCRIPTS,
+            'dbVersions'            => $GLOBALS['glmMembersMessagesDbVersions']
         );
     } else {
         $addOns[GLM_MEMBERS_MESSAGES_PLUGIN_SLUG]['database'] = false;
index deaad4f..12b47a9 100644 (file)
@@ -134,7 +134,7 @@ class GlmMembersAdmin_messages_index extends GlmDataEmailMessages
             $Categories = new GlmDataCategories( $this->wpdb, $this->config );
             $categories = $Categories->getListSortedParentChild( false );
 
-            echo '<pre>$_REQUEST: ' . print_r( $_REQUEST, true ) . '</pre>';
+            // echo '<pre>$_REQUEST: ' . print_r( $_REQUEST, true ) . '</pre>';
 
             // Check if this is a request to show archived members
             if ( isset( $_REQUEST['filterArchived'] ) ) {
@@ -229,8 +229,11 @@ class GlmMembersAdmin_messages_index extends GlmDataEmailMessages
         case 'list':
             $view = 'list';
             $this->postStats = true;
+            $this->postSent  = true;
             $messages = $this->getList();
             $this->postStats = false;
+            $this->postSent  = false;
+            // echo '<pre>$messages: ' . print_r( $messages, true ) . '</pre>';
             $tData = array(
                 'messages' => $messages,
             );
diff --git a/models/admin/messages/sendMessagesEmails.php b/models/admin/messages/sendMessagesEmails.php
new file mode 100644 (file)
index 0000000..f3094ec
--- /dev/null
@@ -0,0 +1,207 @@
+<?php
+/**
+ * Gaslight Media Members Database
+ * Admin Registrations - Send any current notifications
+ *
+ * PHP version 5.5
+ *
+ * @category glmWordPressPlugin
+ * @package  glmMembersDatabase
+ * @author   Chuck Scott <cscott@gaslightmedia.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @release  index.php,v 1.0 2014/10/31 19:31:47 cscott Exp $
+ * @link     http://dev.gaslightmedia.com/
+ */
+
+// Load Registrations Notification data class
+// require_once GLM_MEMBERS_REGISTRATIONS_PLUGIN_CLASS_PATH.'/data/dataRegNotification.php';
+
+class GlmMembersAdmin_messages_sendMessagesEmails //extends GlmDataRegistrationsRegNotification
+{
+
+    use GlmLock;
+
+    /**
+     * WordPress Database Object
+     *
+     * @var $wpdb
+     * @access public
+     */
+    public $wpdb;
+    /**
+     * Plugin Configuration Data
+     *
+     * @var $config
+     * @access public
+     */
+    public $config;
+
+    /**
+     * Constructor
+     *
+     * This contructor performs the work for this model. This model returns
+     * an array containing the following.
+     *
+     * 'status'
+     *
+     * True if successfull and false if there was a fatal failure.
+     *
+     * 'view'
+     *
+     * A suggested view name that the contoller should use instead of the
+     * default view for this model or false to indicate that the default view
+     * should be used.
+     *
+     * 'data'
+     *
+     * Data that the model is returning for use in merging with the view to
+     * produce output.
+     *
+     * @wpdb object WordPress database object
+     *
+     * @return array Array containing status, suggested view, and any data
+     */
+    public function __construct ($wpdb, $config)
+    {
+
+        // Save WordPress Database object
+        $this->wpdb = $wpdb;
+
+        // Save plugin configuration object
+        $this->config = $config;
+
+        /*
+         * Run constructor for the Registrations data class
+         *
+         * Note, the third parameter is a flag that indicates to the Contacts
+         * data class that it should flag a group of fields as 'view_only'.
+         */
+        // parent::__construct( false, false, true );
+
+    }
+
+    // $notiicationTest to true to just display notification messages
+    public function modelAction( $actionData = false, $notificationTest = false )
+    {
+        trigger_error( 'sendMessagesEmail started', E_USER_NOTICE );
+
+        // Request a Lock
+        $lock = $this->requestLock(
+            array(
+                'lockName' => GLM_MEMBERS_MESSAGES_QUEUE_LOCK,
+                'timeout'  => GLM_MEMBERS_MESSAGES_QUEUE_LOCK_TIMEOUT
+            )
+        );
+
+        echo '<pre>$lock: ' . print_r( $lock, true ) . '</pre>';
+
+        if ( $lock && !empty( $lock ) ) {
+            // Process Emails Queue
+            $emailQueues = $this->wpdb->get_results(
+                "SELECT *
+                   FROM " . GLM_MEMBERS_MESSAGES_PLUGIN_DB_PREFIX . "email_queue
+                  WHERE processed = false",
+                ARRAY_A
+            );
+
+            if ( $emailQueues ) {
+                foreach ( $emailQueues as $email ) {
+                    $this->sendHtmlEmail( $email['from_email'], $email['to_email'], $email['subject'], $email['message_body'], $email['reply_to_email'] );
+                    // Update this to processed
+                    $this->wpdb->update(
+                        GLM_MEMBERS_MESSAGES_PLUGIN_DB_PREFIX . 'email_queue',
+                        array(
+                            'processed' => true
+                        ),
+                        array( 'id' => $email['id'] ),
+                        array( '%s' ),
+                        array( '%d' )
+                    );
+                    // Move this entry into the email_log
+                    $this->wpdb->insert(
+                        GLM_MEMBERS_MESSAGES_PLUGIN_DB_PREFIX . 'email_logs',
+                        array(
+                            'message_id'     => $email['message_id'],
+                            'to_email'       => $email['to_email'],
+                            'subject'        => $email['subject'],
+                            'from_email'     => $email['from_email'],
+                            'reply_to_email' => $email['reply_to_email'],
+                            'message_body'   => '',
+                            'send_date'      => date( 'Y-m-d H:i:s' ),
+                        ),
+                        array(
+                            '%d',
+                            '%s',
+                            '%s',
+                            '%s',
+                            '%s',
+                            '%s',
+                            '%s',
+                        )
+                    );
+                }
+            }
+
+            // Once all the email_queue items are processed we can remove them from the queue.
+            $this->wpdb->delete(
+                GLM_MEMBERS_MESSAGES_PLUGIN_DB_PREFIX . 'email_queue',
+                array( 'processed' => true ),
+                array( '%s' )
+            );
+
+            // Remove the Lock
+            $this->requestUnLock(
+                array(
+                    'lockName' => GLM_MEMBERS_MESSAGES_QUEUE_LOCK,
+                )
+            );
+        }
+
+    }
+
+    /**
+     * sendHtmlEmail
+     *
+     * Create html email and send using wp_mail.
+     *
+     * @param mixed $to          To email address
+     * @param mixed $subject     Subject line for the email
+     * @param mixed $htmlMessage Html message for the email
+     *
+     * @access public
+     * @return void
+     */
+    public function sendHtmlEmail( $from, $to, $subject, $htmlMessage, $replyTo = null )
+    {
+
+        // Set the From name using this wordpress hook.
+        add_filter(
+            'wp_mail_from_name',
+            function ( $name ) {
+                return $this->config['settings']['reg_org_name'];
+            }
+        );
+        // Send confirmation email, set the content type to allow html by using this filter
+        add_filter( 'wp_mail_content_type', array( $this, 'set_content_type' ) );
+
+
+        $message  = $htmlMessage;
+        $header[] = 'From:' . $from;
+        if ( $replyTo ) {
+            $header[] = 'Reply-To:' . $replyTo;
+        }
+
+        wp_mail( $to, $subject, $message, $header );
+
+    }
+
+    /**
+     * Set content type of the email.
+     *
+     * Used as filter for the wp_mail_content_type
+     */
+    function set_content_type()
+    {
+        return 'text/html';
+    }
+}
index 97670c8..2b8e769 100644 (file)
   */
 
 // Add content to member detail page
-add_filter('glm-member-db-admin-management-hooksHelp', function($content) {
+add_filter( 'glm-member-db-admin-management-hooksHelp', function( $content ) {
 
         // Read in this plugin/addon hook help file
         $fname = GLM_MEMBERS_MESSAGES_PLUGIN_PATH.'/setup/hooksHelp.html';
-        if (is_file($fname)) {
+        if ( is_file( $fname ) ) {
             $hooksHelp = file_get_contents($fname);
-            if ($hooksHelp != false) {
+            if ( $hooksHelp != false ) {
                 $content .= $hooksHelp;
             }
         }
@@ -48,18 +48,18 @@ add_filter('glm-member-db-admin-management-hooksHelp', function($content) {
  *
  * Run only once per day. Everyday.
  */
-// add_filter(
-//     'glm_associate_cron_request',
-//     function( $cron_task ){
-//         $new_cron = array(
-//             array(
-//                 'menu'       => 'ajax',
-//                 'action'     => 'SendMessagesEmails',
-//                 'daysOfWeek' => false,
-//                 'times'      => false,
-//                 'params'     => array()
-//             )
-//         );
-//         return array_merge( $cron_task, $new_cron );
-//     }
-// );
+add_filter(
+    'glm_associate_cron_request',
+    function( $cron_task ){
+        $new_cron = array(
+            array(
+                'menu'       => 'messages',
+                'action'     => 'sendMessagesEmails',
+                'daysOfWeek' => false,
+                'times'      => false,
+                'params'     => array()
+            )
+        );
+        return array_merge( $cron_task, $new_cron );
+    }
+);
index 159fa20..9775b61 100644 (file)
 $glmMembersMessagesAddOnValidActions = array(
     'adminActions' => array(
         'messages' => array(
-            'index' => GLM_MEMBERS_MESSAGES_PLUGIN_SLUG,
+            'index'              => GLM_MEMBERS_MESSAGES_PLUGIN_SLUG,
+            'sendMessagesEmails' => GLM_MEMBERS_MESSAGES_PLUGIN_SLUG,
         ),
     ),
     'frontActions' => array(
     )
 );
-
-?>
index 470c5b7..12d34eb 100644 (file)
@@ -7,7 +7,7 @@
             <th align="left">ID</th>
             <th align="left">Subject</th>
             <th align="left">Last Updated</th>
-            <th align="left">Sent</th>
+            <th align="left">Last Sent</th>
             <th align="left">Queued</th>
         </tr>
     </thead>
@@ -18,8 +18,8 @@
                     <td> {$message.id} </td>
                     <td> <a href="{$thisUrl}?page={$thisPage}&option=editHtmlEmail&id={$message.id}">{$message.subject}</a> </td>
                     <td> {$message.last_updated.timestamp|date_format:"%D %r"} </td>
-                    <td> </td>
-                    <td> {$message.stats} </td>
+                    <td> {$message.sent|date_format:"%D %r"} </td>
+                    <td> {$message.stats|date_format:"%D %r"} </td>
                 </tr>
             {/foreach}
         {/if}