Even more rewrites/fixes from EL branch (please report any broken part after you...
[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: */ outputHtml("*L:".__LINE__.'/'.SQL_NUMROWS($result_user)."*<br />");
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: */ outputHtml("!L:".__LINE__.'/'.SQL_NUMROWS($result_stats)."!<br />");
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: */ outputHtml("!L:".__LINE__.'/'.SQL_NUMROWS($result_stats)."!<br />");
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: */ outputHtml("?L:".__LINE__.'/'.$dummy.'/'.$key.'/'.$userid.'('.['sender'].")/".$DATA['id'].'/'.$stats_id."?<br />");
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                                                                 $DATA['surname']  = getUserData('surname');
126                                                                 $DATA['family']   = getUserData('family');
127                                                                 $DATA['gender']   = translateGender(getUserData('gender'));
128
129                                                                 // Replace text variables
130                                                                 foreach ($GLOBALS['replacer'] as $key => $value) {
131                                                                         if (isset($DATA[$key])) $DATA['text'] = str_replace($value, $DATA[$key], $DATA['text']);
132                                                                 } // END - if
133
134                                                                 // Prepare content
135                                                                 $content = array(
136                                                                         'id'            => $DATA['stats_id'],
137                                                                         'url'           => $DATA['url'],
138                                                                         'sender_userid' => $DATA['sender'],
139                                                                         'category'      => getCategory($DATA['cat_id']),
140                                                                         'time'          => createFancyTime(getPaymentPoints($DATA['payment_id'], 'time')),
141                                                                         'points'        => translateComma(getPaymentPoints($DATA['payment_id'], 'payment')),
142                                                                         'text'          => $DATA['text']
143                                                                 );
144
145                                                                 // Load message template
146                                                                 $mailText = loadEmailTemplate('normal-mail', $content, bigintval($userid));
147
148                                                                 // Send mail away
149                                                                 sendEmail(getUserData('email'), $DATA['subject'], $mailText, $HTML);
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($DATA['sender'])), __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: */ outputHtml("*MEDIA/L:".__LINE__."*<br />");
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: */ outputHtml("*EXIT/L:".__LINE__.'/'.$GLOBALS['pool_cnt']."*<br />");
171                                                                 break;
172
173                                                         case 'already':
174                                                                 // Entry already found, but we still count one up!
175                                                                 $GLOBALS['pool_cnt']++;
176                                                                 //* DEBUG: */ outputHtml("*EXIT/L:".__LINE__.'/'.$GLOBALS['pool_cnt']."<br />");
177                                                                 break;
178                                                 }
179                                         }
180
181                                         // Do we have reached the maximum to send mails? || (getConfig('max_send') >= $GLOBALS['pool_cnt'])
182                                         //* DEBUG: */ outputHtml("*L:".__LINE__.'/'.$GLOBALS['pool_cnt'].">=".$DATA['target_send'].'/'.getConfig('max_send').">=".$GLOBALS['pool_cnt'].'/'.$lastSentId."!=".$DATA['id']."*<br />");
183                                         if ((($GLOBALS['pool_cnt'] >= $DATA['target_send'])) && ($lastSentId != $DATA['id'])) {
184                                                 // Prepare content
185                                                 $content = array(
186                                                         'sender_userid' => $DATA['sender'],
187                                                         'category'      => getCategory($DATA['cat_id']),
188                                                         'text'          => $DATA['text'],
189                                                         'url'           => $DATA['url'],
190                                                         'expiration'    => createFancyTime(getPaymentPoints($DATA['payment_id'], "time"))
191                                                 );
192
193                                                 // Yes we do, so we notify admin and sender about fully sent mail!
194                                                 sendAdminNotification(getMessage('ADMIN_SUBJ_SEND_DONE'), 'done-admin', $content, $userid);
195
196                                                 // Get sender's data
197                                                 if (fetchUserData($DATA['sender'])) {
198                                                         // Load email template
199                                                         $mailText = loadEmailTemplate('done-member', $content, $DATA['sender']);
200
201                                                         // Send it also waway
202                                                         sendEmail(getUserData('email'), getMessage('MEMBER_SUBJ_SEND_DONE'), $mailText);
203                                                 } // END - if
204
205                                                 // Set status to SEND because we completely send it away
206                                                 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_pool` SET `data_type`='SEND', `target_send`=0, `receivers`='' WHERE `id`=%s LIMIT 1",
207                                                         array(bigintval($DATA['id'])), __FILE__, __LINE__);
208
209                                                 // Update send-completed-time
210                                                 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_stats` SET `timestamp_send`=UNIX_TIMESTAMP() WHERE `pool_id`=%s LIMIT 1",
211                                                         array(bigintval($DATA['id'])), __FILE__, __LINE__);
212
213                                                 $lastSentId = $DATA['id']; $GLOBALS['pool_cnt'] = '0';
214                                                 $cnt2 += $GLOBALS['pool_cnt'];
215
216                                                 // Update mediadata if version is 0.0.4 or higher
217                                                 if (isExtensionInstalledAndNewer('mediadata', '0.0.4')) {
218                                                         // Update entry (or add missing)
219                                                         //* DEBUG: */ outputHtml("*MEDIA/L:".__LINE__."*<br />");
220                                                         updateMediadataEntry(array('total_orders', 'normal_orders'), 'add', 1);
221                                                 } // END - if
222
223                                                 //* DEBUG: */ outputHtml("*EXIT/L:".__LINE__.'/'.$P."<br />");
224                                                 break;
225                                         }
226                                         // Do we have send maximum mails?
227                                         elseif (($GLOBALS['pool_cnt'] >= getConfig('max_send')) || ($cnt2 >= getConfig('max_send'))) {
228                                                 // There are some mails left to send for next round, so we reset the status back to NEW (=still not fully delivered)
229                                                 $add = '';
230                                                 if ($GLOBALS['pool_cnt'] <= $DATA['target_send']) $add = ", target_send=target_send-".$GLOBALS['pool_cnt'];
231                                                 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_pool` SET `data_type`='NEW', receivers='%s'" . $add . " WHERE `id`=%s LIMIT 1",
232                                                         array(
233                                                                 implode(';', $dummy),
234                                                                 bigintval($DATA['id'])
235                                                         ), __FILE__, __LINE__);
236
237                                                 //* DEBUG: */ outputHtml("*EXIT/L:".__LINE__."*<br />");
238                                                 break;
239                                         }
240
241                                         // Free result
242                                         SQL_FREERESULT($result_stats);
243                                 } else {
244                                         // User does not exists so we have add the sender's points back to sender's account
245                                         if (($receiverS['id'] == '0') || (empty($receiverS['id']))) {
246                                                 // List was empty
247                                                 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_pool` SET `data_type`='SEND' WHERE `id`=%s LIMIT 1",
248                                                         array(bigintval($DATA['id'])), __FILE__, __LINE__);
249                                         } else {
250                                                 // Is the userid set?
251                                                 if ($userid > 0) {
252                                                         // User does not exists, pay points back
253                                                         $points = getPaymentPoints($DATA['payment_id']);
254                                                         addPointsDirectly('pool_payback', $DATA['sender'], $points);
255
256                                                         // Add points together and remove user
257                                                         $pointsBack[$DATA['sender']] += $points;
258                                                 } // END - if
259
260                                                 // Count up
261                                                 $cnt_back[$DATA['sender']]++;
262                                         }
263
264                                         // Remove entry from list
265                                         unset($dummy[$key]);
266
267                                         // Update receivers
268                                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_pool` SET `receivers`='%s' WHERE `id`=%s LIMIT 1",
269                                                 array(implode(';', $dummy), bigintval($DATA['id'])), __FILE__, __LINE__);
270                                 }
271                         }
272                 }
273         }
274
275         // Do we have points to "pay back"?
276         if ((count($pointsBack) > 0) && (!empty($pointsBack[0]))) {
277                 // Walk through all points
278                 foreach ($pointsBack as $userid => $PB) {
279                         // Add points only when we have points left to add and a valid user id
280                         if (($PB > 0) && ($userid > 0)) {
281                                 // Prepare content
282                                 $content = array(
283                                         'points' => translateComma($PB)
284                                 );
285
286                                 // We have to pay back some points to the sender (we add them directly :-P)
287                                 if (fetchUserData($userid)) {
288                                         // User account does exists, so we can safely pay back!
289                                         $mailText = loadEmailTemplate('back-member', $content, bigintval($userid));
290
291                                         // Send mail out to member
292                                         sendEmail(getUserData('email'), getMessage('MEMBER_BACK_JACKPOT') . ' (' . $userid . ')', $mailText);
293                                 } elseif (isExtensionActive('jackpot')) {
294                                         // Add to jackpot
295                                         addPointsToJackpot($PB);
296
297                                         // Send mail out to admin
298                                         sendAdminNotification(getMessage('ADMIN_BACK_JACKPOT') . ' (' . $userid . ')', 'back-admin', $content, 'admin');
299                                 }
300                         } // END - if
301                 } // END - foreach
302         } // END - if
303 }
304
305 // Free memory
306 SQL_FREERESULT($result_main);
307
308 // Remove variable
309 unset($mailText);
310
311 //
312 ?>