Renamed ifSqlHasZeroNums() to ifSqlHasZeroNumRows() and improved some queries.
[mailer.git] / inc / pool / pool-bonus.php
index 9af04721bdbd131bb6739710e7606795ce8fb5d5..eb263b9905241feda5c5aa0995d6539756be13b6 100644 (file)
@@ -1,7 +1,7 @@
 <?php
 /************************************************************************
- * MXChange v0.2.1                                    Start: 12/12/2008 *
- * ===============                              Last change: 12/12/2008 *
+ * Mailer v0.2.1-FINAL                                Start: 12/12/2008 *
+ * ===================                          Last change: 12/12/2008 *
  *                                                                      *
  * -------------------------------------------------------------------- *
  * File              : pool-bonus.php                                   *
  * -------------------------------------------------------------------- *
  * Kurzbeschreibung  : Sendet freigegebene Bonus-Mails aus dem Pool     *
  * -------------------------------------------------------------------- *
- *                                                                      *
+ * $Revision::                                                        $ *
+ * $Date::                                                            $ *
+ * $Tag:: 0.2.1-FINAL                                                 $ *
+ * $Author::                                                          $ *
  * -------------------------------------------------------------------- *
- * Copyright (c) 2003 - 2008 by Roland Haeder                           *
- * For more information visit: http://www.mxchange.org                  *
+ * Copyright (c) 2003 - 2009 by Roland Haeder                           *
+ * Copyright (c) 2009 - 2015 by Mailer Developer Team                   *
+ * For more information visit: http://mxchange.org                      *
  *                                                                      *
  * This program is free software; you can redistribute it and/or modify *
  * it under the terms of the GNU General Public License as published by *
 
 // Some security stuff...
 if (!defined('__SECURITY')) {
-       $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), "/inc") + 4) . "/security.php";
-       require($INC);
-}
+       die();
+} // END - if
 
 // Don't run on daily reset
-if (defined('__DAILY_RESET')) {
+if ((isResetModeEnabled()) || (!isHtmlOutputMode())) {
        // Skip here
-       return false;
-} elseif (!EXT_IS_ACTIVE("bonus")) {
-       // Abort if extension bonus is not active
-       return false;
+       return FALSE;
+} elseif ((!isExtensionActive('bonus')) || (!isExtensionActive('other'))) {
+       // Abort if extension bonus/other are not active
+       return FALSE;
 }
 
-// Need this here
-global $REPLACER;
-
 // Only send bonus mail when bonus extension is active and maximum send-mails is not reached
-if ($GLOBALS['pool_cnt'] < getConfig('max_send')) {
-       // Do we need to send out bonus mails?
-       if (EXT_IS_ACTIVE("html_mail")) {
-               //                                 0     1       2        3        4      5       6          7       8      9         10         11
-               $result_bonus = SQL_QUERY("SELECT id, subject, text, receivers, points, time, data_type, timestamp, url, cat_id, target_send, html_msg FROM "._MYSQL_PREFIX."_bonus WHERE data_type='NEW' ORDER BY timestamp DESC", __FILE__, __LINE__);
-       } else {
-               //                                 0     1       2        3        4      5       6          7       8      9         10
-               $result_bonus = SQL_QUERY("SELECT id, subject, text, receivers, points, time, data_type, timestamp, url, cat_id, target_send FROM "._MYSQL_PREFIX."_bonus WHERE data_type='NEW' ORDER BY timestamp DESC", __FILE__, __LINE__);
-       }
-
-       if (SQL_NUMROWS($result_bonus) > 0) {
-               // Send these mails away...
-               $cnt2 = "";
-               while ($DATA = SQL_FETCHARRAY($result_bonus)) {
-                       // Compile URL
-                       $DATA['url'] = COMPILE_CODE($DATA['url']);
+if ($GLOBALS['pool_cnt'] < getMaxSend()) {
+       // Default is ext-html_mail is gone
+       $add = '';
+
+       // Send out bonus mails?
+       if (isExtensionActive('html_mail')) {
+               //  With HTML support
+               $add = ', `html_msg`';
+       } // END - if
+
+       // Run query
+       $result_main = sqlQuery("SELECT
+       `id`,
+       `subject`,
+       `text`,
+       `receivers`,
+       `points`,
+       `time`,
+       `data_type`,
+       `timestamp`,
+       `url`,
+       `cat_id`,
+       `target_send`
+       " . $add . "
+FROM
+       `{?_MYSQL_PREFIX?}_bonus`
+WHERE
+       `data_type`='NEW'
+ORDER BY
+       `timestamp` DESC", __FILE__, __LINE__);
+
+       // Some mails left?
+       if (!ifSqlHasZeroNumRows($result_main)) {
+               // Init SQLs here
+               initSqls();
 
+               // Send these mails away...
+               $count2 = '';
+               while ($mailData = sqlFetchArray($result_main)) {
                        // Message is active in queue
-                       SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_bonus SET data_type='QUEUE' WHERE id=%s LIMIT 1",
-                               array(bigintval($DATA['id'])), __FILE__, __LINE__);
+                       sqlQueryEscaped("UPDATE `{?_MYSQL_PREFIX?}_bonus` SET `data_type`='QUEUE' WHERE `id`=%s LIMIT 1",
+                               array(bigintval($mailData['id'])), __FILE__, __LINE__);
+
+                       // Default is no users left
+                       $receivers = array();
 
                        // "Explode" all receivers into an array
-                       if (ereg(";", $DATA['receivers'])) {
+                       if (isInString(';', $mailData['receivers'])) {
                                // There's more than one receiver in the list...
-                               $RECEIVERS = explode(";", $DATA['receivers']);
-                       } elseif (!empty($DATA['points'])) {
+                               $receivers = explode(';', $mailData['receivers']);
+                       } elseif (!empty($mailData['points'])) {
                                // Only one user left
-                               $RECEIVERS = array($DATA['receivers']);
-                       } else {
-                               // No users left
-                               $RECEIVERS = array("0");
+                               $receivers = array($mailData['receivers']);
                        }
-                       $dummy = $RECEIVERS;
+                       $temporaryReceivers = $receivers;
 
-                       // Now, if we are good little boys and girls Santa left us some user-ids.
-                       // We can now send mails to them...
-                       foreach ($RECEIVERS as $key => $uid) {
+                       /*
+                        * Now, if we are good little boys and girls Santa Claus left us
+                        * some user-ids and send out mails to them.
+                        */
+                       foreach ($receivers as $key => $userid) {
                                // Load personal data
-                               //* DEBUG: */ echo "*L:".__LINE__."/".$uid."*<br />";
-                               $result_user = SQL_QUERY_ESC("SELECT surname, family, email FROM `"._MYSQL_PREFIX."_user_data` WHERE userid=%s LIMIT 1",
-                                       array(bigintval($uid)), __FILE__, __LINE__);
-
-                               // Is his data available?
-                               if (SQL_NUMROWS($result_user) == 1) {
+                               if (fetchUserData($userid)) {
                                        // The final receiver does exists so we can continue...
-                                       list($sname, $fname, $email) = SQL_FETCHROW($result_user);
-                                       //* DEBUG: */ echo "OK!/L:".__LINE__."<br />";
-
-                                       // Mark this user as "spammed" ;-) And place a line for him...
-                                       if (REMOVE_RECEIVER($dummy, $key, $uid, $DATA['id'], $DATA['id'], true) == "done") {
-                                               // Replace text variables
-                                               foreach ($REPLACER as $key => $value) {
-                                                       if (isset($DATA[$key])) $DATA['text'] = str_replace($value, $DATA[$key], $DATA['text']);
-                                               } // END - foreach
-
-                                               // Prepare content
-                                               $content = array(
-                                                       'id'       => $DATA['id'],
-                                                       'url'      => $DATA['url'],
-                                                       'time'     => CREATE_FANCY_TIME($DATA['time']),
-                                                       'points'   => TRANSLATE_COMMA($DATA['points']),
-                                                       'category' => GET_CATEGORY($DATA['cat_id']),
-                                                       'text'     => $DATA['text']
-                                               );
-
-                                               // Prepare the mail
-                                               $mailText = LOAD_EMAIL_TEMPLATE("bonus-mail", $content, $uid);
-
-                                               // Send mail away
-                                               if (isset($DATA['html_msg'])) {
-                                                       // Send HTML?
-                                                       SEND_EMAIL($email, $DATA['subject'], $mailText, $DATA['html_msg']);
-                                               } else {
-                                                       // No HTML mail!
-                                                       SEND_EMAIL($email, $DATA['subject'], $mailText);
-                                               }
-
-                                               // Count one up and remove entry from dummy array
-                                               $GLOBALS['pool_cnt']++; unset($dummy[$key]);
-
-                                               if (GET_EXT_VERSION("user") >= "0.1.4") {
-                                                       // Update mails received for receiver
-                                                       SQL_QUERY_ESC("UPDATE `"._MYSQL_PREFIX."_user_data` SET emails_received=emails_received+1 WHERE userid=%s LIMIT 1",
-                                                               array(bigintval($uid)), __FILE__, __LINE__);
-                                               } // END - if
-
-                                               // Do we have send maximum mails?
-                                               if (($GLOBALS['pool_cnt'] >= getConfig('max_send')) || (SELECTION_COUNT($dummy) == 0)) {
-                                                       // Yes, we have
-                                                       //* DEBUG: */ echo "*EXIT/L:".__LINE__."<br />";
+                                       //* DEBUG: */ debugOutput('OK!/L:'.__LINE__);
+
+                                       // Remove receiver from list
+                                       $status = removeReceiver($temporaryReceivers, $key, $userid, $mailData['id'], $mailData['id'], TRUE);
+
+                                       // Did it work?
+                                       switch ($status) {
+                                               case 'done': // Done!
+                                                       // Prepare the mail
+                                                       $mailText = loadEmailTemplate('member_bonus_pool_normal', $mailData, $userid);
+
+                                                       // Send mail away
+                                                       if (isset($mailData['html_msg'])) {
+                                                               // Send HTML?
+                                                               sendEmail(getUserData('userid'), $mailData['subject'], $mailText, $mailData['html_msg']);
+                                                       } else {
+                                                               // No HTML mail!
+                                                               sendEmail(getUserData('userid'), $mailData['subject'], $mailText);
+                                                       }
+
+                                                       // Count one up and remove entry from dummy array
+                                                       $GLOBALS['pool_cnt']++; unset($temporaryReceivers[$key]);
+
+                                                       // Is ext-user installed?
+                                                       if (isExtensionInstalledAndNewer('user', '0.1.4')) {
+                                                               // Debug message
+                                                               //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',mailData[id]=' . $mailData['id']);
+                                                               // Update mails received for receiver
+                                                               addSql(sprintf("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `emails_received`=`emails_received`+1 WHERE `userid`=%s LIMIT 1", bigintval($userid)));
+                                                       } // END - if
+
+                                                       // Is the size of pool reached or nothing to sent left?
+                                                       if (($GLOBALS['pool_cnt'] >= getMaxSend()) || (countSelection($temporaryReceivers) == 0)) {
+                                                               // Yes, it is. So abort here
+                                                               break;
+                                                       } // END - if
+                                                       break;
+
+                                               default: // Unknown return type
+                                                       logDebugMessage(__FILE__, __LINE__, 'Unknown status ' . $status . ' detected. pool_id=' . $mailData['id'] . ',userid=' . $mailData['userid'] . ',stats_id=' . $stats_id);
                                                        break;
-                                               } // END - if
-                                       } // END - if
+                                       } // END - switch
                                } // END - if
+                       } // END - foreach
 
-                               // Free some memory
-                               SQL_FREERESULT($result_user);
-                       }
+                       // Run all SQLs
+                       runFilterChain('run_sqls');
 
                        // Update mediadata if version is 0.0.4 or higher
-                       if (GET_EXT_VERSION("mediadata") >= "0.0.4") {
+                       if (isExtensionInstalledAndNewer('mediadata', '0.0.4')) {
                                // Update entry (or add missing
                                $P = $GLOBALS['pool_cnt'];
-                               if (!empty($cnt2) && empty($GLOBALS['pool_cnt'])) $P = $cnt2;
-                               //* DEBUG: */ echo "+MEDIA/L:".__LINE__."/".$P."+<br />";
-                               MEDIA_UPDATE_ENTRY(array("total_send", "bonus_send"), "add", $P);
+                               if (!empty($count2) && empty($GLOBALS['pool_cnt'])) $P = $count2;
+                               //* DEBUG: */ debugOutput('+MEDIA/L:'.__LINE__.'/'.$P.'+');
+                               updateMediadataEntry(array('total_send', 'bonus_send'), 'add', $P);
                        } // END - if
 
                        // Close sending system
-                       //* DEBUG: */ echo "-L:".__LINE__."/".SELECTION_COUNT($dummy)."-<br />";
-                       if (SELECTION_COUNT($dummy) == 0) {
+                       //* DEBUG: */ debugOutput('-L:'.__LINE__.'/'.countSelection($temporaryReceivers).'-');
+                       if (countSelection($temporaryReceivers) == 0) {
                                // Queue reached!
-                               SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_bonus SET data_type='SEND', target_send='0', receivers='' WHERE id=%s LIMIT 1",
-                                       array(bigintval($DATA['id'])), __FILE__, __LINE__);
-                               //* DEBUG: */ echo "*L:".__LINE__."*<br />";
+                               sqlQueryEscaped("UPDATE
+       `{?_MYSQL_PREFIX?}_bonus`
+SET
+       `data_type`='SEND',
+       `target_send`=0,
+       `receivers`=''
+WHERE
+       `id`=%s
+LIMIT 1",
+                                       array(bigintval($mailData['id'])), __FILE__, __LINE__);
+                               //* DEBUG: */ debugOutput('*L:'.__LINE__.'*');
 
                                // Update mediadata if version is 0.0.4 or higher
-                               if (GET_EXT_VERSION("mediadata") >= "0.0.4") {
+                               if (isExtensionInstalledAndNewer('mediadata', '0.0.4')) {
                                        // Update entry (or add missing)
-                                       //* DEBUG: */ echo "*MEDIA/L:".__LINE__."*<br />";
-                                       MEDIA_UPDATE_ENTRY(array("total_orders", "bonus_orders"), "add", 1);
+                                       //* DEBUG: */ debugOutput('*MEDIA/L:'.__LINE__.'*');
+                                       updateMediadataEntry(array('total_orders', 'bonus_orders'), 'add', 1);
                                } // END - if
-                       } elseif ($GLOBALS['pool_cnt'] >= getConfig('max_send')) {
+                       } elseif ($GLOBALS['pool_cnt'] >= getMaxSend()) {
                                // Update bonus pool
-                               SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_bonus SET data_type='NEW', target_send=%s, receivers='%s' WHERE id=%s LIMIT 1",
-                                       array(SELECTION_COUNT($dummy), implode(";", $dummy), bigintval($DATA['id'])), __FILE__, __LINE__);
-                               //* DEBUG: */ echo "*L:".__LINE__."<pre>";
-                               //* DEBUG: */ print_r($dummy);
-                               //* DEBUG: */ echo "</pre>\n!!!<br />";
+                               sqlQueryEscaped("UPDATE
+       `{?_MYSQL_PREFIX?}_bonus`
+SET
+       `data_type`='NEW',
+       `target_send`=%s,
+       `receivers`='%s'
+WHERE
+       `id`=%s
+LIMIT 1",
+                                       array(
+                                               countSelection($temporaryReceivers),
+                                               implode(';', $temporaryReceivers),
+                                               bigintval($mailData['id'])
+                                       ), __FILE__, __LINE__);
+                               //* DEBUG: */ debugOutput('*L:'.__LINE__.'<pre>'.print_r($temporaryReceivers, TRUE).'</pre>!!!');
+
+                               // Run any SQLs
+                               runFilterChain('run_sqls');
                                break;
                        }
-               }
-       }
+               } // END - while
+       } // END - if
 
        // Free memory
-       SQL_FREERESULT($result_bonus);
+       sqlFreeResult($result_main);
 
        // Remove variable
        unset($mailText);
-}
+} // END - if
 
-//
+// [EOF]
 ?>