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