c9ce82d799044ae4d7448dc72c7030f9bc0ffacb
[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         $OUT = "";
425         $FILE = sprintf("%sinc/modules/sponsor/%s.php", PATH, $what);
426         if (FILE_READABLE($FILE)) {
427                 // Every sponsor action will output nothing directly. It will be written into $OUT!
428                 require_once($FILE);
429         } else {
430                 // File not found!
431                 $OUT .= LOAD_TEMPLATE("admin_settings_saved", true, SPONSOR_CONTENT_404_1.$what.SPONSOR_CONTENT_404_2);
432         }
433
434         // Return content
435         return $OUT;
436 }
437 //
438 function UPDATE_SPONSOR_LOGIN()
439 {
440         global $_COOKIE, $CONFIG;
441
442         // Check if cookies are set
443         if ((empty($_COOKIE['sponsorid'])) || (empty($_COOKIE['sponsorpass']))) return false;
444
445         // Calculate cookie lifetime, maybe we have to change this so the admin can setup a
446         // seperate timeout for these two cookies?
447         $life = (time() + $CONFIG['online_timeout']);
448
449         // Is confirmed so both is fine and we can continue with login procedure
450         $login = ((setcookie("sponsorid"  , bigintval($_COOKIE['sponsorid']), $life, COOKIE_PATH)) &&
451                   (setcookie("sponsorpass", $_COOKIE['sponsorpass']         , $life, COOKIE_PATH)));
452
453         // Update database?
454         if ($login)
455         {
456                 // Update last online timestamp
457                 $result = SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_sponsor_data
458 SET last_online='".time()."'
459 WHERE id='%s' AND password='%s' LIMIT 1",
460  array(bigintval($_COOKIE['sponsorid']), $_COOKIE['sponsorpass']), __FILE__, __LINE__);
461         }
462
463         // Return status
464         return $login;
465 }
466 //
467 function SPONSOR_SAVE_DATA($POST, $content)
468 {
469         global $_COOKIE, $_SERVER, $_GET;
470         $EMAIL = false;
471
472         // Unsecure data which we don't want
473         $UNSAFE = array('password', 'id', 'remote_addr', 'sponsor_created', 'last_online', 'status', 'ref_count',
474                         'points_amount', 'points_used', 'refid', 'hash' , 'last_pay', 'last_curr', 'pass_old',
475                         'ok', 'pass1', 'pass2');
476
477         // Set default message ("not saved")
478         $MSG = SPONSOR_ACCOUNT_DATA_NOT_SAVED;
479
480         // Check for submitted passwords
481         if ((!empty($_POST['pass1'])) && (!empty($_POST['pass2'])))
482         {
483                 // Are both passwords the same?
484                 if ($_POST['pass1'] == $_POST['pass2'])
485                 {
486                         // Okay, then set password and remove pass1 and pass2
487                         $_POST['password'] = md5($_POST['pass1']);
488                 }
489         }
490
491         // Remove all (maybe spoofed) unsafe data from array
492         foreach ($UNSAFE as $remove)
493         {
494                 unset($POST[$remove]);
495         }
496
497         // This array is for the submitted data which we will use with the SQL_QUERY_ESC() function to
498         // secure the data
499         $DATA = array();
500
501         // Prepare SQL string
502         $SQL = "UPDATE "._MYSQL_PREFIX."_sponsor_data SET";
503         foreach ($POST as $key => $value)
504         {
505                 // Mmmmm, too less security here???
506                 $SQL   .= " ".strip_tags($key)."='%s',";
507
508                 // We will secure this later inside the SQL_QUERY_ESC() function
509                 $DATA[] = strip_tags($value);
510
511                 // Compile {SLASH} and so on for the email templates
512                 $POST[$key] = COMPILE_CODE($value);
513         }
514
515         // Check if email has changed
516         if ((!empty($content['email'])) && (!empty($POST['email'])))
517         {
518                 if ($content['email'] != $POST['email'])
519                 {
520                         // Change email address
521                         $EMAIL = true;
522
523                         // Okay, has changed then add status with UNCONFIRMED and new hash code
524                         $SQL .= " status='EMAIL', hash='%s',";
525
526                         // Generate hash code
527                         $HASH = md5($_COOKIE['PHPSESSID'].":".$POST['email'].":".$_SERVER['REMOTE_ADDR'].":".$_SERVER['HTTP_USER_AGENT'].":".time());
528                         $DATA[] = $HASH;
529                 }
530         }
531
532         // Remove last commata
533         $SQL = substr($SQL, 0, -1);
534
535         // Add SQL tail data
536         $SQL .= " WHERE id='%s' AND password='%s' LIMIT 1";
537         $DATA[] = bigintval($_COOKIE['sponsorid']);
538         $DATA[] = $_COOKIE['sponsorpass'];
539
540         // Saving data was completed... ufff...
541         switch ($_GET['what'])
542         {
543         case "account": // Change account data
544                 if ($EMAIL)
545                 {
546                         $MSG   = SPONSOR_ACCOUNT_EMAIL_CHANGED;
547                         $templ = "admin_sponsor_change_email";
548                         $subj  = ADMIN_SPONSOR_ACC_EMAIL_SUBJ;
549                 }
550                  else
551                 {
552                         $MSG   = SPONSOR_ACCOUNT_DATA_SAVED;
553                         $templ = "admin_sponsor_change_data";
554                         $subj  = ADMIN_SPONSOR_ACC_DATA_SUBJ;
555                 }
556                 break;
557
558         case "settings": // Change settings
559                 // Translate some data
560                 $content['receive']  = TRANSLATE_YESNO($content['receive_warnings']);
561                 $content['interval'] = CREATE_FANCY_TIME($content['warning_interval']);
562
563                 // Set message template and subject for admin
564                 $MSG   = SPONSOR_SETTINGS_SAVED;
565                 $templ = "admin_sponsor_settings";
566                 $subj  = ADMIN_SPONSOR_SETTINGS_SUBJ;
567                 break;
568
569         default: // Unknown sponsor what value!
570                 $MSG = SPONSOR_UNKNOWN_WHAT_1.$_GET['what'].SPONSOR_UNKNOWN_WHAT_2;
571                 $templ = ""; $subj = "";
572                 break;
573         }
574
575         if (SQL_AFFECTEDROWS() == 1)
576         {
577                 if (!empty($templ) && !empty($subj))
578                 {
579                         // Run SQL command and check for success
580                         $result = SQL_QUERY_ESC($SQL, $DATA, __FILE__, __LINE__);
581
582                         // Add all data to content
583                         global $DATA;
584                         $DATA = $POST;
585
586                         // Change some data
587                         if (isset($content['salut'])) $content['salut'] = TRANSLATE_SEX($content['salut']);
588                         if (isset($DATA['salut']))    $DATA['salut']    = TRANSLATE_SEX($DATA['salut']);
589                         if (isset($content['receive_warnings'])) $DATA['receive']     = TRANSLATE_YESNO($POST['receive_warnings']);
590                         if (isset($content['warning_interval'])) $DATA['interval']    = CREATE_FANCY_TIME($POST['warning_interval']);
591
592                         // Send email to admins
593                         SEND_ADMIN_NOTIFICATION($subj, $templ, $content);
594
595                         // Shall we send mail to the sponsor's new email address?
596                         if ($content['receive_warnings'] == "Y")
597                         {
598                                 // Okay send email with confirmation link to new address and with no confirmation link
599                                 // to the old address
600
601                                 // First to old address
602                                 switch ($_GET['what'])
603                                 {
604                                 case "account": // Change account data
605                                         $email_msg = LOAD_EMAIL_TEMPLATE("sponsor_change_data", $content);
606                                         SEND_EMAIL($content['email'], SPONSOR_ACC_DATA_SUBJ, $email_msg);
607
608                                         if ($EMAIL)
609                                         {
610                                                 // Add hash code to content array
611                                                 $content['hash'] = $HASH;
612
613                                                 // Second mail goes to the new address
614                                                 $email_msg = LOAD_EMAIL_TEMPLATE("sponsor_change_email", $content);
615                                                 SEND_EMAIL($content['email'], SPONSOR_ACC_EMAIL_SUBJ, $email_msg);
616                                         }
617                                         break;
618
619                                 case "settings": // Change settings
620                                         // Send email
621                                         $email_msg = LOAD_EMAIL_TEMPLATE("sponsor_settings", $content);
622                                         SEND_EMAIL($content['email'], SPONSOR_SETTINGS_SUBJ, $email_msg);
623                                         break;
624                                 }
625                         }
626                 }
627         }
628
629         // Return final message
630         return $MSG;
631 }
632 //
633 ?>