c10638afb4048489e672ffca143f21db8aae57c2
[mailer.git] / inc / pool / pool-user.php
1 <?php
2 /************************************************************************
3  * MXChange v0.2.1                                    Start: 12/12/2008 *
4  * ===============                              Last change: 12/12/2008 *
5  *                                                                      *
6  * -------------------------------------------------------------------- *
7  * File              : pool-user.php                                    *
8  * -------------------------------------------------------------------- *
9  * Short description : Sends queued user mails from the pool            *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Sendet freigegebene Mitglieder-Mails aus Pool    *
12  * -------------------------------------------------------------------- *
13  * $Revision::                                                        $ *
14  * $Date::                                                            $ *
15  * $Tag:: 0.2.1-FINAL                                                 $ *
16  * $Author::                                                          $ *
17  * Needs to be in all Files and every File needs "svn propset           *
18  * svn:keywords Date Revision" (autoprobset!) at least!!!!!!            *
19  * -------------------------------------------------------------------- *
20  * Copyright (c) 2003 - 2008 by Roland Haeder                           *
21  * For more information visit: http://www.mxchange.org                  *
22  *                                                                      *
23  * This program is free software; you can redistribute it and/or modify *
24  * it under the terms of the GNU General Public License as published by *
25  * the Free Software Foundation; either version 2 of the License, or    *
26  * (at your option) any later version.                                  *
27  *                                                                      *
28  * This program is distributed in the hope that it will be useful,      *
29  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
30  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
31  * GNU General Public License for more details.                         *
32  *                                                                      *
33  * You should have received a copy of the GNU General Public License    *
34  * along with this program; if not, write to the Free Software          *
35  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
36  * MA  02110-1301  USA                                                  *
37  ************************************************************************/
38
39 // Some security stuff...
40 if (!defined('__SECURITY')) {
41         $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), '/inc') + 4) . '/security.php';
42         require($INC);
43 }
44
45 // Don't run on daily reset
46 if (isResetModeEnabled()) {
47         // Skip here
48         return false;
49 } elseif (!EXT_IS_ACTIVE('user')) {
50         // Abort here if extension user is not active
51         return false;
52 }
53
54 // Need this here
55 // Check for freed mail orders to send out
56 if (EXT_IS_ACTIVE('html_mail')) {
57         //                                0     1        2      3       4          5            6      7        8          9       10
58         $result_main = SQL_QUERY("SELECT id, sender, subject, text, receivers, payment_id, timestamp, url, target_send, cat_id, html_msg FROM `{!_MYSQL_PREFIX!}_pool` WHERE `data_type`='NEW' ORDER BY timestamp DESC", __FILE__, __LINE__);
59 } else {
60         //                                0     1        2      3       4          5            6      7        8          9    10
61         $result_main = SQL_QUERY("SELECT id, sender, subject, text, receivers, payment_id, timestamp, url, target_send, cat_id, id FROM `{!_MYSQL_PREFIX!}_pool` WHERE `data_type`='NEW' ORDER BY timestamp DESC", __FILE__, __LINE__);
62 }
63
64 // Reset variables
65 $cnt2 = 0; $lastSentId = 0; $cnt_back = array('0'); $pointsBack = array('0');
66 if (SQL_NUMROWS($result_main) > 0) {
67         // Parse all mails
68         while ($DATA = SQL_FETCHROW($result_main)) {
69                 // Set mail order as 'active'. That means it will be sent out
70                 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_pool` SET `data_type`='ACTIVE' WHERE `id`=%s AND `data_type`='NEW' LIMIT 1",
71                         array($DATA[0]), __FILE__, __LINE__);
72
73                 // Check fetched data for HTML
74                 $HTML = $DATA[10]; if ($HTML == $DATA[0]) $HTML = 'N';
75
76                 // Compile URL and subject line
77                 $DATA[7] = COMPILE_CODE($DATA[7]);
78
79                 // Entry updated?
80                 if (SQL_AFFECTEDROWS() == 1) {
81                         // "Explode" all receivers into an array
82                         if (ereg(';', $DATA[4])) {
83                                 // There's more than one receiver in the list...
84                                 $RECEIVERS = explode(';', $DATA[4]);
85                         } elseif (!empty($DATA[4])) {
86                                 // Only one user left
87                                 $RECEIVERS = array($DATA[4]);
88                         } else {
89                                 // No users left
90                                 $RECEIVERS = array('0');
91                         }
92                         $dummy = $RECEIVERS;
93
94                         // Now, if we are good little boys and girls Santa left us some user-ids.
95                         // We can now send mails to them...
96                         foreach ($RECEIVERS as $key => $uid) {
97                                 // Lookup user ID
98                                 $result_user = SQL_QUERY_ESC("SELECT gender, surname, family, email FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
99                                         array(bigintval($uid)), __FILE__, __LINE__);
100
101                                 // Is his data available?
102                                 //* DEBUG: */ OUTPUT_HTML("*L:".__LINE__.'/'.SQL_NUMROWS($result_user)."*<br />");
103                                 if (SQL_NUMROWS($result_user) == 1) {
104                                         // The final receiver does exists so we can continue...
105                                         list($gender, $sname, $fname, $email) = SQL_FETCHROW($result_user);
106
107                                         // Free memory
108                                         SQL_FREERESULT($result_user);
109
110                                         // Do we have a stats entry?
111                                         $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",
112                                                 array($DATA[0], $DATA[1], $DATA[6]), __FILE__, __LINE__);
113
114                                         // If there's no stats entry add it!
115                                         //* DEBUG: */ OUTPUT_HTML("!L:".__LINE__.'/'.SQL_NUMROWS($result_stats)."!<br />");
116                                         if (SQL_NUMROWS($result_stats) == 0) {
117                                                 // No entry was found, so we add him!
118                                                 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())",
119                                                         array(bigintval($DATA[0]), bigintval($DATA[1]), bigintval($DATA[9]), bigintval($DATA[5]), $DATA[2], $DATA[7], $DATA[8], bigintval($DATA[6])), __FILE__, __LINE__);
120
121                                                 // Receive it's ID for the links table
122                                                 $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",
123                                                         array(bigintval($DATA[0]), bigintval($DATA[1]), bigintval($DATA[6])), __FILE__, __LINE__);
124                                         } // END - if
125
126                                         //* DEBUG: */ OUTPUT_HTML("!L:".__LINE__.'/'.SQL_NUMROWS($result_stats)."!<br />");
127                                         if (SQL_NUMROWS($result_stats) == 1) {
128                                                 // We got one!
129                                                 list($stats_id) = SQL_FETCHROW($result_stats);
130
131                                                 // Mark this user as "spammed" ;-) And place a line for him...
132                                                 //* DEBUG: */ OUTPUT_HTML("?L:".__LINE__.'/'.$dummy.'/'.$key.'/'.$uid.'('.$DATA[1].")/".$DATA[0].'/'.$stats_id."?<br />");
133                                                 switch (removeReceiver($dummy, $key, bigintval($uid), bigintval($DATA[0]), bigintval($stats_id))) {
134                                                         case 'done':
135                                                                 // Prepare the mail
136                                                                 $DATA[11] = bigintval($stats_id);
137                                                                 $DATA[12] = $sname;
138                                                                 $DATA[13] = $fname;
139                                                                 $DATA[14] = translateGender($gender);
140
141                                                                 // Replace text variables
142                                                                 foreach ($GLOBALS['replacer'] as $key => $value) {
143                                                                         if (isset($DATA[$key])) $DATA[3] = str_replace($value, $DATA[$key], $DATA[3]);
144                                                                 } // END - if
145
146                                                                 // Prepare content
147                                                                 $content = array(
148                                                                 'id'         => $DATA[11],
149                                                                 'url'        => $DATA[7],
150                                                                 'sender_uid' => $DATA[1],
151                                                                 'category'   => getCategory($DATA[9]),
152                                                                 'time'       => createFancyTime(getPaymentPoints($DATA[5], "time")),
153                                                                 'points'     => translateComma(getPaymentPoints($DATA[5], "payment")),
154                                                                 'text'       => $DATA[3]
155                                                                 );
156
157                                                                 // Load message template
158                                                                 $mailText = LOAD_EMAIL_TEMPLATE("normal-mail", $content, bigintval($uid));
159
160                                                                 // Send mail away
161                                                                 sendEmail($email, $DATA[2], $mailText, $HTML);
162
163                                                                 // Count sent mails...
164                                                                 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_user_data` SET emails_sent=emails_sent+1 WHERE userid=%s LIMIT 1",
165                                                                         array(bigintval($DATA[1])), __FILE__, __LINE__);
166
167                                                                 if (GET_EXT_VERSION('user') >= '0.1.4') {
168                                                                         // Update mails received for receiver
169                                                                         SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_user_data` SET emails_received=emails_received+1 WHERE userid=%s LIMIT 1",
170                                                                                 array(bigintval($uid)), __FILE__, __LINE__);
171                                                                 } // END - if
172
173                                                                 // Update mediadata if version is 0.0.4 or higher
174                                                                 if (GET_EXT_VERSION('mediadata') >= '0.0.4') {
175                                                                         // Update entry (or add missing)
176                                                                         //* DEBUG: */ OUTPUT_HTML("*MEDIA/L:".__LINE__."*<br />");
177                                                                         MEDIA_UPDATE_ENTRY(array("total_send", "normal_send"), 'add', 1);
178                                                                 } // END - if
179
180                                                                 // And count up the mail
181                                                                 $GLOBALS['pool_cnt']++;
182                                                                 //* DEBUG: */ OUTPUT_HTML("*EXIT/L:".__LINE__.'/'.$GLOBALS['pool_cnt']."*<br />");
183                                                                 break;
184
185                                                         case 'already':
186                                                                 // Entry already found, but we still count one up!
187                                                                 $GLOBALS['pool_cnt']++;
188                                                                 //* DEBUG: */ OUTPUT_HTML("*EXIT/L:".__LINE__.'/'.$GLOBALS['pool_cnt']."<br />");
189                                                                 break;
190                                                 }
191                                         }
192
193                                         // Do we have reached the maximum to send mails? || (getConfig('max_send') >= $GLOBALS['pool_cnt'])
194                                         //* DEBUG: */ OUTPUT_HTML("*L:".__LINE__.'/'.$GLOBALS['pool_cnt'].">=".$DATA[8].'/'.getConfig('max_send').">=".$GLOBALS['pool_cnt'].'/'.$lastSentId."!=".$DATA[0]."*<br />");
195                                         if ((($GLOBALS['pool_cnt'] >= $DATA[8])) && ($lastSentId != $DATA[0])) {
196                                                 // Prepare content
197                                                 $content = array(
198                                                         'sender_uid' => $DATA[1],
199                                                         'category'   => getCategory($DATA[9]),
200                                                         'text'       => $DATA[3],
201                                                         'url'        => $DATA[7],
202                                                         'expiration' => createFancyTime(getPaymentPoints($DATA[5], "time"))
203                                                 );
204
205                                                 // Yes we do, so we notify admin and sender about fully sent mail!
206                                                 sendAdminNotification(ADMIN_SUBJ_SEND_DONE, "done-admin", $content, $uid);
207
208                                                 // Get sender's data
209                                                 $result_sender = SQL_QUERY_ESC("SELECT surname, family, email FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
210                                                         array(bigintval($DATA[1])), __FILE__, __LINE__);
211
212                                                 // Is the sender found?
213                                                 if (SQL_NUMROWS($result_sender) == 1) {
214                                                         // Load data and prepare mail
215                                                         list($sname, $fname, $email) = SQL_FETCHROW($result_sender);
216
217                                                         // Load email template
218                                                         $mailText = LOAD_EMAIL_TEMPLATE("done-member", $content, $DATA[1]);
219
220                                                         // Send it also waway
221                                                         sendEmail($email, MEMBER_SUBJ_SEND_DONE, $mailText);
222                                                 } // END - if
223
224                                                 // Free result
225                                                 SQL_FREERESULT($result_sender);
226
227                                                 // Set status to SEND because we completely send it away
228                                                 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_pool` SET `data_type`='SEND', `target_send`=0, `receivers`='' WHERE `id`=%s LIMIT 1",
229                                                         array(bigintval($DATA[0])), __FILE__, __LINE__);
230
231                                                 // Update send-completed-time
232                                                 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_user_stats` SET `timestamp_send`=UNIX_TIMESTAMP() WHERE `pool_id`=%s LIMIT 1",
233                                                         array(bigintval($DATA[0])), __FILE__, __LINE__);
234
235                                                 $lastSentId = $DATA[0]; $GLOBALS['pool_cnt'] = 0;
236                                                 $cnt2 += $GLOBALS['pool_cnt'];
237
238                                                 // Update mediadata if version is 0.0.4 or higher
239                                                 if (GET_EXT_VERSION('mediadata') >= '0.0.4') {
240                                                         // Update entry (or add missing)
241                                                         //* DEBUG: */ OUTPUT_HTML("*MEDIA/L:".__LINE__."*<br />");
242                                                         MEDIA_UPDATE_ENTRY(array("total_orders", "normal_orders"), 'add', 1);
243                                                 } // END - if
244
245                                                 //* DEBUG: */ OUTPUT_HTML("*EXIT/L:".__LINE__.'/'.$P."<br />");
246                                                 break;
247                                         }
248                                         // Do we have send maximum mails?
249                                         elseif (($GLOBALS['pool_cnt'] >= getConfig('max_send')) || ($cnt2 >= getConfig('max_send'))) {
250                                                 // There are some mails left to send for next round, so we reset the status back to NEW (=still not fully delivered)
251                                                 $add = '';
252                                                 if ($GLOBALS['pool_cnt'] <= $DATA[8]) $add = ", target_send=target_send-".$GLOBALS['pool_cnt'];
253                                                 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_pool` SET `data_type`='NEW', receivers='%s'".$add." WHERE `id`=%s LIMIT 1",
254                                                         array(implode(';', $dummy), bigintval($DATA[0])), __FILE__, __LINE__);
255
256                                                 //* DEBUG: */ OUTPUT_HTML("*EXIT/L:".__LINE__."*<br />");
257                                                 break;
258                                         }
259
260                                         // Free result
261                                         SQL_FREERESULT($result_stats);
262                                 } else {
263                                         // User does not exists so we have add the sender's points back to sender's account
264                                         if (($RECEIVERS[0] == '0') || (empty($RECEIVERS[0]))) {
265                                                 // List was empty
266                                                 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_pool` SET `data_type`='SEND' WHERE `id`=%s LIMIT 1",
267                                                         array(bigintval($DATA[0])), __FILE__, __LINE__);
268                                         } else {
269                                                 // Is the userid set?
270                                                 if ($uid > 0) {
271                                                         // User does not exists, pay points back
272                                                         $points = getPaymentPoints($DATA[5]);
273                                                         ADD_POINTS_REFSYSTEM_DIRECT('pool_payback', $DATA[1], $points);
274
275                                                         // Add points together and remove user
276                                                         $pointsBack[$DATA[1]] += $points;
277                                                 } // END - if
278
279                                                 // Count up
280                                                 $cnt_back[$DATA[1]]++;
281                                         }
282
283                                         // Remove entry from list
284                                         unset($dummy[$key]);
285
286                                         // Update receivers
287                                         SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_pool` SET receivers='%s' WHERE `id`=%s LIMIT 1",
288                                                 array(implode(';', $dummy), bigintval($DATA[0])), __FILE__, __LINE__);
289                                 }
290                         }
291                 }
292         }
293
294         // Do we have points to "pay back"?
295         if ((count($pointsBack) > 0) && (!empty($pointsBack[0]))) {
296                 // Walk through all points
297                 foreach ($pointsBack as $uid => $PB) {
298                         // Add points only when we have points left to add and a valid user ID
299                         if (($PB > 0) && ($uid > 0)) {
300                                 // Prepare content
301                                 $content = array(
302                                         'points' => translateComma($DATA[10])
303                                 );
304
305                                 // We have to pay back some points to the sender (we add them directly :-P)
306                                 $result = SQL_QUERY_ESC("SELECT email FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s AND `status`='CONFIRMED' LIMIT 1",
307                                 array(bigintval($uid)), __FILE__, __LINE__);
308                                 $DATA[10] = $PB; $DATA[11] = $cnt_back[$uid];
309
310                                 // User found?
311                                 if (SQL_NUMROWS($result) == 1) {
312                                         list($email) = SQL_FETCHROW($result);
313                                         SQL_FREERESULT($result);
314
315                                         // User account does exists, so we can safely pay back!
316                                         $mailText = LOAD_EMAIL_TEMPLATE("back-member", $content, bigintval($uid));
317
318                                         // Send mail out to member
319                                         sendEmail($email, getMessage('MEMBER_BACK_JACKPOT')." (".$uid.')', $mailText);
320                                 } else {
321                                         // Add to jackpot
322                                         ADD_JACKPOT($PB);
323
324                                         // Send mail out to admin
325                                         sendAdminNotification(getMessage('ADMIN_BACK_JACKPOT')." (".$uid.')', "back-admin", $content, 'admin');
326                                 }
327                         } // END - if
328                 } // END - foreach
329         } // END - if
330 }
331
332 // Free memory
333 SQL_FREERESULT($result_main);
334
335 // Remove variable
336 unset($mailText);
337
338 //
339 ?>