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