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