Fixed logfile writing in installation phase, .revision is now ignored
[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:: 856                                                    $ *
14  * $Date:: 2009-03-06 20:24:32 +0100 (Fr, 06. Mär 2009)              $ *
15  * $Tag:: 0.2.1-FINAL                                                 $ *
16  * $Author:: stelzi                                                   $ *
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, $MSGs=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 (!VALIDATE_EMAIL($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 (($GLOBALS['what'] == "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 (!VALIDATE_URL($v)) $SAVE = false;
107                                 break;
108
109                         default:
110                                 // Test if there is are time selections
111                                 CONVERT_SELECTIONS_TO_TIMESTAMP($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 = ""; $MSG = "";
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                         $MSG = SPONSOR_GET_MESSAGE(ADMIN_SPONSOR_UPDATED, "updated", $MSGs);
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()) && ($GLOBALS['what'] == "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'].":".GET_REMOTE_ADDR().":".GET_USER_AGENT().":".time());
159                                 $DATA['keys'][] = "remote_addr";
160                                 $DATA['values'][] = GET_REMOTE_ADDR();
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                         $MSG = SPONSOR_GET_MESSAGE(getMessage('ADMIN_SPONSOR_ADDED'), "added", $MSGs);
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                         $MSG = 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                 }
198
199                 // Output message
200                 if ((!$NO_UPDATE) && (IS_ADMIN())) {
201                         LOAD_TEMPLATE("admin_settings_saved", false, $MSG);
202                 }
203         } else {
204                 // Error found!
205                 $MSG = SPONSOR_GET_MESSAGE(getMessage('SPONSOR_DATA_NOT_SAVED'), "failed", $MSGs);
206                 LOAD_TEMPLATE("admin_settings_saved", false, $MSG);
207         }
208
209         // Shall we return the status?
210         if ($RET_STATUS) return $ret;
211 }
212 //
213 function SPONSOR_TRANSLATE_STATUS ($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 ($msg, $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 = $msg;
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 id FROM `{!_MYSQL_PREFIX!}_sponsor_data`
258 WHERE id='%s' AND password='%s' AND `status`='CONFIRMED' LIMIT 1",
259                         array(bigintval(get_session('sponsorid')), get_session('sponsorpass')), __FUNCTION__, __LINE__);
260                 if (SQL_NUMROWS($result) == 1) {
261                         // All is fine
262                         $ret = true;
263                 }
264
265                 // Free memory
266                 SQL_FREERESULT($result);
267         }
268
269         // Return status
270         return $ret;
271 }
272 //
273 function GENERATE_SPONSOR_MENU($current)
274 {
275         $OUT = "";
276         $WHERE = " AND active='Y'";
277         if (IS_ADMIN()) $WHERE = "";
278
279         // Load main menu entries
280         $result_main = SQL_QUERY("SELECT action AS main_action, title AS main_title FROM `{!_MYSQL_PREFIX!}_sponsor_menu`
281 WHERE (what='' OR `what` IS NULL) ".$WHERE."
282 ORDER BY `sort`", __FUNCTION__, __LINE__);
283         if (SQL_NUMROWS($result_main) > 0) {
284                 // Load every menu and it's sub menus
285                 while ($content = SQL_FETCHARRAY($result_main)) {
286                         // Load sub menus
287                         $result_sub = SQL_QUERY_ESC("SELECT what AS sub_what, title AS sub_title FROM `{!_MYSQL_PREFIX!}_sponsor_menu`
288 WHERE `action`='%s' AND `what` != '' AND `what` IS NOT NULL ".$WHERE."
289 ORDER BY `sort`",
290                                 array($content['main_action']), __FUNCTION__, __LINE__);
291                         if (SQL_NUMROWS($result_sub) > 0) {
292                                 // Load sub menus
293                                 $SUB = "";
294                                 while ($content2 = SQL_FETCHARRAY($result_sub)) {
295                                         // Merge both arrays
296                                         $content = merge_array($content, $content2);
297
298                                         // Check if current selected menu is matching the loaded one
299                                         if ($current == $content['sub_what']) $content['sub_title'] = "<strong>".$content['sub_title']."</strong>";
300
301                                         // Prepare data for the sub template
302                                         $content = array(
303                                                 'what'  => $content['sub_what'],
304                                                 'title' => $content['sub_title']
305                                         );
306
307                                         // Load row template
308                                         $SUB .= LOAD_TEMPLATE("sponsor_what", true, $content);
309                                 }
310
311                                 // Prepare data for the main template
312                                 $content = array(
313                                         'title' => $content['main_title'],
314                                         'menu'  => $SUB
315                                 );
316
317                                 // Load menu template
318                                 $OUT .= LOAD_TEMPLATE("sponsor_action", true, $content);
319                         } else {
320                                 // No sub menus active
321                                 $OUT .= LOAD_TEMPLATE("admin_settings_saved", true, getMessage('SPONSOR_NO_SUB_MENUS_ACTIVE'));
322                         }
323
324                         // Free memory
325                         SQL_FREERESULT($result_sub);
326                 }
327         } else {
328                 // No main menus active
329                 $OUT .= LOAD_TEMPLATE("admin_settings_saved", true, getMessage('SPONSOR_NO_MAIN_MENUS_ACTIVE'));
330         }
331
332         // Free memory
333         SQL_FREERESULT($result_main);
334
335         // Return content
336         return $OUT;
337 }
338
339 //
340 function GENERATE_SPONSOR_CONTENT ($what) {
341         $OUT = "";
342         $INC = sprintf("inc/modules/sponsor/%s.php", $what);
343         if (INCLUDE_READABLE($INC)) {
344                 // Every sponsor action will output nothing directly. It will be written into $OUT!
345                 LOAD_INC_ONCE($INC);
346         } else {
347                 // File not found!
348                 $OUT .= LOAD_TEMPLATE("admin_settings_saved", true, sprintf(getMessage('SPONSOR_CONTENT_404'), $what));
349         }
350
351         // Return content
352         return $OUT;
353 }
354
355 //
356 function UPDATE_SPONSOR_LOGIN () {
357         // Failed by default
358         $login = false;
359
360         // Is sponsor?
361         if (IS_SPONSOR()) {
362                 // Update last online timestamp
363                 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_sponsor_data`
364 SET last_online=UNIX_TIMESTAMP()
365 WHERE id='%s' AND password='%s' LIMIT 1",
366                         array(bigintval(get_session('sponsorid')), get_session('sponsorpass')), __FUNCTION__, __LINE__);
367
368                 // This update went fine?
369                 $login = (SQL_AFFECTEDROWS() == 1);
370         }
371
372         // Return status
373         return $login;
374 }
375 //
376 function SPONSOR_SAVE_DATA ($POST, $content) {
377         $EMAIL = false;
378
379         // Unsecure data which we don't want
380         $UNSAFE = array('password', 'id', 'remote_addr', 'sponsor_created', 'last_online', 'status', 'ref_count',
381                         'points_amount', 'points_used', 'refid', 'hash', 'last_pay', 'last_curr', 'pass_old',
382                         'ok', 'pass1', 'pass2');
383
384         // Set default message ("not saved")
385         $MSG = getMessage('SPONSOR_ACCOUNT_DATA_NOT_SAVED');
386
387         // Check for submitted passwords
388         if ((!empty($POST['pass1'])) && (!empty($POST['pass2']))) {
389                 // Are both passwords the same?
390                 if ($POST['pass1'] == $POST['pass2']) {
391                         // Okay, then set password and remove pass1 and pass2
392                         $POST['password'] = md5($POST['pass1']);
393                 } // END - if
394         } // END - if
395
396         // Remove all (maybe spoofed) unsafe data from array
397         foreach ($UNSAFE as $remove) {
398                 unset($POST[$remove]);
399         } // END - foreach
400
401         // This array is for the submitted data which we will use with the SQL_QUERY_ESC() function to
402         // secure the data
403         $DATA = array();
404
405         // Prepare SQL string
406         $sql = "UPDATE `{!_MYSQL_PREFIX!}_sponsor_data` SET";
407         foreach ($POST as $key => $value) {
408                 // Mmmmm, too less security here???
409                 $sql   .= " ".strip_tags($key)."='%s',";
410
411                 // We will secure this later inside the SQL_QUERY_ESC() function
412                 $DATA[] = strip_tags($value);
413
414                 // Compile {SLASH} and so on for the email templates
415                 $POST[$key] = COMPILE_CODE($value);
416         } // END - foreach
417
418         // Check if email has changed
419         if ((!empty($content['email'])) && (!empty($POST['email']))) {
420                 if ($content['email'] != $POST['email']) {
421                         // Change email address
422                         $EMAIL = true;
423
424                         // Okay, has changed then add status with UNCONFIRMED and new hash code
425                         $sql .= " `status`='EMAIL', hash='%s',";
426
427                         // Generate hash code
428                         $HASH = md5(session_id().":".$POST['email'].":".GET_REMOTE_ADDR().":".GET_USER_AGENT().":".time());
429                         $DATA[] = $HASH;
430                 } // END - if
431         } // END - if
432
433         // Remove last commata
434         $sql = substr($sql, 0, -1);
435
436         // Add SQL tail data
437         $sql .= " WHERE id='%s' AND password='%s' LIMIT 1";
438         $DATA[] = bigintval(get_session('sponsorid'));
439         $DATA[] = get_session('sponsorpass');
440
441         // Saving data was completed... ufff...
442         switch ($GLOBALS['what'])
443         {
444         case "account": // Change account data
445                 if ($EMAIL === true) {
446                         $MSG   = getMessage('SPONSOR_ACCOUNT_EMAIL_CHANGED');
447                         $templ = "admin_sponsor_change_email";
448                         $subj  = getMessage('ADMIN_SPONSOR_ACC_EMAIL_SUBJ');
449                 } else {
450                         $MSG   = getMessage('SPONSOR_ACCOUNT_DATA_SAVED');
451                         $templ = "admin_sponsor_change_data";
452                         $subj  = getMessage('ADMIN_SPONSOR_ACC_DATA_SUBJ');
453                 }
454                 break;
455
456         case "settings": // Change settings
457                 // Translate some data
458                 $content['receive']  = TRANSLATE_YESNO($content['receive_warnings']);
459                 $content['interval'] = CREATE_FANCY_TIME($content['warning_interval']);
460
461                 // Set message template and subject for admin
462                 $MSG   = getMessage('SPONSOR_SETTINGS_SAVED');
463                 $templ = "admin_sponsor_settings";
464                 $subj  = getMessage('ADMIN_SPONSOR_SETTINGS_SUBJ');
465                 break;
466
467         default: // Unknown sponsor what value!
468                 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown sponsor module (what) %s detected.", $GLOBALS['what']));
469                 $MSG = sprintf(getMessage('SPONSOR_UNKNOWN_WHAT'), $GLOBALS['what']);
470                 $templ = ""; $subj = "";
471                 break;
472         }
473
474         if (SQL_AFFECTEDROWS() == 1) {
475                 if (!empty($templ) && !empty($subj)) {
476                         // Run SQL command and check for success
477                         $result = SQL_QUERY_ESC($sql, $DATA, __FUNCTION__, __LINE__);
478
479                         // Add all data to content
480                         global $DATA;
481                         $DATA = $POST;
482
483                         // Change some data
484                         if (isset($content['gender'])) $content['gender'] = TRANSLATE_GENDER($content['gender']);
485                         if (isset($DATA['gender']))    $DATA['gender']    = TRANSLATE_GENDER($DATA['gender']);
486                         if (isset($content['receive_warnings'])) $DATA['receive']     = TRANSLATE_YESNO($POST['receive_warnings']);
487                         if (isset($content['warning_interval'])) $DATA['interval']    = CREATE_FANCY_TIME($POST['warning_interval']);
488
489                         // Send email to admins
490                         SEND_ADMIN_NOTIFICATION($subj, $templ, $content);
491
492                         // Shall we send mail to the sponsor's new email address?
493                         if ($content['receive_warnings'] == "Y") {
494                                 // Okay send email with confirmation link to new address and with no confirmation link
495                                 // to the old address
496
497                                 // First to old address
498                                 switch ($GLOBALS['what'])
499                                 {
500                                 case "account": // Change account data
501                                         $email_msg = LOAD_EMAIL_TEMPLATE("sponsor_change_data", $content);
502                                         SEND_EMAIL($content['email'], getMessage('SPONSOR_ACC_DATA_SUBJ'), $email_msg);
503
504                                         if ($EMAIL === true) {
505                                                 // Add hash code to content array
506                                                 $content['hash'] = $HASH;
507
508                                                 // Second mail goes to the new address
509                                                 $email_msg = LOAD_EMAIL_TEMPLATE("sponsor_change_email", $content);
510                                                 SEND_EMAIL($content['email'], getMessage('SPONSOR_ACC_EMAIL_SUBJ'), $email_msg);
511                                         }
512                                         break;
513
514                                 case "settings": // Change settings
515                                         // Send email
516                                         $email_msg = LOAD_EMAIL_TEMPLATE("sponsor_settings", $content);
517                                         SEND_EMAIL($content['email'], getMessage('SPONSOR_SETTINGS_SUBJ'), $email_msg);
518                                         break;
519                                 }
520                         } // END - if
521                 } // END - if
522         } // END - if
523
524         // Return final message
525         return $MSG;
526 }
527
528 //
529 ?>