Minor cleanups/renaming
[mailer.git] / inc / pool / pool-user.php
1 <?php
2 /************************************************************************
3  * Mailer v0.2.1-FINAL                                Start: 12/12/2008 *
4  * ===================                          Last change: 12/12/2008 *
5  *                                                                      *
6  * -------------------------------------------------------------------- *
7  * File              : pool-user.php                                    *
8  * -------------------------------------------------------------------- *
9  * Short description : Sends queued user mails from the pool            *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Sendet freigegebene Mitglieder-Mails aus Pool    *
12  * -------------------------------------------------------------------- *
13  * $Revision::                                                        $ *
14  * $Date::                                                            $ *
15  * $Tag:: 0.2.1-FINAL                                                 $ *
16  * $Author::                                                          $ *
17  * -------------------------------------------------------------------- *
18  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
19  * Copyright (c) 2009 - 2011 by Mailer Developer Team                   *
20  * For more information visit: http://www.mxchange.org                  *
21  *                                                                      *
22  * This program is free software; you can redistribute it and/or modify *
23  * it under the terms of the GNU General Public License as published by *
24  * the Free Software Foundation; either version 2 of the License, or    *
25  * (at your option) any later version.                                  *
26  *                                                                      *
27  * This program is distributed in the hope that it will be useful,      *
28  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
29  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
30  * GNU General Public License for more details.                         *
31  *                                                                      *
32  * You should have received a copy of the GNU General Public License    *
33  * along with this program; if not, write to the Free Software          *
34  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
35  * MA  02110-1301  USA                                                  *
36  ************************************************************************/
37
38 // Some security stuff...
39 if (!defined('__SECURITY')) {
40         die();
41 } // END - if
42
43 // Don't run on daily reset
44 if ((isResetModeEnabled()) || (!isHtmlOutputMode())) {
45         // Skip here
46         return false;
47 } elseif (!isExtensionActive('user')) {
48         // Abort here if extension user is not active
49         return false;
50 }
51
52 // No HTML is default
53 $HTML = '';
54
55 // Check for freed mail orders to send out
56 if (isExtensionActive('html_mail')) {
57         // With HTML mails
58         $HTML = ', `html_msg`';
59 } // END - if
60
61 // Main query
62 $result_main = SQL_QUERY("SELECT
63         `id`, `sender` AS `sender_userid`, `subject`, `text`, `receivers`,
64         `payment_id`, `timestamp`, `url`, `target_send`, `cat_id`
65         ".$HTML."
66 FROM
67         `{?_MYSQL_PREFIX?}_pool`
68 WHERE
69         `data_type`='NEW'
70 ORDER BY
71         `timestamp` DESC", __FILE__, __LINE__);
72
73 // Reset variables
74 $count2 = '0';
75 $lastSentId = '0';
76 $count_back = array(0);
77 $pointsBack = array(0);
78
79 if (!SQL_HASZERONUMS($result_main)) {
80         // Parse all mails
81         while ($mailData = SQL_FETCHARRAY($result_main, 0, false)) {
82                 // Set mail order as 'active'. That means it will be sent out
83                 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_pool` SET `data_type`='ACTIVE' WHERE `id`=%s AND `data_type`='NEW' LIMIT 1",
84                         array($mailData['id']), __FILE__, __LINE__);
85
86                 // Check fetched data for HTML
87                 $isHtml = 'N';
88                 if (isset($mailData['html_msg'])) $isHtml = $mailData['html_msg'];
89
90                 // Entry updated?
91                 if (!SQL_HASZEROAFFECTED()) {
92                         // "Explode" all receivers into an array
93                         if (isInString(';', $mailData['receivers'])) {
94                                 // There's more than one receiver in the list...
95                                 $receivers = explode(';', $mailData['receivers']);
96                         } elseif (!empty($mailData['receivers'])) {
97                                 // Only one user left
98                                 $receivers = array($mailData['receivers']);
99                         } else {
100                                 // No users left
101                                 $receivers = array(0);
102                         }
103                         $dummy = $receivers;
104
105                         // Now, if we are good little boys and girls Santa Claus left us some user-ids.
106                         // We can now send mails to them...
107                         foreach ($receivers as $key => $userid) {
108                                 // Lookup user id
109                                 //* DEBUG: */ debugOutput('*L:'.__LINE__.'/'.SQL_NUMROWS($result_user).'*');
110                                 if (fetchUserData($userid)) {
111                                         // Do we have a stats entry?
112                                         $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",
113                                                 array($mailData['id'], $mailData['sender_userid'], $mailData['timestamp']), __FILE__, __LINE__);
114
115                                         // If there's no stats entry add it!
116                                         //* DEBUG: */ debugOutput('!L:'.__LINE__.'/'.SQL_NUMROWS($result_stats).'!');
117                                         if (SQL_HASZERONUMS($result_stats)) {
118                                                 // No entry was found, so we add him!
119                                                 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())",
120                                                         array(bigintval($mailData['id']), bigintval($mailData['sender_userid']), bigintval($mailData['cat_id']), bigintval($mailData['payment_id']), $mailData['subject'], $mailData['url'], $mailData['target_send'], bigintval($mailData['timestamp'])), __FILE__, __LINE__);
121
122                                                 // Receive it's id for the links table
123                                                 $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",
124                                                         array(bigintval($mailData['id']), bigintval($mailData['sender_userid']), bigintval($mailData['timestamp'])), __FILE__, __LINE__);
125                                         } // END - if
126
127                                         //* DEBUG: */ debugOutput('!L:'.__LINE__.'/'.SQL_NUMROWS($result_stats).'!');
128                                         if (SQL_NUMROWS($result_stats) == 1) {
129                                                 // We got one!
130                                                 list($stats_id) = SQL_FETCHROW($result_stats);
131
132                                                 // Remove receiver from list
133                                                 $status = removeReceiver($dummy, $key, bigintval($userid), bigintval($mailData['id']), bigintval($stats_id));
134
135                                                 //* DEBUG: */ debugOutput('?L:'.__LINE__.'/'.$dummy.'/'.$key.'/'.$userid.'('.['sender_userid'].')/'.$mailData['id'].'/'.$stats_id.'?');
136                                                 switch ($status) {
137                                                         case 'done':
138                                                                 // Prepare the mail
139                                                                 $mailData['stats_id'] = bigintval($stats_id);
140
141                                                                 // Prepare content
142                                                                 $mailData['time']   = getPaymentPoints($mailData['payment_id'], 'time');
143                                                                 $mailData['points'] = getPaymentPoints($mailData['payment_id'], 'payment');
144
145                                                                 // Load message template
146                                                                 $mailText = loadEmailTemplate('member_user_pool_normal', $mailData, bigintval($userid));
147
148                                                                 // Send mail away
149                                                                 sendEmail(getUserData('userid'), $mailData['subject'], $mailText, $isHtml);
150
151                                                                 // Count sent mails...
152                                                                 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `emails_sent`=`emails_sent`+1 WHERE `userid`=%s LIMIT 1",
153                                                                         array(bigintval($mailData['sender_userid'])), __FILE__, __LINE__);
154
155                                                                 if (isExtensionInstalledAndNewer('user', '0.1.4')) {
156                                                                         // Update mails received for receiver
157                                                                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `emails_received`=`emails_received`+1 WHERE `userid`=%s LIMIT 1",
158                                                                                 array(bigintval($userid)), __FILE__, __LINE__);
159                                                                 } // END - if
160
161                                                                 // Update mediadata if version is 0.0.4 or higher
162                                                                 if (isExtensionInstalledAndNewer('mediadata', '0.0.4')) {
163                                                                         // Update entry (or add missing)
164                                                                         //* DEBUG: */ debugOutput('*MEDIA/L:'.__LINE__.'*');
165                                                                         updateMediadataEntry(array('total_send', 'normal_send'), 'add', 1);
166                                                                 } // END - if
167
168                                                                 // And count up the mail
169                                                                 $GLOBALS['pool_cnt']++;
170                                                                 //* DEBUG: */ debugOutput('*EXIT/L:'.__LINE__.'/'.$GLOBALS['pool_cnt'].'*');
171                                                                 break;
172
173                                                         case 'already':
174                                                                 // Entry already found, but we still count one up!
175                                                                 $GLOBALS['pool_cnt']++;
176                                                                 //* DEBUG: */ debugOutput('*EXIT/L:'.__LINE__.'/'.$GLOBALS['pool_cnt']);
177                                                                 break;
178
179                                                         default: // Unknown return type
180                                                                 logDebugMessage(__FILE__, __LINE__, 'Unknown status ' . $status . ' detected. pool_id=' . $mailData['id'] . ',sender=' . $mailData['sender_userid'] . ',stats_id=' . $stats_id);
181                                                                 break;
182                                                 } // END - switch
183                                         } // END - if
184
185                                         // Do we have reached the maximum to send mails? || (getConfig('max_send') >= $GLOBALS['pool_cnt'])
186                                         //* DEBUG: */ debugOutput('*L:'.__LINE__.'/'.$GLOBALS['pool_cnt'].'>='.$mailData['target_send'].'/'.getConfig('max_send').'>='.$GLOBALS['pool_cnt'].'/'.$lastSentId.'!='.$mailData['id'].'*');
187                                         if ((($GLOBALS['pool_cnt'] >= $mailData['target_send'])) && ($lastSentId != $mailData['id'])) {
188                                                 // Prepare content
189                                                 $content = array(
190                                                         'sender_userid' => $mailData['sender_userid'],
191                                                         'cat_id'        => $mailData['cat_id'],
192                                                         'text'          => $mailData['text'],
193                                                         'url'           => $mailData['url'],
194                                                         'expiration'    => '{%pipe,createFancyTime=' . getPaymentPoints($mailData['payment_id'], 'time') . '%}'
195                                                 );
196
197                                                 // Yes we do, so we notify admin and sender about fully sent mail!
198                                                 sendAdminNotification('{--ADMIN_SEND_DONE_SUBJECT--}', 'admin_user_pool_done', $content, $userid);
199
200                                                 // Get sender's data
201                                                 if (fetchUserData($mailData['sender_userid'])) {
202                                                         // Load email template
203                                                         $mailText = loadEmailTemplate('member_user_pool_done', $content, $mailData['sender_userid']);
204
205                                                         // Send it also waway
206                                                         sendEmail(getUserData('userid'), '{--MEMBER_SEND_DONE_SUBJECT--}', $mailText);
207                                                 } // END - if
208
209                                                 // Set status to SEND because we completely send it away
210                                                 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_pool` SET `data_type`='SEND', `target_send`=0, `receivers`='' WHERE `id`=%s LIMIT 1",
211                                                         array(bigintval($mailData['id'])), __FILE__, __LINE__);
212
213                                                 // Update send-completed-time
214                                                 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_stats` SET `timestamp_send`=UNIX_TIMESTAMP() WHERE `pool_id`=%s LIMIT 1",
215                                                         array(bigintval($mailData['id'])), __FILE__, __LINE__);
216
217                                                 $lastSentId = $mailData['id']; $GLOBALS['pool_cnt'] = '0';
218                                                 $count2 += $GLOBALS['pool_cnt'];
219
220                                                 // Update mediadata if version is 0.0.4 or higher
221                                                 if (isExtensionInstalledAndNewer('mediadata', '0.0.4')) {
222                                                         // Update entry (or add missing)
223                                                         //* DEBUG: */ debugOutput('*MEDIA/L:'.__LINE__.'*');
224                                                         updateMediadataEntry(array('total_orders', 'normal_orders'), 'add', 1);
225                                                 } // END - if
226
227                                                 //* DEBUG: */ debugOutput('*EXIT/L:'.__LINE__.'/'.$P);
228                                                 break;
229                                         }
230                                         // Do we have send maximum mails?
231                                         elseif (($GLOBALS['pool_cnt'] >= getConfig('max_send')) || ($count2 >= getConfig('max_send'))) {
232                                                 // There are some mails left to send for next round, so we reset the status back to NEW (=still not fully delivered)
233                                                 $add = '';
234                                                 if ($GLOBALS['pool_cnt'] <= $mailData['target_send']) $add = ", target_send=target_send-".$GLOBALS['pool_cnt'];
235                                                 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_pool` SET `data_type`='NEW', receivers='%s'" . $add . " WHERE `id`=%s LIMIT 1",
236                                                         array(
237                                                                 implode(';', $dummy),
238                                                                 bigintval($mailData['id'])
239                                                         ), __FILE__, __LINE__);
240
241                                                 //* DEBUG: */ debugOutput('*EXIT/L:'.__LINE__.'*');
242                                                 break;
243                                         }
244
245                                         // Free result
246                                         SQL_FREERESULT($result_stats);
247                                 } else {
248                                         // User does not exists so we have add the sender's points back to sender's account
249                                         if (($receivers['id'] == '0') || (empty($receivers['id']))) {
250                                                 // List was empty
251                                                 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_pool` SET `data_type`='SEND' WHERE `id`=%s LIMIT 1",
252                                                         array(bigintval($mailData['id'])), __FILE__, __LINE__);
253                                         } else {
254                                                 // Is the userid set?
255                                                 if (isValidUserId($userid)) {
256                                                         // User does not exists, pay points back
257                                                         $points = getPaymentPoints($mailData['payment_id']);
258                                                         addPointsThroughReferalSystem('pool_payback', $mailData['sender_userid'], $points);
259
260                                                         // Add points together and remove user
261                                                         $pointsBack[$mailData['sender_userid']] += $points;
262                                                 } // END - if
263
264                                                 // Count up
265                                                 $count_back[$mailData['sender_userid']]++;
266                                         }
267
268                                         // Remove entry from list
269                                         unset($dummy[$key]);
270
271                                         // Update receivers
272                                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_pool` SET `receivers`='%s' WHERE `id`=%s LIMIT 1",
273                                                 array(implode(';', $dummy), bigintval($mailData['id'])), __FILE__, __LINE__);
274                                 }
275                         } // END - foreach
276                 } // END - if
277         } // END - while
278
279         // Do we have points to "pay back"?
280         if ((count($pointsBack) > 0) && (!empty($pointsBack[0]))) {
281                 // Walk through all points
282                 foreach ($pointsBack as $userid => $PB) {
283                         // Add points only when we have points left to add and a valid user id
284                         if (($PB > 0) && (isValidUserId($userid))) {
285                                 // Prepare content
286                                 $content = array(
287                                         'points' => $PB
288                                 );
289
290                                 // We have to pay back some points to the sender (we add them directly :-P)
291                                 if (fetchUserData($userid)) {
292                                         // User account does exists, so we can safely pay back!
293                                         $mailText = loadEmailTemplate('member_user_pool_back', $content, bigintval($userid));
294
295                                         // Send mail out to member
296                                         sendEmail($userid, '{--MEMBER_BACK_JACKPOT--}' . ' (' . $userid . ')', $mailText);
297                                 } elseif (isExtensionActive('jackpot')) {
298                                         // Add to jackpot
299                                         addPointsToJackpot($PB);
300
301                                         // Send mail out to admin
302                                         sendAdminNotification('{--ADMIN_BACK_JACKPOT--}' . ' (' . $userid . ')', 'admin_user_pool_back', $content, 'admin');
303                                 }
304                         } // END - if
305                 } // END - foreach
306         } // END - if
307 } // END - if
308
309 // Free memory
310 SQL_FREERESULT($result_main);
311
312 // Remove variable
313 unset($mailText);
314
315 // [EOF]
316 ?>