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