Renamed ifSqlHasZeroNums() to ifSqlHasZeroNumRows() and improved some queries.
[mailer.git] / inc / pool / pool-user.php
index 290770b259efebda033070b18e570d41342cbeb2..128d793eea663d566c30dfa225e20f7bab524949 100644 (file)
  * $Date::                                                            $ *
  * $Tag:: 0.2.1-FINAL                                                 $ *
  * $Author::                                                          $ *
- * Needs to be in all Files and every File needs "svn propset           *
- * svn:keywords Date Revision" (autoprobset!) at least!!!!!!            *
  * -------------------------------------------------------------------- *
  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
- * Copyright (c) 2009, 2010 by Mailer Developer Team                    *
- * For more information visit: http://www.mxchange.org                  *
+ * 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 *
@@ -43,108 +41,156 @@ if (!defined('__SECURITY')) {
 } // END - if
 
 // Don't run on daily reset
-if (isResetModeEnabled()) {
+if ((isResetModeEnabled()) || (!isHtmlOutputMode())) {
        // Skip here
-       return false;
-} elseif (!isExtensionActive('user')) {
-       // Abort here if extension user is not active
-       return false;
+       return FALSE;
+} elseif ((!isExtensionActive('user')) || (!isExtensionActive('other'))) {
+       // Abort here if extension user/other are not active
+       return FALSE;
 }
 
-// Need this here
+// No HTML is default
+$HTML = '';
+
 // Check for freed mail orders to send out
 if (isExtensionActive('html_mail')) {
-       //                                0     1        2      3       4          5            6      7        8          9       10
-       $result_main = SQL_QUERY("SELECT id, sender, subject, text, receivers, payment_id, timestamp, url, target_send, cat_id, html_msg FROM `{?_MYSQL_PREFIX?}_pool` WHERE `data_type`='NEW' ORDER BY timestamp DESC", __FILE__, __LINE__);
-} else {
-       //                                0     1        2      3       4          5            6      7        8          9    10
-       $result_main = SQL_QUERY("SELECT id, sender, subject, text, receivers, payment_id, timestamp, url, target_send, cat_id, id FROM `{?_MYSQL_PREFIX?}_pool` WHERE `data_type`='NEW' ORDER BY timestamp DESC", __FILE__, __LINE__);
-}
+       // With HTML mails
+       $HTML = ',`html_msg`';
+} // END - if
+
+// Main query
+$result_main = sqlQuery("SELECT
+       `id`,
+       `sender` AS `sender_userid`,
+       `subject`,
+       `text`,
+       `receivers`,
+       `payment_id`,
+       `timestamp`,
+       `url`,
+       `target_send`,
+       `cat_id`
+       " . $HTML . "
+FROM
+       `{?_MYSQL_PREFIX?}_pool`
+WHERE
+       `data_type`='NEW'
+ORDER BY
+       `timestamp` DESC", __FILE__, __LINE__);
 
 // Reset variables
-$cnt2 = '0'; $lastSentId = '0'; $cnt_back = array(0); $pointsBack = array(0);
-if (!SQL_HASZERONUMS($result_main)) {
+$count2 = '0';
+$lastSentId = '0';
+$count_back = array(0);
+$pointsBack = array(0);
+
+if (!ifSqlHasZeroNumRows($result_main)) {
        // Parse all mails
-       while ($DATA = SQL_FETCHARRAY($result_main, 0, false)) {
+       while ($mailData = sqlFetchArray($result_main)) {
                // Set mail order as 'active'. That means it will be sent out
-               SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_pool` SET `data_type`='ACTIVE' WHERE `id`=%s AND `data_type`='NEW' LIMIT 1",
-                       array($DATA['id']), __FILE__, __LINE__);
+               updatePoolDataById($mailData['id'], 'data_type', 'ACTIVE', NULL, " AND `data_type`='NEW'");
 
                // Check fetched data for HTML
-               $HTML = 'N';
-               if (isset($DATA['html_msg'])) $HTML = $DATA['html_msg'];
+               $isHtml = 'N';
+               if (isset($mailData['html_msg'])) {
+                       $isHtml = $mailData['html_msg'];
+               } // END - if
 
                // Entry updated?
-               if (SQL_AFFECTEDROWS() == 1) {
+               if (!ifSqlHasZeroAffectedRows()) {
                        // "Explode" all receivers into an array
-                       if (isInString(';', $DATA['receivers'])) {
+                       if (isInString(';', $mailData['receivers'])) {
                                // There's more than one receiver in the list...
-                               $receiverS = explode(';', $DATA['receivers']);
-                       } elseif (!empty($DATA['receivers'])) {
+                               $receivers = explode(';', $mailData['receivers']);
+                       } elseif (!empty($mailData['receivers'])) {
                                // Only one user left
-                               $receiverS = array($DATA['receivers']);
+                               $receivers = array($mailData['receivers']);
                        } else {
                                // No users left
-                               $receiverS = array(0);
+                               $receivers = array(0);
                        }
-                       $dummy = $receiverS;
+                       $temporaryReceivers = $receivers;
 
                        // Now, if we are good little boys and girls Santa Claus left us some user-ids.
                        // We can now send mails to them...
-                       foreach ($receiverS as $key => $userid) {
+                       foreach ($receivers as $key => $userid) {
                                // Lookup user id
-                               //* DEBUG: */ debugOutput('*L:'.__LINE__.'/'.SQL_NUMROWS($result_user).'*');
+                               //* DEBUG: */ debugOutput('*L:'.__LINE__.'/'.sqlNumRows($result_user).'*');
                                if (fetchUserData($userid)) {
-                                       // Do we have a stats entry?
-                                       $result_stats = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_user_stats` WHERE `pool_id`=%s AND `userid`=%s AND timestamp_ordered='%s' LIMIT 1",
-                                               array($DATA['id'], $DATA['sender'], $DATA['timestamp']), __FILE__, __LINE__);
+                                       // Is there a stats entry?
+                                       $result_stats = sqlQueryEscaped("SELECT `id` FROM `{?_MYSQL_PREFIX?}_user_stats` WHERE `pool_id`=%s AND `userid`=%s AND timestamp_ordered='%s' LIMIT 1",
+                                               array($mailData['id'], $mailData['sender_userid'], $mailData['timestamp']), __FILE__, __LINE__);
 
                                        // If there's no stats entry add it!
-                                       //* DEBUG: */ debugOutput('!L:'.__LINE__.'/'.SQL_NUMROWS($result_stats).'!');
-                                       if (SQL_NUMROWS($result_stats) == 0) {
+                                       //* DEBUG: */ debugOutput('!L:'.__LINE__.'/'.sqlNumRows($result_stats).'!');
+                                       if (ifSqlHasZeroNumRows($result_stats)) {
                                                // No entry was found, so we add him!
-                                               SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_stats` (`pool_id` , `userid`, `cat_id`, `payment_id`, `subject`, `url` , `max_rec` , `timestamp_ordered`, `timestamp_sstart`) VALUES ('%s','%s','%s','%s','%s','%s','%s','%s' , UNIX_TIMESTAMP())",
-                                                       array(bigintval($DATA['id']), bigintval($DATA['sender']), bigintval($DATA['cat_id']), bigintval($DATA['payment_id']), $DATA['subject'], $DATA['url'], $DATA['target_send'], bigintval($DATA['timestamp'])), __FILE__, __LINE__);
+                                               sqlQueryEscaped("INSERT INTO
+       `{?_MYSQL_PREFIX?}_user_stats`
+(
+       `pool_id`,
+       `userid`,
+       `cat_id`,
+       `payment_id`,
+       `subject`,
+       `url`,
+       `max_rec`,
+       `timestamp_ordered`,
+       `timestamp_sstart`
+) VALUES (
+       %s,
+       %s,
+       %s,
+       %s,
+       '%s',
+       '%s',
+       %s,
+       %s,
+       UNIX_TIMESTAMP()
+)",
+                                                       array(
+                                                               bigintval($mailData['id']),
+                                                               bigintval($mailData['sender_userid']),
+                                                               bigintval($mailData['cat_id']),
+                                                               bigintval($mailData['payment_id']),
+                                                               $mailData['subject'],
+                                                               $mailData['url'],
+                                                               bigintval($mailData['target_send']),
+                                                               bigintval($mailData['timestamp'])
+                                                       ), __FILE__, __LINE__);
 
                                                // Receive it's id for the links table
-                                               $result_stats = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_user_stats` WHERE `pool_id`=%s AND `userid`=%s AND timestamp_ordered='%s' LIMIT 1",
-                                                       array(bigintval($DATA['id']), bigintval($DATA['sender']), bigintval($DATA['timestamp'])), __FILE__, __LINE__);
+                                               $result_stats = sqlQueryEscaped("SELECT `id` FROM `{?_MYSQL_PREFIX?}_user_stats` WHERE `pool_id`=%s AND `userid`=%s AND timestamp_ordered='%s' LIMIT 1",
+                                                       array(bigintval($mailData['id']), bigintval($mailData['sender_userid']), bigintval($mailData['timestamp'])), __FILE__, __LINE__);
                                        } // END - if
 
-                                       //* DEBUG: */ debugOutput('!L:'.__LINE__.'/'.SQL_NUMROWS($result_stats).'!');
-                                       if (SQL_NUMROWS($result_stats) == 1) {
+                                       //* DEBUG: */ debugOutput('!L:'.__LINE__.'/'.sqlNumRows($result_stats).'!');
+                                       if (sqlNumRows($result_stats) == 1) {
                                                // We got one!
-                                               list($stats_id) = SQL_FETCHROW($result_stats);
+                                               list($stats_id) = sqlFetchRow($result_stats);
+
+                                               // Remove receiver from list
+                                               $status = removeReceiver($temporaryReceivers, $key, bigintval($userid), bigintval($mailData['id']), bigintval($stats_id));
 
-                                               // Mark this user as "spammed" ;-) And place a line for him...
-                                               //* DEBUG: */ debugOutput('?L:'.__LINE__.'/'.$dummy.'/'.$key.'/'.$userid.'('.['sender'].')/'.$DATA['id'].'/'.$stats_id.'?');
-                                               switch (removeReceiver($dummy, $key, bigintval($userid), bigintval($DATA['id']), bigintval($stats_id))) {
+                                               //* DEBUG: */ debugOutput('?L:'.__LINE__.'/'.$temporaryReceivers.'/'.$key.'/'.$userid.'('.['sender_userid'].')/'.$mailData['id'].'/'.$stats_id.'?');
+                                               switch ($status) {
                                                        case 'done':
                                                                // Prepare the mail
-                                                               $DATA['stats_id'] = bigintval($stats_id);
-
-                                                               // Replace text variables
-                                                               foreach ($GLOBALS['replacer'] as $key => $value) {
-                                                                       if (isset($DATA[$key])) $DATA['text'] = str_replace($value, $DATA[$key], $DATA['text']);
-                                                               } // END - if
-
-                                                               // Prepare content
-                                                               $DATA['time']   = getPaymentPoints($DATA['payment_id'], 'time');
-                                                               $DATA['points'] = getPaymentPoints($DATA['payment_id'], 'payment');
+                                                               $mailData['stats_id'] = bigintval($stats_id);
 
                                                                // Load message template
-                                                               $mailText = loadEmailTemplate('normal-mail', $DATA, bigintval($userid));
+                                                               $mailText = loadEmailTemplate('member_user_pool_normal', $mailData, bigintval($userid));
 
                                                                // Send mail away
-                                                               sendEmail(getUserData('email'), $DATA['subject'], $mailText, $HTML);
+                                                               sendEmail(getUserData('userid'), $mailData['subject'], $mailText, $isHtml);
 
                                                                // Count sent mails...
-                                                               SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET emails_sent=emails_sent+1 WHERE `userid`=%s LIMIT 1",
-                                                                       array(bigintval($DATA['sender'])), __FILE__, __LINE__);
+                                                               sqlQueryEscaped("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `emails_sent`=`emails_sent`+1 WHERE `userid`=%s LIMIT 1",
+                                                                       array(bigintval($mailData['sender_userid'])), __FILE__, __LINE__);
 
                                                                if (isExtensionInstalledAndNewer('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",
+                                                                       sqlQueryEscaped("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `emails_received`=`emails_received`+1 WHERE `userid`=%s LIMIT 1",
                                                                                array(bigintval($userid)), __FILE__, __LINE__);
                                                                } // END - if
 
@@ -165,43 +211,46 @@ if (!SQL_HASZERONUMS($result_main)) {
                                                                $GLOBALS['pool_cnt']++;
                                                                //* DEBUG: */ debugOutput('*EXIT/L:'.__LINE__.'/'.$GLOBALS['pool_cnt']);
                                                                break;
-                                               }
-                                       }
 
-                                       // Do we have reached the maximum to send mails? || (getConfig('max_send') >= $GLOBALS['pool_cnt'])
-                                       //* DEBUG: */ debugOutput('*L:'.__LINE__.'/'.$GLOBALS['pool_cnt'].'>='.$DATA['target_send'].'/'.getConfig('max_send').'>='.$GLOBALS['pool_cnt'].'/'.$lastSentId.'!='.$DATA['id'].'*');
-                                       if ((($GLOBALS['pool_cnt'] >= $DATA['target_send'])) && ($lastSentId != $DATA['id'])) {
+                                                       default: // Unknown return type
+                                                               logDebugMessage(__FILE__, __LINE__, 'Unknown status ' . $status . ' detected. pool_id=' . $mailData['id'] . ',sender=' . $mailData['sender_userid'] . ',stats_id=' . $stats_id);
+                                                               break;
+                                               } // END - switch
+                                       } // END - if
+
+                                       // Is there reached the maximum to send mails? || (getMaxSend() >= $GLOBALS['pool_cnt'])
+                                       //* DEBUG: */ debugOutput('*L:'.__LINE__.'/'.$GLOBALS['pool_cnt'].'>='.$mailData['target_send'].'/'.getMaxSend().'>='.$GLOBALS['pool_cnt'].'/'.$lastSentId.'!='.$mailData['id'].'*');
+                                       if ((($GLOBALS['pool_cnt'] >= $mailData['target_send'])) && ($lastSentId != $mailData['id'])) {
                                                // Prepare content
                                                $content = array(
-                                                       'sender_userid' => $DATA['sender'],
-                                                       'cat_id'        => $DATA['cat_id'],
-                                                       'text'          => $DATA['text'],
-                                                       'url'           => $DATA['url'],
-                                                       'expiration'    => createFancyTime(getPaymentPoints($DATA['payment_id'], 'time'))
+                                                       'sender_userid' => $mailData['sender_userid'],
+                                                       'cat_id'        => $mailData['cat_id'],
+                                                       'text'          => $mailData['text'],
+                                                       'url'           => $mailData['url'],
+                                                       'expiration'    => '{%pipe,getPaymentTime,createFancyTime=' . $mailData['payment_id'] . '%}'
                                                );
 
                                                // Yes we do, so we notify admin and sender about fully sent mail!
-                                               sendAdminNotification('{--ADMIN_SEND_DONE_SUBJECT--}', 'done-admin', $content, $userid);
+                                               sendAdminNotification('{--ADMIN_SEND_DONE_SUBJECT--}', 'admin_user_pool_done', $content, $userid);
 
                                                // Get sender's data
-                                               if (fetchUserData($DATA['sender'])) {
+                                               if (fetchUserData($mailData['sender_userid'])) {
                                                        // Load email template
-                                                       $mailText = loadEmailTemplate('done-member', $content, $DATA['sender']);
+                                                       $mailText = loadEmailTemplate('member_user_pool_done', $content, $mailData['sender_userid']);
 
                                                        // Send it also waway
-                                                       sendEmail(getUserData('email'), '{--MEMBER_SEND_DONE_SUBJECT--}', $mailText);
+                                                       sendEmail(getUserData('userid'), '{--MEMBER_SEND_DONE_SUBJECT--}', $mailText);
                                                } // END - if
 
                                                // Set status to SEND because we completely send it away
-                                               SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_pool` SET `data_type`='SEND', `target_send`=0, `receivers`='' WHERE `id`=%s LIMIT 1",
-                                                       array(bigintval($DATA['id'])), __FILE__, __LINE__);
+                                               updatePoolDataById($mailData['id'], NULL, array('data_type' => 'SEND', 'target_send' => '0', 'receivers' => ''));
 
                                                // Update send-completed-time
-                                               SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_stats` SET `timestamp_send`=UNIX_TIMESTAMP() WHERE `pool_id`=%s LIMIT 1",
-                                                       array(bigintval($DATA['id'])), __FILE__, __LINE__);
+                                               sqlQueryEscaped("UPDATE `{?_MYSQL_PREFIX?}_user_stats` SET `timestamp_send`=UNIX_TIMESTAMP() WHERE `pool_id`=%s LIMIT 1",
+                                                       array(bigintval($mailData['id'])), __FILE__, __LINE__);
 
-                                               $lastSentId = $DATA['id']; $GLOBALS['pool_cnt'] = '0';
-                                               $cnt2 += $GLOBALS['pool_cnt'];
+                                               $lastSentId = $mailData['id']; $GLOBALS['pool_cnt'] = '0';
+                                               $count2 += $GLOBALS['pool_cnt'];
 
                                                // Update mediadata if version is 0.0.4 or higher
                                                if (isExtensionInstalledAndNewer('mediadata', '0.0.4')) {
@@ -213,61 +262,55 @@ if (!SQL_HASZERONUMS($result_main)) {
                                                //* DEBUG: */ debugOutput('*EXIT/L:'.__LINE__.'/'.$P);
                                                break;
                                        }
-                                       // Do we have send maximum mails?
-                                       elseif (($GLOBALS['pool_cnt'] >= getConfig('max_send')) || ($cnt2 >= getConfig('max_send'))) {
+                                       // Is there send maximum mails?
+                                       elseif (($GLOBALS['pool_cnt'] >= getMaxSend()) || ($count2 >= getMaxSend())) {
                                                // There are some mails left to send for next round, so we reset the status back to NEW (=still not fully delivered)
                                                $add = '';
-                                               if ($GLOBALS['pool_cnt'] <= $DATA['target_send']) $add = ", target_send=target_send-".$GLOBALS['pool_cnt'];
-                                               SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_pool` SET `data_type`='NEW', receivers='%s'" . $add . " WHERE `id`=%s LIMIT 1",
-                                                       array(
-                                                               implode(';', $dummy),
-                                                               bigintval($DATA['id'])
-                                                       ), __FILE__, __LINE__);
+                                               if ($GLOBALS['pool_cnt'] <= $mailData['target_send']) $add = ',`target_send`=`target_send`-' . $GLOBALS['pool_cnt'];
+                                               updatePoolDataById($mailData['id'], NULL, array('data_type' => 'NEW', 'receivers' => implode(';', $temporaryReceivers)), NULL, '', $add);
 
                                                //* DEBUG: */ debugOutput('*EXIT/L:'.__LINE__.'*');
                                                break;
                                        }
 
                                        // Free result
-                                       SQL_FREERESULT($result_stats);
+                                       sqlFreeResult($result_stats);
                                } else {
                                        // User does not exists so we have add the sender's points back to sender's account
-                                       if (($receiverS['id'] == '0') || (empty($receiverS['id']))) {
+                                       if (($receivers['id'] == '0') || (empty($receivers['id']))) {
                                                // List was empty
-                                               SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_pool` SET `data_type`='SEND' WHERE `id`=%s LIMIT 1",
-                                                       array(bigintval($DATA['id'])), __FILE__, __LINE__);
+                                               updatePoolDataById($mailData['id'], 'data_type', 'SEND');
                                        } else {
                                                // Is the userid set?
-                                               if (isValidUserId($userid)) {
+                                               if (isValidId($userid)) {
                                                        // User does not exists, pay points back
-                                                       $points = getPaymentPoints($DATA['payment_id']);
-                                                       addPointsDirectly('pool_payback', $DATA['sender'], $points);
+                                                       initReferralSystem();
+                                                       addPointsThroughReferralSystem('pool_payback', $mailData['sender_userid'], getPaymentPrice($mailData['payment_id']));
 
                                                        // Add points together and remove user
-                                                       $pointsBack[$DATA['sender']] += $points;
+                                                       $pointsBack[$mailData['sender_userid']] += getPaymentPrice($mailData['payment_id']);
                                                } // END - if
 
                                                // Count up
-                                               $cnt_back[$DATA['sender']]++;
+                                               $count_back[$mailData['sender_userid']]++;
                                        }
 
                                        // Remove entry from list
-                                       unset($dummy[$key]);
+                                       unset($temporaryReceivers[$key]);
 
                                        // Update receivers
-                                       SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_pool` SET `receivers`='%s' WHERE `id`=%s LIMIT 1",
-                                               array(implode(';', $dummy), bigintval($DATA['id'])), __FILE__, __LINE__);
+                                       updatePoolData($mailData['id'], 'receivers', implode(';', $temporaryReceivers));
                                }
                        } // END - foreach
                } // END - if
        } // END - while
 
-       // Do we have points to "pay back"?
-       if ((count($pointsBack) > 0) && (!empty($pointsBack[0]))) {
+       // Is there points to "pay back"?
+       if ((isFilledArray($pointsBack)) && (!empty($pointsBack[0]))) {
                // Walk through all points
                foreach ($pointsBack as $userid => $PB) {
                        // Add points only when we have points left to add and a valid user id
-                       if (($PB > 0) && (isValidUserId($userid))) {
+                       if (($PB > 0) && (isValidId($userid))) {
                                // Prepare content
                                $content = array(
                                        'points' => $PB
@@ -276,16 +319,16 @@ if (!SQL_HASZERONUMS($result_main)) {
                                // We have to pay back some points to the sender (we add them directly :-P)
                                if (fetchUserData($userid)) {
                                        // User account does exists, so we can safely pay back!
-                                       $mailText = loadEmailTemplate('back-member', $content, bigintval($userid));
+                                       $mailText = loadEmailTemplate('member_user_pool_back', $content, bigintval($userid));
 
                                        // Send mail out to member
-                                       sendEmail(getUserData('email'), '{--MEMBER_BACK_JACKPOT--}' . ' (' . $userid . ')', $mailText);
+                                       sendEmail($userid, '{--MEMBER_BACK_JACKPOT--}' . ' (' . $userid . ')', $mailText);
                                } elseif (isExtensionActive('jackpot')) {
                                        // Add to jackpot
                                        addPointsToJackpot($PB);
 
                                        // Send mail out to admin
-                                       sendAdminNotification('{--ADMIN_BACK_JACKPOT--}' . ' (' . $userid . ')', 'back-admin', $content, 'admin');
+                                       sendAdminNotification('{--ADMIN_BACK_JACKPOT--}' . ' (' . $userid . ')', 'admin_user_pool_back', $content, 'admin');
                                }
                        } // END - if
                } // END - foreach
@@ -293,7 +336,7 @@ if (!SQL_HASZERONUMS($result_main)) {
 } // END - if
 
 // Free memory
-SQL_FREERESULT($result_main);
+sqlFreeResult($result_main);
 
 // Remove variable
 unset($mailText);