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