2 /************************************************************************
3 * Mailer v0.2.1-FINAL Start: 04/23/2005 *
4 * =================== Last change: 05/18/2008 *
6 * -------------------------------------------------------------------- *
7 * File : sponsor_functions.php *
8 * -------------------------------------------------------------------- *
9 * Short description : Functions for the sponsor area *
10 * -------------------------------------------------------------------- *
11 * Kurzbeschreibung : Funktionen fuer den Sponsorenbereich *
12 * -------------------------------------------------------------------- *
15 * $Tag:: 0.2.1-FINAL $ *
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 *
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. *
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. *
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, *
38 ************************************************************************/
40 // Some security stuff...
41 if (!defined('__SECURITY')) {
46 function handleSponsorRequest ($postData, $update=false, $messageArray=array(), $RET_STATUS=false) {
47 // Init a lot variables
56 'ok', 'edit', 'terms', 'pay_type'
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
73 if (!isEmailValid($v)) {
74 // Email address is not valid
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__);
81 // Is a sponsor alread in the db?
82 if (SQL_NUMROWS($result) == 1) {
84 if ((getWhat() == 'add_sponsor') || ($update)) {
94 SQL_FREERESULT($result);
103 $k = 'password'; $v = md5($v);
107 if (!isUrlValid($v)) $SAVE = false;
111 // Test if there is are time selections
112 convertSelectionsToTimestamp($postData, $DATA, $k, $skip);
116 if ((!empty($k)) && ($skip == false)) {
118 $DATA['keys'][] = $k; $DATA['values'][] = $v;
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';
128 // SQL and message string is empty by default
129 $sql = ''; $message = '';
134 $sql = "UPDATE `{?_MYSQL_PREFIX?}_sponsor_data` SET ";
135 foreach ($DATA['keys'] as $k => $v) {
136 $sql .= $v."='%s', ";
139 // Remove last ", " from SQL string
140 $sql = substr($sql, 0, -2)." WHERE `id`='%s' LIMIT 1";
141 $DATA['values'][] = bigintval(getRequestParameter('id'));
144 $message = getMessageFromIndexedArray('{--ADMIN_SPONSOR_UPDATED--}', 'updated', $messageArray);
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';
155 $DATA['values'][] = 'UNCONFIRMED';
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();
165 $key = array_search('force', $DATA['keys']);
167 // Remove force from both arrays
168 unset($DATA['keys'][$key]);
169 unset($DATA['values'][$key]);
171 // Implode all data into strings
172 $keyArray = implode('`, `' , $DATA['keys']);
173 $valueArray = str_repeat("%s', '", count($DATA['values']) - 1);
176 $sql = 'INSERT INTO `{?_MYSQL_PREFIX?}_sponsor_data` (`' . $keyArray . "`) VALUES ('" . $valueArray . "%s')";
179 $message = getMessageFromIndexedArray('{--ADMIN_SPONSOR_ADDED--}', 'added', $messageArray);
181 } elseif (($update === true) && (isAdmin())) {
182 // Add all data as hidden data
184 foreach ($postData as $k => $v) {
185 // Do not add 'force' !
187 $OUT .= '<input type="hidden" name="' . secureString($k) . '" value="' . SQL_ESCAPE($v) . '" />';
192 $content['hidden'] = $OUT;
193 $content['email'] = $postData['email'];
195 // Ask for adding a sponsor with same email address
196 loadTemplate('admin_add_sponsor_already', false, $content);
200 $message = getMaskedMessage('SPONSOR_ALREADY_FOUND', $postData['email']);
206 $result = SQL_QUERY_ESC($sql, $DATA['values'], __FUNCTION__, __LINE__);
210 $message = getMessageFromIndexedArray('{--SPONSOR_DATA_NOT_SAVED--}', 'failed', $messageArray);
211 loadTemplate('admin_settings_saved', false, $message);
214 // Always return the status
219 function sponsorTranslateUserStatus ($status) {
220 // Construct constant name
221 $constantName = sprintf("ACCOUNT_STATUS_%s", $status);
223 // Is the constant there?
224 if (isMessageIdValid($constantName)) {
226 $ret = getMessage($constantName);
229 /* DEBUG: */ debug_report_bug(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
230 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
231 $ret = getMaskedMessage('ACCOUNT_STATUS_UNKNOWN_STATUS', $status);
238 // Search for an email address in the database
239 function isSponsorRegisteredWithEmail ($email) {
240 // Do we already have the provided email address in our DB?
241 $ret = (countSumTotalData($email, 'sponsor_data', 'id', 'email', true) == 1);
247 // Wether the current user is a sponsor
248 function isSponsor () {
251 if ((isSessionVariableSet('sponsor_id')) && (isSessionVariableSet('sponsorpass'))) {
252 // Check cookies against database records...
253 $result = SQL_QUERY_ESC("SELECT
256 `{?_MYSQL_PREFIX?}_sponsor_data`
258 `id`='%s' AND `password`='%s' AND `status`='CONFIRMED'
261 bigintval(getSession('sponsor_id')),
262 getSession('sponsorpass')
263 ), __FUNCTION__, __LINE__);
264 if (SQL_NUMROWS($result) == 1) {
270 SQL_FREERESULT($result);
278 function addSponsorMenu ($current) {
280 $WHERE = " AND `active`='Y'";
281 if (isAdmin()) $WHERE = '';
283 // Load main menu entries
284 $result_main = SQL_QUERY("SELECT
285 `action` AS `main_action`, `title` AS `main_title`
287 `{?_MYSQL_PREFIX?}_sponsor_menu`
289 (`what`='' OR `what` IS NULL)
292 `sort` ASC", __FUNCTION__, __LINE__);
293 if (!SQL_HASZERONUMS($result_main)) {
294 // Load every menu and it's sub menus
295 while ($content = SQL_FETCHARRAY($result_main)) {
297 $result_sub = SQL_QUERY_ESC("SELECT
298 `what` AS `sub_what`, `title` AS `sub_title`
300 `{?_MYSQL_PREFIX?}_sponsor_menu`
308 array($content['main_action']), __FUNCTION__, __LINE__);
309 if (!SQL_HASZERONUMS($result_sub)) {
312 while ($content2 = SQL_FETCHARRAY($result_sub)) {
314 $content = merge_array($content, $content2);
316 // Check if current selected menu is matching the loaded one
317 if ($current == $content['sub_what']) $content['sub_title'] = '<strong>' . $content['sub_title'] . '</strong>';
319 // Prepare data for the sub template
321 'what' => $content['sub_what'],
322 'title' => $content['sub_title']
326 $SUB .= loadTemplate('sponsor_what', true, $content);
329 // Prepare data for the main template
331 'title' => $content['main_title'],
335 // Load menu template
336 $OUT .= loadTemplate('sponsor_action', true, $content);
338 // No sub menus active
339 $OUT .= loadTemplate('admin_settings_saved', true, '{--SPONSOR_NO_SUB_MENUS_ACTIVE--}');
343 SQL_FREERESULT($result_sub);
346 // No main menus active
347 $OUT .= loadTemplate('admin_settings_saved', true, '{--SPONSOR_NO_MAIN_MENUS_ACTIVE--}');
351 SQL_FREERESULT($result_main);
358 function addSponsorContent ($what) {
360 $INC = sprintf("inc/modules/sponsor/%s.php", $what);
361 if (isIncludeReadable($INC)) {
362 // Every sponsor action will output nothing directly. It will be written into $OUT!
363 loadIncludeOnce($INC);
366 $OUT .= loadTemplate('admin_settings_saved', true, getMaskedMessage('SPONSOR_CONTENT_404', $what));
374 function updateSponsorLogin () {
380 // Update last online timestamp
381 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_sponsor_data`
382 SET `last_online`=UNIX_TIMESTAMP()
383 WHERE `id`='%s' AND `password`='%s' LIMIT 1",
385 bigintval(getSession('sponsor_id')),
386 getSession('sponsorpass')
387 ), __FUNCTION__, __LINE__);
389 // This update went fine?
390 $login = (SQL_AFFECTEDROWS() == 1);
397 // Saves sponsor's data
398 function saveSponsorData ($postData, $content) {
401 // Unsecure data which we don't want
402 $UNSAFE = array('password', 'id', 'remote_addr', 'sponsor_created', 'last_online', 'status', 'ref_count',
403 'points_amount', 'points_used', 'refid', 'hash', 'last_pay', 'last_curr', 'pass_old',
404 'ok', 'pass1', 'pass2');
406 // Set default message ("not saved")
407 $message = '{--SPONSOR_ACCOUNT_DATA_NOT_SAVED--}';
409 // Check for submitted passwords
410 if ((!empty($postData['pass1'])) && (!empty($postData['pass2']))) {
411 // Are both passwords the same?
412 if ($postData['pass1'] == $postData['pass2']) {
413 // Okay, then set password and remove pass1 and pass2
414 $postData['password'] = md5($postData['pass1']);
418 // Remove all (maybe spoofed) unsafe data from array
419 foreach ($UNSAFE as $remove) {
420 unset($postData[$remove]);
423 // This array is for the submitted data which we will use with the SQL_QUERY_ESC() function to
427 // Prepare SQL string
428 $sql = "UPDATE `{?_MYSQL_PREFIX?}_sponsor_data` SET";
429 foreach ($postData as $key => $value) {
430 // Mmmmm, too less security here???
431 $sql .= " `" . secureString($key) . "`='%s',";
433 // We will secure this later inside the SQL_QUERY_ESC() function
434 $DATA[] = secureString($value);
437 // Check if email has changed
438 if ((!empty($content['email'])) && (!empty($postData['email']))) {
439 if ($content['email'] != $postData['email']) {
440 // Change email address
443 // Okay, has changed then add status with UNCONFIRMED and new hash code
444 $sql .= " `status`='EMAIL', `hash`='%s',";
446 // Generate hash code
447 $HASH = md5(session_id().':'.$postData['email'].':'.detectRemoteAddr().':'.detectUserAgent().':'.time());
452 // Remove last commata
453 $sql = substr($sql, 0, -1);
456 $sql .= " WHERE `id`=%s AND `password`='%s' LIMIT 1";
457 $DATA[] = bigintval(getSession('sponsor_id'));
458 $DATA[] = getSession('sponsorpass');
460 // Saving data was completed... ufff...
462 case 'account': // Change account data
463 if ($EMAIL === true) {
464 $message = '{--SPONSOR_ACCOUNT_EMAIL_CHANGED--}';
465 $templ = 'admin_sponsor_change_email';
466 $subj = '{--ADMIN_SPONSOR_ACC_EMAIL_SUBJECT--}';
468 $message = '{--SPONSOR_ACCOUNT_DATA_SAVED--}';
469 $templ = 'admin_sponsor_change_data';
470 $subj = '{--ADMIN_SPONSOR_ACC_DATA_SUBJECT--}';
474 case 'settings': // Change settings
475 // Set message template and subject for admin
476 $message = '{--SPONSOR_SETTINGS_SAVED--}';
477 $templ = 'admin_sponsor_settings';
478 $subj = '{--ADMIN_SPONSOR_SETTINGS_SUBJECT--}';
481 default: // Unknown sponsor what value!
482 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown sponsor module (what) %s detected.", getWhat()));
483 $message = getMaskedMessage('SPONSOR_UNKNOWN_WHAT', getWhat());
489 // Has an entry updated?
490 if (SQL_AFFECTEDROWS() == 1) {
491 // Template and subject are set?
492 if (!empty($templ) && !empty($subj)) {
493 // Run SQL command and check for success
494 $result = SQL_QUERY_ESC($sql, $DATA, __FUNCTION__, __LINE__);
496 // Add all data to content
497 $content['new_data'] = $postData;
499 // Send email to admins
500 sendAdminNotification($subj, $templ, $content);
502 // Shall we send mail to the sponsor's new email address?
503 if ($content['receive_warnings'] == 'Y') {
505 * Okay send email with confirmation link to new address and with no confirmation link
506 * to the old address.
509 // First to old address
511 case 'account': // Change account data
512 $email_msg = loadEmailTemplate('sponsor_change_data', $content);
513 sendEmail($content['email'], '{--SPONSOR_ACC_DATA_SUBJECT--}', $email_msg);
515 if ($EMAIL === true) {
516 // Add hash code to content array
517 $content['hash'] = $HASH;
519 // Second mail goes to the new address
520 $email_msg = loadEmailTemplate('sponsor_change_email', $content);
521 sendEmail($content['email'], '{--SPONSOR_ACC_EMAIL_SUBJECT--}', $email_msg);
525 case 'settings': // Change settings
527 $email_msg = loadEmailTemplate('sponsor_settings', $content);
528 sendEmail($content['email'], '{--SPONSOR_SETTINGS_SUBJECT--}', $email_msg);
535 // Return final message
539 // Create email link to sponsor's account
540 function generateSponsorEmailLink ($email, $mod = 'admin') {
541 // Show contact link only if sponsor is confirmed by default
542 $locked = " AND `status`='CONFIRMED'";
544 // But admins shall always see it
545 if (isAdmin()) $locked = '';
547 $result = SQL_QUERY_ESC("SELECT
550 `{?_MYSQL_PREFIX?}_sponsor_data`
552 `email`='%s'" . $locked."
554 array($email), __FUNCTION__, __LINE__);
555 if (SQL_NUMROWS($result) == 1) {
557 list($sponsor_id) = SQL_FETCHROW($result);
559 // Rewrite email address to contact link
560 $email = '{%url=modules.php?module=' . $mod . '&what=sponsor_contct&sponsor_id=' . bigintval($sponsor_id) . '%}';
564 SQL_FREERESULT($result);
566 // Return rewritten (?) email address
570 // Processes a sponsor request and handles it
571 function doProcessSponsorFormRequest ($messageArray = array()) {
575 // Handle the request
576 $status = handleSponsorRequest(postRequestArray(), true, $messageArray, true);
578 // Check the status of the registration process
580 case 'added': // Sponsor successfully added with account status = UNCONFIRMED!
581 // Check for his id number
582 $result = SQL_QUERY_ESC("SELECT `id`, `hash` FROM `{?_MYSQL_PREFIX?}_sponsor_data` WHERE `email`='%s' LIMIT 1",
583 array(postRequestParameter('email')), __FILE__, __LINE__);
584 if (SQL_NUMROWS($result) == 1) {
585 // id found so let's load it for the confirmation email
586 list($id, $hash) = SQL_FETCHROW($result);
588 // Prepare data for the email template
589 $content['id'] = $id;
590 $content['hash'] = $hash;
591 $content['email'] = secureString(postRequestParameter('email'));
592 $content['surname'] = secureString(postRequestParameter('surname'));
593 $content['family'] = secureString(postRequestParameter('family'));
594 $content['timestamp'] = generateDateTime(time(), 0);
595 $content['password'] = secureString(postRequestParameter('pass1'));
597 // Generate email and send it to the new sponsor
598 $message = loadEmailTemplate('sponsor_confirm', $hash);
599 sendEmail(postRequestParameter('email'), '{--SPONSOR_PLEASE_CONFIRM_SUBJECT--}', $message);
601 // Send mail to admin
602 sendAdminNotification('{--ADMIN_NEW_SPONSOR--}', 'admin_sponsor_reg', $hash);
604 // Output message: DONE
605 $message = $messageArray['added'];
607 // Sponsor account not found???
608 $message = getMaskedMessage('SPONSOR_EMAIL_404', postRequestParameter('email'));
612 SQL_FREERESULT($result);
616 logDebugMessage(__FILE__, __LINE__, sprintf("Unknown status %s detected.", $status));
618 // Message for testing admin
619 $message = getMaskedMessage('ADMIN_SPONSOR_UNKNOWN_STATUS', $status);
621 // Message for the guest
622 $message = getMaskedMessage('SPONSOR_UNKNOWN_STATUS', $status);