addslashes() did escape also single quotes (') which breaks some banner rotation...
[mailer.git] / inc / libs / sponsor_functions.php
1 <?php
2 /************************************************************************
3  * MXChange v0.2.1                                    Start: 04/23/2005 *
4  * ===============                              Last change: 05/18/2008 *
5  *                                                                      *
6  * -------------------------------------------------------------------- *
7  * File              : sponsor_functions.php                            *
8  * -------------------------------------------------------------------- *
9  * Short description : Functions for the sponsor area                   *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Funktionen fuer den Sponsorenbereich             *
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 - 2009 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         die();
42 }
43
44 //
45 function handlSponsorRequest (&$postData, $update=false, $messageArray=array(), $RET_STATUS=false) {
46         // Init a lot variables
47         $SAVE = true;
48         $UPDATE = false;
49         $skip = false;
50         $ALREADY = false;
51         $ret = "unused";
52
53         // Skip these entries
54         $SKIPPED = array(
55                 'ok', 'edit', 'terms', 'pay_type'
56         );
57
58         // Save sponsor data
59         $DATA = array(
60                 'keys'   => array(),
61                 'values' => array()
62         );
63
64                 // Check if sponsor already exists
65                 foreach ($postData as $k => $v) {
66                         if (!(array_search($k, $SKIPPED) > -1)) {
67                                 // Check only posted input entries not the submit button
68                                 switch ($k)
69                                 {
70                                         case 'email':
71                                                 $ALREADY = false;
72                                                 if (!isEmailValid($v)) {
73                                                         // Email address is not valid
74                                                         $SAVE = false;
75                                                 } else {
76                                                         // Do we want to add a new sponsor or update his data?
77                                                         $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_sponsor_data` WHERE email='%s' LIMIT 1",
78                                                         array($postData['email']), __FUNCTION__, __LINE__);
79
80                                                         // Is a sponsor alread in the db?
81                                                         if (SQL_NUMROWS($result) == 1) {
82                                                                 // Yes, he is!
83                                                                 if ((getWhat() == 'add_sponsor') || ($update)) {
84                                                                         // Already found!
85                                                                         $ALREADY = true;
86                                                                 } else {
87                                                                         // Update his data
88                                                                         $UPDATE = true;
89                                                                 }
90                                                         }
91
92                                                         // Free memory
93                                                         SQL_FREERESULT($result);
94                                                 }
95                                                 break;
96
97                                         case 'pass1':
98                                                 $k = ''; $v = '';
99                                                 break;
100
101                                         case 'pass2':
102                                                 $k = 'password'; $v = md5($v);
103                                                 break;
104
105                                         case 'url':
106                                                 if (!isUrlValid($v)) $SAVE = false;
107                                                 break;
108
109                                         default:
110                                                 // Test if there is are time selections
111                                                 convertSelectionsToTimestamp($postData, $DATA, $k, $skip);
112                                                 break;
113                                 }
114
115                                 if ((!empty($k)) && ($skip == false)) {
116                                         // Add data
117                                         $DATA['keys'][] = $k; $DATA['values'][] = $v;
118                                 }
119                         }
120                 }
121
122                 // Save sponsor?
123                 if ($SAVE === true) {
124                         // Default is no force even when a guest want to abuse this force switch
125                         if ((empty($postData['force'])) || (!isAdmin())) $postData['force'] = '0';
126
127                         // SQL and message string is empty by default
128                         $sql = ''; $message = '';
129
130                         // Update?
131                         if ($UPDATE) {
132                                 // Update his data
133                                 $sql = "UPDATE `{?_MYSQL_PREFIX?}_sponsor_data` SET ";
134                                 foreach ($DATA['keys'] as $k => $v) {
135                                         $sql .= $v."='%s', ";
136                                 }
137
138                                 // Remove last ", " from SQL string
139                                 $sql = substr($sql, 0, -2)." WHERE `id`='%s' LIMIT 1";
140                                 $DATA['values'][] = bigintval(getRequestElement('id'));
141
142                                 // Generate message
143                                 $message = getMessageFromIndexedArray(getMessage('ADMIN_SPONSOR_UPDATED'), 'updated', $messageArray);
144                                 $ret = "updated";
145                         } elseif (($ALREADY === false) || (($postData['force'] == 1) && (isAdmin()))) {
146                                 // Add new sponsor, first add more data
147                                 $DATA['keys'][] = 'sponsor_created'; $DATA['values'][] = time();
148                                 $DATA['keys'][] = 'status';
149                                 if (($update === true) && (isAdmin()) && (getWhat() == 'add_sponsor')) {
150                                         // Only allowed for admin
151                                         $DATA['values'][] = 'PENDING';
152                                 } else {
153                                         // Guest area
154                                         $DATA['values'][] = 'UNCONFIRMED';
155
156                                         // Generate hash code
157                                         $DATA['keys'][] = 'hash';
158                                         $DATA['values'][] = md5(session_id().':'.$postData['email'].':'.detectRemoteAddr().':'.detectUserAgent().':'.time());
159                                         $DATA['keys'][] = 'remote_addr';
160                                         $DATA['values'][] = detectRemoteAddr();
161                                 }
162
163                                 // Implode all data into strings
164                                 $KEYS   = implode("`, `"  , $DATA['keys']);
165                                 $valueS = str_repeat("%s', '", count($DATA['values']) - 1);
166
167                                 // Generate string
168                                 $sql = "INSERT INTO `{?_MYSQL_PREFIX?}_sponsor_data` (`".$KEYS."`) VALUES ('".$valueS."%s')";
169
170                                 // Generate message
171                                 $message = getMessageFromIndexedArray(getMessage('ADMIN_SPONSOR_ADDED'), "added", $messageArray);
172                                 $ret = 'added';
173                         } elseif (($update === true) && (isAdmin())) {
174                                 // Add all data as hidden data
175                                 $OUT = '';
176                                 foreach ($postData as $k => $v) {
177                                         // Do not add 'force' !
178                                         if ($k != 'force') {
179                                                 $OUT .= "<input type=\"hidden\" name=\"" . secureString($k) . "\" value=\"" . SQL_ESCAPE($v) . "\" />\n";
180                                         } // END - if
181                                 } // END - foreach
182
183                                 // Remember data
184                                 $content['hidden'] = $OUT;
185                                 $content['email']  = $postData['email'];
186
187                                 // Ask for adding a sponsor with same email address
188                                 loadTemplate('admin_add_sponsor_already', false, $content);
189                                 return;
190                         } else {
191                                 // Already added!
192                                 $message = sprintf(getMessage('SPONSOR_ALREADY_FOUND'), $postData['email']);
193                                 $ret = 'already';
194                         }
195
196                         if (!empty($sql)) {
197                                 // Run SQL command
198                                 $result = SQL_QUERY_ESC($sql, $DATA['values'], __FUNCTION__, __LINE__);
199                         } // END - if
200
201                         // Output message
202                         if (($update === true) && (isAdmin())) {
203                                 loadTemplate('admin_settings_saved', false, $message);
204                         } // END - if
205                 } else {
206                         // Error found!
207                         $message = getMessageFromIndexedArray(getMessage('SPONSOR_DATA_NOT_SAVED'), 'failed', $messageArray);
208                         loadTemplate('admin_settings_saved', false, $message);
209                 }
210
211                 // Shall we return the status?
212                 if ($RET_STATUS === true) return $ret;
213 }
214
215 //
216 function sponsorTranslateUserStatus ($status) {
217         // Construct constant name
218         $constantName = sprintf("ACCOUNT_%s", $status);
219
220         // Is the constant there?
221         if (defined($constantName)) {
222                 // Then use it
223                 $ret = constant($constantName);
224         } else {
225                 // Not found!
226                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
227                 $ret = sprintf(getMessage('UNKNOWN_STATUS'), $status);
228         }
229         return $ret;
230 }
231
232 // Search for an email address in the database
233 function isSponsorRegisteredWithEmail ($email) {
234         // Do we already have the provided email address in our DB?
235         $ret = (countSumTotalData($email, 'sponsor_data', 'id', 'email', true) == 1);
236
237         // Return result
238         return $ret;
239 }
240
241 // Wether the current user is a sponsor
242 function isSponsor () {
243         // Failed...
244         $ret = false;
245         if ((isSessionVariableSet('sponsorid')) && (isSessionVariableSet('sponsorpass'))) {
246                 // Check cookies against database records...
247                 $result = SQL_QUERY_ESC("SELECT
248         `id`
249 FROM
250         `{?_MYSQL_PREFIX?}_sponsor_data`
251 WHERE
252         `id`='%s' AND `password`='%s' AND `status`='CONFIRMED'
253 LIMIT 1",
254                         array(
255                                 bigintval(getSession('sponsorid')),
256                                 getSession('sponsorpass')
257                         ), __FUNCTION__, __LINE__);
258                 if (SQL_NUMROWS($result) == 1) {
259                         // All is fine
260                         $ret = true;
261                 } // END - if
262
263                 // Free memory
264                 SQL_FREERESULT($result);
265         } // END - if
266
267         // Return status
268         return $ret;
269 }
270
271 //
272 function addSponsorMenu ($current) {
273         $OUT = '';
274         $WHERE = " AND active='Y'";
275         if (isAdmin()) $WHERE = '';
276
277         // Load main menu entries
278         $result_main = SQL_QUERY("SELECT action AS main_action, title AS main_title FROM `{?_MYSQL_PREFIX?}_sponsor_menu`
279 WHERE (`what`='' OR `what` IS NULL) ".$WHERE."
280 ORDER BY `sort`", __FUNCTION__, __LINE__);
281         if (SQL_NUMROWS($result_main) > 0) {
282                 // Load every menu and it's sub menus
283                 while ($content = SQL_FETCHARRAY($result_main)) {
284                         // Load sub menus
285                         $result_sub = SQL_QUERY_ESC("SELECT what AS sub_what, title AS sub_title FROM `{?_MYSQL_PREFIX?}_sponsor_menu`
286 WHERE `action`='%s' AND `what` != '' AND `what` IS NOT NULL ".$WHERE."
287 ORDER BY `sort`",
288                         array($content['main_action']), __FUNCTION__, __LINE__);
289                         if (SQL_NUMROWS($result_sub) > 0) {
290                                 // Load sub menus
291                                 $SUB = '';
292                                 while ($content2 = SQL_FETCHARRAY($result_sub)) {
293                                         // Merge both arrays
294                                         $content = merge_array($content, $content2);
295
296                                         // Check if current selected menu is matching the loaded one
297                                         if ($current == $content['sub_what']) $content['sub_title'] = "<strong>".$content['sub_title']."</strong>";
298
299                                         // Prepare data for the sub template
300                                         $content = array(
301                                                 'what'  => $content['sub_what'],
302                                                 'title' => $content['sub_title']
303                                         );
304
305                                         // Load row template
306                                         $SUB .= loadTemplate('sponsor_what', true, $content);
307                                 }
308
309                                 // Prepare data for the main template
310                                 $content = array(
311                                         'title' => $content['main_title'],
312                                         'menu'  => $SUB
313                                 );
314
315                                 // Load menu template
316                                 $OUT .= loadTemplate('sponsor_action', true, $content);
317                         } else {
318                                 // No sub menus active
319                                 $OUT .= loadTemplate('admin_settings_saved', true, getMessage('SPONSOR_NO_SUB_MENUS_ACTIVE'));
320                         }
321
322                         // Free memory
323                         SQL_FREERESULT($result_sub);
324                 }
325         } else {
326                 // No main menus active
327                 $OUT .= loadTemplate('admin_settings_saved', true, getMessage('SPONSOR_NO_MAIN_MENUS_ACTIVE'));
328         }
329
330         // Free memory
331         SQL_FREERESULT($result_main);
332
333         // Return content
334         return $OUT;
335 }
336
337 //
338 function addSponsorContent ($what) {
339         $OUT = '';
340         $INC = sprintf("inc/modules/sponsor/%s.php", $what);
341         if (isIncludeReadable($INC)) {
342                 // Every sponsor action will output nothing directly. It will be written into $OUT!
343                 loadIncludeOnce($INC);
344         } else {
345                 // File not found!
346                 $OUT .= loadTemplate('admin_settings_saved', true, sprintf(getMessage('SPONSOR_CONTENT_404'), $what));
347         }
348
349         // Return content
350         return $OUT;
351 }
352
353 //
354 function updateSponsorLogin () {
355         // Failed by default
356         $login = false;
357
358         // Is sponsor?
359         if (isSponsor()) {
360                 // Update last online timestamp
361                 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_sponsor_data`
362 SET `last_online`=UNIX_TIMESTAMP()
363 WHERE `id`='%s' AND `password`='%s' LIMIT 1",
364                         array(
365                                 bigintval(getSession('sponsorid')),
366                                 getSession('sponsorpass')
367                         ), __FUNCTION__, __LINE__);
368
369                 // This update went fine?
370                 $login = (SQL_AFFECTEDROWS() == 1);
371         }
372
373         // Return status
374         return $login;
375 }
376
377 // Saves sponsor's data
378 function saveSponsorData ($postData, $content) {
379         $EMAIL = false;
380
381         // Unsecure data which we don't want
382         $UNSAFE = array('password', 'id', 'remote_addr', 'sponsor_created', 'last_online', 'status', 'ref_count',
383                         'points_amount', 'points_used', 'refid', 'hash', 'last_pay', 'last_curr', 'pass_old',
384                         'ok', 'pass1', 'pass2');
385
386         // Set default message ("not saved")
387         $message = getMessage('SPONSOR_ACCOUNT_DATA_NOT_SAVED');
388
389         // Check for submitted passwords
390         if ((!empty($postData['pass1'])) && (!empty($postData['pass2']))) {
391                 // Are both passwords the same?
392                 if ($postData['pass1'] == $postData['pass2']) {
393                         // Okay, then set password and remove pass1 and pass2
394                         $postData['password'] = md5($postData['pass1']);
395                 } // END - if
396         } // END - if
397
398         // Remove all (maybe spoofed) unsafe data from array
399         foreach ($UNSAFE as $remove) {
400                 unset($postData[$remove]);
401         } // END - foreach
402
403         // This array is for the submitted data which we will use with the SQL_QUERY_ESC() function to
404         // secure the data
405         $DATA = array();
406
407         // Prepare SQL string
408         $sql = "UPDATE `{?_MYSQL_PREFIX?}_sponsor_data` SET";
409         foreach ($postData as $key => $value) {
410                 // Mmmmm, too less security here???
411                 $sql   .= " `".secureString($key)."`='%s',";
412
413                 // We will secure this later inside the SQL_QUERY_ESC() function
414                 $DATA[] = secureString($value);
415         } // END - foreach
416
417         // Check if email has changed
418         if ((!empty($content['email'])) && (!empty($postData['email']))) {
419                 if ($content['email'] != $postData['email']) {
420                         // Change email address
421                         $EMAIL = true;
422
423                         // Okay, has changed then add status with UNCONFIRMED and new hash code
424                         $sql .= " `status`='EMAIL', `hash`='%s',";
425
426                         // Generate hash code
427                         $HASH = md5(session_id().':'.$postData['email'].':'.detectRemoteAddr().':'.detectUserAgent().':'.time());
428                         $DATA[] = $HASH;
429                 } // END - if
430         } // END - if
431
432         // Remove last commata
433         $sql = substr($sql, 0, -1);
434
435         // Add SQL tail data
436         $sql .= " WHERE `id`='%s' AND password='%s' LIMIT 1";
437         $DATA[] = bigintval(getSession('sponsorid'));
438         $DATA[] = getSession('sponsorpass');
439
440         // Saving data was completed... ufff...
441         switch (getWhat())
442         {
443                 case 'account': // Change account data
444                         if ($EMAIL === true) {
445                                 $message   = getMessage('SPONSOR_ACCOUNT_EMAIL_CHANGED');
446                                 $templ = 'admin_sponsor_change_email';
447                                 $subj  = getMessage('ADMIN_SPONSOR_ACC_EMAIL_SUBJ');
448                         } else {
449                                 $message   = getMessage('SPONSOR_ACCOUNT_DATA_SAVED');
450                                 $templ = 'admin_sponsor_change_data';
451                                 $subj  = getMessage('ADMIN_SPONSOR_ACC_DATA_SUBJ');
452                         }
453                         break;
454
455                 case 'settings': // Change settings
456                         // Translate some data
457                         $content['receive']  = translateYesNo($content['receive_warnings']);
458                         $content['interval'] = createFancyTime($content['warning_interval']);
459
460                         // Set message template and subject for admin
461                         $message   = getMessage('SPONSOR_SETTINGS_SAVED');
462                         $templ = 'admin_sponsor_settings';
463                         $subj  = getMessage('ADMIN_SPONSOR_SETTINGS_SUBJ');
464                         break;
465
466                 default: // Unknown sponsor what value!
467                         logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown sponsor module (what) %s detected.", getWhat()));
468                         $message = sprintf(getMessage('SPONSOR_UNKNOWN_WHAT'), getWhat());
469                         $templ = ''; $subj = '';
470                         break;
471         }
472
473         if (SQL_AFFECTEDROWS() == 1) {
474                 if (!empty($templ) && !empty($subj)) {
475                         // Run SQL command and check for success
476                         $result = SQL_QUERY_ESC($sql, $DATA, __FUNCTION__, __LINE__);
477
478                         // Add all data to content
479                         $content['new_data'] = $postData;
480
481                         // Change some data
482                         if (isset($content['gender']))             $content['gender']                  = translateGender($content['gender']);
483                         if (isset($content['new_data']['gender'])) $content['new_data']['gender']      = translateGender($content['new_data']['gender']);
484                         if (isset($content['receive_warnings']))   $content['new_data']['receive']     = translateYesNo($content['new_data']['receive_warnings']);
485                         if (isset($content['warning_interval']))   $content['new_data']['interval']    = createFancyTime($content['new_data']['warning_interval']);
486
487                         // Send email to admins
488                         sendAdminNotification($subj, $templ, $content);
489
490                         // Shall we send mail to the sponsor's new email address?
491                         if ($content['receive_warnings'] == 'Y') {
492                                 // Okay send email with confirmation link to new address and with no confirmation link
493                                 // to the old address
494
495                                 // First to old address
496                                 switch (getWhat())
497                                 {
498                                         case 'account': // Change account data
499                                                 $email_msg = loadEmailTemplate('sponsor_change_data', $content);
500                                                 sendEmail($content['email'], getMessage('SPONSOR_ACC_DATA_SUBJ'), $email_msg);
501
502                                                 if ($EMAIL === true) {
503                                                         // Add hash code to content array
504                                                         $content['hash'] = $HASH;
505
506                                                         // Second mail goes to the new address
507                                                         $email_msg = loadEmailTemplate('sponsor_change_email', $content);
508                                                         sendEmail($content['email'], getMessage('SPONSOR_ACC_EMAIL_SUBJ'), $email_msg);
509                                                 }
510                                                 break;
511
512                                         case 'settings': // Change settings
513                                                 // Send email
514                                                 $email_msg = loadEmailTemplate('sponsor_settings', $content);
515                                                 sendEmail($content['email'], getMessage('SPONSOR_SETTINGS_SUBJ'), $email_msg);
516                                                 break;
517                                 }
518                         } // END - if
519                 } // END - if
520         } // END - if
521
522         // Return final message
523         return $message;
524 }
525
526 // [EOF]
527 ?>