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