5293a5b28a1ae8b0fe4e44a8d255acbe951b2164
[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, 2010 by Mailer Developer Team                    *
20  * For more information visit: http://www.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()) {
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 // Need this here
53 // Check for freed mail orders to send out
54 if (isExtensionActive('html_mail')) {
55         //                                0     1        2      3       4          5            6      7        8          9       10
56         $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__);
57 } else {
58         //                                0     1        2      3       4          5            6      7        8          9    10
59         $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__);
60 }
61
62 // Reset variables
63 $count2 = '0'; $lastSentId = '0'; $count_back = array(0); $pointsBack = array(0);
64 if (!SQL_HASZERONUMS($result_main)) {
65         // Parse all mails
66         while ($DATA = SQL_FETCHARRAY($result_main, 0, false)) {
67                 // Set mail order as 'active'. That means it will be sent out
68                 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_pool` SET `data_type`='ACTIVE' WHERE `id`=%s AND `data_type`='NEW' LIMIT 1",
69                         array($DATA['id']), __FILE__, __LINE__);
70
71                 // Check fetched data for HTML
72                 $HTML = 'N';
73                 if (isset($DATA['html_msg'])) $HTML = $DATA['html_msg'];
74
75                 // Entry updated?
76                 if (!SQL_HASZEROAFFECTED()) {
77                         // "Explode" all receivers into an array
78                         if (isInString(';', $DATA['receivers'])) {
79                                 // There's more than one receiver in the list...
80                                 $receiverS = explode(';', $DATA['receivers']);
81                         } elseif (!empty($DATA['receivers'])) {
82                                 // Only one user left
83                                 $receiverS = array($DATA['receivers']);
84                         } else {
85                                 // No users left
86                                 $receiverS = array(0);
87                         }
88                         $dummy = $receiverS;
89
90                         // Now, if we are good little boys and girls Santa Claus left us some user-ids.
91                         // We can now send mails to them...
92                         foreach ($receiverS as $key => $userid) {
93                                 // Lookup user id
94                                 //* DEBUG: */ debugOutput('*L:'.__LINE__.'/'.SQL_NUMROWS($result_user).'*');
95                                 if (fetchUserData($userid)) {
96                                         // Do we have a stats entry?
97                                         $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",
98                                                 array($DATA['id'], $DATA['sender'], $DATA['timestamp']), __FILE__, __LINE__);
99
100                                         // If there's no stats entry add it!
101                                         //* DEBUG: */ debugOutput('!L:'.__LINE__.'/'.SQL_NUMROWS($result_stats).'!');
102                                         if (SQL_HASZERONUMS($result_stats)) {
103                                                 // No entry was found, so we add him!
104                                                 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())",
105                                                         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__);
106
107                                                 // Receive it's id for the links table
108                                                 $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",
109                                                         array(bigintval($DATA['id']), bigintval($DATA['sender']), bigintval($DATA['timestamp'])), __FILE__, __LINE__);
110                                         } // END - if
111
112                                         //* DEBUG: */ debugOutput('!L:'.__LINE__.'/'.SQL_NUMROWS($result_stats).'!');
113                                         if (SQL_NUMROWS($result_stats) == 1) {
114                                                 // We got one!
115                                                 list($stats_id) = SQL_FETCHROW($result_stats);
116
117                                                 // Mark this user as "spammed" ;-) And place a line for him...
118                                                 //* DEBUG: */ debugOutput('?L:'.__LINE__.'/'.$dummy.'/'.$key.'/'.$userid.'('.['sender'].')/'.$DATA['id'].'/'.$stats_id.'?');
119                                                 switch (removeReceiver($dummy, $key, bigintval($userid), bigintval($DATA['id']), bigintval($stats_id))) {
120                                                         case 'done':
121                                                                 // Prepare the mail
122                                                                 $DATA['stats_id'] = bigintval($stats_id);
123
124                                                                 // Prepare content
125                                                                 $DATA['time']   = getPaymentPoints($DATA['payment_id'], 'time');
126                                                                 $DATA['points'] = getPaymentPoints($DATA['payment_id'], 'payment');
127
128                                                                 // Load message template
129                                                                 $mailText = loadEmailTemplate('normal-mail', $DATA, bigintval($userid));
130
131                                                                 // Send mail away
132                                                                 sendEmail(getUserData('email'), $DATA['subject'], $mailText, $HTML);
133
134                                                                 // Count sent mails...
135                                                                 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET emails_sent=emails_sent+1 WHERE `userid`=%s LIMIT 1",
136                                                                         array(bigintval($DATA['sender'])), __FILE__, __LINE__);
137
138                                                                 if (isExtensionInstalledAndNewer('user', '0.1.4')) {
139                                                                         // Update mails received for receiver
140                                                                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `emails_received`=`emails_received`+1 WHERE `userid`=%s LIMIT 1",
141                                                                                 array(bigintval($userid)), __FILE__, __LINE__);
142                                                                 } // END - if
143
144                                                                 // Update mediadata if version is 0.0.4 or higher
145                                                                 if (isExtensionInstalledAndNewer('mediadata', '0.0.4')) {
146                                                                         // Update entry (or add missing)
147                                                                         //* DEBUG: */ debugOutput('*MEDIA/L:'.__LINE__.'*');
148                                                                         updateMediadataEntry(array('total_send', 'normal_send'), 'add', 1);
149                                                                 } // END - if
150
151                                                                 // And count up the mail
152                                                                 $GLOBALS['pool_cnt']++;
153                                                                 //* DEBUG: */ debugOutput('*EXIT/L:'.__LINE__.'/'.$GLOBALS['pool_cnt'].'*');
154                                                                 break;
155
156                                                         case 'already':
157                                                                 // Entry already found, but we still count one up!
158                                                                 $GLOBALS['pool_cnt']++;
159                                                                 //* DEBUG: */ debugOutput('*EXIT/L:'.__LINE__.'/'.$GLOBALS['pool_cnt']);
160                                                                 break;
161                                                 }
162                                         }
163
164                                         // Do we have reached the maximum to send mails? || (getConfig('max_send') >= $GLOBALS['pool_cnt'])
165                                         //* DEBUG: */ debugOutput('*L:'.__LINE__.'/'.$GLOBALS['pool_cnt'].'>='.$DATA['target_send'].'/'.getConfig('max_send').'>='.$GLOBALS['pool_cnt'].'/'.$lastSentId.'!='.$DATA['id'].'*');
166                                         if ((($GLOBALS['pool_cnt'] >= $DATA['target_send'])) && ($lastSentId != $DATA['id'])) {
167                                                 // Prepare content
168                                                 $content = array(
169                                                         'sender_userid' => $DATA['sender'],
170                                                         'cat_id'        => $DATA['cat_id'],
171                                                         'text'          => $DATA['text'],
172                                                         'url'           => $DATA['url'],
173                                                         'expiration'    => '{%pipe,createFancyTime=' . getPaymentPoints($DATA['payment_id'], 'time') . '%}'
174                                                 );
175
176                                                 // Yes we do, so we notify admin and sender about fully sent mail!
177                                                 sendAdminNotification('{--ADMIN_SEND_DONE_SUBJECT--}', 'done-admin', $content, $userid);
178
179                                                 // Get sender's data
180                                                 if (fetchUserData($DATA['sender'])) {
181                                                         // Load email template
182                                                         $mailText = loadEmailTemplate('done-member', $content, $DATA['sender']);
183
184                                                         // Send it also waway
185                                                         sendEmail(getUserData('email'), '{--MEMBER_SEND_DONE_SUBJECT--}', $mailText);
186                                                 } // END - if
187
188                                                 // Set status to SEND because we completely send it away
189                                                 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_pool` SET `data_type`='SEND', `target_send`=0, `receivers`='' WHERE `id`=%s LIMIT 1",
190                                                         array(bigintval($DATA['id'])), __FILE__, __LINE__);
191
192                                                 // Update send-completed-time
193                                                 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_stats` SET `timestamp_send`=UNIX_TIMESTAMP() WHERE `pool_id`=%s LIMIT 1",
194                                                         array(bigintval($DATA['id'])), __FILE__, __LINE__);
195
196                                                 $lastSentId = $DATA['id']; $GLOBALS['pool_cnt'] = '0';
197                                                 $count2 += $GLOBALS['pool_cnt'];
198
199                                                 // Update mediadata if version is 0.0.4 or higher
200                                                 if (isExtensionInstalledAndNewer('mediadata', '0.0.4')) {
201                                                         // Update entry (or add missing)
202                                                         //* DEBUG: */ debugOutput('*MEDIA/L:'.__LINE__.'*');
203                                                         updateMediadataEntry(array('total_orders', 'normal_orders'), 'add', 1);
204                                                 } // END - if
205
206                                                 //* DEBUG: */ debugOutput('*EXIT/L:'.__LINE__.'/'.$P);
207                                                 break;
208                                         }
209                                         // Do we have send maximum mails?
210                                         elseif (($GLOBALS['pool_cnt'] >= getConfig('max_send')) || ($count2 >= getConfig('max_send'))) {
211                                                 // There are some mails left to send for next round, so we reset the status back to NEW (=still not fully delivered)
212                                                 $add = '';
213                                                 if ($GLOBALS['pool_cnt'] <= $DATA['target_send']) $add = ", target_send=target_send-".$GLOBALS['pool_cnt'];
214                                                 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_pool` SET `data_type`='NEW', receivers='%s'" . $add . " WHERE `id`=%s LIMIT 1",
215                                                         array(
216                                                                 implode(';', $dummy),
217                                                                 bigintval($DATA['id'])
218                                                         ), __FILE__, __LINE__);
219
220                                                 //* DEBUG: */ debugOutput('*EXIT/L:'.__LINE__.'*');
221                                                 break;
222                                         }
223
224                                         // Free result
225                                         SQL_FREERESULT($result_stats);
226                                 } else {
227                                         // User does not exists so we have add the sender's points back to sender's account
228                                         if (($receiverS['id'] == '0') || (empty($receiverS['id']))) {
229                                                 // List was empty
230                                                 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_pool` SET `data_type`='SEND' WHERE `id`=%s LIMIT 1",
231                                                         array(bigintval($DATA['id'])), __FILE__, __LINE__);
232                                         } else {
233                                                 // Is the userid set?
234                                                 if (isValidUserId($userid)) {
235                                                         // User does not exists, pay points back
236                                                         $points = getPaymentPoints($DATA['payment_id']);
237                                                         addPointsDirectly('pool_payback', $DATA['sender'], $points);
238
239                                                         // Add points together and remove user
240                                                         $pointsBack[$DATA['sender']] += $points;
241                                                 } // END - if
242
243                                                 // Count up
244                                                 $count_back[$DATA['sender']]++;
245                                         }
246
247                                         // Remove entry from list
248                                         unset($dummy[$key]);
249
250                                         // Update receivers
251                                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_pool` SET `receivers`='%s' WHERE `id`=%s LIMIT 1",
252                                                 array(implode(';', $dummy), bigintval($DATA['id'])), __FILE__, __LINE__);
253                                 }
254                         } // END - foreach
255                 } // END - if
256         } // END - while
257
258         // Do we have points to "pay back"?
259         if ((count($pointsBack) > 0) && (!empty($pointsBack[0]))) {
260                 // Walk through all points
261                 foreach ($pointsBack as $userid => $PB) {
262                         // Add points only when we have points left to add and a valid user id
263                         if (($PB > 0) && (isValidUserId($userid))) {
264                                 // Prepare content
265                                 $content = array(
266                                         'points' => $PB
267                                 );
268
269                                 // We have to pay back some points to the sender (we add them directly :-P)
270                                 if (fetchUserData($userid)) {
271                                         // User account does exists, so we can safely pay back!
272                                         $mailText = loadEmailTemplate('back-member', $content, bigintval($userid));
273
274                                         // Send mail out to member
275                                         sendEmail(getUserData('email'), '{--MEMBER_BACK_JACKPOT--}' . ' (' . $userid . ')', $mailText);
276                                 } elseif (isExtensionActive('jackpot')) {
277                                         // Add to jackpot
278                                         addPointsToJackpot($PB);
279
280                                         // Send mail out to admin
281                                         sendAdminNotification('{--ADMIN_BACK_JACKPOT--}' . ' (' . $userid . ')', 'back-admin', $content, 'admin');
282                                 }
283                         } // END - if
284                 } // END - foreach
285         } // END - if
286 } // END - if
287
288 // Free memory
289 SQL_FREERESULT($result_main);
290
291 // Remove variable
292 unset($mailText);
293
294 // [EOF]
295 ?>