2 /************************************************************************
3 * Mailer v0.2.1-FINAL Start: 08/26/2003 *
4 * =================== Last change: 11/29/2004 *
6 * -------------------------------------------------------------------- *
7 * File : mysql-manager.php *
8 * -------------------------------------------------------------------- *
9 * Short description : All database-related functions *
10 * -------------------------------------------------------------------- *
11 * Kurzbeschreibung : Alle datenbank-relevanten Funktionen *
12 * -------------------------------------------------------------------- *
15 * $Tag:: 0.2.1-FINAL $ *
17 * -------------------------------------------------------------------- *
18 * Copyright (c) 2003 - 2009 by Roland Haeder *
19 * Copyright (c) 2009 - 2011 by Mailer Developer Team *
20 * For more information visit: http://mxchange.org *
22 * This program is free software; you can redistribute it and/or modify *
23 * it under the terms of the GNU General Public License as published by *
24 * the Free Software Foundation; either version 2 of the License, or *
25 * (at your option) any later version. *
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. *
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, *
36 ************************************************************************/
38 // Some security stuff...
39 if (!defined('__SECURITY')) {
43 // "Getter" for module description
44 // @TODO Can we cache this?
45 function getTitleFromMenu ($mode, $what, $column = 'what', $ADD='') {
48 $what = getIndexHome();
49 } elseif ((isGetRequestElementSet('action')) && ($column == 'what')) {
51 return getTitleFromMenu($mode, getAction(), 'action', $ADD);
52 } elseif ($what == 'overview') {
54 return '{--WHAT_IS_OVERVIEW--}';
57 // Default is not found
58 $data['title'] = '??? (' . $what . ')';
61 $result = SQL_QUERY_ESC("SELECT `title` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `%s`='%s'" . $ADD . " LIMIT 1",
66 ), __FUNCTION__, __LINE__);
69 if (SQL_NUMROWS($result) == 1) {
71 $data = SQL_FETCHARRAY($result);
75 SQL_FREERESULT($result);
78 return $data['title'];
81 // Add link into output stream (or return it) for 'You Are Here' navigation
82 function addYouAreHereLink ($accessLevel, $FQFN, $return = false) {
83 // Use only filename of the FQFN...
84 $file = basename($FQFN);
92 // First we have to do some analysis...
93 if (substr($file, 0, 7) == 'action-') {
94 // This is an action file!
96 $search = substr($file, 7);
98 // Get access level from it
99 $modCheck = getModuleFromFileName($file, $accessLevel);
102 $ADD = " AND (`what`='' OR `what` IS NULL)";
103 } elseif (substr($file, 0, 5) == 'what-') {
104 // This is a 'what file'!
106 $search = substr($file, 5);
108 // Get access level from it
109 $modCheck = getModuleFromFileName($file, $accessLevel);
111 // Do we have admin? Then display all
112 $ADD = " AND `visible`='Y' AND `locked`='N'";
118 $dummy = substr($search, 0, -4);
119 $ADD .= sprintf(" AND `action`='%s'", getActionFromModuleWhat($accessLevel, $dummy));
120 } elseif ($accessLevel == 'sponsor') {
124 $modCheck = getModule();
130 $modCheck = getModule();
134 // Begin the navigation line
135 if (!isset($GLOBALS['nav_depth'])) {
137 $GLOBALS['nav_depth'] = '0';
139 // Run the pre-filter chain
140 $ret = runFilterChain('pre_youhere_line', array('access_level' => $accessLevel, 'type' => $type, 'search' => $search, 'prefix' => $prefix, 'link_add' => $LINK_ADD, 'content' => '', 'add' => $ADD));
143 $prefix = $ret['content'];
145 // Add default content
146 $prefix .= '<div class="you_are_here">{--YOU_ARE_HERE--} <strong><a class="you_are_here" href="{%url=modules.php?module=' . getModule() . $LINK_ADD . '%}">Home</a></strong>';
147 } elseif ($return === false) {
149 $GLOBALS['nav_depth']++;
152 $prefix .= ' -> ';
154 // We need to remove .php and the end
155 if (substr($search, -4, 4) == '.php') {
157 $search = substr($search, 0, -4);
160 if (((isExtensionInstalledAndNewer('sql_patches', '0.2.3')) && (getConfig('youre_here') == 'Y')) || ((isAdmin()) && ($modCheck == 'admin'))) {
162 $OUT = $prefix . '<strong><a class="you_are_here" href="{%url=modules.php?module=' . $modCheck . '&' . $type . '=' . $search . $LINK_ADD . '%}">' . getTitleFromMenu($accessLevel, $search, $type, $ADD) . '</a></strong>';
164 // Can we close the you-are-here navigation?
165 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'type=' . $type . 'getWhat()=' . getWhat());
166 if (($type == 'what') || (($type == 'action') && ((!isWhatSet()) || (getWhat() == 'overview')))) {
167 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'type=' . $type);
168 // Add closing div and br-tag
169 $GLOBALS['nav_depth'] = '0';
171 // Run the post-filter chain
172 $ret = runFilterChain('post_youhere_line', array('access_level' => $accessLevel, 'type' => $type, 'search' => $search, 'prefix' => $prefix, 'link_add' => $LINK_ADD, 'content' => $OUT, 'add' => $ADD));
174 // Get content from filter back
175 $OUT = $ret['content'];
177 // Close div-tag, so not the filters have to do it
182 // Return or output HTML code?
183 if ($return === true) {
187 // Output HTML code here
192 // Adds a menu (mode = guest/member/admin/sponsor) to output
193 function addMenu ($mode, $action, $what) {
194 // Init some variables
197 // is the menu action valid?
198 if (!isMenuActionValid($mode, $action, $what, true)) {
199 return getCode('MENU_NOT_VALID');
202 // Non-admin shall not see all menus
203 $ADD = " AND `visible`='Y' AND `locked`='N'";
205 // Is admin, so make all visible
209 // Load SQL data and add the menu to the output stream...
210 $result_main = SQL_QUERY_ESC("SELECT
211 `title`,`what`,`action`,`visible`,`locked`
213 `{?_MYSQL_PREFIX?}_%s_menu`
215 (`what`='' OR `what` IS NULL)
219 array($mode), __FUNCTION__, __LINE__);
221 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',getWhat()=' . getWhat());
222 if (!SQL_HASZERONUMS($result_main)) {
223 // There are menus available, so we simply display them... :)
224 $GLOBALS['rows'] = '';
225 while ($content = SQL_FETCHARRAY($result_main)) {
226 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',action=' . $content['action'] . ',getWhat()=' . getWhat());
227 // Disable the block-mode
228 enableBlockMode(false);
230 // Load menu header template
231 $GLOBALS['rows'] .= loadTemplate($mode . '_menu_title', true, $content);
234 $result_sub = SQL_QUERY_ESC("SELECT
235 `title` AS `sub_title`,
236 `what` AS `sub_what`,
237 `visible` AS `sub_visible`,
238 `locked` AS `sub_locked`
240 `{?_MYSQL_PREFIX?}_%s_menu`
248 array($mode, $content['action']), __FUNCTION__, __LINE__);
250 // Do we have some entries?
251 if (!SQL_HASZERONUMS($result_sub)) {
255 // Load all sub menus
256 while ($content2 = SQL_FETCHARRAY($result_sub)) {
257 // Merge both arrays in one
258 $content = merge_array($content, $content2);
263 // Full file name for checking menu
264 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sub_what=' . $content['sub_what']);
265 $inc = sprintf("inc/modules/%s/what-%s.php", $mode, $content['sub_what']);
266 if (isIncludeReadable($inc)) {
267 // Mark currently selected menu - open
268 if ((!empty($what)) && (($what == $content['sub_what']))) {
272 // Is ext-sql_patches up-to-date, and display_home_in_index is Y?
273 if ((isExtensionInstalledAndNewer('sql_patches', '0.8.3')) && (isDisplayHomeInIndexEnabled()) && ($content['sub_what'] == getIndexHome())) {
274 // Use index.php as link
275 $OUT .= '<a name="menu" class="menu_blur" href="{%url=index.php%}" target="_self">';
277 // Regular navigation link
278 $OUT .= '<a name="menu" class="menu_blur" href="{%url=modules.php?module=' . getModule() . '&what=' . $content['sub_what'] . '%}" target="_self">';
282 $OUT .= '<em style="cursor:help" class="notice" title="{%message,ADMIN_MENU_WHAT_404_TITLE=' . $content['sub_what'] . '%}">';
286 $OUT .= '{?menu_blur_spacer?}' . $content['sub_title'];
288 if (isIncludeReadable($inc)) {
291 // Mark currently selected menu - close
292 if ((!empty($what)) && (($what == $content['sub_what']))) {
306 'what' => $content['sub_what'],
307 'visible' => $content['sub_visible'],
308 'locked' => $content['locked'],
311 // Add regular menu row or bottom row?
312 if ($count < SQL_NUMROWS($result_sub)) {
313 $GLOBALS['rows'] .= loadTemplate($mode . '_menu_row', true, $content);
315 $GLOBALS['rows'] .= loadTemplate($mode . '_menu_bottom', true, $content);
319 // This is a menu block... ;-)
323 $INC = sprintf("inc/modules/%s/action-%s.php", $mode, $content['action']);
324 if (isFileReadable($INC)) {
326 if ((!isExtensionActive($content['action'])) || ($content['action'] == 'online')) $GLOBALS['rows'] .= loadTemplate('menu_what_begin', true, $mode);
327 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',action=' . $content['action'] . ',getWhat()=' . getWhat());
329 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',action=' . $content['action'] . ',getWhat()=' . getWhat());
330 if ((!isExtensionActive($content['action'])) || ($content['action'] == 'online')) $GLOBALS['rows'] .= loadTemplate('menu_what_end', true, $mode);
332 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',action=' . $content['action'] . ',getWhat()=' . getWhat());
336 SQL_FREERESULT($result_sub);
341 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',getWhat()=' . getWhat());
342 if (SQL_NUMROWS($result_main) > $main_cnt) {
344 $GLOBALS['rows'] .= loadTemplate('menu_separator', true, $mode);
346 // Should we display adverts in this menu?
347 if ((isExtensionInstalledAndNewer('menu', '0.0.1')) && (getConfig($mode . '_menu_advert_enabled') == 'Y') && ($action != 'admin')) {
348 // Display advert template
349 $GLOBALS['rows'] .= loadTemplate('menu_' . $mode . '_advert_' . $action, true);
351 // Add separator again
352 $GLOBALS['rows'] .= loadTemplate('menu_separator', true, $mode);
358 SQL_FREERESULT($result_main);
360 // Should we display adverts in this menu?
361 if ((isExtensionInstalledAndNewer('menu', '0.0.1')) && (getConfig($mode . '_menu_advert_enabled') == 'Y')) {
362 // Add separator again
363 $GLOBALS['rows'] .= loadTemplate('menu_separator', true, $mode);
365 // Display advert template
366 $GLOBALS['rows'] .= loadTemplate('menu_' . $mode . '_advert_end', true);
371 'rows' => $GLOBALS['rows'],
375 // Load main template
376 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',getWhat()=' . getWhat());
377 loadTemplate('menu_table', false, $content);
381 // Checks wether the current user is a member
382 function isMember () {
383 // By default no member
386 // Fix missing 'last_online' array, damn stupid code :(((
387 // @TODO Try to rewrite this to one or more functions
388 if ((!isset($GLOBALS['last_online'])) || (!is_array($GLOBALS['last_online']))) {
389 $GLOBALS['last_online'] = array();
392 // Is the cache entry there?
393 if (isset($GLOBALS[__FUNCTION__])) {
395 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'CACHED! (' . intval($GLOBALS[__FUNCTION__]) . ')');
396 return $GLOBALS[__FUNCTION__];
397 } elseif ((!isSessionVariableSet('userid')) || (!isSessionVariableSet('u_hash'))) {
398 // Destroy any existing user session data
399 destroyMemberSession();
400 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'No member set in cookie/session.');
402 // Abort further processing
406 // Get userid secured from session
407 setMemberId(getSession('userid'));
409 // ... and set it as currently handled user id
410 setCurrentUserId(getMemberId());
412 // Init user data array
415 // Fix "deleted" cookies first
416 fixDeletedCookies(array('userid', 'u_hash'));
418 // Are cookies set and can the member data be loaded?
419 if ((isMemberIdSet()) && (isSessionVariableSet('u_hash')) && (fetchUserData(getMemberId()) === true)) {
420 // Validate password by created the difference of it and the secret key
421 $valPass = encodeHashForCookie(getUserData('password'));
423 // So did we now have valid data and an unlocked user?
424 if ((getUserData('status') == 'CONFIRMED') && ($valPass == getSession('u_hash'))) {
425 // Transfer last module and online time
426 $GLOBALS['last_online']['module'] = getUserData('last_module');
427 $GLOBALS['last_online']['online'] = getUserData('last_online');
429 // Account is confirmed and all cookie data is valid so he is definely logged in! :-)
434 // Is $ret still false?
435 if ($ret === false) {
436 // Yes, so destroy the session
437 destroyMemberSession();
441 $GLOBALS[__FUNCTION__] = $ret;
444 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . intval($ret));
448 // Fetch user data for given user id
449 function fetchUserData ($value, $column = 'userid') {
450 // Extension ext-user must be there at any case
451 if (!isExtensionActive('user')) {
452 // Absent ext-user is really not good
454 } elseif (is_null($value)) {
455 // This shall never happen, so please report it
456 debug_report_bug(__FUNCTION__, __LINE__, 'value=NULL,column=' . $column . ' - value can never be NULL');
459 // If we should look for userid secure&set it here
460 if (substr($column, -2, 2) == 'id') {
462 $value = bigintval($value);
465 setCurrentUserId($value);
467 // Don't look for invalid userids...
468 if (!isValidUserId($value)) {
469 // Invalid, so abort here
470 debug_report_bug(__FUNCTION__, __LINE__, 'User id ' . $value . ' is invalid.');
471 } elseif (isUserDataValid()) {
472 // Use cache, so it is fine
473 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'value=' . $value . ' is valid, using cache #1');
476 } elseif (isUserDataValid()) {
477 // Using cache is fine
478 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'value=' . $value . ' is valid, using cache #2');
482 // By default none was found
487 if (isExtensionInstalledAndNewer('user', '0.3.5')) {
488 $ADD = ', UNIX_TIMESTAMP(`lock_timestamp`) AS `lock_timestamp`';
491 // Query for the user
492 $result = SQL_QUERY_ESC("SELECT *".$ADD." FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `%s`='%s' LIMIT 1",
493 array($column, $value), __FUNCTION__, __LINE__);
495 // Do we have a record?
496 if (SQL_NUMROWS($result) == 1) {
497 // Load data from cookies
498 $data = SQL_FETCHARRAY($result);
500 // Set the userid for later use
501 setCurrentUserId($data['userid']);
503 // And cache the data for this userid
504 $GLOBALS['user_data'][getCurrentUserId()] = $data;
506 // Rewrite 'last_failure' if found and ext-user has version >= 0.3.7
507 if ((isExtensionInstalledAndNewer('user', '0.3.7')) && (isset($GLOBALS['user_data'][getCurrentUserId()]['last_failure']))) {
508 // Backup the raw one and zero it
509 $GLOBALS['user_data'][getCurrentUserId()]['last_failure_raw'] = $GLOBALS['user_data'][getCurrentUserId()]['last_failure'];
510 $GLOBALS['user_data'][getCurrentUserId()]['last_failure'] = NULL;
513 if (!is_null($GLOBALS['user_data'][getCurrentUserId()]['last_failure_raw'])) {
514 // Seperate data/time
515 $array = explode(' ', $GLOBALS['user_data'][getCurrentUserId()]['last_failure_raw']);
517 // Seperate data and time again
518 $array['date'] = explode('-', $array[0]);
519 $array['time'] = explode(':', $array[1]);
521 // Now pass it to mktime()
522 $GLOBALS['user_data'][getCurrentUserId()]['last_failure'] = mktime(
534 $found = isUserDataValid();
538 SQL_FREERESULT($result);
544 // This patched function will reduce many SELECT queries for the specified or current admin login
545 function isAdmin () {
546 // No admin in installation phase!
547 if ((isInstallationPhase()) || (!isAdminRegistered())) {
556 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $adminId);
558 // If admin login is not given take current from cookies...
559 if ((isSessionVariableSet('admin_id')) && (isSessionVariableSet('admin_md5'))) {
560 // Get admin login and password from session/cookies
561 $adminId = getCurrentAdminId();
562 $passCookie = getAdminMd5();
564 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mainId=' . $adminId . 'passCookie=' . $passCookie);
566 // Abort if admin id is zero
567 if ($adminId == '0') {
572 if (!isset($GLOBALS[__FUNCTION__][$adminId])) {
573 // Init it with failed
574 $GLOBALS[__FUNCTION__][$adminId] = false;
576 // Search in array for entry
577 if (isset($GLOBALS['admin_hash'])) {
579 $valPass = $GLOBALS['admin_hash'];
580 } elseif ((!empty($passCookie)) && (isAdminHashSet($adminId) === true) && (!empty($adminId))) {
581 // Login data is valid or not?
582 $valPass = encodeHashForCookie(getAdminHash($adminId));
585 $GLOBALS['admin_hash'] = $valPass;
588 incrementStatsEntry('cache_hits');
589 } elseif ((!empty($adminId)) && ((!isExtensionActive('cache')) || (isAdminHashSet($adminId) === false))) {
590 // Get admin hash and hash it
591 $valPass = encodeHashForCookie(getAdminHash($adminId));
594 $GLOBALS['admin_hash'] = $valPass;
597 if (!empty($valPass)) {
598 // Check if password is valid
599 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '(' . $valPass . '==' . $passCookie . ')='.intval($valPass == $passCookie));
600 $GLOBALS[__FUNCTION__][$adminId] = (($GLOBALS['admin_hash'] == $passCookie) || ((strlen($GLOBALS['admin_hash']) == 32) && ($GLOBALS['admin_hash'] == md5($passCookie))) || (($GLOBALS['admin_hash'] == '*FAILED*') && (!isExtensionActive('cache'))));
604 // Return result of comparision
605 return $GLOBALS[__FUNCTION__][$adminId];
608 // Generates a list of "max receiveable emails per day"
609 function addMaxReceiveList ($mode, $default = '', $return = false) {
615 // Guests (in the registration form) are not allowed to select 0 mails per day.
616 $result = SQL_QUERY('SELECT `value`,`comment` FROM `{?_MYSQL_PREFIX?}_max_receive` WHERE `value` > 0 ORDER BY `value` ASC',
617 __FUNCTION__, __LINE__);
621 // Members are allowed to set to zero mails per day (we will change this soon!)
622 $result = SQL_QUERY('SELECT `value`,`comment` FROM `{?_MYSQL_PREFIX?}_max_receive` ORDER BY `value` ASC',
623 __FUNCTION__, __LINE__);
627 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid mode %s detected.", $mode));
631 // Some entries are found?
632 if (!SQL_HASZERONUMS($result)) {
634 while ($content = SQL_FETCHARRAY($result)) {
635 $OUT .= ' <option value="' . $content['value'] . '"';
636 if (postRequestElement('max_mails') == $content['value']) $OUT .= ' selected="selected"';
637 $OUT .= '>' . $content['value'] . ' {--PER_DAY--}';
638 if (!empty($content['comment'])) $OUT .= '(' . $content['comment'] . ')';
643 $OUT = loadTemplate(($mode . '_receive_table'), true, $OUT);
645 // Maybe the admin has to setup some maximum values?
646 debug_report_bug(__FUNCTION__, __LINE__, 'Nothing is being done here?');
650 SQL_FREERESULT($result);
652 if ($return === true) {
653 // Return generated HTML code
656 // Output directly (default)
661 // Checks wether the given email address is used.
662 function isEmailTaken ($email) {
663 // Replace dot with {DOT}
664 $email = str_replace('.', '{DOT}', $email);
666 // Query the database
667 $result = SQL_QUERY_ESC("SELECT `userid` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `email` LIKE '%%%s%%' LIMIT 1",
668 array($email), __FUNCTION__, __LINE__);
670 // Is the email there?
671 $isTaken = (SQL_NUMROWS($result) == 1);
674 SQL_FREERESULT($result);
680 // Validate the given menu action
681 function isMenuActionValid ($mode, $action, $what, $updateEntry=false) {
682 // Is the cache entry there and we shall not update?
683 if ((isset($GLOBALS['action_valid'][$mode][$action][$what])) && ($updateEntry === false)) {
685 incrementStatsEntry('cache_hits');
687 // Then use this cache
688 return $GLOBALS['action_valid'][$mode][$action][$what];
691 // By default nothing is valid
694 // Look in all menus or only unlocked
696 if ((!isAdmin()) && ($mode != 'admin')) $add = " AND `locked`='N'";
698 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mode=' . $mode . ',action=' . $action . ',what=' . $what);
699 if (($mode != 'admin') && ($updateEntry === true)) {
700 // Update guest or member menu
701 $sql = SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET `counter`=`counter`+1 WHERE `action`='%s' AND `what`='%s'".$add." LIMIT 1",
706 ), __FUNCTION__, __LINE__, false);
707 } elseif (($what != 'overview') && (!empty($what))) {
709 $sql = SQL_QUERY_ESC("SELECT `id`,`what` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `action`='%s' AND `what`='%s'".$add." ORDER BY `action` DESC LIMIT 1",
714 ), __FUNCTION__, __LINE__, false);
716 // Admin login overview
717 $sql = SQL_QUERY_ESC("SELECT `id`,`what` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `action`='%s' AND (`what`='' OR `what` IS NULL)".$add." ORDER BY `action` DESC LIMIT 1",
721 ), __FUNCTION__, __LINE__, false);
725 $result = SQL_QUERY($sql, __FUNCTION__, __LINE__);
727 // Should we look for affected rows (only update) or found rows?
728 if ($updateEntry === true) {
729 // Check updated/affected rows
730 $ret = (!SQL_HASZEROAFFECTED());
733 $ret = (!SQL_HASZERONUMS($result));
737 SQL_FREERESULT($result);
740 $GLOBALS['action_valid'][$mode][$action][$what] = $ret;
746 // Get action value from mode (admin/guest/member) and what-value
747 function getActionFromModuleWhat ($module, $what) {
748 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'module=' . $module . ',what=' . $what);
750 $data['action'] = '';
752 if (!isExtensionInstalledAndNewer('sql_patches', '0.0.5')) {
753 // sql_patches is missing so choose depending on mode
757 } elseif ($module == 'admin') {
764 } elseif ((empty($what)) && ($module != 'admin')) {
765 // Use configured 'home'
766 $what = getIndexHome();
769 if ($module == 'admin') {
770 // Action value for admin area
771 if (isGetRequestElementSet('action')) {
773 return getRequestElement('action');
774 } elseif (isActionSet()) {
775 // Get it directly from URL
777 } elseif (($what == 'overview') || (!isWhatSet())) {
778 // Default value for admin area
779 $data['action'] = 'login';
781 } elseif (isActionSet()) {
782 // Get it directly from URL
785 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, ' ret=' . $data['action']);
787 // Does the module have a menu?
788 if (ifModuleHasMenu($module)) {
789 // Rewriting modules to menu
790 $module = mapModuleToTable($module);
792 // Guest and member menu is 'main' as the default
793 if (empty($data['action'])) {
794 $data['action'] = 'main';
797 // Load from database
798 $result = SQL_QUERY_ESC("SELECT `action` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `what`='%s' LIMIT 1",
802 ), __FUNCTION__, __LINE__);
803 if (SQL_NUMROWS($result) == 1) {
804 // Load action value and pray that this one is the right you want... ;-)
805 $data = SQL_FETCHARRAY($result);
809 SQL_FREERESULT($result);
810 } elseif ((!isExtensionInstalled('sql_patches')) && ($module != 'admin') && ($module != 'unknown')) {
811 // No sql_patches installed, but maybe we need to register an admin?
812 if (isAdminRegistered()) {
813 // Redirect to admin area
814 redirectToUrl('admin.php');
818 // Return action value
819 return $data['action'];
822 // Get category name back
823 function getCategory ($cid) {
824 // Default is not found
825 $data['cat'] = '{--_CATEGORY_404--}';
827 // Is the category id set?
830 $data['cat'] = '{--_CATEGORY_NONE--}';
831 } elseif ($cid > 0) {
832 // Lookup the category in database
833 $result = SQL_QUERY_ESC("SELECT `cat` FROM `{?_MYSQL_PREFIX?}_cats` WHERE `id`=%s LIMIT 1",
834 array(bigintval($cid)), __FUNCTION__, __LINE__);
835 if (SQL_NUMROWS($result) == 1) {
836 // Category found... :-)
837 $data = SQL_FETCHARRAY($result);
841 SQL_FREERESULT($result);
848 // Get a string of "mail title" and price back
849 function getPaymentTitlePrice ($pid, $full=false) {
850 // Default is not found
851 $ret = '{--_PAYMENT_404--}';
854 $result = SQL_QUERY_ESC("SELECT `mail_title`,`price` FROM `{?_MYSQL_PREFIX?}_payments` WHERE `id`=%s LIMIT 1",
855 array(bigintval($pid)), __FUNCTION__, __LINE__);
857 // Do we have an entry?
858 if (SQL_NUMROWS($result) == 1) {
859 // Payment type found... :-)
860 $data = SQL_FETCHARRAY($result);
862 // Only title or also including price?
863 if ($full === false) {
864 $ret = $data['mail_title'];
866 $ret = $data['mail_title'] . ' / {%pipe,translateComma=' . $data['price'] . '%} {?POINTS?}';
871 SQL_FREERESULT($result);
877 // Get (basicly) the price of given payment id
878 function getPaymentPoints ($pid, $lookFor = 'price') {
880 $data[$lookFor] = -1;
882 // Search for it in database
883 $result = SQL_QUERY_ESC("SELECT `%s` FROM `{?_MYSQL_PREFIX?}_payments` WHERE `id`=%s LIMIT 1",
884 array($lookFor, $pid), __FUNCTION__, __LINE__);
886 // Is the entry there?
887 if (SQL_NUMROWS($result) == 1) {
888 // Payment type found... :-)
889 $data = SQL_FETCHARRAY($result);
893 SQL_FREERESULT($result);
896 return $data[$lookFor];
899 // Remove a receiver's id from $receivers and add a link for him to confirm
900 function removeReceiver (&$receivers, $key, $userid, $pool_id, $stats_id = 0, $isBonusMail = false) {
901 // Default is not removed
904 // Is the userid valid?
905 if (isValidUserId($userid)) {
906 // Remove entry from array
907 unset($receivers[$key]);
909 // Is there already a line for this user available?
911 // Default is 'normal' mail
913 $rowName = 'stats_id';
915 // Only when we got a real stats id continue searching for the entry
916 if ($isBonusMail === true) {
918 $rowName = 'bonus_id';
921 // Try to look the entry up
922 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_user_links` WHERE %s='%s' AND `userid`=%s AND link_type='%s' LIMIT 1",
923 array($rowName, $stats_id, bigintval($userid), $type), __FUNCTION__, __LINE__);
925 // Was it *not* found?
926 if (SQL_HASZERONUMS($result)) {
928 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_links` (`%s`,`userid`,`link_type`) VALUES ('%s','%s','%s')",
929 array($rowName, $stats_id, bigintval($userid), $type), __FUNCTION__, __LINE__);
931 // Update 'mails_sent' if sql_patches is updated
932 if (isExtensionInstalledAndNewer('sql_patches', '0.7.4')) {
934 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_pool` SET `mails_sent`=`mails_sent`+1 WHERE `id`=%s LIMIT 1",
935 array(bigintval($pool_id)), __FUNCTION__, __LINE__);
944 SQL_FREERESULT($result);
948 // Return status for sending routine
952 // Calculate sum (default) or count records of given criteria
953 function countSumTotalData ($search, $tableName, $lookFor = 'id', $whereStatement = 'userid', $countRows = false, $add = '', $mode = '=') {
957 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',tableName=' . $tableName . ',lookFor=' . $lookFor . ',whereStatement=' . $whereStatement . ',add=' . $add);
958 if ((empty($search)) && ($search != '0')) {
959 // Count or sum whole table?
960 if ($countRows === true) {
962 $result = SQL_QUERY_ESC("SELECT COUNT(`%s`) AS `res` FROM `{?_MYSQL_PREFIX?}_%s`" . $add . ' LIMIT 1',
966 ), __FUNCTION__, __LINE__);
969 $result = SQL_QUERY_ESC("SELECT SUM(`%s`) AS `res` FROM `{?_MYSQL_PREFIX?}_%s`" . $add . ' LIMIT 1',
973 ), __FUNCTION__, __LINE__);
975 } elseif (($countRows === true) || ($lookFor == 'userid')) {
977 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'COUNT!');
978 $result = SQL_QUERY_ESC("SELECT COUNT(`%s`) AS `res` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`%s'%s'" . $add . ' LIMIT 1',
985 ), __FUNCTION__, __LINE__);
988 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'SUM!');
989 $result = SQL_QUERY_ESC("SELECT SUM(`%s`) AS `res` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`%s'%s'" . $add . ' LIMIT 1',
996 ), __FUNCTION__, __LINE__);
1000 $data = SQL_FETCHARRAY($result);
1003 SQL_FREERESULT($result);
1006 if ((empty($data['res'])) && ($lookFor != 'counter') && ($lookFor != 'id') && ($lookFor != 'userid')) {
1008 $data['res'] = '0.00000';
1009 } elseif (''.$data['res'].'' == '') {
1015 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'res=' . $data['res']);
1016 return $data['res'];
1019 // Sends out mail to all administrators. This function is no longer obsolete
1020 // because we need it when there is no ext-admins installed
1021 function sendAdminEmails ($subj, $message) {
1022 // Load all admin email addresses
1023 $result = SQL_QUERY('SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` ORDER BY `id` ASC', __FUNCTION__, __LINE__);
1024 while ($content = SQL_FETCHARRAY($result)) {
1025 // Send the email out
1026 sendEmail($content['email'], $subj, $message);
1030 SQL_FREERESULT($result);
1032 // Really simple... ;-)
1035 // Get id number from administrator's login name
1036 function getAdminId ($adminLogin) {
1037 // By default no admin is found
1041 if (isset($GLOBALS['cache_array']['admin']['admin_id'][$adminLogin])) {
1042 // Use it if found to save SQL queries
1043 $data['id'] = $GLOBALS['cache_array']['admin']['admin_id'][$adminLogin];
1045 // Update cache hits
1046 incrementStatsEntry('cache_hits');
1047 } elseif (!isExtensionActive('cache')) {
1048 // Load from database
1049 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
1050 array($adminLogin), __FUNCTION__, __LINE__);
1052 // Do we have an entry?
1053 if (SQL_NUMROWS($result) == 1) {
1055 $data = SQL_FETCHARRAY($result);
1059 SQL_FREERESULT($result);
1066 // "Getter" for current admin id
1067 function getCurrentAdminId () {
1068 // Log debug message
1069 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'called!');
1071 // Do we have cache?
1072 if (!isset($GLOBALS['current_admin_id'])) {
1073 // Get the admin login from session
1074 $adminId = getSession('admin_id');
1076 // Remember in cache securely
1077 setCurrentAdminId(bigintval($adminId));
1081 return $GLOBALS['current_admin_id'];
1084 // Setter for current admin id
1085 function setCurrentAdminId ($currentAdminId) {
1087 $GLOBALS['current_admin_id'] = bigintval($currentAdminId);
1090 // Get password hash from administrator's login name
1091 function getAdminHash ($adminId) {
1092 // By default an invalid hash is returned
1093 $data['password'] = -1;
1095 if (isAdminHashSet($adminId)) {
1097 $data['password'] = $GLOBALS['cache_array']['admin']['password'][$adminId];
1099 // Update cache hits
1100 incrementStatsEntry('cache_hits');
1101 } elseif (!isExtensionActive('cache')) {
1102 // Load from database
1103 $result = SQL_QUERY_ESC("SELECT `password` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1104 array(bigintval($adminId)), __FUNCTION__, __LINE__);
1106 // Do we have an entry?
1107 if (SQL_NUMROWS($result) == 1) {
1109 $data = SQL_FETCHARRAY($result);
1112 setAdminHash($adminId, $data['password']);
1116 SQL_FREERESULT($result);
1119 // Return password hash
1120 return $data['password'];
1123 // "Getter" for admin login
1124 function getAdminLogin ($adminId) {
1125 // By default a non-existent login is returned (other functions react on this!)
1126 $data['login'] = '***';
1128 if (isset($GLOBALS['cache_array']['admin']['login'][$adminId])) {
1130 $data['login'] = $GLOBALS['cache_array']['admin']['login'][$adminId];
1132 // Update cache hits
1133 incrementStatsEntry('cache_hits');
1134 } elseif (!isExtensionActive('cache')) {
1135 // Load from database
1136 $result = SQL_QUERY_ESC("SELECT `login` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1137 array(bigintval($adminId)), __FUNCTION__, __LINE__);
1140 if (SQL_NUMROWS($result) == 1) {
1142 $data = SQL_FETCHARRAY($result);
1145 $GLOBALS['cache_array']['admin']['login'][$adminId] = $data['login'];
1149 SQL_FREERESULT($result);
1152 // Return the result
1153 return $data['login'];
1156 // Get email address of admin id
1157 function getAdminEmail ($adminId) {
1158 // By default an invalid emails is returned
1159 $data['email'] = '***';
1161 if (isset($GLOBALS['cache_array']['admin']['email'][$adminId])) {
1163 $data['email'] = $GLOBALS['cache_array']['admin']['email'][$adminId];
1165 // Update cache hits
1166 incrementStatsEntry('cache_hits');
1167 } elseif (!isExtensionActive('cache')) {
1168 // Load from database
1169 $result_admin_id = SQL_QUERY_ESC("SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1170 array(bigintval($adminId)), __FUNCTION__, __LINE__);
1173 if (SQL_NUMROWS($result_admin_id) == 1) {
1175 $data = SQL_FETCHARRAY($result_admin_id);
1178 $GLOBALS['cache_array']['admin']['email'][$adminId] = $data['email'];
1182 SQL_FREERESULT($result_admin_id);
1186 return $data['email'];
1189 // Get default ACL of admin id
1190 function getAdminDefaultAcl ($adminId) {
1191 // By default an invalid ACL value is returned
1192 $data['default_acl'] = 'NO-ACL';
1194 // Is sql_patches there and was it found in cache?
1195 if (!isExtensionActive('sql_patches')) {
1196 // Not found, which is bad, so we need to allow all
1197 $data['default_acl'] = 'allow';
1198 } elseif (isset($GLOBALS['cache_array']['admin']['default_acl'][$adminId])) {
1200 $data['default_acl'] = $GLOBALS['cache_array']['admin']['default_acl'][$adminId];
1202 // Update cache hits
1203 incrementStatsEntry('cache_hits');
1204 } elseif (!isExtensionActive('cache')) {
1205 // Load from database
1206 $result_admin_id = SQL_QUERY_ESC("SELECT `default_acl` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1207 array(bigintval($adminId)), __FUNCTION__, __LINE__);
1209 // Do we have an entry?
1210 if (SQL_NUMROWS($result_admin_id) == 1) {
1212 $data = SQL_FETCHARRAY($result_admin_id);
1215 $GLOBALS['cache_array']['admin']['default_acl'][$adminId] = $data['default_acl'];
1219 SQL_FREERESULT($result_admin_id);
1222 // Return default ACL
1223 return $data['default_acl'];
1226 // Get menu mode (la_mode) of admin id
1227 function getAdminMenuMode ($adminId) {
1228 // By default an invalid mode
1229 $data['la_mode'] = 'INVALID';
1231 // Is sql_patches there and was it found in cache?
1232 if (!isExtensionActive('sql_patches')) {
1233 // Not found, which is bad, so we need to allow all
1234 $data['la_mode'] = 'global';
1235 } elseif (isset($GLOBALS['cache_array']['admin']['la_mode'][$adminId])) {
1237 $data['la_mode'] = $GLOBALS['cache_array']['admin']['la_mode'][$adminId];
1239 // Update cache hits
1240 incrementStatsEntry('cache_hits');
1241 } elseif (!isExtensionActive('cache')) {
1242 // Load from database
1243 $result_admin_id = SQL_QUERY_ESC("SELECT `la_mode` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1244 array(bigintval($adminId)), __FUNCTION__, __LINE__);
1246 // Do we have an entry?
1247 if (SQL_NUMROWS($result_admin_id) == 1) {
1249 $data = SQL_FETCHARRAY($result_admin_id);
1252 $GLOBALS['cache_array']['admin']['la_mode'][$adminId] = $data['la_mode'];
1256 SQL_FREERESULT($result_admin_id);
1259 // Return default ACL
1260 return $data['la_mode'];
1263 // Generates an option list from various parameters
1264 function generateOptionList ($table, $id, $name, $default = '', $special = '', $whereStatement = '', $disabled = array(), $callback = '') {
1266 if ($table == '/ARRAY/') {
1267 // Selection from array
1268 if ((is_array($id)) && (is_array($name)) && ((count($id)) == (count($name)) || (!empty($callback)))) {
1270 foreach ($id as $idx => $value) {
1271 $ret .= '<option value="' . $value . '"';
1272 if ($default == $value) {
1273 // Selected by default
1274 $ret .= ' selected="selected"';
1275 } elseif (isset($disabled[$value])) {
1277 $ret .= ' disabled="disabled"';
1280 // Is the call-back function set?
1281 if (!empty($callback)) {
1283 $name[$idx] = call_user_func_array($callback, array($id[$idx]));
1286 // Finish option tag
1287 $ret .= '>' . $name[$idx] . '</option>';
1290 // Problem in request
1291 debug_report_bug(__FUNCTION__, __LINE__, 'Not all are arrays: id[' . count($id) . ']=' . gettype($id) . ',name[' . count($name) . ']=' . gettype($name) . ',callback=' . $callback);
1294 // Data from database
1295 $SPEC = ',`' . $id . '`';
1296 if (!empty($special)) {
1297 $SPEC = ',`' . $special . '` AS `special`';
1300 // Query the database
1301 $result = SQL_QUERY_ESC("SELECT `%s` AS `id`,`%s` AS `name`".$SPEC." FROM `{?_MYSQL_PREFIX?}_%s` ".$whereStatement." ORDER BY `%s` ASC",
1307 ), __FUNCTION__, __LINE__);
1310 if (!SQL_HASZERONUMS($result)) {
1311 // Found data so add them as OPTION lines
1312 while ($content = SQL_FETCHARRAY($result)) {
1314 if (!isset($content['special'])) {
1316 $content['special'] = '';
1319 $ret .= '<option value="' . $content['id'] . '"';
1321 if ($default == $content['id']) {
1322 // Selected by default
1323 $ret .= ' selected="selected"';
1324 } elseif (isset($disabled[$content['id']])) {
1326 $ret .= ' disabled="disabled"';
1330 if (!empty($content['special'])) {
1331 $content['special'] = ' (' . $content['special'] . ')';
1334 // Is the call-back function set?
1335 if (!empty($callback)) {
1337 $content['name'] = call_user_func_array($callback, array($content['name']));
1340 // Finish option list
1341 $ret .= '>' . $content['name'] . $content['special'] . '</option>';
1345 $ret = '<option value="x">{--SELECT_NONE--}</option>';
1349 SQL_FREERESULT($result);
1352 // Return - hopefully - the requested data
1356 // Deletes a user account with given reason
1357 function deleteUserAccount ($userid, $reason) {
1359 $data['points'] = '0';
1361 // Search for the points and user data
1362 $result = SQL_QUERY_ESC("SELECT
1363 (SUM(p.`points`) - d.`used_points`) AS `points`
1365 `{?_MYSQL_PREFIX?}_user_points` AS p
1367 `{?_MYSQL_PREFIX?}_user_data` AS d
1369 p.`userid`=d.`userid`
1373 array(bigintval($userid)), __FUNCTION__, __LINE__);
1375 // Do we have an entry?
1376 if (SQL_NUMROWS($result) == 1) {
1377 // Save his points to add them to the jackpot
1378 $data = SQL_FETCHARRAY($result);
1380 // Delete points entries as well
1381 // @TODO Rewrite these lines to a filter
1382 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_points` WHERE `userid`=%s",
1383 array(bigintval($userid)), __FUNCTION__, __LINE__);
1385 // Update mediadata as well
1386 if (isExtensionInstalledAndNewer('mediadata', '0.0.4')) {
1388 updateMediadataEntry(array('total_points'), 'sub', $data['points']);
1391 // Now, when we have all his points adds them do the jackpot!
1392 if (isExtensionActive('jackpot')) {
1393 addPointsToJackpot($data['points']);
1398 SQL_FREERESULT($result);
1400 // Delete category selections as well...
1401 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_cats` WHERE `userid`=%s",
1402 array(bigintval($userid)), __FUNCTION__, __LINE__);
1404 // Remove from rallye if found
1405 // @TODO Rewrite this to a filter
1406 if (isExtensionActive('rallye')) {
1407 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_rallye_users` WHERE `userid`=%s",
1408 array(bigintval($userid)), __FUNCTION__, __LINE__);
1411 // Add reason and translate points
1412 $data['text'] = $reason;
1414 // Now a mail to the user and that's all...
1415 $message = loadEmailTemplate('member_user_deleted', $data, $userid);
1416 sendEmail($userid, '{--ADMIN_DELETE_ACCOUNT--}', $message);
1418 // Ok, delete the account!
1419 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1", array(bigintval($userid)), __FUNCTION__, __LINE__);
1422 // Gets the matching what name from module
1423 function getWhatFromModule ($modCheck) {
1424 // Is the request element set?
1425 if (isGetRequestElementSet('what')) {
1426 // Then return this!
1427 return getRequestElement('what');
1433 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'modCheck=' . $modCheck);
1434 switch ($modCheck) {
1441 // Is ext-sql_patches installed and newer than 0.0.5?
1442 if (isExtensionInstalledAndNewer('sql_patches', '0.0.5')) {
1443 // Use it from config
1444 $what = getIndexHome();
1446 // Use default 'welcome'
1456 // Return what value
1460 // Returns HTML code with an option list of all categories
1461 function generateCategoryOptionsList ($mode) {
1462 // Prepare WHERE statement
1463 $whereStatement = " WHERE `visible`='Y'";
1464 if (isAdmin()) $whereStatement = '';
1466 // Initialize array...
1470 'userids' => array()
1474 $result = SQL_QUERY('SELECT `id`,`cat` FROM `{?_MYSQL_PREFIX?}_cats`' . $whereStatement . ' ORDER BY `sort` ASC',
1475 __FUNCTION__, __LINE__);
1477 // Do we have entries?
1478 if (!SQL_HASZERONUMS($result)) {
1479 // ... and begin loading stuff
1480 while ($content = SQL_FETCHARRAY($result)) {
1481 // Transfer some data
1482 $CATS['id'][] = $content['id'];
1483 $CATS['name'][] = $content['cat'];
1485 // Check which users are in this category
1486 $result_userids = SQL_QUERY_ESC("SELECT `userid` FROM `{?_MYSQL_PREFIX?}_user_cats` WHERE `cat_id`=%s ORDER BY `userid` ASC",
1487 array(bigintval($content['id'])), __FUNCTION__, __LINE__);
1493 while ($data = SQL_FETCHARRAY($result_userids)) {
1495 $userid_cnt += countSumTotalData($data['userid'], 'user_data', 'userid', 'userid', true, " AND `status`='CONFIRMED' AND `receive_mails` > 0");
1499 SQL_FREERESULT($result_userids);
1502 $CATS['userids'][] = $userid_cnt;
1506 SQL_FREERESULT($result);
1510 foreach ($CATS['id'] as $key => $value) {
1511 if (strlen($CATS['name'][$key]) > 20) $CATS['name'][$key] = substr($CATS['name'][$key], 0, 17)."...";
1512 $OUT .= ' <option value="' . $value . '">' . $CATS['name'][$key] . ' (' . $CATS['userids'][$key] . ' {--USER_IN_CAT--})</option>';
1515 // No cateogries are defined yet
1516 $OUT = '<option class="notice">{--MEMBER_NO_CATEGORIES--}</option>';
1523 // Add bonus mail to queue
1524 function addBonusMailToQueue ($subject, $text, $receiverList, $points, $seconds, $url, $categoryId, $mode='normal', $receiver=0) {
1525 // Is admin or bonus extension there?
1529 } elseif (!isExtensionActive('bonus')) {
1534 // Calculcate target sent
1535 $target = countSelection(explode(';', $receiverList));
1537 // Receiver is zero?
1538 if ($receiver == '0') {
1540 $receiver = $target;
1543 // HTML extension active?
1544 if (isExtensionActive('html_mail')) {
1545 // Determine if we have HTML mode active
1546 $HTML = convertBooleanToYesNo($mode == 'html');
1549 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_bonus`
1550 (`subject`,`text`,`receivers`,`points`,`time`,`data_type`,`timestamp`,`url`,`cat_id`,`target_send`,`mails_sent`,`html_msg`)
1551 VALUES ('%s','%s','%s',%s,%s,'NEW', UNIX_TIMESTAMP(),'%s',%s,%s,%s,'%s')",
1557 bigintval($seconds),
1559 bigintval($categoryId),
1561 bigintval($receiver),
1563 ), __FUNCTION__, __LINE__);
1566 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_bonus`
1567 (`subject`,`text`,`receivers`,`points`,`time`,`data_type`,`timestamp`,`url`,`cat_id`,`target_send`,`mails_sent`)
1568 VALUES ('%s','%s','%s',%s,%s,'NEW', UNIX_TIMESTAMP(),'%s',%s,%s,%s)",
1574 bigintval($seconds),
1576 bigintval($categoryId),
1578 bigintval($receiver),
1579 ), __FUNCTION__, __LINE__);
1583 // Generate a receiver list for given category and maximum receivers
1584 function generateReceiverList ($categoryId, $receiver, $mode = '') {
1592 $categoryId = bigintval($categoryId);
1593 $receiver = bigintval($receiver);
1595 // Is the receiver zero and mode set?
1596 if (($receiver == '0') && (!empty($mode))) {
1597 // Auto-fix receiver maximum
1598 $receiver = getTotalReceivers($mode);
1602 if ($categoryId > 0) {
1604 $CAT_TABS = "LEFT JOIN `{?_MYSQL_PREFIX?}_user_cats` AS c ON d.`userid`=c.`userid`";
1605 $CAT_WHERE = sprintf(" AND c.`cat_id`=%s", $categoryId);
1608 // Exclude users in holiday?
1609 if (isExtensionInstalledAndNewer('holiday', '0.1.3')) {
1610 // Add something for the holiday extension
1611 $CAT_WHERE .= " AND d.`holiday_active`='N'";
1614 if ((isExtensionActive('html_mail')) && ($mode == 'html')) {
1615 // Only include HTML receivers
1616 $result = SQL_QUERY_ESC("SELECT d.`userid` FROM `{?_MYSQL_PREFIX?}_user_data` AS d ".$CAT_TABS." WHERE d.`status`='CONFIRMED' AND d.`html`='Y'".$CAT_WHERE." ORDER BY d.`{?order_select?}` {?order_mode?} LIMIT %s",
1619 ), __FUNCTION__, __LINE__);
1622 $result = SQL_QUERY_ESC("SELECT d.`userid` FROM `{?_MYSQL_PREFIX?}_user_data` AS d ".$CAT_TABS." WHERE d.`status`='CONFIRMED'".$CAT_WHERE." ORDER BY d.`{?order_select?}` {?order_mode?} LIMIT %s",
1625 ), __FUNCTION__, __LINE__);
1629 if ((SQL_NUMROWS($result) >= $receiver) && ($receiver > 0)) {
1631 while ($content = SQL_FETCHARRAY($result)) {
1632 // Add receiver when not empty
1633 if (!empty($content['userid'])) {
1634 $receiverList .= $content['userid'] . ';';
1639 SQL_FREERESULT($result);
1641 // Remove trailing semicolon
1642 $receiverList = substr($receiverList, 0, -1);
1646 return $receiverList;
1649 // Recuce the amount of received emails for the receipients for given email
1650 function reduceRecipientReceivedMails ($column, $id, $count) {
1651 // Search for mail in database
1652 $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_user_links` WHERE `%s`=%s ORDER BY `userid` ASC LIMIT %s",
1653 array($column, bigintval($id), $count), __FUNCTION__, __LINE__);
1655 // Are there entries?
1656 if (!SQL_HASZERONUMS($result)) {
1657 // Now load all userids for one big query!
1659 while ($data = SQL_FETCHARRAY($result)) {
1660 // By default we want to reduce and have no mails found
1663 // We must now look if he has already confirmed this mail, so might sound double, but it may resolve problems
1664 // @TODO Rewrite this to a filter
1665 if ((isset($data['stats_id'])) && ($data['stats_id'] > 0)) {
1667 $num = countSumTotalData($data['userid'], 'user_stats_data', 'id', 'userid', true, sprintf(" AND `stats_type`='mailid' AND `stats_data`=%s", bigintval($data['stats_id'])));
1668 } elseif ((isset($data['bonus_id'])) && ($data['bonus_id'] > 0)) {
1670 $num = countSumTotalData($data['userid'], 'user_stats_data', 'id', 'userid', true, sprintf(" AND `stats_type`='bonusid' AND `stats_data`=%s", bigintval($data['bonus_id'])));
1673 // Reduce this users total received emails?
1675 $userids[$data['userid']] = $data['userid'];
1679 if (count($userids) > 0) {
1680 // Now update all user accounts
1681 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `emails_received`=`emails_received`-1 WHERE `userid` IN (%s) LIMIT %s",
1682 array(implode(',', $userids), count($userids)), __FUNCTION__, __LINE__);
1685 displayMessage('{%message,ADMIN_MAIL_NOTHING_DELETED=' . $id . '%}');
1690 SQL_FREERESULT($result);
1693 // Creates a new task
1694 function createNewTask ($subject, $notes, $taskType, $userid = NULL, $adminId = NULL, $strip = true) {
1695 // Insert the task data into the database
1696 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_task_system` (`assigned_admin`,`userid`,`status`,`task_type`,`subject`,`text`,`task_created`) VALUES (%s,%s,'NEW','%s','%s','%s', UNIX_TIMESTAMP())",
1698 makeZeroToNull($adminId),
1699 makeZeroToNull($userid),
1703 ), __FUNCTION__, __LINE__, true, $strip);
1705 // Return insert id which is the task id
1706 return SQL_INSERTID();
1709 // Updates last module / online time
1710 // @TODO Fix inconsistency between last_module and getWhat()
1711 function updateLastActivity($userid) {
1712 // Run the update query
1713 SQL_QUERY_ESC("UPDATE
1714 `{?_MYSQL_PREFIX?}_user_data`
1717 `last_online`=UNIX_TIMESTAMP(),
1726 ), __FUNCTION__, __LINE__);