5c511f85a61e96b1f2ebc002d527657b07b1f2b0
[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 (!defined('__SECURITY')) {
35         $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), "/inc") + 4)."/security.php";
36         require($INC);
37 }
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 (($GLOBALS['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()) && ($GLOBALS['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'].":".GET_REMOTE_ADDR().":".GET_USER_AGENT().":".time());
197                                 $DATA['keys'][] = "remote_addr";
198                                 $DATA['values'][] = GET_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                 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
287                 $ret = UNKNOWN_STATUS_1.$status.UNKNOWN_STATUS_2;
288                 break;
289         }
290         return $ret;
291 }
292 // Search for an email address in the database
293 function SPONSOR_FOUND_EMAIL_DB($email)
294 {
295         // Default status is failed (as it is always be...)
296         $ret = false;
297
298         // Check for email (and secure input)
299         $result = SQL_QUERY_ESC("SELECT id FROM "._MYSQL_PREFIX."_sponsor_data WHERE email='%s' LIMIT 1",
300          array($email), __FILE__, __LINE__);
301
302         // Do we already have the provided email address in our DB?
303         if (SQL_NUMROWS($result) == 1) $ret = true;
304
305         // Return result
306         return $ret;
307 }
308 //
309 function SPONSOR_SET_MESSAGE($msg, $pos, $array)
310 {
311         // Check if the requested message was found in array
312         if (isset($array[$pos]))
313         {
314                 // ... if yes then use it!
315                 $ret = $array[$pos];
316         }
317          else
318         {
319                 // ... else use default message
320                 $ret = $msg;
321         }
322
323         // Return result
324         return $ret;
325 }
326 //
327 function IS_SPONSOR()
328 {
329         global $_COOKIE;
330         // Failed...
331         $ret = false;
332         if ((!empty($_COOKIE['sponsorid'])) && (!empty($_COOKIE['sponsorpass'])))
333         {
334                 // Check cookies against database records...
335                 $result = SQL_QUERY_ESC("SELECT id FROM "._MYSQL_PREFIX."_sponsor_data
336 WHERE id='%s' AND password='%s' AND status='CONFIRMED' LIMIT 1",
337  array(bigintval($_COOKIE['sponsorid']), $_COOKIE['sponsorpass']), __FILE__, __LINE__);
338                 if (SQL_NUMROWS($result) == 1)
339                 {
340                         // All is fine
341                         $ret = true;
342                 }
343
344                 // Free memory
345                 SQL_FREERESULT($result);
346         }
347
348         // Return status
349         return $ret;
350 }
351 //
352 function GENERATE_SPONSOR_MENU($current)
353 {
354         $OUT = "";
355         $WHERE = " AND active='Y'";
356         if (IS_ADMIN()) $WHERE = "";
357
358         // Load main menu entries
359         $result_main = SQL_QUERY("SELECT action, title FROM "._MYSQL_PREFIX."_sponsor_menu
360 WHERE (what='' OR what IS NULL) ".$WHERE."
361 ORDER BY sort", __FILE__, __LINE__);
362         if (SQL_NUMROWS($result_main) > 0)
363         {
364                 // Load every menu and it's sub menus
365                 while(list($action, $title_main) = SQL_FETCHROW($result_main))
366                 {
367                         // Load sub menus
368                         $result_sub = SQL_QUERY_ESC("SELECT what, title FROM "._MYSQL_PREFIX."_sponsor_menu
369 WHERE action='%s' AND what != '' AND what IS NOT NULL ".$WHERE."
370 ORDER BY sort", array($action), __FILE__, __LINE__);
371                         if (SQL_NUMROWS($result_sub) > 0)
372                         {
373                                 // Load sub menus
374                                 $SUB = "";
375                                 while(list($what, $title_sub) = SQL_FETCHROW($result_sub))
376                                 {
377                                         // Check if current selected menu is matching the loaded one
378                                         if ($current == $what) $title_sub = "<STRONG>".$title_sub."</STRONG>";
379
380                                         // Prepare data for the sub template
381                                         $content = array(
382                                                 'what'  => $what,
383                                                 'title' => $title_sub
384                                         );
385
386                                         // Load row template
387                                         $SUB .= LOAD_TEMPLATE("sponsor_what", true, $content);
388                                 }
389
390                                 // Prepare data for the main template
391                                 $content = array(
392                                         'title' => $title_main,
393                                         'menu'  => $SUB
394                                 );
395
396                                 // Load menu template
397                                 $OUT .= LOAD_TEMPLATE("sponsor_action", true, $content);
398                         }
399                          else
400                         {
401                                 // No sub menus active
402                                 $OUT .= LOAD_TEMPLATE("admin_settings_saved", true, SPONSOR_NO_SUB_MENUS_ACTIVE);
403                         }
404
405                         // Free memory
406                         SQL_FREERESULT($result_sub);
407                 }
408         }
409          else
410         {
411                 // No main menus active
412                 $OUT .= LOAD_TEMPLATE("admin_settings_saved", true, SPONSOR_NO_MAIN_MENUS_ACTIVE);
413         }
414
415         // Free memory
416         SQL_FREERESULT($result_main);
417
418         // Return content
419         return $OUT;
420 }
421 //
422 function GENERATE_SPONSOR_CONTENT($what)
423 {
424         global $_CONFIG;
425         $OUT = "";
426         $FILE = sprintf("%sinc/modules/sponsor/%s.php", PATH, $what);
427         if (FILE_READABLE($FILE)) {
428                 // Every sponsor action will output nothing directly. It will be written into $OUT!
429                 require_once($FILE);
430         } else {
431                 // File not found!
432                 $OUT .= LOAD_TEMPLATE("admin_settings_saved", true, SPONSOR_CONTENT_404_1.$what.SPONSOR_CONTENT_404_2);
433         }
434
435         // Return content
436         return $OUT;
437 }
438 //
439 function UPDATE_SPONSOR_LOGIN()
440 {
441         global $_COOKIE, $_CONFIG;
442
443         // Check if cookies are set
444         if ((empty($_COOKIE['sponsorid'])) || (empty($_COOKIE['sponsorpass']))) return false;
445
446         // Calculate cookie lifetime, maybe we have to change this so the admin can setup a
447         // seperate timeout for these two cookies?
448         $life = (time() + $_CONFIG['online_timeout']);
449
450         // Is confirmed so both is fine and we can continue with login procedure
451         $login = ((setcookie("sponsorid"  , bigintval($_COOKIE['sponsorid']), $life, COOKIE_PATH)) &&
452                   (setcookie("sponsorpass", $_COOKIE['sponsorpass']         , $life, COOKIE_PATH)));
453
454         // Update database?
455         if ($login)
456         {
457                 // Update last online timestamp
458                 $result = SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_sponsor_data
459 SET last_online='".time()."'
460 WHERE id='%s' AND password='%s' LIMIT 1",
461  array(bigintval($_COOKIE['sponsorid']), $_COOKIE['sponsorpass']), __FILE__, __LINE__);
462         }
463
464         // Return status
465         return $login;
466 }
467 //
468 function SPONSOR_SAVE_DATA($POST, $content)
469 {
470         global $_COOKIE, $_SERVER, $_GET;
471         $EMAIL = false;
472
473         // Unsecure data which we don't want
474         $UNSAFE = array('password', 'id', 'remote_addr', 'sponsor_created', 'last_online', 'status', 'ref_count',
475                         'points_amount', 'points_used', 'refid', 'hash', 'last_pay', 'last_curr', 'pass_old',
476                         'ok', 'pass1', 'pass2');
477
478         // Set default message ("not saved")
479         $MSG = SPONSOR_ACCOUNT_DATA_NOT_SAVED;
480
481         // Check for submitted passwords
482         if ((!empty($_POST['pass1'])) && (!empty($_POST['pass2'])))
483         {
484                 // Are both passwords the same?
485                 if ($_POST['pass1'] == $_POST['pass2'])
486                 {
487                         // Okay, then set password and remove pass1 and pass2
488                         $_POST['password'] = md5($_POST['pass1']);
489                 }
490         }
491
492         // Remove all (maybe spoofed) unsafe data from array
493         foreach ($UNSAFE as $remove)
494         {
495                 unset($POST[$remove]);
496         }
497
498         // This array is for the submitted data which we will use with the SQL_QUERY_ESC() function to
499         // secure the data
500         $DATA = array();
501
502         // Prepare SQL string
503         $SQL = "UPDATE "._MYSQL_PREFIX."_sponsor_data SET";
504         foreach ($POST as $key => $value)
505         {
506                 // Mmmmm, too less security here???
507                 $SQL   .= " ".strip_tags($key)."='%s',";
508
509                 // We will secure this later inside the SQL_QUERY_ESC() function
510                 $DATA[] = strip_tags($value);
511
512                 // Compile {SLASH} and so on for the email templates
513                 $POST[$key] = COMPILE_CODE($value);
514         }
515
516         // Check if email has changed
517         if ((!empty($content['email'])) && (!empty($POST['email'])))
518         {
519                 if ($content['email'] != $POST['email'])
520                 {
521                         // Change email address
522                         $EMAIL = true;
523
524                         // Okay, has changed then add status with UNCONFIRMED and new hash code
525                         $SQL .= " status='EMAIL', hash='%s',";
526
527                         // Generate hash code
528                         $HASH = md5($_COOKIE['PHPSESSID'].":".$POST['email'].":".GET_REMOTE_ADDR().":".GET_USER_AGENT().":".time());
529                         $DATA[] = $HASH;
530                 }
531         }
532
533         // Remove last commata
534         $SQL = substr($SQL, 0, -1);
535
536         // Add SQL tail data
537         $SQL .= " WHERE id='%s' AND password='%s' LIMIT 1";
538         $DATA[] = bigintval($_COOKIE['sponsorid']);
539         $DATA[] = $_COOKIE['sponsorpass'];
540
541         // Saving data was completed... ufff...
542         switch ($GLOBALS['what'])
543         {
544         case "account": // Change account data
545                 if ($EMAIL)
546                 {
547                         $MSG   = SPONSOR_ACCOUNT_EMAIL_CHANGED;
548                         $templ = "admin_sponsor_change_email";
549                         $subj  = ADMIN_SPONSOR_ACC_EMAIL_SUBJ;
550                 }
551                  else
552                 {
553                         $MSG   = SPONSOR_ACCOUNT_DATA_SAVED;
554                         $templ = "admin_sponsor_change_data";
555                         $subj  = ADMIN_SPONSOR_ACC_DATA_SUBJ;
556                 }
557                 break;
558
559         case "settings": // Change settings
560                 // Translate some data
561                 $content['receive']  = TRANSLATE_YESNO($content['receive_warnings']);
562                 $content['interval'] = CREATE_FANCY_TIME($content['warning_interval']);
563
564                 // Set message template and subject for admin
565                 $MSG   = SPONSOR_SETTINGS_SAVED;
566                 $templ = "admin_sponsor_settings";
567                 $subj  = ADMIN_SPONSOR_SETTINGS_SUBJ;
568                 break;
569
570         default: // Unknown sponsor what value!
571                 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown sponsor module (what) %s detected.", $GLOBALS['what']));
572                 $MSG = SPONSOR_UNKNOWN_WHAT_1.$GLOBALS['what'].SPONSOR_UNKNOWN_WHAT_2;
573                 $templ = ""; $subj = "";
574                 break;
575         }
576
577         if (SQL_AFFECTEDROWS() == 1)
578         {
579                 if (!empty($templ) && !empty($subj))
580                 {
581                         // Run SQL command and check for success
582                         $result = SQL_QUERY_ESC($SQL, $DATA, __FILE__, __LINE__);
583
584                         // Add all data to content
585                         global $DATA;
586                         $DATA = $POST;
587
588                         // Change some data
589                         if (isset($content['gender'])) $content['gender'] = TRANSLATE_GENDER($content['gender']);
590                         if (isset($DATA['gender']))    $DATA['gender']    = TRANSLATE_GENDER($DATA['gender']);
591                         if (isset($content['receive_warnings'])) $DATA['receive']     = TRANSLATE_YESNO($POST['receive_warnings']);
592                         if (isset($content['warning_interval'])) $DATA['interval']    = CREATE_FANCY_TIME($POST['warning_interval']);
593
594                         // Send email to admins
595                         SEND_ADMIN_NOTIFICATION($subj, $templ, $content);
596
597                         // Shall we send mail to the sponsor's new email address?
598                         if ($content['receive_warnings'] == "Y")
599                         {
600                                 // Okay send email with confirmation link to new address and with no confirmation link
601                                 // to the old address
602
603                                 // First to old address
604                                 switch ($GLOBALS['what'])
605                                 {
606                                 case "account": // Change account data
607                                         $email_msg = LOAD_EMAIL_TEMPLATE("sponsor_change_data", $content);
608                                         SEND_EMAIL($content['email'], SPONSOR_ACC_DATA_SUBJ, $email_msg);
609
610                                         if ($EMAIL)
611                                         {
612                                                 // Add hash code to content array
613                                                 $content['hash'] = $HASH;
614
615                                                 // Second mail goes to the new address
616                                                 $email_msg = LOAD_EMAIL_TEMPLATE("sponsor_change_email", $content);
617                                                 SEND_EMAIL($content['email'], SPONSOR_ACC_EMAIL_SUBJ, $email_msg);
618                                         }
619                                         break;
620
621                                 case "settings": // Change settings
622                                         // Send email
623                                         $email_msg = LOAD_EMAIL_TEMPLATE("sponsor_settings", $content);
624                                         SEND_EMAIL($content['email'], SPONSOR_SETTINGS_SUBJ, $email_msg);
625                                         break;
626                                 }
627                         }
628                 }
629         }
630
631         // Return final message
632         return $MSG;
633 }
634 //
635 ?>