config.php partly solved, see #117
[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: */ echo "*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: */ echo "!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: */ echo "!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: */ echo "?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                                                 {
135                                                 case 'done':
136                                                         // Prepare the mail
137                                                         $DATA[11] = bigintval($stats_id);
138                                                         $DATA[12] = $sname;
139                                                         $DATA[13] = $fname;
140                                                         $DATA[14] = translateGender($gender);
141
142                                                         // Replace text variables
143                                                         foreach ($GLOBALS['replacer'] as $key => $value) {
144                                                                 if (isset($DATA[$key])) $DATA[3] = str_replace($value, $DATA[$key], $DATA[3]);
145                                                         } // END - if
146
147                                                         // Prepare content
148                                                         $content = array(
149                                                                 'id'         => $DATA[11],
150                                                                 'url'        => $DATA[7],
151                                                                 'sender_uid' => $DATA[1],
152                                                                 'category'   => getCategory($DATA[9]),
153                                                                 'time'       => createFancyTime(getPaymentPoints($DATA[5], "time")),
154                                                                 'points'     => translateComma(getPaymentPoints($DATA[5], "payment")),
155                                                                 'text'       => $DATA[3]
156                                                         );
157
158                                                         // Load message template
159                                                         $mailText = LOAD_EMAIL_TEMPLATE("normal-mail", $content, bigintval($uid));
160
161                                                         // Send mail away
162                                                         sendEmail($email, $DATA[2], $mailText, $HTML);
163
164                                                         // Count sent mails...
165                                                         SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_user_data` SET emails_sent=emails_sent+1 WHERE userid=%s LIMIT 1",
166                                                                 array(bigintval($DATA[1])), __FILE__, __LINE__);
167
168                                                         if (GET_EXT_VERSION('user') >= '0.1.4') {
169                                                                 // Update mails received for receiver
170                                                                 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_user_data` SET emails_received=emails_received+1 WHERE userid=%s LIMIT 1",
171                                                                         array(bigintval($uid)), __FILE__, __LINE__);
172                                                         } // END - if
173
174                                                         // Update mediadata if version is 0.0.4 or higher
175                                                         if (GET_EXT_VERSION('mediadata') >= '0.0.4') {
176                                                                 // Update entry (or add missing)
177                                                                 //* DEBUG: */ echo "*MEDIA/L:".__LINE__."*<br />";
178                                                                 MEDIA_UPDATE_ENTRY(array("total_send", "normal_send"), 'add', 1);
179                                                         } // END - if
180
181                                                         // And count up the mail
182                                                         $GLOBALS['pool_cnt']++;
183                                                         //* DEBUG: */ echo"*EXIT/L:".__LINE__.'/'.$GLOBALS['pool_cnt']."*<br />";
184                                                         break;
185
186                                                 case "already":
187                                                         // Entry already found, but we still count one up!
188                                                         $GLOBALS['pool_cnt']++;
189                                                         //* DEBUG: */ echo"*EXIT/L:".__LINE__.'/'.$GLOBALS['pool_cnt']."<br />";
190                                                         break;
191                                                 }
192                                         }
193
194                                         // Do we have reached the maximum to send mails? || (getConfig('max_send') >= $GLOBALS['pool_cnt'])
195                                         //* DEBUG: */ echo "*L:".__LINE__.'/'.$GLOBALS['pool_cnt'].">=".$DATA[8].'/'.getConfig('max_send').">=".$GLOBALS['pool_cnt'].'/'.$lastSentId."!=".$DATA[0]."*<br />";
196                                         if ((($GLOBALS['pool_cnt'] >= $DATA[8])) && ($lastSentId != $DATA[0])) {
197                                                 // Prepare content
198                                                 $content = array(
199                                                         'sender_uid' => $DATA[1],
200                                                         'category'   => getCategory($DATA[9]),
201                                                         'text'       => $DATA[3],
202                                                         'url'        => $DATA[7],
203                                                         'expiration' => createFancyTime(getPaymentPoints($DATA[5], "time"))
204                                                 );
205
206                                                 // Yes we do, so we notify admin and sender about fully sent mail!
207                                                 sendAdminNotification(ADMIN_SUBJ_SEND_DONE, "done-admin", $content, $uid);
208
209                                                 // Get sender's data
210                                                 $result_sender = SQL_QUERY_ESC("SELECT surname, family, email FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
211                                                         array(bigintval($DATA[1])), __FILE__, __LINE__);
212
213                                                 // Is the sender found?
214                                                 if (SQL_NUMROWS($result_sender) == 1) {
215                                                         // Load data and prepare mail
216                                                         list($sname, $fname, $email) = SQL_FETCHROW($result_sender);
217
218                                                         // Load email template
219                                                         $mailText = LOAD_EMAIL_TEMPLATE("done-member", $content, $DATA[1]);
220
221                                                         // Send it also waway
222                                                         sendEmail($email, MEMBER_SUBJ_SEND_DONE, $mailText);
223                                                 } // END - if
224
225                                                 // Free result
226                                                 SQL_FREERESULT($result_sender);
227
228                                                 // Set status to SEND because we completely send it away
229                                                 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_pool` SET `data_type`='SEND', `target_send`=0, `receivers`='' WHERE `id`=%s LIMIT 1",
230                                                         array(bigintval($DATA[0])), __FILE__, __LINE__);
231
232                                                 // Update send-completed-time
233                                                 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_user_stats` SET `timestamp_send`=UNIX_TIMESTAMP() WHERE `pool_id`=%s LIMIT 1",
234                                                         array(bigintval($DATA[0])), __FILE__, __LINE__);
235
236                                                 $lastSentId = $DATA[0]; $GLOBALS['pool_cnt'] = 0;
237                                                 $cnt2 += $GLOBALS['pool_cnt'];
238
239                                                 // Update mediadata if version is 0.0.4 or higher
240                                                 if (GET_EXT_VERSION('mediadata') >= '0.0.4') {
241                                                         // Update entry (or add missing)
242                                                         //* DEBUG: */ echo "*MEDIA/L:".__LINE__."*<br />";
243                                                         MEDIA_UPDATE_ENTRY(array("total_orders", "normal_orders"), 'add', 1);
244                                                 } // END - if
245
246                                                 //* DEBUG: */ echo"*EXIT/L:".__LINE__.'/'.$P."<br />";
247                                                 break;
248                                         }
249                                         // Do we have send maximum mails?
250                                          elseif (($GLOBALS['pool_cnt'] >= getConfig('max_send')) || ($cnt2 >= getConfig('max_send'))) {
251                                                 // There are some mails left to send for next round, so we reset the status back to NEW (=still not fully delivered)
252                                                 $add = '';
253                                                 if ($GLOBALS['pool_cnt'] <= $DATA[8]) $add = ", target_send=target_send-".$GLOBALS['pool_cnt'];
254                                                 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_pool` SET data_type='NEW', receivers='%s'".$add." WHERE `id`=%s LIMIT 1",
255                                                  array(implode(';', $dummy), bigintval($DATA[0])), __FILE__, __LINE__);
256
257                                                 //* DEBUG: */ echo"*EXIT/L:".__LINE__."*<br />";
258                                                 break;
259                                         }
260
261                                         // Free result
262                                         SQL_FREERESULT($result_stats);
263                                 } else {
264                                         // User does not exists so we have add the sender's points back to sender's account
265                                         if (($RECEIVERS[0] == '0') || (empty($RECEIVERS[0]))) {
266                                                 // List was empty
267                                                 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_pool` SET data_type='SEND' WHERE `id`=%s LIMIT 1",
268                                                  array(bigintval($DATA[0])), __FILE__, __LINE__);
269                                         } else {
270                                                 // Is the userid set?
271                                                 if ($uid > 0) {
272                                                         // User does not exists, pay points back
273                                                         $points = getPaymentPoints($DATA[5]);
274                                                         ADD_POINTS_REFSYSTEM_DIRECT('pool_payback', $DATA[1], $points);
275
276                                                         // Add points together and remove user
277                                                         $pointsBack[$DATA[1]] += $points;
278                                                 } // END - if
279
280                                                 // Count up
281                                                 $cnt_back[$DATA[1]]++;
282                                         }
283
284                                         // Remove entry from list
285                                         unset($dummy[$key]);
286
287                                         // Update receivers
288                                         SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_pool` SET receivers='%s' WHERE `id`=%s LIMIT 1",
289                                                 array(implode(';', $dummy), bigintval($DATA[0])), __FILE__, __LINE__);
290                                 }
291                         }
292                 }
293         }
294
295         // Do we have points to "pay back"?
296         if ((count($pointsBack) > 0) && (!empty($pointsBack[0]))) {
297                 // Walk through all points
298                 foreach ($pointsBack as $uid => $PB) {
299                         // Add points only when we have points left to add and a valid user ID
300                         if (($PB > 0) && ($uid > 0)) {
301                                 // Prepare content
302                                 $content = array(
303                                         'points' => translateComma($DATA[10])
304                                 );
305
306                                 // We have to pay back some points to the sender (we add them directly :-P)
307                                 $result = SQL_QUERY_ESC("SELECT email FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s AND `status`='CONFIRMED' LIMIT 1",
308                                         array(bigintval($uid)), __FILE__, __LINE__);
309                                 $DATA[10] = $PB; $DATA[11] = $cnt_back[$uid];
310
311                                 // User found?
312                                 if (SQL_NUMROWS($result) == 1) {
313                                         list($email) = SQL_FETCHROW($result);
314                                         SQL_FREERESULT($result);
315
316                                         // User account does exists, so we can safely pay back!
317                                         $mailText = LOAD_EMAIL_TEMPLATE("back-member", $content, bigintval($uid));
318
319                                         // Send mail out to member
320                                         sendEmail($email, getMessage('MEMBER_BACK_JACKPOT')." (".$uid.')', $mailText);
321                                 } else {
322                                         // Add to jackpot
323                                         ADD_JACKPOT($PB);
324
325                                         // Send mail out to admin
326                                         sendAdminNotification(getMessage('ADMIN_BACK_JACKPOT')." (".$uid.')', "back-admin", $content, 'admin');
327                                 }
328                         } // END - if
329                 } // END - foreach
330         } // END - if
331 }
332
333 // Free memory
334 SQL_FREERESULT($result_main);
335
336 // Remove variable
337 unset($mailText);
338
339 //
340 ?>