9d8b295dd67c06ba164926f23c3c233dae2a347b
[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 - 2012 by Mailer Developer Team                   *
20  * For more information visit: http://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`,
64         `sender` AS `sender_userid`,
65         `subject`,
66         `text`,
67         `receivers`,
68         `payment_id`,
69         `timestamp`,
70         `url`,
71         `target_send`,
72         `cat_id`
73         ".$HTML."
74 FROM
75         `{?_MYSQL_PREFIX?}_pool`
76 WHERE
77         `data_type`='NEW'
78 ORDER BY
79         `timestamp` DESC", __FILE__, __LINE__);
80
81 // Reset variables
82 $count2 = '0';
83 $lastSentId = '0';
84 $count_back = array(0);
85 $pointsBack = array(0);
86
87 if (!SQL_HASZERONUMS($result_main)) {
88         // Parse all mails
89         while ($mailData = SQL_FETCHARRAY($result_main)) {
90                 // Set mail order as 'active'. That means it will be sent out
91                 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_pool` SET `data_type`='ACTIVE' WHERE `id`=%s AND `data_type`='NEW' LIMIT 1",
92                         array($mailData['id']), __FILE__, __LINE__);
93
94                 // Check fetched data for HTML
95                 $isHtml = 'N';
96                 if (isset($mailData['html_msg'])) $isHtml = $mailData['html_msg'];
97
98                 // Entry updated?
99                 if (!SQL_HASZEROAFFECTED()) {
100                         // "Explode" all receivers into an array
101                         if (isInString(';', $mailData['receivers'])) {
102                                 // There's more than one receiver in the list...
103                                 $receivers = explode(';', $mailData['receivers']);
104                         } elseif (!empty($mailData['receivers'])) {
105                                 // Only one user left
106                                 $receivers = array($mailData['receivers']);
107                         } else {
108                                 // No users left
109                                 $receivers = array(0);
110                         }
111                         $temporaryReceivers = $receivers;
112
113                         // Now, if we are good little boys and girls Santa Claus left us some user-ids.
114                         // We can now send mails to them...
115                         foreach ($receivers as $key => $userid) {
116                                 // Lookup user id
117                                 //* DEBUG: */ debugOutput('*L:'.__LINE__.'/'.SQL_NUMROWS($result_user).'*');
118                                 if (fetchUserData($userid)) {
119                                         // Is there a stats entry?
120                                         $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",
121                                                 array($mailData['id'], $mailData['sender_userid'], $mailData['timestamp']), __FILE__, __LINE__);
122
123                                         // If there's no stats entry add it!
124                                         //* DEBUG: */ debugOutput('!L:'.__LINE__.'/'.SQL_NUMROWS($result_stats).'!');
125                                         if (SQL_HASZERONUMS($result_stats)) {
126                                                 // No entry was found, so we add him!
127                                                 SQL_QUERY_ESC("INSERT INTO
128         `{?_MYSQL_PREFIX?}_user_stats`
129 (
130         `pool_id`,
131         `userid`,
132         `cat_id`,
133         `payment_id`,
134         `subject`,
135         `url`,
136         `max_rec`,
137         `timestamp_ordered`,
138         `timestamp_sstart`
139 ) VALUES (
140         %s,
141         %s,
142         %s,
143         %s,
144         '%s',
145         '%s',
146         %s,
147         %s,
148         UNIX_TIMESTAMP()
149 )",
150                                                         array(
151                                                                 bigintval($mailData['id']),
152                                                                 bigintval($mailData['sender_userid']),
153                                                                 bigintval($mailData['cat_id']),
154                                                                 bigintval($mailData['payment_id']),
155                                                                 $mailData['subject'],
156                                                                 $mailData['url'],
157                                                                 bigintval($mailData['target_send']),
158                                                                 bigintval($mailData['timestamp'])
159                                                         ), __FILE__, __LINE__);
160
161                                                 // Receive it's id for the links table
162                                                 $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",
163                                                         array(bigintval($mailData['id']), bigintval($mailData['sender_userid']), bigintval($mailData['timestamp'])), __FILE__, __LINE__);
164                                         } // END - if
165
166                                         //* DEBUG: */ debugOutput('!L:'.__LINE__.'/'.SQL_NUMROWS($result_stats).'!');
167                                         if (SQL_NUMROWS($result_stats) == 1) {
168                                                 // We got one!
169                                                 list($stats_id) = SQL_FETCHROW($result_stats);
170
171                                                 // Remove receiver from list
172                                                 $status = removeReceiver($temporaryReceivers, $key, bigintval($userid), bigintval($mailData['id']), bigintval($stats_id));
173
174                                                 //* DEBUG: */ debugOutput('?L:'.__LINE__.'/'.$temporaryReceivers.'/'.$key.'/'.$userid.'('.['sender_userid'].')/'.$mailData['id'].'/'.$stats_id.'?');
175                                                 switch ($status) {
176                                                         case 'done':
177                                                                 // Prepare the mail
178                                                                 $mailData['stats_id'] = bigintval($stats_id);
179
180                                                                 // Prepare content
181                                                                 $mailData['time']   = getPaymentData($mailData['payment_id'], 'time');
182                                                                 $mailData['points'] = getPaymentData($mailData['payment_id'], 'payment');
183
184                                                                 // Load message template
185                                                                 $mailText = loadEmailTemplate('member_user_pool_normal', $mailData, bigintval($userid));
186
187                                                                 // Send mail away
188                                                                 sendEmail(getUserData('userid'), $mailData['subject'], $mailText, $isHtml);
189
190                                                                 // Count sent mails...
191                                                                 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `emails_sent`=`emails_sent`+1 WHERE `userid`=%s LIMIT 1",
192                                                                         array(bigintval($mailData['sender_userid'])), __FILE__, __LINE__);
193
194                                                                 if (isExtensionInstalledAndNewer('user', '0.1.4')) {
195                                                                         // Update mails received for receiver
196                                                                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `emails_received`=`emails_received`+1 WHERE `userid`=%s LIMIT 1",
197                                                                                 array(bigintval($userid)), __FILE__, __LINE__);
198                                                                 } // END - if
199
200                                                                 // Update mediadata if version is 0.0.4 or higher
201                                                                 if (isExtensionInstalledAndNewer('mediadata', '0.0.4')) {
202                                                                         // Update entry (or add missing)
203                                                                         //* DEBUG: */ debugOutput('*MEDIA/L:'.__LINE__.'*');
204                                                                         updateMediadataEntry(array('total_send', 'normal_send'), 'add', 1);
205                                                                 } // END - if
206
207                                                                 // And count up the mail
208                                                                 $GLOBALS['pool_cnt']++;
209                                                                 //* DEBUG: */ debugOutput('*EXIT/L:'.__LINE__.'/'.$GLOBALS['pool_cnt'].'*');
210                                                                 break;
211
212                                                         case 'already':
213                                                                 // Entry already found, but we still count one up!
214                                                                 $GLOBALS['pool_cnt']++;
215                                                                 //* DEBUG: */ debugOutput('*EXIT/L:'.__LINE__.'/'.$GLOBALS['pool_cnt']);
216                                                                 break;
217
218                                                         default: // Unknown return type
219                                                                 logDebugMessage(__FILE__, __LINE__, 'Unknown status ' . $status . ' detected. pool_id=' . $mailData['id'] . ',sender=' . $mailData['sender_userid'] . ',stats_id=' . $stats_id);
220                                                                 break;
221                                                 } // END - switch
222                                         } // END - if
223
224                                         // Is there reached the maximum to send mails? || (getConfig('max_send') >= $GLOBALS['pool_cnt'])
225                                         //* DEBUG: */ debugOutput('*L:'.__LINE__.'/'.$GLOBALS['pool_cnt'].'>='.$mailData['target_send'].'/'.getConfig('max_send').'>='.$GLOBALS['pool_cnt'].'/'.$lastSentId.'!='.$mailData['id'].'*');
226                                         if ((($GLOBALS['pool_cnt'] >= $mailData['target_send'])) && ($lastSentId != $mailData['id'])) {
227                                                 // Prepare content
228                                                 $content = array(
229                                                         'sender_userid' => $mailData['sender_userid'],
230                                                         'cat_id'        => $mailData['cat_id'],
231                                                         'text'          => $mailData['text'],
232                                                         'url'           => $mailData['url'],
233                                                         'expiration'    => '{%pipe,createFancyTime=' . getPaymentData($mailData['payment_id'], 'time') . '%}'
234                                                 );
235
236                                                 // Yes we do, so we notify admin and sender about fully sent mail!
237                                                 sendAdminNotification('{--ADMIN_SEND_DONE_SUBJECT--}', 'admin_user_pool_done', $content, $userid);
238
239                                                 // Get sender's data
240                                                 if (fetchUserData($mailData['sender_userid'])) {
241                                                         // Load email template
242                                                         $mailText = loadEmailTemplate('member_user_pool_done', $content, $mailData['sender_userid']);
243
244                                                         // Send it also waway
245                                                         sendEmail(getUserData('userid'), '{--MEMBER_SEND_DONE_SUBJECT--}', $mailText);
246                                                 } // END - if
247
248                                                 // Set status to SEND because we completely send it away
249                                                 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_pool` SET `data_type`='SEND',`target_send`=0,`receivers`='' WHERE `id`=%s LIMIT 1",
250                                                         array(bigintval($mailData['id'])), __FILE__, __LINE__);
251
252                                                 // Update send-completed-time
253                                                 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_stats` SET `timestamp_send`=UNIX_TIMESTAMP() WHERE `pool_id`=%s LIMIT 1",
254                                                         array(bigintval($mailData['id'])), __FILE__, __LINE__);
255
256                                                 $lastSentId = $mailData['id']; $GLOBALS['pool_cnt'] = '0';
257                                                 $count2 += $GLOBALS['pool_cnt'];
258
259                                                 // Update mediadata if version is 0.0.4 or higher
260                                                 if (isExtensionInstalledAndNewer('mediadata', '0.0.4')) {
261                                                         // Update entry (or add missing)
262                                                         //* DEBUG: */ debugOutput('*MEDIA/L:'.__LINE__.'*');
263                                                         updateMediadataEntry(array('total_orders', 'normal_orders'), 'add', 1);
264                                                 } // END - if
265
266                                                 //* DEBUG: */ debugOutput('*EXIT/L:'.__LINE__.'/'.$P);
267                                                 break;
268                                         }
269                                         // Is there send maximum mails?
270                                         elseif (($GLOBALS['pool_cnt'] >= getConfig('max_send')) || ($count2 >= getConfig('max_send'))) {
271                                                 // There are some mails left to send for next round, so we reset the status back to NEW (=still not fully delivered)
272                                                 $add = '';
273                                                 if ($GLOBALS['pool_cnt'] <= $mailData['target_send']) $add = ", target_send=target_send-".$GLOBALS['pool_cnt'];
274                                                 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_pool` SET `data_type`='NEW', receivers='%s'" . $add . " WHERE `id`=%s LIMIT 1",
275                                                         array(
276                                                                 implode(';', $temporaryReceivers),
277                                                                 bigintval($mailData['id'])
278                                                         ), __FILE__, __LINE__);
279
280                                                 //* DEBUG: */ debugOutput('*EXIT/L:'.__LINE__.'*');
281                                                 break;
282                                         }
283
284                                         // Free result
285                                         SQL_FREERESULT($result_stats);
286                                 } else {
287                                         // User does not exists so we have add the sender's points back to sender's account
288                                         if (($receivers['id'] == '0') || (empty($receivers['id']))) {
289                                                 // List was empty
290                                                 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_pool` SET `data_type`='SEND' WHERE `id`=%s LIMIT 1",
291                                                         array(bigintval($mailData['id'])), __FILE__, __LINE__);
292                                         } else {
293                                                 // Is the userid set?
294                                                 if (isValidId($userid)) {
295                                                         // User does not exists, pay points back
296                                                         $points = getPaymentPrice($mailData['payment_id']);
297                                                         initReferralSystem();
298                                                         addPointsThroughReferralSystem('pool_payback', $mailData['sender_userid'], $points);
299
300                                                         // Add points together and remove user
301                                                         $pointsBack[$mailData['sender_userid']] += $points;
302                                                 } // END - if
303
304                                                 // Count up
305                                                 $count_back[$mailData['sender_userid']]++;
306                                         }
307
308                                         // Remove entry from list
309                                         unset($temporaryReceivers[$key]);
310
311                                         // Update receivers
312                                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_pool` SET `receivers`='%s' WHERE `id`=%s LIMIT 1",
313                                                 array(implode(';', $temporaryReceivers), bigintval($mailData['id'])), __FILE__, __LINE__);
314                                 }
315                         } // END - foreach
316                 } // END - if
317         } // END - while
318
319         // Is there points to "pay back"?
320         if ((count($pointsBack) > 0) && (!empty($pointsBack[0]))) {
321                 // Walk through all points
322                 foreach ($pointsBack as $userid => $PB) {
323                         // Add points only when we have points left to add and a valid user id
324                         if (($PB > 0) && (isValidId($userid))) {
325                                 // Prepare content
326                                 $content = array(
327                                         'points' => $PB
328                                 );
329
330                                 // We have to pay back some points to the sender (we add them directly :-P)
331                                 if (fetchUserData($userid)) {
332                                         // User account does exists, so we can safely pay back!
333                                         $mailText = loadEmailTemplate('member_user_pool_back', $content, bigintval($userid));
334
335                                         // Send mail out to member
336                                         sendEmail($userid, '{--MEMBER_BACK_JACKPOT--}' . ' (' . $userid . ')', $mailText);
337                                 } elseif (isExtensionActive('jackpot')) {
338                                         // Add to jackpot
339                                         addPointsToJackpot($PB);
340
341                                         // Send mail out to admin
342                                         sendAdminNotification('{--ADMIN_BACK_JACKPOT--}' . ' (' . $userid . ')', 'admin_user_pool_back', $content, 'admin');
343                                 }
344                         } // END - if
345                 } // END - foreach
346         } // END - if
347 } // END - if
348
349 // Free memory
350 SQL_FREERESULT($result_main);
351
352 // Remove variable
353 unset($mailText);
354
355 // [EOF]
356 ?>