Surfbar now has admin menu (dummy extension!), menu system rebuilded for unique key...
[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  *                                                                      *
14  * -------------------------------------------------------------------- *
15  * Copyright (c) 2003 - 2008 by Roland Haeder                           *
16  * For more information visit: http://www.mxchange.org                  *
17  *                                                                      *
18  * This program is free software. You can redistribute it and/or modify *
19  * it under the terms of the GNU General Public License as published by *
20  * the Free Software Foundation; either version 2 of the License.       *
21  *                                                                      *
22  * This program is distributed in the hope that it will be useful,      *
23  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
24  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
25  * GNU General Public License for more details.                         *
26  *                                                                      *
27  * You should have received a copy of the GNU General Public License    *
28  * along with this program; if not, write to the Free Software          *
29  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
30  * MA  02110-1301  USA                                                  *
31  ************************************************************************/
32
33 // Some security stuff...
34 if (ereg(basename(__FILE__), $_SERVER['PHP_SELF']))
35 {
36         $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), "/inc") + 4)."/security.php";
37         require($INC);
38 }
39 //
40 function SPONSOR_HANDLE_SPONSOR(&$POST, $NO_UPDATE=false, $MSGs=array(), $RET_STATUS=false)
41 {
42         $SAVE = true; $UPDATE = false; $skip = false; $ALREADY = false;
43         $ret = "unused";
44
45         // Skip these entries
46         $SKIPPED = array(
47                 'ok', 'edit', 'terms', 'pay_type'
48         );
49
50         // Save sponsor data
51         $DATA = array(
52                 'keys'   => array(),
53                 'values' => array()
54         );
55
56         // Check if sponsor already exists
57         foreach ($POST as $k=>$v)
58         {
59                 if (!(array_search($k, $SKIPPED) > -1))
60                 {
61                         // Check only posted input entries not the submit button
62                         switch ($k)
63                         {
64                         case "email":
65                                 $ALREADY = false;
66                                 if (!VALIDATE_EMAIL($v))
67                                 {
68                                         // Email address is not valid
69                                         $SAVE = false;
70                                 }
71                                  else
72                                 {
73                                         // Do we want to add a new sponsor or update his data?
74                                         $result = SQL_QUERY_ESC("SELECT id FROM "._MYSQL_PREFIX."_sponsor_data WHERE email='%s' LIMIT 1",
75                                          array($POST['email']), __FILE__, __LINE__);
76
77                                         // Is a sponsor alread in the db?
78                                         if (SQL_NUMROWS($result) == 1)
79                                         {
80                                                 // Free memory
81                                                 SQL_FREERESULT($result);
82
83                                                 // Yes, he is!
84                                                 if (($_GET['what'] == "add_sponsor") || ($NO_UPDATE))
85                                                 {
86                                                         // Already found!
87                                                         $ALREADY = true;
88                                                 }
89                                                  else
90                                                 {
91                                                         // Update his data
92                                                         $UPDATE = true;
93                                                 }
94                                         }
95                                 }
96                                 break;
97
98                         case "pass1":
99                                 $k = ""; $v = "";
100                                 break;
101
102                         case "pass2":
103                                 $k = "password"; $v = md5($v);
104                                 break;
105
106                         case "url":
107                                 if (!VALIDATE_URL($v)) $SAVE = false;
108                                 break;
109
110                         default:
111                                 // Test if there is are time selections
112                                 $TEST = substr($k, -3);
113                                 if ((($TEST == "_ye") || ($TEST == "_mo") || ($TEST == "_we") || ($TEST == "_da") || ($TEST == "_ho") || ($TEST == "_mi") || ($TEST == "_se")) && (!empty($v)))
114                                 {
115                                         // Found a multi-selection for timings?
116                                         $TEST = substr($k, 0, -3);
117                                         if ((!empty($POST[$TEST."_ye"])) && (!empty($POST[$TEST."_mo"])) && (!empty($POST[$TEST."_we"])) && (!empty($POST[$TEST."_da"])) && (!empty($POST[$TEST."_ho"])) && (!empty($POST[$TEST."_mi"])) && (!empty($POST[$TEST."_se"])) && ($TEST != $TEST2))
118                                         {
119                                                 // Generate timestamp
120                                                 $POST[$TEST] = CREATE_TIMESTAMP_FROM_SELECTIONS($TEST, $POST);
121                                                 $DATA['keys'][] = $TEST;
122                                                 $DATA['values'][] = $POST[$TEST];
123
124                                                 // Remove data from array
125                                                 unset($POST[$TEST."_ye"]);
126                                                 unset($POST[$TEST."_mo"]);
127                                                 unset($POST[$TEST."_we"]);
128                                                 unset($POST[$TEST."_da"]);
129                                                 unset($POST[$TEST."_ho"]);
130                                                 unset($POST[$TEST."_mi"]);
131                                                 unset($POST[$TEST."_se"]);
132
133                                                 // Skip adding
134                                                 $k = ""; $skip = true; $TEST2 = $TEST;
135                                         }
136                                 }
137                                  else
138                                 {
139                                         $skip = false; $TEST2 = "";
140                                 }
141                                 break;
142                         }
143
144                         if ((!empty($k)) && ($skip == false))
145                         {
146                                 // Add data
147                                 $DATA['keys'][] = $k; $DATA['values'][] = $v;
148                         }
149                 }
150         }
151
152         // Save sponsor?
153         if ($SAVE)
154         {
155                 // Default is no force even when a guest want to abuse this force switch
156                 if ((empty($POST['force'])) || (!IS_ADMIN())) $POST['force'] = "0";
157
158                 // SQL and message string is empty by default
159                 $SQL = ""; $MSG = "";
160
161                 // Update?
162                 if ($UPDATE)
163                 {
164                         // Update his data
165                         $SQL = "UPDATE "._MYSQL_PREFIX."_sponsor_data SET ";
166                         foreach ($DATA['keys'] as $k=>$v)
167                         {
168                                 $SQL .= $v."='%s', ";
169                         }
170
171                         // Remove last ", " from SQL string
172                         $SQL = substr($SQL, 0, -2)." WHERE id='%s' LIMIT 1";
173                         $DATA['values'][] = bigintval($_GET['id']);
174
175                         // Generate message
176                         $MSG = SPONSOR_SET_MESSAGE(ADMIN_SPONSOR_UPDATED, "updated", $MSGs);
177                         $ret = "updated";
178                 }
179                  elseif ((!$ALREADY) || (($POST['force'] == "1") && (IS_ADMIN())))
180                 {
181                         // Add new sponsor, first add more data
182                         $DATA['keys'][] = "sponsor_created"; $DATA['values'][] = time();
183                         $DATA['keys'][] = "status";
184                         if ((!$NO_UPDATE) && (IS_ADMIN()) && ($_GET['what'] == "add_sponsor"))
185                         {
186                                 // Only allowed for admin
187                                 $DATA['values'][] = "PENDING";
188                         }
189                          else
190                         {
191                                 // Guest area
192                                 $DATA['values'][] = "UNCONFIRMED";
193
194                                 // Generate hash code
195                                 $DATA['keys'][] = "hash";
196                                 $DATA['values'][] = md5($_COOKIE['PHPSESSID'].":".$POST['email'].":".$_SERVER['REMOTE_ADDR'].":".$_SERVER['HTTP_USER_AGENT'].":".time());
197                                 $DATA['keys'][] = "remote_addr";
198                                 $DATA['values'][] = $_SERVER['REMOTE_ADDR'];
199                         }
200
201                         // Implode all data into strings
202                         $KEYS   = implode(", "  , $DATA['keys']);
203                         $VALUES = str_repeat("%s', '", count($DATA['values']) - 1);
204
205                         // Generate string
206                         $SQL = "INSERT INTO "._MYSQL_PREFIX."_sponsor_data (".$KEYS.") VALUES('".$VALUES."%s')";
207
208                         // Generate message
209                         $MSG = SPONSOR_SET_MESSAGE(ADMIN_SPONSOR_ADDED, "added", $MSGs);
210                         $ret = "added";
211                 }
212                  elseif ((!$NO_UPDATE) && (IS_ADMIN()))
213                 {
214                         // Add all data as hidden data
215                         $OUT = "";
216                         foreach ($POST as $k=>$v)
217                         {
218                                 // Do not add 'force' !
219                                 if ($k != "force")
220                                 {
221                                         $OUT .= "<INPUT type=\"hidden\" name=\"".$k."\" value=\"".stripslashes($v)."\">\n";
222                                 }
223                         }
224                         define('__HIDDEN_DATA', $OUT);
225                         define('__EMAIL'      , $POST['email']);
226
227                         // Ask for adding a sponsor with same email address
228                         LOAD_TEMPLATE("admin_add_sponsor_already");
229                         return;
230                 }
231                  else
232                 {
233                         // Already added!
234                         $MSG = SPONSOR_ALREADY_FOUND_1.$POST['email'].SPONSOR_ALREADY_FOUND_2;
235                         $ret = "already";
236                 }
237
238                 if (!empty($SQL))
239                 {
240                         // Run SQL command
241                         $result = SQL_QUERY_ESC($SQL, $DATA['values'], __FILE__, __LINE__);
242                 }
243
244                 // Output message
245                 if ((!$NO_UPDATE) && (IS_ADMIN()))
246                 {
247                         LOAD_TEMPLATE("admin_settings_saved", false, $MSG);
248                 }
249         }
250          else
251         {
252                 // Error found!
253                 $MSG = SPONSOR_SET_MESSAGE(SPONSOR_DATA_NOT_SAVED, "failed", $MSGs);
254                 LOAD_TEMPLATE("admin_settings_saved", false, $MSG);
255         }
256
257         // Shall we return the status?
258         if ($RET_STATUS) return $ret;
259 }
260 //
261 function SPONSOR_TRANSLATE_STATUS($status)
262 {
263         switch ($status)
264         {
265         case "UNCONFIRMED":
266                 $ret = ACCOUNT_UNCONFIRMED;
267                 break;
268
269         case "CONFIRMED":
270                 $ret = ACCOUNT_CONFIRMED;
271                 break;
272
273         case "LOCKED":
274                 $ret = ACCOUNT_LOCKED;
275                 break;
276
277         case "PENDING":
278                 $ret = ACCOUNT_PENDING;
279                 break;
280
281         case "EMAIL":
282                 $ret = ACCOUNT_EMAIL;
283                 break;
284
285         default:
286                 $ret = UNKNOWN_STATUS_1.$status.UNKNOWN_STATUS_2;
287                 break;
288         }
289         return $ret;
290 }
291 // Search for an email address in the database
292 function SPONSOR_FOUND_EMAIL_DB($email)
293 {
294         // Default status is failed (as it is always be...)
295         $ret = false;
296
297         // Check for email (and secure input)
298         $result = SQL_QUERY_ESC("SELECT id FROM "._MYSQL_PREFIX."_sponsor_data WHERE email='%s' LIMIT 1",
299          array($email), __FILE__, __LINE__);
300
301         // Do we already have the provided email address in our DB?
302         if (SQL_NUMROWS($result) == 1) $ret = true;
303
304         // Return result
305         return $ret;
306 }
307 //
308 function SPONSOR_SET_MESSAGE($msg, $pos, $array)
309 {
310         // Check if the requested message was found in array
311         if (isset($array[$pos]))
312         {
313                 // ... if yes then use it!
314                 $ret = $array[$pos];
315         }
316          else
317         {
318                 // ... else use default message
319                 $ret = $msg;
320         }
321
322         // Return result
323         return $ret;
324 }
325 //
326 function IS_SPONSOR()
327 {
328         global $_COOKIE;
329         // Failed...
330         $ret = false;
331         if ((!empty($_COOKIE['sponsorid'])) && (!empty($_COOKIE['sponsorpass'])))
332         {
333                 // Check cookies against database records...
334                 $result = SQL_QUERY_ESC("SELECT id FROM "._MYSQL_PREFIX."_sponsor_data
335 WHERE id='%s' AND password='%s' AND status='CONFIRMED' LIMIT 1",
336  array(bigintval($_COOKIE['sponsorid']), $_COOKIE['sponsorpass']), __FILE__, __LINE__);
337                 if (SQL_NUMROWS($result) == 1)
338                 {
339                         // All is fine
340                         $ret = true;
341                 }
342
343                 // Free memory
344                 SQL_FREERESULT($result);
345         }
346
347         // Return status
348         return $ret;
349 }
350 //
351 function GENERATE_SPONSOR_MENU($current)
352 {
353         $OUT = "";
354         $WHERE = " AND active='Y'";
355         if (IS_ADMIN()) $WHERE = "";
356
357         // Load main menu entries
358         $result_main = SQL_QUERY("SELECT action, title FROM "._MYSQL_PREFIX."_sponsor_menu
359 WHERE (what='' OR what IS NULL) ".$WHERE."
360 ORDER BY sort", __FILE__, __LINE__);
361         if (SQL_NUMROWS($result_main) > 0)
362         {
363                 // Load every menu and it's sub menus
364                 while(list($action, $title_main) = SQL_FETCHROW($result_main))
365                 {
366                         // Load sub menus
367                         $result_sub = SQL_QUERY_ESC("SELECT what, title FROM "._MYSQL_PREFIX."_sponsor_menu
368 WHERE action='%s' AND what != '' ".$WHERE."
369 ORDER BY sort", array($action), __FILE__, __LINE__);
370                         if (SQL_NUMROWS($result_sub) > 0)
371                         {
372                                 // Load sub menus
373                                 $SUB = "";
374                                 while(list($what, $title_sub) = SQL_FETCHROW($result_sub))
375                                 {
376                                         // Check if current selected menu is matching the loaded one
377                                         if ($current == $what) $title_sub = "<STRONG>".$title_sub."</STRONG>";
378
379                                         // Prepare data for the sub template
380                                         $content = array(
381                                                 'what'  => $what,
382                                                 'title' => $title_sub
383                                         );
384
385                                         // Load row template
386                                         $SUB .= LOAD_TEMPLATE("sponsor_what", true, $content);
387                                 }
388
389                                 // Prepare data for the main template
390                                 $content = array(
391                                         'title' => $title_main,
392                                         'menu'  => $SUB
393                                 );
394
395                                 // Load menu template
396                                 $OUT .= LOAD_TEMPLATE("sponsor_action", true, $content);
397                         }
398                          else
399                         {
400                                 // No sub menus active
401                                 $OUT .= LOAD_TEMPLATE("admin_settings_saved", true, SPONSOR_NO_SUB_MENUS_ACTIVE);
402                         }
403
404                         // Free memory
405                         SQL_FREERESULT($result_sub);
406                 }
407         }
408          else
409         {
410                 // No main menus active
411                 $OUT .= LOAD_TEMPLATE("admin_settings_saved", true, SPONSOR_NO_MAIN_MENUS_ACTIVE);
412         }
413
414         // Free memory
415         SQL_FREERESULT($result_main);
416
417         // Return content
418         return $OUT;
419 }
420 //
421 function GENERATE_SPONSOR_CONTENT($what)
422 {
423         global $HTTP_POST_VARS, $_GET, $CONFIG;
424         $FILE = PATH."inc/modules/sponsor/".$what.".php";
425         $OUT = "";
426         if (@file_exists($FILE))
427         {
428                 // Every sponsor action will output nothing directly. It will be written into $OUT!
429                 require_once($FILE);
430         }
431          else
432         {
433                 // File not found!
434                 $OUT .= LOAD_TEMPLATE("admin_settings_saved", true, SPONSOR_CONTENT_404_1.$what.SPONSOR_CONTENT_404_2);
435         }
436
437         // Return content
438         return $OUT;
439 }
440 //
441 function UPDATE_SPONSOR_LOGIN()
442 {
443         global $_COOKIE, $CONFIG;
444
445         // Check if cookies are set
446         if ((empty($_COOKIE['sponsorid'])) || (empty($_COOKIE['sponsorpass']))) return false;
447
448         // Calculate cookie lifetime, maybe we have to change this so the admin can setup a
449         // seperate timeout for these two cookies?
450         $life = (time() + $CONFIG['online_timeout']);
451
452         // Is confirmed so both is fine and we can continue with login procedure
453         $login = ((setcookie("sponsorid"  , bigintval($_COOKIE['sponsorid']), $life, COOKIE_PATH)) &&
454                   (setcookie("sponsorpass", $_COOKIE['sponsorpass']         , $life, COOKIE_PATH)));
455
456         // Update database?
457         if ($login)
458         {
459                 // Update last online timestamp
460                 $result = SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_sponsor_data
461 SET last_online='".time()."'
462 WHERE id='%s' AND password='%s' LIMIT 1",
463  array(bigintval($_COOKIE['sponsorid']), $_COOKIE['sponsorpass']), __FILE__, __LINE__);
464         }
465
466         // Return status
467         return $login;
468 }
469 //
470 function SPONSOR_SAVE_DATA($POST, $content)
471 {
472         global $_COOKIE, $_SERVER, $_GET;
473         $EMAIL = false;
474
475         // Unsecure data which we don't want
476         $UNSAFE = array('password', 'id', 'remote_addr', 'sponsor_created', 'last_online', 'status', 'ref_count',
477                         'points_amount', 'points_used', 'refid', 'hash' , 'last_pay', 'last_curr', 'pass_old',
478                         'ok', 'pass1', 'pass2');
479
480         // Set default message ("not saved")
481         $MSG = SPONSOR_ACCOUNT_DATA_NOT_SAVED;
482
483         // Check for submitted passwords
484         if ((!empty($HTTP_POST_VARS['pass1'])) && (!empty($HTTP_POST_VARS['pass2'])))
485         {
486                 // Are both passwords the same?
487                 if ($HTTP_POST_VARS['pass1'] == $HTTP_POST_VARS['pass2'])
488                 {
489                         // Okay, then set password and remove pass1 and pass2
490                         $HTTP_POST_VARS['password'] = md5($HTTP_POST_VARS['pass1']);
491                 }
492         }
493
494         // Remove all (maybe spoofed) unsafe data from array
495         foreach ($UNSAFE as $remove)
496         {
497                 unset($POST[$remove]);
498         }
499
500         // This array is for the submitted data which we will use with the SQL_QUERY_ESC() function to
501         // secure the data
502         $DATA = array();
503
504         // Prepare SQL string
505         $SQL = "UPDATE "._MYSQL_PREFIX."_sponsor_data SET";
506         foreach ($POST as $key=>$value)
507         {
508                 // Mmmmm, too less security here???
509                 $SQL   .= " ".strip_tags($key)."='%s',";
510
511                 // We will secure this later inside the SQL_QUERY_ESC() function
512                 $DATA[] = strip_tags($value);
513
514                 // Compile {SLASH} and so on for the email templates
515                 $POST[$key] = COMPILE_CODE($value);
516         }
517
518         // Check if email has changed
519         if ((!empty($content['email'])) && (!empty($POST['email'])))
520         {
521                 if ($content['email'] != $POST['email'])
522                 {
523                         // Change email address
524                         $EMAIL = true;
525
526                         // Okay, has changed then add status with UNCONFIRMED and new hash code
527                         $SQL .= " status='EMAIL', hash='%s',";
528
529                         // Generate hash code
530                         $HASH = md5($_COOKIE['PHPSESSID'].":".$POST['email'].":".$_SERVER['REMOTE_ADDR'].":".$_SERVER['HTTP_USER_AGENT'].":".time());
531                         $DATA[] = $HASH;
532                 }
533         }
534
535         // Remove last commata
536         $SQL = substr($SQL, 0, -1);
537
538         // Add SQL tail data
539         $SQL .= " WHERE id='%s' AND password='%s' LIMIT 1";
540         $DATA[] = bigintval($_COOKIE['sponsorid']);
541         $DATA[] = $_COOKIE['sponsorpass'];
542
543         // Saving data was completed... ufff...
544         switch ($_GET['what'])
545         {
546         case "account": // Change account data
547                 if ($EMAIL)
548                 {
549                         $MSG   = SPONSOR_ACCOUNT_EMAIL_CHANGED;
550                         $templ = "admin_sponsor_change_email";
551                         $subj  = ADMIN_SPONSOR_ACC_EMAIL_SUBJ;
552                 }
553                  else
554                 {
555                         $MSG   = SPONSOR_ACCOUNT_DATA_SAVED;
556                         $templ = "admin_sponsor_change_data";
557                         $subj  = ADMIN_SPONSOR_ACC_DATA_SUBJ;
558                 }
559                 break;
560
561         case "settings": // Change settings
562                 // Translate some data
563                 $content['receive']  = TRANSLATE_YESNO($content['receive_warnings']);
564                 $content['interval'] = CREATE_FANCY_TIME($content['warning_interval']);
565
566                 // Set message template and subject for admin
567                 $MSG   = SPONSOR_SETTINGS_SAVED;
568                 $templ = "admin_sponsor_settings";
569                 $subj  = ADMIN_SPONSOR_SETTINGS_SUBJ;
570                 break;
571
572         default: // Unknown sponsor what value!
573                 $MSG = SPONSOR_UNKNOWN_WHAT_1.$_GET['what'].SPONSOR_UNKNOWN_WHAT_2;
574                 $templ = ""; $subj = "";
575                 break;
576         }
577
578         if (SQL_AFFECTEDROWS() == 1)
579         {
580                 if (!empty($templ) && !empty($subj))
581                 {
582                         // Run SQL command and check for success
583                         $result = SQL_QUERY_ESC($SQL, $DATA, __FILE__, __LINE__);
584
585                         // Add all data to content
586                         global $DATA;
587                         $DATA = $POST;
588
589                         // Change some data
590                         if (isset($content['salut'])) $content['salut'] = TRANSLATE_SEX($content['salut']);
591                         if (isset($DATA['salut']))    $DATA['salut']    = TRANSLATE_SEX($DATA['salut']);
592                         if (isset($content['receive_warnings'])) $DATA['receive']     = TRANSLATE_YESNO($POST['receive_warnings']);
593                         if (isset($content['warning_interval'])) $DATA['interval']    = CREATE_FANCY_TIME($POST['warning_interval']);
594
595                         // Send email to admins
596                         if (GET_EXT_VERSION("admins") < "0.4.1")
597                         {
598                                 // Use old method to send out
599                                 $msg = LOAD_EMAIL_TEMPLATE($templ, $content);
600                                 SEND_ADMIN_EMAILS($subj, $msg);
601                         }
602                          else
603                         {
604                                 // Use new system to send out
605                                 SEND_ADMIN_EMAILS_PRO($subj, $templ, $content);
606                         }
607
608                         // Shall we send mail to the sponsor's new email address?
609                         if ($content['receive_warnings'] == "Y")
610                         {
611                                 // Okay send email with confirmation link to new address and with no confirmation link
612                                 // to the old address
613
614                                 // First to old address
615                                 switch ($_GET['what'])
616                                 {
617                                 case "account": // Change account data
618                                         $email_msg = LOAD_EMAIL_TEMPLATE("sponsor_change_data", $content);
619                                         SEND_EMAIL($content['email'], SPONSOR_ACC_DATA_SUBJ, $email_msg);
620
621                                         if ($EMAIL)
622                                         {
623                                                 // Add hash code to content array
624                                                 $content['hash'] = $HASH;
625
626                                                 // Second mail goes to the new address
627                                                 $email_msg = LOAD_EMAIL_TEMPLATE("sponsor_change_email", $content);
628                                                 SEND_EMAIL($content['email'], SPONSOR_ACC_EMAIL_SUBJ, $email_msg);
629                                         }
630                                         break;
631
632                                 case "settings": // Change settings
633                                         // Send email
634                                         $email_msg = LOAD_EMAIL_TEMPLATE("sponsor_settings", $content);
635                                         SEND_EMAIL($content['email'], SPONSOR_SETTINGS_SUBJ, $email_msg);
636                                         break;
637                                 }
638                         }
639                 }
640         }
641
642         // Return final message
643         return $MSG;
644 }
645 //
646 ?>