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