Drupal Ubercart E-commerce Email Notification Module Hook | 2011-06-24

Technology Blog » Web Development

This is the module I wrote for a online store last year.

<?php
/**
* Drupal Ubercart E-commerce Email Notification Module Hook
* This Module codes are written by [email protected]
* http://www.PCinvent.com PCinvent Studio 
* Please do not remove the credit line above, thanks!
* Implimentation of hook_cron()
*/
function ubertcart_custom_cron()
{
    // parameters settings
    $parameters7 = Array
    (
       emailtype => 7,                  // appropriate values: 1 - 1 days_before_trial, 7 - 7 days_before_trial, -30 - 30_days_after_trial 
       email_template => 7,             // appropriate values: 7, 1, -30
       expiration_roleid => 5,          // appropriate values: 5 - member role id
       expiration_threshold => 7,       // appropriate values: (in day unit): 1, 7, -30
       testing => true,                 // appropriate valuesL true - sent all e-mail to [email protected], false - sent to real customer emails
       enabled => true                  // appropriate values: true, false
    );
    $parameters1 = Array
    (
       emailtype => 1,                  // appropriate values: 1 - 1 days_before_trial, 7 - 7 days_before_trial, -30 - 30_days_after_trial 
       email_template => 1,             // appropriate values: 7, 1, -30
       expiration_roleid => 5,          // appropriate values: 5 - member role id
       expiration_threshold => 1,       // appropriate values: (in day unit): 1, 7, -30
       testing => true,                 // appropriate valuesL true - sent all e-mail to [email protected], false - sent to real customer emails
       enabled => true                  // appropriate values: true, false
    );
    $parameters30n = Array
    (
       emailtype => -30,                // appropriate values: 0 - just registered, 7 - 7 days_before_trial, 1 - 1 days_before_trial, -30 - 30_days_after_trial 
       email_template => -30,           // appropriate values: 7, 1, -30
       expiration_roleid => 5,          // appropriate values: 5 - member role id
       expiration_threshold => -30,     // appropriate values: (in day unit): 1, 7, -30
       testing => true,                 // appropriate valuesL true - sent all e-mail to [email protected], false - sent to real customer emails
       enabled => true                  // appropriate values: true, false
    );
    
    // executions
    _ubertcart_custom_send_reminder($parameters7);   // 7 days left
    _ubertcart_custom_send_reminder($parameters1);   // 1 day left
    _ubertcart_custom_send_reminder($parameters30n); // 30 days passed
}
 
/**
* Get expiration date from roles and send reminder
* @param array $parameters
*   string  $parameters["emailtype"] email type id
*   integer $parameters["email_template"] use which template
*   integer $parameters["expiration_roleid"] define the role id
*   integer $parameters["expiration_threshold"] define the expiration time left
*   boolean $parameters["enabled"] to decide switch on and off since cron job will execute constantly in short period
* @return array $expiring_users
*/
function _ubertcart_custom_send_reminder($parameters)
{
    $enabled = $parameters["enabled"];
    if($enabled) // switch on/off
    {
        $expiration_array = _ubertcart_custom_get_expiration($parameters);
        _ubertcart_custom_set_maillist($parameters, $expiration_array);
    }
}
 
/**
* Get array of whose accounts are expired
* @param array $parameters
*   string  $parameters["emailtype"] email type id
*   integer $parameters["email_template"] use which template
*   integer $parameters["expiration_roleid"] define the role id
*   integer $parameters["expiration_threshold"] define the expiration time left
*   boolean $parameters["enabled"] to decide switch on and off since cron job will execute constantly in short period
* @return array $expiration_array
* return values array format:
* array(2) {
  [0]=>
  array(3) {
    ["uid"]=>
    string(4) "1893"
    ["rid"]=>
    string(1) "5"
    ["expiration"]=>
    string(10) "1312743315"
  }
  [1]=>
  array(3) {
    ["uid"]=>
    string(4) "1820"
    ["rid"]=>
    string(1) "5"
    ["expiration"]=>
    string(10) "1344452124"
  }
}
*/
function _ubertcart_custom_get_expiration($parameters)
{
    // when it will be expired ?
    switch($parameters["expiration_threshold"])
    {
        case 7: // 7 days left
            $expiration_time = time() + (7 * 24 * 60 * 60);
            $role_id = $parameters["expiration_roleid"];
            $result = db_query("SELECT e.uid, e.rid, e.expiration FROM {uc_roles_expirations} e WHERE e.rid=%d AND e.expiration >=%d", $role_id, $expiration_time);
        break;
        case 1: // 1 day left
            $expiration_time = time() + (1 * 24 * 60 * 60);
            $result = db_query("SELECT e.uid, e.rid, e.expiration FROM {uc_roles_expirations} e WHERE e.rid=%d AND e.expiration >=%d", $role_id, $expiration_time);
        break;
        case -30: // 30 days after expired
            $expiration_time = time() - (30 * 24 * 60 * 60);
            $role_id = $parameters["expiration_roleid"];
            $result = db_query("SELECT e.uid, e.rid, e.expiration FROM {uc_roles_expirations} e WHERE e.rid=%d AND e.expiration >%d", $role_id, $expiration_time);
        break;
        default:
            echo "Error, parameter expiration_threshold is missing!";
        break;
    }
     
    $expiration_array = Array(); //init
    while ($row = db_fetch_array($result))
    {
        $expiration_array[] = array
        (
            uid => $row["uid"],
            rid => $row["rid"],
            expiration => $row["expiration"]
        );
    }
 
    return $expiration_array;
}
 
/**
* create mail list in  ubertcart_custom_cron_mail
* @param array $mailall_array
* @param array $parameters
* return value array format:
* Array ( [uid] => 1893 [rid] => 5 [expiration] => 1312743315 )
* Array ( [uid] => 1820 [rid] => 5 [expiration] => 1344452124 ) 
*/
function _ubertcart_custom_set_maillist($parameters, $mailall_array)
{
    // get email type from parameter array
    $emailtype = $parameters["emailtype"];
 
    // loop throught multi dimension arrays
    $last = count($mailall_array) - 1; // count size
    foreach($mailall_array as $i => $row)
    {
        $isFirst = ($i == 0);
        $isLast = ($i == $last);
        $result = db_result(db_query("SELECT emailtype, uid FROM {ubertcart_custom_cron_mail} m WHERE (m.emailtype=%d AND m.uid=%d) LIMIT %d", $emailtype, $row["uid"], 1)); // uid should be unique, so limit 1 is optional just in case 
         
        // TODO: need to see if result is t/f to skip db_query below
        if(!$result) // if not in the table row yet
        {
            // Need to check if row exists or not first before insert
            // $emailtype is from pass reference
            // $row["uid"] is from this loop          
            db_query("INSERT INTO {ubertcart_custom_cron_mail} (emailtype, uid, laststatus, lastaccesstime) VALUES (%d, %d, %d, %d)", $emailtype, $row["uid"], 0, time());  // status 0 means not started
        }        
    }
    
    _ubertcart_custom_set_mailqueue($parameters); // execute mail list in queue
}
 
/**
* Send set limit of mail queue that send constant mails at a time
* last status 0 is not started, 1 is in progress, 2 is success, 3 is failed
* @param array $parameters
* @param array $mailsingle_array
*/
function _ubertcart_custom_set_mailqueue($parameters)
{
    $result = db_query("SELECT m.emailtype, m.uid, m.laststatus FROM {ubertcart_custom_cron_mail} m
     WHERE m.laststatus=%d LIMIT %d, %d", 0, 0, 50); // status is 0 and limit to 50 at once
    while ($row = db_fetch_array($result))
    {
        $emailtype = $row["emailtype"];
        $uid         = $row["uid"];
        $laststatus  = $row["laststatus"];
        
        // Send email work flow 0->1->2 or 3
        
        // status log
        db_query("UPDATE {ubertcart_custom_cron_mail} SET laststatus=%d WHERE emailtype=%d AND uid=%d", 1, $emailtype, $uid);
        
        // time log
        db_query("UPDATE {ubertcart_custom_cron_mail} SET lastaccesstime=%d WHERE emailtype=%d AND uid=%d", time(), $emailtype, $uid);  
        _ubertcart_custom_send_phpmail($parameters, $emailtype, $uid);  
    }
}
 
/**
* Send notification email to individual
* @param array $parameters
* @param integer $emailtype
* @param integer $uid use user id to look for user info needed for mail content
*/
function _ubertcart_custom_send_phpmail($parameters, $emailtype, $uid)
{
    // Get user info
    $user_firstname = _ubertcart_custom_get_userfirstname($uid);
    $user_lastname = _ubertcart_custom_get_userlastname($uid);
    $user_email = _ubertcart_custom_get_useremail($parameters, $uid);
    
    
    // Headers
    $to = "'".$user_firstname." ".$user_lastname."' <".$user_email.">";
    $headers  = 'MIME-Version: 1.0' . "\r\n";
    $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
    $headers .= 'From: "[email protected]" <[email protected]>' . "\r\n";
    
    
    // common message header
            $message = '<html><body>';
            $message .= "Dear ".$user_firstname.",";
            $message .= "<br /><br />";
    
// Mail template
    switch($parameters["email_template"])
    {
        case 7:
            $subject = "6 Days Left for Free Trial";
            // 7 days left message
            $message .= "6 Days Left for Free Trial";
            $message .= "<br /><br />";
        break;
        case 1:
            $subject = "Last Day of Free Trial";
            // 1 day left message
            $message .= "Last Day of Free Trial.";
        break;
        case -30:
            $subject = "30 Days after Expired";
            // 30 days expiration passed message
            $message .= "30 Days after Expired";
        break;
    }
    // common message footer
            $message .= "<br /><br />";
            $message .= "Sincerely, <br /><br />";
            $message .= "PCinvent Studio<br />";
            $message .= "<a style='color:black' href='http://www.pcinvent.com'>www.pcinvent.com</a><br />";
            $message .= "<br /><br />";
            $message .= "</body></html>";
    
    // PHP mailer
    if(mail($to, $subject, $message, $headers))
    {
      // status log
      db_query("UPDATE {ubertcart_custom_cron_mail} SET laststatus=%d WHERE emailtype=%d AND uid=%d", 2, $emailtype, $uid); // success
    }
    else
    {
      // status log
      db_query("UPDATE {ubertcart_custom_cron_mail} SET laststatus=%d WHERE emailtype=%d AND uid=%d", 3, $emailtype, $uid); // failed
    } 
    // time log
    db_query("UPDATE {ubertcart_custom_cron_mail} SET lastaccesstime=%d WHERE emailtype=%d AND uid=%d", time(), $emailtype, $uid); 
}
 
/**
* Send notification email to individual
* @param integer $uid use user id to look for user firstname
* @return string $firstname
*/
function _ubertcart_custom_get_userfirstname($uid)
{
    $firstname = db_result(db_query("SELECT p.value FROM {profile_values} p WHERE p.fid=%d AND p.uid=%d", 11, $uid)); // fid 11 is first name
    return $firstname;
}
 
/**
* Send notification email to individual
* @param integer $uid use user id to look for user lastname
* @return string $lastname
*/
function _ubertcart_custom_get_userlastname($uid)
{
    $lastname = db_result(db_query("SELECT p.value FROM {profile_values} p WHERE p.fid=%d AND p.uid=%d", 25, $uid)); // fid 25 is last name
    return $lastname;
}
 
/**
* Send notification email to individual
* If it is testing, it will send all e-mail to [email protected]
* If not, it will send to real customer emails
* @param parameters
* @param integer $uid use user id to look for user email
* @return string $email
*/
function _ubertcart_custom_get_useremail($parameters, $uid)
{
    $testing = $parameters["testing"];
    $email = db_result(db_query("SELECT u.mail FROM {users} u WHERE u.uid=%d", $uid));
    
    if($testing)
    {
        return "[email protected]";
    }
    else
    {
        return $email;
    }
}