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 - 2012 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 = '') {
47 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mode=' . $mode . ',what=' . $what . ',column=' . $column . ',add=' . $ADD);
51 $what = getIndexHome();
52 } elseif ((isGetRequestElementSet('action')) && ($column == 'what')) {
54 return getTitleFromMenu($mode, getAction(), 'action', $ADD);
55 } elseif ($what == 'welcome') {
57 return '{--WHAT_IS_WELCOME--}';
60 // Default is not found
61 $data['title'] = '??? (' . $what . ')';
64 $result = SQL_QUERY_ESC("SELECT `title` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `%s`='%s'" . $ADD . " LIMIT 1",
69 ), __FUNCTION__, __LINE__);
72 if (SQL_NUMROWS($result) == 1) {
74 $data = SQL_FETCHARRAY($result);
78 SQL_FREERESULT($result);
81 return $data['title'];
84 // Add link into output stream (or return it) for 'You Are Here' navigation
85 function addYouAreHereLink ($accessLevel, $FQFN, $return = FALSE) {
86 // Use only filename of the FQFN...
87 $file = basename($FQFN);
95 // First we have to do some analysis...
96 if (substr($file, 0, 7) == 'action-') {
97 // This is an action file!
99 $search = substr($file, 7);
101 // Get access level from it
102 $modCheck = getModuleFromFileName($file, $accessLevel);
105 $ADD = " AND (`what`='' OR `what` IS NULL)";
106 } elseif (substr($file, 0, 5) == 'what-') {
107 // This is a 'what file'!
109 $search = substr($file, 5);
111 // Get access level from it
112 $modCheck = getModuleFromFileName($file, $accessLevel);
114 // Is there admin? Then display all
115 $ADD = " AND `visible`='Y' AND `locked`='N'";
121 $dummy = substr($search, 0, -4);
122 $ADD .= sprintf(" AND `action`='%s'", getActionFromModuleWhat($accessLevel, $dummy));
123 } elseif ($accessLevel == 'sponsor') {
127 $modCheck = getModule();
132 $modCheck = getModule();
135 // Begin the navigation line
136 if (!isset($GLOBALS['nav_depth'])) {
138 $GLOBALS['nav_depth'] = '0';
140 // Run the pre-filter chain
141 $ret = runFilterChain('pre_youhere_line', array('access_level' => $accessLevel, 'type' => $type, 'search' => $search, 'prefix' => $prefix, 'link_add' => $linkAdd, 'content' => '', 'add' => $ADD));
144 $prefix = $ret['content'];
146 // Add default content
147 $prefix .= '<div class="you_are_here">{--YOU_ARE_HERE--} <strong><a class="you_are_here" href="{%url=modules.php?module=' . getModule() . $linkAdd . '%}">Home</a></strong>';
148 } elseif ($return === FALSE) {
150 $GLOBALS['nav_depth']++;
154 $prefix .= ' -> ';
156 // We need to remove .php and the end
157 if (substr($search, -4, 4) == '.php') {
159 $search = substr($search, 0, -4);
162 // Is ext-sql_patches installed?
163 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'isExtensionInstalledAndNewer()=' . intval(isExtensionInstalledAndNewer('sql_patches', '0.2.3')) . ',youre_here=' . getConfig('youre_here') . ',isAdmin()=' . intval(isAdmin()) . ',modCheck=' . $modCheck);
164 if (((isExtensionInstalledAndNewer('sql_patches', '0.2.3')) && (getConfig('youre_here') == 'Y')) || ((isAdmin()) && ($modCheck == 'admin'))) {
166 $OUT = $prefix . '<strong><a class="you_are_here" href="{%url=modules.php?module=' . $modCheck . '&' . $type . '=' . $search . $linkAdd . '%}">' . getTitleFromMenu($accessLevel, $search, $type, $ADD) . '</a></strong>';
168 // Can we close the you-are-here navigation?
169 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'type=' . $type . ',getWhat()=' . getWhat() . ',accessLevel=' . $accessLevel . ',isWhatSet()=' . intval(isWhatSet()));
170 if (($type == 'what') || (($type == 'action') && ((!isWhatSet()) || (($accessLevel == 'admin') && (getWhat() == 'welcome'))))) {
171 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'type=' . $type);
172 // Add closing div and br-tag
173 $GLOBALS['nav_depth'] = '0';
175 // Run the post-filter chain
176 $ret = runFilterChain('post_youhere_line', array('access_level' => $accessLevel, 'type' => $type, 'search' => $search, 'prefix' => $prefix, 'link_add' => $linkAdd, 'content' => $OUT, 'add' => $ADD));
178 // Get content from filter back
179 $OUT = $ret['content'];
181 // Close div-tag, so not the filters have to do it
186 // Return or output HTML code?
187 if ($return === TRUE) {
191 // Output HTML code here
196 // Adds a menu (mode = guest/member/admin/sponsor) to output
197 function addMenu ($mode, $action, $what) {
198 // Init some variables
201 // is the menu action valid?
202 if (!isMenuActionValid($mode, $action, $what, TRUE)) {
203 return getCode('MENU_NOT_VALID');
206 // Non-admin shall not see all menus
207 $ADD = " AND `visible`='Y' AND `locked`='N'";
209 // Is admin, so make all visible
213 // Load SQL data and add the menu to the output stream...
214 $result_main = SQL_QUERY_ESC("SELECT
221 `{?_MYSQL_PREFIX?}_%s_menu`
223 (`what`='' OR `what` IS NULL)
227 array($mode), __FUNCTION__, __LINE__);
229 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',getWhat()=' . getWhat());
230 if (!SQL_HASZERONUMS($result_main)) {
231 // There are menus available, so we simply display them... :)
232 $GLOBALS['rows'] = '';
233 while ($content = SQL_FETCHARRAY($result_main)) {
234 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',action=' . $content['action'] . ',getWhat()=' . getWhat());
235 // Disable the block-mode
236 enableBlockMode(FALSE);
238 // Load menu header template
239 $GLOBALS['rows'] .= loadTemplate($mode . '_menu_title', TRUE, $content);
242 $result_sub = SQL_QUERY_ESC("SELECT
243 `title` AS `sub_title`,
244 `what` AS `sub_what`,
245 `visible` AS `sub_visible`,
246 `locked` AS `sub_locked`
248 `{?_MYSQL_PREFIX?}_%s_menu`
259 ), __FUNCTION__, __LINE__);
261 // Are there some entries?
262 if (!SQL_HASZERONUMS($result_sub)) {
266 // Load all sub menus
267 while ($content2 = SQL_FETCHARRAY($result_sub)) {
268 // Merge both arrays in one
269 $content = merge_array($content, $content2);
274 // Full file name for checking menu
275 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sub_what=' . $content['sub_what']);
276 $inc = sprintf("inc/modules/%s/what-%s.php", $mode, $content['sub_what']);
277 if (isIncludeReadable($inc)) {
278 // Mark currently selected menu - open
279 if ((!empty($what)) && (($what == $content['sub_what']))) {
283 // Is ext-sql_patches up-to-date, and display_home_in_index is Y?
284 if ((getModule() == 'index') && (isExtensionInstalledAndNewer('sql_patches', '0.8.3')) && (isDisplayHomeInIndexEnabled()) && ($content['sub_what'] == getIndexHome())) {
285 // Use index.php as link
286 $OUT .= '<a name="menu" class="menu_blur" href="{%url=index.php%}" target="_self">';
288 // Regular navigation link
289 $OUT .= '<a name="menu" class="menu_blur" href="{%url=modules.php?module=' . getModule() . '&what=' . $content['sub_what'] . '%}" target="_self">';
293 $OUT .= '<span class="bad" style="cursor:help" title="{%message,ADMIN_MENU_WHAT_404_TITLE=' . $content['sub_what'] . '%}">';
297 $OUT .= '{?menu_blur_spacer?}' . $content['sub_title'];
299 if (isIncludeReadable($inc)) {
302 // Mark currently selected menu - close
303 if ((!empty($what)) && (($what == $content['sub_what']))) {
317 'what' => $content['sub_what'],
318 'visible' => $content['sub_visible'],
319 'locked' => $content['locked'],
322 // Add regular menu row or bottom row?
323 if ($count < SQL_NUMROWS($result_sub)) {
324 $GLOBALS['rows'] .= loadTemplate($mode . '_menu_row', TRUE, $content);
326 $GLOBALS['rows'] .= loadTemplate($mode . '_menu_bottom', TRUE, $content);
330 // This is a menu block... ;-)
334 $INC = sprintf("inc/modules/%s/action-%s.php", $mode, $content['action']);
335 if (isFileReadable($INC)) {
337 if ((!isExtensionActive($content['action'])) || ($content['action'] == 'online')) $GLOBALS['rows'] .= loadTemplate('menu_what_begin', TRUE, $mode);
338 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',action=' . $content['action'] . ',getWhat()=' . getWhat());
340 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',action=' . $content['action'] . ',getWhat()=' . getWhat());
341 if ((!isExtensionActive($content['action'])) || ($content['action'] == 'online')) $GLOBALS['rows'] .= loadTemplate('menu_what_end', TRUE, $mode);
343 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',action=' . $content['action'] . ',getWhat()=' . getWhat());
347 SQL_FREERESULT($result_sub);
352 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',getWhat()=' . getWhat());
353 if (SQL_NUMROWS($result_main) > $main_cnt) {
355 $GLOBALS['rows'] .= loadTemplate('menu_separator', TRUE, $mode);
357 // Prepare filter data array
360 'exclusive' => FALSE,
366 $filterData = runFilterChain($mode . '_menu_advert', $filterData);
368 // Add content output
369 $GLOBALS['rows'] .= $filterData['output'];
374 SQL_FREERESULT($result_main);
376 // Prepare filter data array
379 'exclusive' => FALSE,
385 $filterData = runFilterChain($mode . '_menu_advert_end', $filterData);
387 // Add content output
388 $GLOBALS['rows'] .= $filterData['output'];
392 'rows' => $GLOBALS['rows'],
396 // Load main template
397 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'main_cnt=' . $main_cnt . ',getWhat()=' . getWhat());
398 loadTemplate('menu_table', FALSE, $content);
402 // Checks whether the current user is a member
403 function isMember () {
404 // By default no member
407 // Fix missing 'last_online' array, damn stupid code :(((
408 // @TODO Try to rewrite this to one or more functions
409 if ((!isset($GLOBALS['last_online'])) || (!is_array($GLOBALS['last_online']))) {
410 $GLOBALS['last_online'] = array();
413 // Is the cache entry there?
414 if (isset($GLOBALS[__FUNCTION__])) {
416 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'CACHED! (' . intval($GLOBALS[__FUNCTION__]) . ')');
417 return $GLOBALS[__FUNCTION__];
418 } elseif ((!isSessionVariableSet('userid')) || (!isSessionVariableSet('u_hash'))) {
419 // Destroy any existing user session data
420 destroyMemberSession();
421 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'No member set in cookie/session.');
423 // Abort further processing
427 // Get userid secured from session
428 setMemberId(getSession('userid'));
430 // ... and set it as currently handled user id
431 setCurrentUserId(getMemberId());
433 // Init user data array
436 // Fix "deleted" cookies
437 fixDeletedCookies(array('userid', 'u_hash'));
439 // Are cookies set and can the member data be loaded?
440 if ((isMemberIdSet()) && (isSessionVariableSet('u_hash')) && (fetchUserData(getMemberId()) === TRUE)) {
441 // Validate password by created the difference of it and the secret key
442 $valPass = encodeHashForCookie(getUserData('password'));
444 // So did we now have valid data and an unlocked user?
445 if ((getUserData('status') == 'CONFIRMED') && ($valPass == getSession('u_hash'))) {
446 // Transfer last module and online time
447 $GLOBALS['last_online']['module'] = getUserData(getUserLastWhatName());
448 $GLOBALS['last_online']['online'] = getUserData('last_online');
450 // Account is confirmed and all cookie data is valid so he is definely logged in! :-)
455 // Is $ret still false?
456 if ($ret === FALSE) {
457 // Yes, so destroy the session
458 destroyMemberSession();
462 $GLOBALS[__FUNCTION__] = $ret;
465 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret=' . intval($ret));
469 // Fetch user data for given user id
470 function fetchUserData ($value, $column = 'userid') {
471 // Extension ext-user must be there at any case
472 if (!isExtensionActive('user')) {
473 // Absent ext-user is really not good
475 } elseif (is_null($value)) {
476 // This shall never happen, so please report it
477 reportBug(__FUNCTION__, __LINE__, 'value=NULL,column=' . $column . ' - value can never be NULL');
480 // If we should look for userid secure&set it here
481 if (substr($column, -2, 2) == 'id') {
483 $value = bigintval($value);
485 // Don't look for invalid userids...
486 if (!isValidUserId($value)) {
487 // Invalid, so abort here
488 reportBug(__FUNCTION__, __LINE__, 'User id ' . $value . ' is invalid.');
491 // Unset cached values if found and different
492 if ((isCurrentUserIdSet()) && (getCurrentUserId() != $value)) {
494 unsetCurrentUserId();
495 } elseif (isUserDataValid()) {
496 // Use cache, so it is fine
497 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'value=' . $value . ' is valid, using cache #1');
500 } elseif (isUserDataValid()) {
501 // Using cache is fine
502 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'value=' . $value . ' is valid, using cache #2');
506 // By default none was found
509 // Extra SQL statements
510 $ADD = runFilterChain('convert_user_data_columns', ' ');
512 // Query for the user
513 $result = SQL_QUERY_ESC("SELECT *" . $ADD . " FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `%s`='%s' LIMIT 1",
517 ), __FUNCTION__, __LINE__);
519 // Is there a record?
520 if (SQL_NUMROWS($result) == 1) {
521 // Load data from cookies
522 $data = SQL_FETCHARRAY($result);
524 // Set the userid for later use
525 setCurrentUserId($data['userid']);
527 // And cache the data for this userid
528 $GLOBALS['user_data'][getCurrentUserId()] = $data;
530 // Rewrite 'last_failure' if found and ext-user has version >= 0.3.7
531 if ((isExtensionInstalledAndNewer('user', '0.3.7')) && (isset($GLOBALS['user_data'][getCurrentUserId()]['last_failure']))) {
532 // Backup the raw one and zero it
533 $GLOBALS['user_data'][getCurrentUserId()]['last_failure_raw'] = $GLOBALS['user_data'][getCurrentUserId()]['last_failure'];
534 $GLOBALS['user_data'][getCurrentUserId()]['last_failure'] = NULL;
537 if (!is_null($GLOBALS['user_data'][getCurrentUserId()]['last_failure_raw'])) {
538 // Seperate data/time
539 $array = explode(' ', $GLOBALS['user_data'][getCurrentUserId()]['last_failure_raw']);
541 // Seperate data and time again
542 $array['date'] = explode('-', $array[0]);
543 $array['time'] = explode(':', $array[1]);
545 // Now pass it to mktime()
546 $GLOBALS['user_data'][getCurrentUserId()]['last_failure'] = mktime(
558 $found = isUserDataValid();
562 SQL_FREERESULT($result);
569 * Checks whether the current session bears a valid admin id and password hash.
571 * This patched function will reduce many SELECT queries for the current admin
574 function isAdmin () {
576 if (isset($GLOBALS[__FUNCTION__])) {
578 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'isAdmin()=' . intval($GLOBALS[__FUNCTION__]));
579 return $GLOBALS[__FUNCTION__];
582 // No admin in installation phase!
583 if ((isInstallationPhase()) || (!isAdminRegistered())) {
584 $GLOBALS[__FUNCTION__] = FALSE;
591 $passwordFromCookie = '';
592 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $adminId);
594 // If admin login is not given take current from cookies...
595 if ((isSessionVariableSet('admin_id')) && (isSessionVariableSet('admin_md5'))) {
596 // Get admin login and password from session/cookies
597 $adminId = getCurrentAdminId();
598 $passwordFromCookie = getAdminMd5();
600 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'adminId=' . $adminId . ',passwordFromCookie=' . $passwordFromCookie);
602 // Abort if admin id is zero
603 if (($adminId == '0') || (empty($passwordFromCookie))) {
604 // A very noisy debug message ...
605 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Current adminId is zero. isSessionVariableSet(admin_id)=' . intval(isSessionVariableSet('admin_id')) . ',isSessionVariableSet(admin_md5)=' . intval(isSessionVariableSet('admin_md5')));
608 $GLOBALS[__FUNCTION__] = FALSE;
612 // Init it with failed
613 $GLOBALS[__FUNCTION__] = FALSE;
615 // Search in array for entry
616 if (isset($GLOBALS['admin_hash'])) {
618 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Using admin_hash=' . $GLOBALS['admin_hash'] . ' from cache');
619 } elseif ((!empty($adminId)) && (!empty($passwordFromCookie)) && (isAdminHashSet($adminId) === TRUE)) {
620 // Get admin hash and hash it
621 $GLOBALS['admin_hash'] = encodeHashForCookie(getAdminHash($adminId));
622 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'valPass=' . $GLOBALS['admin_hash']);
625 incrementStatsEntry('cache_hits');
626 } elseif ((!empty($adminId)) && ((!isExtensionActive('cache')) || (isAdminHashSet($adminId) === FALSE))) {
627 // Get admin hash and hash it
628 $GLOBALS['admin_hash'] = encodeHashForCookie(getAdminHash($adminId));
629 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'valPass=' . $GLOBALS['admin_hash']);
632 // Check if password is valid
633 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '(' . $GLOBALS['admin_hash'] . '==' . $passwordFromCookie . ')='.intval($GLOBALS['admin_hash'] == $passwordFromCookie));
634 $GLOBALS[__FUNCTION__] = ((!empty($GLOBALS['admin_hash'])) && ($GLOBALS['admin_hash'] == $passwordFromCookie));
636 // Return result of comparision
637 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'isAdmin()=' . intval($GLOBALS[__FUNCTION__]));
638 return $GLOBALS[__FUNCTION__];
641 // Generates a list of "max receiveable emails per day"
642 function addMaxReceiveList ($mode, $default = '') {
648 // Guests (in the registration form) are not allowed to select 0 mails per day.
649 $result = SQL_QUERY('SELECT `value`, `comment` FROM `{?_MYSQL_PREFIX?}_max_receive` WHERE `value` > 0 ORDER BY `value` ASC',
650 __FUNCTION__, __LINE__);
655 // Members are allowed to set to zero mails per day (we will change this soon!)
656 $result = SQL_QUERY('SELECT `value`, `comment` FROM `{?_MYSQL_PREFIX?}_max_receive` ORDER BY `value` ASC',
657 __FUNCTION__, __LINE__);
661 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid mode %s detected.", $mode));
665 // Some entries are found?
666 if (!SQL_HASZERONUMS($result)) {
668 while ($content = SQL_FETCHARRAY($result)) {
669 $OUT .= ' <option value="' . $content['value'] . '"';
671 if (postRequestElement('max_mails') == $content['value']) {
672 $OUT .= ' selected="selected"';
675 $OUT .= '>' . $content['value'] . ' {--PER_DAY--}';
676 if (!empty($content['comment'])) $OUT .= '(' . $content['comment'] . ')';
681 $OUT = loadTemplate(($mode . '_receive_table'), TRUE, $OUT);
683 // Maybe the admin has to setup some maximum values?
684 reportBug(__FUNCTION__, __LINE__, 'Nothing is being done here?');
688 SQL_FREERESULT($result);
690 // Return generated HTML code
694 // Checks whether the given email address is used.
695 function isEmailTaken ($email) {
696 // Default is no userid
697 $useridSql = ' IS NOT NULL';
699 // Is a member logged in?
702 $useridSql = '!= ' . bigintval(getMemberId());
705 // Replace dot with {DOT}
706 $email = str_replace('.', '{DOT}', $email);
708 // Query the database
709 $result = SQL_QUERY_ESC("SELECT
710 COUNT(`userid`) AS `cnt`
712 `{?_MYSQL_PREFIX?}_user_data`
714 '%s' REGEXP `email` AND
720 ), __FUNCTION__, __LINE__);
722 // Is the email there?
723 list($count) = SQL_FETCHROW($result);
726 SQL_FREERESULT($result);
729 return ($count == 1);
732 // Validate the given menu action
733 function isMenuActionValid ($mode, $action, $what, $updateEntry = FALSE) {
734 // Is the cache entry there and we shall not update?
735 if ((isset($GLOBALS['action_valid'][$mode][$action][$what])) && ($updateEntry === FALSE)) {
737 incrementStatsEntry('cache_hits');
739 // Then use this cache
740 return $GLOBALS['action_valid'][$mode][$action][$what];
743 // By default nothing is valid
746 // Look in all menus or only unlocked
748 if ((!isAdmin()) && ($mode != 'admin')) $add = " AND `locked`='N'";
750 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mode=' . $mode . ',action=' . $action . ',what=' . $what);
751 if (($mode != 'admin') && ($updateEntry === TRUE)) {
752 // Update guest or member menu
753 $sql = SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET `counter`=`counter`+1 WHERE `action`='%s' AND `what`='%s'".$add." LIMIT 1",
758 ), __FUNCTION__, __LINE__, FALSE);
759 } elseif (($what != 'welcome') && (!empty($what))) {
761 $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",
766 ), __FUNCTION__, __LINE__, FALSE);
768 // Admin login overview
769 $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",
773 ), __FUNCTION__, __LINE__, FALSE);
777 $result = SQL_QUERY($sql, __FUNCTION__, __LINE__);
779 // Should we look for affected rows (only update) or found rows?
780 if ($updateEntry === TRUE) {
781 // Check updated/affected rows
782 $ret = (!SQL_HASZEROAFFECTED());
785 $ret = (!SQL_HASZERONUMS($result));
789 SQL_FREERESULT($result);
792 $GLOBALS['action_valid'][$mode][$action][$what] = $ret;
798 // Get action value from mode (admin/guest/member) and what-value
799 function getActionFromModuleWhat ($module, $what) {
800 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'module=' . $module . ',what=' . $what);
802 $data['action'] = '';
804 if (!isExtensionInstalledAndNewer('sql_patches', '0.0.5')) {
805 // ext-sql_patches is missing so choose depending on mode
806 $what = determineWhat($module);
807 } elseif ((empty($what)) && ($module != 'admin')) {
808 // Use configured 'home'
809 $what = getIndexHome();
812 if ($module == 'admin') {
813 // Action value for admin area
814 if (isGetRequestElementSet('action')) {
816 return getRequestElement('action');
817 } elseif (isActionSet()) {
818 // Get it directly from URL
820 } elseif (($what == 'welcome') || (!isWhatSet())) {
821 // Default value for admin area
822 $data['action'] = 'login';
824 } elseif (isActionSet()) {
825 // Get it directly from URL
828 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, ' ret=' . $data['action']);
830 // Does the module have a menu?
831 if (ifModuleHasMenu($module)) {
832 // Rewriting modules to menu
833 $module = mapModuleToTable($module);
835 // Guest and member menu is 'main' as the default
836 if (empty($data['action'])) {
837 $data['action'] = 'main';
840 // Load from database
841 $result = SQL_QUERY_ESC("SELECT `action` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `what`='%s' LIMIT 1",
845 ), __FUNCTION__, __LINE__);
846 if (SQL_NUMROWS($result) == 1) {
847 // Load action value and pray that this one is the right you want... ;-)
848 $data = SQL_FETCHARRAY($result);
852 SQL_FREERESULT($result);
853 } elseif ((!isExtensionInstalled('sql_patches')) && ($module != 'admin') && ($module != 'unknown')) {
854 // No ext-sql_patches installed, but maybe we need to register an admin?
855 if (isAdminRegistered()) {
856 // Redirect to admin area
857 redirectToUrl('admin.php');
861 // Return action value
862 return $data['action'];
865 // Get category name back
866 function getCategory ($cid) {
867 // Default is not found
868 $data['cat'] = '{--_CATEGORY_404--}';
870 // Is the category id set?
873 $data['cat'] = '{--_CATEGORY_NONE--}';
874 } elseif ($cid > 0) {
875 // Lookup the category in database
876 $result = SQL_QUERY_ESC('SELECT `cat` FROM `{?_MYSQL_PREFIX?}_cats` WHERE `id`=%s LIMIT 1',
877 array(bigintval($cid)), __FUNCTION__, __LINE__);
878 if (SQL_NUMROWS($result) == 1) {
879 // Category found... :-)
880 $data = SQL_FETCHARRAY($result);
884 SQL_FREERESULT($result);
891 // Get a string of "mail title" and price back
892 function getPaymentTitlePrice ($paymentsId, $full = FALSE) {
893 // Only title or also including price?
894 if ($full === FALSE) {
895 $ret = getPaymentData($paymentsId, 'main_title');
897 $ret = getPaymentData($paymentsId, 'main_title') . ' / {%pipe,getPaymentData,translateComma=' . $paymentsId . '%} {?POINTS?}';
904 // "Getter" for payment data (cached)
905 function getPaymentData ($paymentsId, $lookFor = 'price') {
907 $data[$lookFor] = NULL;
910 if (isset($GLOBALS['cache_array']['payments'][$lookFor][$paymentsId])) {
911 // Use it if found to save SQL queries
912 $data[$lookFor] = $GLOBALS['cache_array']['payments'][$lookFor][$paymentsId];
915 incrementStatsEntry('cache_hits');
916 } elseif (!isExtensionActive('cache')) {
917 // Search for it in database
918 $result = SQL_QUERY_ESC('SELECT `%s` FROM `{?_MYSQL_PREFIX?}_payments` WHERE `id`=%s LIMIT 1',
921 bigintval($paymentsId)
922 ), __FUNCTION__, __LINE__);
924 // Is the entry there?
925 if (SQL_NUMROWS($result) == 1) {
926 // Payment type found... :-)
927 $data = SQL_FETCHARRAY($result);
931 SQL_FREERESULT($result);
935 return $data[$lookFor];
938 // Remove a receiver's id from $receivers and add a link for him to confirm
939 function removeReceiver (&$receivers, $key, $userid, $poolId, $statsId = 0, $isBonusMail = FALSE) {
940 // Default is not removed
943 // Is the userid valid?
944 if (isValidUserId($userid)) {
945 // Remove entry from array
946 unset($receivers[$key]);
948 // Is there already a line for this user available?
950 // Default is 'normal' mail
952 $rowName = 'stats_id';
954 // Only when we got a real stats id continue searching for the entry
955 if ($isBonusMail === TRUE) {
957 $rowName = 'bonus_id';
960 // Try to look the entry up
961 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_user_links` WHERE `%s`=%s AND `userid`=%s AND `link_type`='%s' LIMIT 1",
967 ), __FUNCTION__, __LINE__);
969 // Was it *not* found?
970 if (SQL_HASZERONUMS($result)) {
972 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_links` (`%s`, `userid`, `link_type`) VALUES (%s,%s,'%s')",
978 ), __FUNCTION__, __LINE__);
980 // Update 'mails_sent' if ext-sql_patches is updated
981 if (isExtensionInstalledAndNewer('sql_patches', '0.7.4')) {
983 SQL_QUERY_ESC('UPDATE `{?_MYSQL_PREFIX?}_pool` SET `mails_sent`=`mails_sent`+1 WHERE `id`=%s LIMIT 1',
984 array(bigintval($poolId)), __FUNCTION__, __LINE__);
993 SQL_FREERESULT($result);
997 // Return status for sending routine
1001 // Calculate sum (default) or count records of given criteria
1002 function countSumTotalData ($search, $tableName, $lookFor = 'id', $whereStatement = 'userid', $countRows = FALSE, $add = '', $mode = '=') {
1004 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',tableName=' . $tableName . ',lookFor=' . $lookFor . ',whereStatement=' . $whereStatement . ',add=' . $add);
1005 if ((empty($search)) && ($search != '0')) {
1006 // Count or sum whole table?
1007 if ($countRows === TRUE) {
1008 // Count whole table
1009 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'COUNT!');
1010 $result = SQL_QUERY_ESC('SELECT COUNT(`%s`) AS `res` FROM `{?_MYSQL_PREFIX?}_%s`' . $add . ' LIMIT 1',
1014 ), __FUNCTION__, __LINE__);
1017 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'SUM!');
1018 $result = SQL_QUERY_ESC('SELECT SUM(`%s`) AS `res` FROM `{?_MYSQL_PREFIX?}_%s`' . $add . ' LIMIT 1',
1022 ), __FUNCTION__, __LINE__);
1024 } elseif (($countRows === TRUE) || ($lookFor == 'userid')) {
1026 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'COUNT!');
1027 $result = SQL_QUERY_ESC("SELECT COUNT(`%s`) AS `res` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`%s'%s'" . $add . ' LIMIT 1',
1034 ), __FUNCTION__, __LINE__);
1037 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'SUM!');
1038 $result = SQL_QUERY_ESC("SELECT SUM(`%s`) AS `res` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`%s'%s'" . $add . ' LIMIT 1',
1045 ), __FUNCTION__, __LINE__);
1049 $data = SQL_FETCHARRAY($result);
1052 SQL_FREERESULT($result);
1055 if ((empty($data['res'])) && ($lookFor != 'counter') && ($lookFor != 'id') && ($lookFor != 'userid') && ($lookFor != 'rallye_id')) {
1057 $data['res'] = '0.00000';
1058 } elseif (''.$data['res'].'' == '') {
1064 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'res=' . $data['res']);
1065 return $data['res'];
1069 * Sends out mail to all administrators. This function is no longer obsolete
1070 * because we need it when there is no ext-admins installed
1072 function sendAdminEmails ($subject, $message, $isBugReport = FALSE) {
1073 // Default is no special header
1076 // Is it a bug report?
1077 if ($isBugReport === TRUE) {
1078 // Then add a reply-to line back to the author (me)
1079 $mailHeader = 'Reply-To: webmaster@mxchange.org' . PHP_EOL;
1082 // Load all admin email addresses
1083 $result = SQL_QUERY('SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` ORDER BY `id` ASC', __FUNCTION__, __LINE__);
1085 // And send the notification to all of them
1086 while ($content = SQL_FETCHARRAY($result)) {
1087 // Send the email out
1088 sendEmail($content['email'], $subject, $message, 'N', $mailHeader);
1092 SQL_FREERESULT($result);
1094 // Really simple... ;-)
1097 // Get id number from administrator's login name
1098 function getAdminId ($adminLogin) {
1099 // By default no admin is found
1103 if (isset($GLOBALS['cache_array']['admin']['admin_id'][$adminLogin])) {
1104 // Use it if found to save SQL queries
1105 $data['id'] = $GLOBALS['cache_array']['admin']['admin_id'][$adminLogin];
1107 // Update cache hits
1108 incrementStatsEntry('cache_hits');
1109 } elseif (!isExtensionActive('cache')) {
1110 // Load from database
1111 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
1112 array($adminLogin), __FUNCTION__, __LINE__);
1114 // Is there an entry?
1115 if (SQL_NUMROWS($result) == 1) {
1117 $data = SQL_FETCHARRAY($result);
1121 SQL_FREERESULT($result);
1128 // "Getter" for current admin id
1129 function getCurrentAdminId () {
1130 // Log debug message
1131 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'called!');
1134 if (!isset($GLOBALS['current_admin_id'])) {
1135 // Get the admin login from session
1136 $adminId = getSession('admin_id');
1138 // Remember in cache securely
1139 setCurrentAdminId(bigintval($adminId));
1143 return $GLOBALS['current_admin_id'];
1146 // Setter for current admin id
1147 function setCurrentAdminId ($currentAdminId) {
1149 $GLOBALS['current_admin_id'] = bigintval($currentAdminId);
1152 // Get password hash from administrator's login name
1153 function getAdminHash ($adminId) {
1154 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'adminId=' . $adminId . ' - ENTERED!');
1155 // By default an invalid hash is returned
1156 $data['password'] = -1;
1158 // Is admin hash set?
1159 if (isAdminHashSet($adminId)) {
1161 $data['password'] = $GLOBALS['cache_array']['admin']['password'][$adminId];
1163 // Update cache hits
1164 incrementStatsEntry('cache_hits');
1165 } elseif (!isExtensionActive('cache')) {
1166 // Load from database
1167 $result = SQL_QUERY_ESC("SELECT `password` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1168 array(bigintval($adminId)), __FUNCTION__, __LINE__);
1170 // Is there an entry?
1171 if (SQL_NUMROWS($result) == 1) {
1173 $data = SQL_FETCHARRAY($result);
1176 setAdminHash($adminId, $data['password']);
1180 SQL_FREERESULT($result);
1183 // Return password hash
1184 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'adminId=' . $adminId . ',data[password]=' . $data['password'] . ' - EXIT!');
1185 return $data['password'];
1188 // "Getter" for admin login
1189 function getAdminLogin ($adminId) {
1190 // By default a non-existent login is returned (other functions react on this!)
1191 $data['login'] = '***';
1193 if (isset($GLOBALS['cache_array']['admin']['login'][$adminId])) {
1195 $data['login'] = $GLOBALS['cache_array']['admin']['login'][$adminId];
1197 // Update cache hits
1198 incrementStatsEntry('cache_hits');
1199 } elseif (!isExtensionActive('cache')) {
1200 // Load from database
1201 $result = SQL_QUERY_ESC("SELECT `login` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1202 array(bigintval($adminId)), __FUNCTION__, __LINE__);
1205 if (SQL_NUMROWS($result) == 1) {
1207 $data = SQL_FETCHARRAY($result);
1210 $GLOBALS['cache_array']['admin']['login'][$adminId] = $data['login'];
1214 SQL_FREERESULT($result);
1217 // Return the result
1218 return $data['login'];
1221 // Get email address of admin id
1222 function getAdminEmail ($adminId) {
1223 // By default an invalid emails is returned
1224 $data['email'] = '***';
1226 if (isset($GLOBALS['cache_array']['admin']['email'][$adminId])) {
1228 $data['email'] = $GLOBALS['cache_array']['admin']['email'][$adminId];
1230 // Update cache hits
1231 incrementStatsEntry('cache_hits');
1232 } elseif (!isExtensionActive('cache')) {
1233 // Load from database
1234 $result_admin_id = SQL_QUERY_ESC("SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1235 array(bigintval($adminId)), __FUNCTION__, __LINE__);
1238 if (SQL_NUMROWS($result_admin_id) == 1) {
1240 $data = SQL_FETCHARRAY($result_admin_id);
1243 $GLOBALS['cache_array']['admin']['email'][$adminId] = $data['email'];
1247 SQL_FREERESULT($result_admin_id);
1251 return $data['email'];
1254 // Get default ACL of admin id
1255 function getAdminDefaultAcl ($adminId) {
1256 // By default an invalid ACL value is returned
1257 $data['default_acl'] = 'NO-ACL';
1259 // Is ext-sql_patches there and was it found in cache?
1260 if (!isExtensionActive('sql_patches')) {
1261 // Not found, which is bad, so we need to allow all
1262 $data['default_acl'] = 'allow';
1263 } elseif (isset($GLOBALS['cache_array']['admin']['default_acl'][$adminId])) {
1265 $data['default_acl'] = $GLOBALS['cache_array']['admin']['default_acl'][$adminId];
1267 // Update cache hits
1268 incrementStatsEntry('cache_hits');
1269 } elseif (!isExtensionActive('cache')) {
1270 // Load from database
1271 $result_admin_id = SQL_QUERY_ESC("SELECT `default_acl` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1272 array(bigintval($adminId)), __FUNCTION__, __LINE__);
1274 // Is there an entry?
1275 if (SQL_NUMROWS($result_admin_id) == 1) {
1277 $data = SQL_FETCHARRAY($result_admin_id);
1280 $GLOBALS['cache_array']['admin']['default_acl'][$adminId] = $data['default_acl'];
1284 SQL_FREERESULT($result_admin_id);
1287 // Return default ACL
1288 return $data['default_acl'];
1291 // Get menu mode (la_mode) of admin id
1292 function getAdminMenuMode ($adminId) {
1293 // By default an invalid mode
1294 $data['la_mode'] = 'INVALID';
1296 // Is ext-sql_patches there and was it found in cache?
1297 if (!isExtensionActive('sql_patches')) {
1298 // Not found, which is bad, so we need to allow all
1299 $data['la_mode'] = 'global';
1300 } elseif (isset($GLOBALS['cache_array']['admin']['la_mode'][$adminId])) {
1302 $data['la_mode'] = $GLOBALS['cache_array']['admin']['la_mode'][$adminId];
1304 // Update cache hits
1305 incrementStatsEntry('cache_hits');
1306 } elseif (!isExtensionActive('cache')) {
1307 // Load from database
1308 $result_admin_id = SQL_QUERY_ESC("SELECT `la_mode` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
1309 array(bigintval($adminId)), __FUNCTION__, __LINE__);
1311 // Is there an entry?
1312 if (SQL_NUMROWS($result_admin_id) == 1) {
1314 $data = SQL_FETCHARRAY($result_admin_id);
1317 $GLOBALS['cache_array']['admin']['la_mode'][$adminId] = $data['la_mode'];
1321 SQL_FREERESULT($result_admin_id);
1324 // Return default ACL
1325 return $data['la_mode'];
1328 // Generates an option list from various parameters
1329 function generateOptions ($table, $key, $value, $default = '', $extra = '', $whereStatement = '', $disabled = array(), $callback = '') {
1331 if ($table == '/ARRAY/') {
1332 // Selection from array
1333 if ((is_array($key)) && (is_array($value)) && ((count($key)) == (count($value)) || (!empty($callback)))) {
1335 foreach ($key as $idx => $optionValue) {
1336 $ret .= '<option value="' . $optionValue . '"';
1337 if ($default == $optionValue) {
1338 // Selected by default
1339 $ret .= ' selected="selected"';
1340 } elseif (isset($disabled[$optionValue])) {
1342 $ret .= ' disabled="disabled"';
1345 // Is the call-back function set?
1346 if (!empty($callback)) {
1348 $value[$idx] = call_user_func_array($callback, array($key[$idx]));
1351 // Finish option tag
1352 $ret .= '>' . $value[$idx] . '</option>';
1355 // Problem in request
1356 reportBug(__FUNCTION__, __LINE__, 'Not all are arrays: key[' . count($key) . ']=' . gettype($key) . ',value[' . count($value) . ']=' . gettype($value) . ',callback=' . $callback);
1359 ///////////////////////
1360 // Data from database /
1361 ///////////////////////
1363 // Init extra column (if requested)
1365 if (!empty($extra)) {
1366 $extraColumn = ',`' . $extra . '` AS `extra`';
1370 $result = SQL_QUERY_ESC("SELECT `%s` AS `key`, `%s` AS `value`" . $extraColumn . " FROM `{?_MYSQL_PREFIX?}_%s` " . $whereStatement . " ORDER BY `%s` ASC",
1376 ), __FUNCTION__, __LINE__);
1379 if (!SQL_HASZERONUMS($result)) {
1380 // Found data so add them as OPTION lines
1381 while ($content = SQL_FETCHARRAY($result)) {
1383 if (!isset($content['extra'])) {
1385 $content['extra'] = '';
1388 $ret .= '<option value="' . $content['key'] . '"';
1390 if ($default == $content['key']) {
1391 // Selected by default
1392 $ret .= ' selected="selected"';
1393 } elseif (isset($disabled[$content['key']])) {
1395 $ret .= ' disabled="disabled"';
1399 if (!empty($content['extra'])) {
1400 $content['extra'] = ' (' . $content['extra'] . ')';
1403 // Is the call-back function set?
1404 if (!empty($callback)) {
1406 $content['value'] = call_user_func_array($callback, array($content['value']));
1409 // Finish option list
1410 $ret .= '>' . $content['value'] . $content['extra'] . '</option>';
1414 $ret = '<option value="x">{--SELECT_NONE--}</option>';
1418 SQL_FREERESULT($result);
1421 // Return - hopefully - the requested data
1425 // Deletes a user account with given reason
1426 function deleteUserAccount ($userid, $reason) {
1428 $data['points'] = '0';
1430 // Search for the points and user data
1431 $result = SQL_QUERY_ESC("SELECT
1432 (SUM(p.`points`) - d.`used_points`) AS `points`
1434 `{?_MYSQL_PREFIX?}_user_points` AS `p`
1436 `{?_MYSQL_PREFIX?}_user_data` AS `d`
1438 p.`userid`=d.`userid`
1442 array(bigintval($userid)), __FUNCTION__, __LINE__);
1444 // Is there an entry?
1445 if (SQL_NUMROWS($result) == 1) {
1446 // Save his points to add them to the jackpot
1447 $data = SQL_FETCHARRAY($result);
1449 // Delete points entries as well
1450 // @TODO Rewrite these lines to a filter
1451 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_points` WHERE `userid`=%s",
1452 array(bigintval($userid)), __FUNCTION__, __LINE__);
1454 // Update mediadata as well
1455 if (isExtensionInstalledAndNewer('mediadata', '0.0.4')) {
1457 updateMediadataEntry(array('total_points'), 'sub', $data['points']);
1460 // Now, when we have all his points adds them do the jackpot!
1461 if (isExtensionActive('jackpot')) {
1462 addPointsToJackpot($data['points']);
1467 SQL_FREERESULT($result);
1469 // Delete category selections as well...
1470 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_cats` WHERE `userid`=%s",
1471 array(bigintval($userid)), __FUNCTION__, __LINE__);
1473 // Remove from rallye if found
1474 // @TODO Rewrite this to a filter
1475 if (isExtensionActive('rallye')) {
1476 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_rallye_users` WHERE `userid`=%s",
1477 array(bigintval($userid)), __FUNCTION__, __LINE__);
1480 // Add reason and translate points
1481 $data['text'] = $reason;
1483 // Now a mail to the user and that's all...
1484 $message = loadEmailTemplate('member_user_deleted', $data, $userid);
1485 sendEmail($userid, '{--ADMIN_DELETE_ACCOUNT--}', $message);
1487 // Ok, delete the account!
1488 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1", array(bigintval($userid)), __FUNCTION__, __LINE__);
1491 // Gets the matching what name from module
1492 function getWhatFromModule ($modCheck) {
1493 // Is the request element set?
1494 if (isGetRequestElementSet('what')) {
1495 // Then return this!
1496 return getRequestElement('what');
1502 // Check on given module
1503 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'modCheck=' . $modCheck);
1504 switch ($modCheck) {
1505 case 'index': // Guest area
1506 // Is ext-sql_patches installed and newer than 0.0.5?
1507 if (isExtensionInstalledAndNewer('sql_patches', '0.0.5')) {
1508 // Use it from config
1509 $what = getIndexHome();
1511 // Use default 'welcome'
1516 default: // Default for all other menus (getIndexHome() is for index module only)
1521 // Return what value
1525 // Returns HTML code with an option list of all categories
1526 function generateCategoryOptionsList ($mode, $userid = NULL) {
1527 // Prepare WHERE statement
1528 $whereStatement = " WHERE `visible`='Y'";
1529 if (isAdmin()) $whereStatement = '';
1531 // Initialize array...
1532 $categories = array(
1535 'userids' => array()
1539 $result = SQL_QUERY('SELECT
1543 `{?_MYSQL_PREFIX?}_cats`
1544 ' . $whereStatement . '
1547 __FUNCTION__, __LINE__);
1549 // Are there entries?
1550 if (!SQL_HASZERONUMS($result)) {
1551 // ... and begin loading stuff
1552 while ($content = SQL_FETCHARRAY($result)) {
1553 // Transfer some data
1554 $categories['id'][] = $content['id'];
1555 array_push($categories['name'], $content['cat']);
1557 // Check which users are in this category
1558 $result_userids = SQL_QUERY_ESC("SELECT `userid` FROM `{?_MYSQL_PREFIX?}_user_cats` WHERE `cat_id`=%s AND `userid` != %s ORDER BY `userid` ASC",
1560 bigintval($content['id']),
1561 convertNullToZero($userid)
1562 ), __FUNCTION__, __LINE__);
1568 while ($data = SQL_FETCHARRAY($result_userids)) {
1570 $userid_cnt += countSumTotalData($data['userid'], 'user_data', 'userid', 'userid', TRUE, runFilterChain('user_exclusion_sql', " AND `status`='CONFIRMED' AND `receive_mails` > 0"));
1574 SQL_FREERESULT($result_userids);
1577 array_push($categories['userids'], $userid_cnt);
1581 SQL_FREERESULT($result);
1585 foreach ($categories['id'] as $key => $value) {
1586 $OUT .= ' <option value="' . $value . '">' . $categories['name'][$key] . ' (' . $categories['userids'][$key] . ' {--USERS_IN_CATEGORY--})</option>';
1589 // No cateogries are defined yet
1590 $OUT = '<option class="bad">{--MEMBER_NO_CATEGORIES--}</option>';
1597 // Add bonus mail to queue
1598 function addBonusMailToQueue ($subject, $text, $receiverList, $points, $seconds, $url, $categoryId, $mode='normal', $receiver=0) {
1599 // Is admin or bonus extension there?
1603 } elseif (!isExtensionActive('bonus')) {
1608 // Calculcate target sent
1609 $target = countSelection(explode(';', $receiverList));
1611 // Receiver is zero?
1612 if ($receiver == '0') {
1614 $receiver = $target;
1617 // HTML extension active?
1618 if (isExtensionActive('html_mail')) {
1620 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_bonus` (
1652 bigintval($seconds),
1654 bigintval($categoryId),
1656 bigintval($receiver),
1657 convertBooleanToYesNo($mode == 'html')
1658 ), __FUNCTION__, __LINE__);
1661 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_bonus` (
1691 bigintval($seconds),
1693 bigintval($categoryId),
1695 bigintval($receiver),
1696 ), __FUNCTION__, __LINE__);
1700 // Generate a receiver list for given category and maximum receivers
1701 function generateReceiverList ($categoryId, $receiver, $mode = '') {
1708 $categoryId = bigintval($categoryId);
1709 $receiver = bigintval($receiver);
1711 // Is the receiver zero and mode set?
1712 if (($receiver == '0') && (!empty($mode))) {
1713 // Auto-fix receiver maximum
1714 $receiver = getTotalReceivers($mode);
1717 // Exclude (maybe exclude) testers
1718 $addWhere = runFilterChain('user_exclusion_sql', ' ');
1721 if ($categoryId > 0) {
1723 $extraColumns = "LEFT JOIN `{?_MYSQL_PREFIX?}_user_cats` AS c ON d.`userid`=c.`userid`";
1724 $addWhere = sprintf(" AND c.`cat_id`=%s", $categoryId);
1727 // Exclude users in holiday?
1728 if (isExtensionInstalledAndNewer('holiday', '0.1.3')) {
1729 // Add something for the holiday extension
1730 $addWhere .= " AND d.`holiday_active`='N'";
1733 // Include only HTML recipients?
1734 if ((isExtensionActive('html_mail')) && ($mode == 'html')) {
1735 $addWhere .= " AND d.`html`='Y'";
1739 $result = SQL_QUERY_ESC("SELECT d.`userid` FROM `{?_MYSQL_PREFIX?}_user_data` AS d ".$extraColumns." WHERE d.`status`='CONFIRMED' ".$addWhere." ORDER BY d.`{?order_select?}` {?order_mode?} LIMIT %s",
1742 ), __FUNCTION__, __LINE__);
1745 if ((SQL_NUMROWS($result) >= $receiver) && ($receiver > 0)) {
1747 while ($content = SQL_FETCHARRAY($result)) {
1748 // Add receiver when not empty
1749 if (!empty($content['userid'])) {
1750 $receiverList .= $content['userid'] . ';';
1755 SQL_FREERESULT($result);
1757 // Remove trailing semicolon
1758 $receiverList = substr($receiverList, 0, -1);
1762 return $receiverList;
1765 // Recuce the amount of received emails for the receipients for given email
1766 function reduceRecipientReceivedMails ($column, $id, $count) {
1767 // Search for mail in database
1768 $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_user_links` WHERE `%s`=%s ORDER BY `userid` ASC LIMIT %s",
1769 array($column, bigintval($id), $count), __FUNCTION__, __LINE__);
1771 // Are there entries?
1772 if (!SQL_HASZERONUMS($result)) {
1773 // Now load all userids for one big query!
1775 while ($data = SQL_FETCHARRAY($result)) {
1776 // By default reduce and found no emails
1779 // We must now look if he has already confirmed this mail, so might sound double, but it may resolve problems
1780 // @TODO Rewrite this to a filter
1781 if ((isset($data['stats_id'])) && ($data['stats_id'] > 0)) {
1783 $num = countSumTotalData($data['userid'], 'user_stats_data', 'id', 'userid', TRUE, sprintf(" AND `stats_type`='mailid' AND `stats_data`=%s", bigintval($data['stats_id'])));
1784 } elseif ((isset($data['bonus_id'])) && ($data['bonus_id'] > 0)) {
1786 $num = countSumTotalData($data['userid'], 'user_stats_data', 'id', 'userid', TRUE, sprintf(" AND `stats_type`='bonusid' AND `stats_data`=%s", bigintval($data['bonus_id'])));
1789 // Reduce this users total received emails?
1791 $userids[$data['userid']] = $data['userid'];
1795 if (count($userids) > 0) {
1796 // Now update all user accounts
1797 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `emails_received`=`emails_received`-1 WHERE `userid` IN (%s) LIMIT %s",
1799 implode(',', $userids),
1801 ), __FUNCTION__, __LINE__);
1804 displayMessage('{%message,ADMIN_MAIL_NOTHING_DELETED=' . $id . '%}');
1809 SQL_FREERESULT($result);
1812 // Creates a new task
1813 function createNewTask ($subject, $notes, $taskType, $userid = NULL, $adminId = NULL, $strip = TRUE) {
1814 // Insert the task data into the database
1815 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())",
1817 convertZeroToNull($adminId),
1818 convertZeroToNull($userid),
1822 ), __FUNCTION__, __LINE__, TRUE, $strip);
1824 // Return insert id which is the task id
1825 return SQL_INSERTID();
1828 // Updates last module / online time
1829 function updateLastActivity ($userid) {
1832 // Run the update query
1833 SQL_QUERY_ESC("UPDATE
1834 `{?_MYSQL_PREFIX?}_user_data`
1836 `{%%pipe,getUserLastWhatName%%}`='{%%pipe,getWhat%%}',
1837 `last_online`=UNIX_TIMESTAMP(),
1838 `REMOTE_ADDR`='{%%pipe,detectRemoteAddr%%}'
1844 ), __FUNCTION__, __LINE__);
1846 // No what set, needs to be ignored (last_module is last_what)
1847 SQL_QUERY_ESC("UPDATE
1848 `{?_MYSQL_PREFIX?}_user_data`
1850 `{%%pipe,getUserLastWhatName%%}`=NULL,
1851 `last_online`=UNIX_TIMESTAMP(),
1852 `REMOTE_ADDR`='{%%pipe,detectRemoteAddr%%}'
1858 ), __FUNCTION__, __LINE__);
1862 // List all given rows (callback function from XML)
1863 function doGenericListEntries ($tableTemplate, $rowTemplate, $noEntryMessageId, $tableName, $columns, $whereColumns, $orderByColumns, $callbackColumns, $extraParameters = array(), $conditions = array(), $content = array()) {
1864 // Verify that tableName and columns are not empty
1865 if ((!is_array($tableName)) || (count($tableName) != 1)) {
1866 // No tableName specified
1867 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array,tableTemplate=' . $tableTemplate . ',rowTemplate=' . $rowTemplate);
1868 } elseif (count($columns) == 0) {
1869 // No columns specified
1870 reportBug(__FUNCTION__, __LINE__, 'columns is not given. Please fix your XML,tableTemplate=' . $tableTemplate . ',rowTemplate=' . $rowTemplate . ',tableName[0]=' . $tableName[0]);
1873 // This is the minimum query, so at least columns and tableName must have entries
1876 // Get the sql part back from given array
1877 $sql .= getSqlPartFromXmlArray($columns);
1879 // Remove last commata and add FROM statement
1880 $sql .= ' FROM `{?_MYSQL_PREFIX?}_' . $tableName[0] . '`';
1882 // Are there entries from whereColumns to add?
1883 if (count($whereColumns) > 0) {
1884 // Then add these as well
1885 if (count($whereColumns) == 1) {
1889 // Table/alias included?
1890 if (!empty($whereColumns[0]['table'])) {
1892 $sql .= $whereColumns[0]['table'] . '.';
1896 $sql .= '`' . $whereColumns[0]['column'] . '`' . $whereColumns[0]['condition'] . chr(39) . $whereColumns[0]['look_for'] . chr(39);
1897 } elseif ((count($whereColumns > 1)) && (count($conditions) > 0)) {
1898 // More than one "WHERE" + condition found
1899 foreach ($whereColumns as $idx => $columnArray) {
1901 $condition = ' WHERE ';
1903 // Is the condition element there?
1904 if (isset($conditions[$columnArray['column']])) {
1905 // Assume the condition
1906 $condition = ' ' . $conditions[$columnArray['column']] . ' ';
1912 // Table/alias included?
1913 if (!empty($whereColumns[$idx]['table'])) {
1915 $sql .= $whereColumns[$idx]['table'] . '.';
1919 $sql .= '`' . $whereColumns[$idx]['column'] . '`' . $whereColumns[$idx]['condition'] . chr(39) . convertDollarDataToGetElement($whereColumns[$idx]['look_for']) . chr(39);
1922 // Did not set $conditions
1923 reportBug(__FUNCTION__, __LINE__, 'Supplied more than "whereColumns" entries but no conditions! Please fix your XML template.');
1927 // Are there entries from orderByColumns to add?
1928 if (count($orderByColumns) > 0) {
1930 $sql .= ' ORDER BY ';
1931 foreach ($orderByColumns as $orderByColumn => $array) {
1932 // Get keys (table/alias) and values (sorting itself)
1933 $table = trim(implode('', array_keys($array)));
1934 $sorting = trim(implode('', array_values($array)));
1936 // table/alias can be omitted
1937 if (!empty($table)) {
1938 // table/alias is given
1939 $sql .= $table . '.';
1942 // Add order-by column
1943 $sql .= '`' . $orderByColumn . '` ' . $sorting . ',';
1946 // Remove last column
1947 $sql = substr($sql, 0, -1);
1950 // Now handle all over to the inner function which will execute the listing
1951 doListEntries($sql, $tableTemplate, $noEntryMessageId, $rowTemplate, $callbackColumns, $extraParameters, $content);
1954 // Do the listing of entries
1955 function doListEntries ($sql, $tableTemplate, $noEntryMessageId, $rowTemplate, $callbackColumns, $extraParameters = array(), $content = array()) {
1956 // Run the SQL query
1957 $result = SQL_QUERY($sql, __FUNCTION__, __LINE__);
1959 // Are there some URLs left?
1960 if (!SQL_HASZERONUMS($result)) {
1963 while ($row = SQL_FETCHARRAY($result)) {
1964 // "Translate" content
1965 foreach ($callbackColumns as $columnName => $callbackName) {
1966 // Fill the callback arguments
1967 $args = array($row[$columnName]);
1969 // Is there more to add?
1970 if (isset($extraParameters[$columnName])) {
1972 $args = merge_array($args, $extraParameters[$columnName]);
1975 // Call the callback-function
1976 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'callbackFunction=' . $callbackName . ',args=<pre>'.print_r($args, TRUE).'</pre>');
1977 // @TODO If we can rewrite the EL sub-system to support more than one parameter, this call_user_func_array() can be avoided
1978 $row[$columnName] = call_user_func_array($callbackName, $args);
1981 // Load row template
1982 $OUT .= loadTemplate(trim($rowTemplate[0]), TRUE, $row);
1985 // Is at least one entry set in content?
1986 if ((is_array($content)) && (count($content) > 0)) {
1987 // Then add generic 'rows' element
1988 $content['rows'] = $OUT;
1990 // Direct output is content
1994 // Load main template
1995 loadTemplate(trim($tableTemplate[0]), FALSE, $content);
1997 // No URLs in surfbar
1998 displayMessage('{--' .$noEntryMessageId[0] . '--}');
2002 SQL_FREERESULT($result);
2005 // Adds a given entry to the database
2006 function doGenericAddEntries ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $timeColumns = array(), $columnIndex = NULL) {
2007 //* DEBUG: */ die(__FUNCTION__.':columns=<pre>'.print_r($columns,TRUE).'</pre>,filterFunctions=<pre>'.print_r($filterFunctions,TRUE).'</pre>,extraValues=<pre>'.print_r($extraValues,TRUE).'</pre>,timeColumns=<pre>'.print_r($timeColumns,TRUE).'</pre>,columnIndex=<pre>'.print_r($columnIndex,TRUE).'</pre>,POST=<pre>'.print_r($_POST,TRUE).'</pre>');
2008 // Verify that tableName and columns are not empty
2009 if ((!is_array($tableName)) || (count($tableName) != 1)) {
2010 // No tableName specified
2011 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
2012 } elseif (count($columns) == 0) {
2013 // No columns specified
2014 reportBug(__FUNCTION__, __LINE__, 'columns is not given. Please fix your XML.');
2017 // Init columns and value elements
2018 $sqlColumns = array();
2019 $sqlValues = array();
2021 // Default is that all went fine
2022 $GLOBALS['__XML_PARSE_RESULT'] = TRUE;
2024 // Is there "time columns"?
2025 if (count($timeColumns) > 0) {
2026 // Then "walk" through all entries
2027 foreach ($timeColumns as $column) {
2028 // Convert all (possible) selections
2029 convertSelectionsToEpocheTimeInPostData($column . '_ye');
2033 // Add columns and values
2034 foreach ($columns as $key => $columnName) {
2035 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',columnName=' . $columnName);
2036 // Is columnIndex set?
2037 if (!is_null($columnIndex)) {
2039 //* DEBUG: */ die('columnName=<pre>'.print_r($columnName,TRUE).'</pre>columnIndex=<pre>'.print_r($columnIndex,TRUE).'</pre>'.debug_get_printable_backtrace());
2040 assert((is_array($columnName)) && (is_string($columnIndex)) && (isset($columnName[$columnIndex])));
2042 // Then use that index "blindly"
2043 $columnName = $columnName[$columnIndex];
2047 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',columnName[' . gettype($columnName) . ']=' . $columnName . ',filterFunctions=' . $filterFunctions[$key] . ',extraValues=' . intval(isset($extraValues[$key])) . ',extraValuesName=' . intval(isset($extraValues[$columnName . '_list'])));
2049 // Copy entry securely to the final arrays
2050 $sqlColumns[$key] = SQL_ESCAPE($columnName);
2051 $sqlValues[$key] = SQL_ESCAPE(postRequestElement($columnName));
2054 $search = key(search_array($columns, 'column', $columnName));
2056 // Try to handle call-back functions and/or extra values on the list
2057 //* DEBUG: */ outputHtml($key . '/' . $columnName . '=<pre>'.print_r($columns,true).'</pre>search_array()=<pre>'.print_r(search_array($columns, 'column', $columnName), true).'</pre>');
2058 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sqlValues[' . $key . '(' . gettype($key) . ')][' . gettype($sqlValues[$key]) . ']=' . $sqlValues[$key] . ' - BEFORE!');
2059 if (is_string($key)) {
2061 $sqlValues[$key] = doHandleExtraValues($filterFunctions, $extraValues, $key . '_list', $sqlValues[$key], array(''), $search);
2064 $sqlValues[$key] = doHandleExtraValues($filterFunctions, $extraValues, $key, $sqlValues[$key], array(''), $search);
2067 // Is the value not a number?
2068 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sqlValues[' . $key . '(' . gettype($key) . ')][' . gettype($sqlValues[$key]) . ']=' . $sqlValues[$key] . ' - AFTER!');
2069 if (($sqlValues[$key] != 'NULL') && (is_string($sqlValues[$key]))) {
2070 // Add quotes around it
2071 $sqlValues[$key] = chr(39) . $sqlValues[$key] . chr(39);
2074 // Is the value false?
2075 if ($sqlValues[$key] === FALSE) {
2076 // One "parser" didn't like it
2077 $GLOBALS['__XML_PARSE_RESULT'] = FALSE;
2082 // If all values are okay, continue
2083 if ($sqlValues[$key] !== FALSE) {
2084 // Build the SQL query
2085 $sql = 'INSERT INTO `{?_MYSQL_PREFIX?}_' . $tableName[0] . '` (`' . implode('`, `', $sqlColumns) . "`) VALUES (" . implode(',', $sqlValues) . ')';
2087 // Run the SQL query
2088 SQL_QUERY($sql, __FUNCTION__, __LINE__);
2091 setPostRequestElement('id', SQL_INSERTID());
2093 // Prepare filter data array
2094 $filterData = array(
2096 'table_name' => $tableName,
2097 'content' => postRequestArray(),
2098 'id' => SQL_INSERTID(),
2100 // @TODO Used generic 'userid' here
2101 'userid_column' => array('userid'),
2102 'raw_userid' => array('userid'),
2103 'affected' => SQL_AFFECTEDROWS(),
2107 // Send "build mail" out
2108 runFilterChain('send_build_mail', $filterData);
2112 // Edit rows by given id numbers
2113 function doGenericEditEntriesConfirm ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $timeColumns = array(), $editNow = array(FALSE), $idColumn = array('id'), $userIdColumn = array('userid'), $rawUserId = array('userid'), $cacheFiles = array(), $subject = '') {
2114 // Is there "time columns"?
2115 if (count($timeColumns) > 0) {
2116 // Then "walk" through all entries
2117 foreach ($timeColumns as $column) {
2118 // Convert all (possible) selections
2119 convertSelectionsToEpocheTimeInPostData($column . '_ye');
2125 foreach (postRequestElement($idColumn[0]) as $id => $sel) {
2127 $id = bigintval($id);
2129 // Prepare content array (new values)
2132 // Prepare SQL for this row
2133 $sql = sprintf("UPDATE `{?_MYSQL_PREFIX?}_%s` SET",
2134 SQL_ESCAPE($tableName[0])
2137 // "Walk" through all entries
2138 foreach (postRequestArray() as $key => $entries) {
2139 // Skip raw userid which is always invalid
2140 if (($key == $rawUserId[0]) || ($key == ($rawUserId[0] . '_raw')) || ($key == 'do_edit')) {
2141 // Continue with next field
2142 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',idColumn[0]=' . $idColumn[0] . ',rawUserId=' . $rawUserId[0]);
2147 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',id=' . $id . ',idColumn[0]=' . $idColumn[0] . ',entries=<pre>'.print_r($entries,TRUE).'</pre>');
2149 // Is entries an array?
2150 if (($key != $idColumn[0]) && (is_array($entries)) && (isset($entries[$id]))) {
2151 // Search for the right array index
2152 $search = key(search_array($columns, 'column', $key));
2154 // Add this entry to content
2155 $content[$key] = $entries[$id];
2158 //* BUG: */ die($key.'/'.$id.'/'.$search.'=<pre>'.print_r($columns,TRUE).'</pre><pre>'.print_r($filterFunctions,TRUE).'</pre>');
2160 // Handle possible call-back functions and/or extra values
2161 $entries[$id] = doHandleExtraValues($filterFunctions, $extraValues, $key, $entries[$id], $userIdColumn, $search);
2163 // Add key/value pair to SQL string
2164 $sql .= addKeyValueSql($key, $entries[$id]);
2165 } elseif (($key != $idColumn[0]) && (!is_array($entries))) {
2167 $search = key(search_array($columns, 'column', $key));
2168 //* BUG: */ die($key.'/<pre>'.print_r($search, TRUE).'</pre>=<pre>'.print_r($columns, TRUE).'</pre>');
2171 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',entries[' . gettype($entries) . ']=' . $entries . ',search=' . $search . ' - BEFORE!');
2173 // Add normal entries as well
2174 $content[$key] = $entries;
2176 // Handle possible call-back functions and/or extra values
2177 $entries = doHandleExtraValues($filterFunctions, $extraValues, $key, $entries, $userIdColumn, $search);
2180 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',entries[' . gettype($entries) . ']=' . $entries . ',search=' . $search . ' - AFTER!');
2182 // Add key/value pair to SQL string
2183 $sql .= addKeyValueSql($key, $entries);
2187 // Finish SQL command
2188 $sql = substr($sql, 0, -1) . " WHERE `" . SQL_ESCAPE($idColumn[0]) . "`=" . $id;
2189 if ((isset($rawUserId[0])) && (isset($userIdColumn[0])) && (isPostRequestElementSet($rawUserId[0])) && (!is_array(postRequestElement($rawUserId[0])))) {
2190 // Add user id as well
2191 $sql .= ' AND `' . $userIdColumn[0] . '`=' . bigintval(postRequestElement($rawUserId[0]));
2196 //* BUG: */ die($sql.'<pre>'.print_r(postRequestArray(), TRUE).'</pre>');
2197 SQL_QUERY($sql, __FUNCTION__, __LINE__);
2199 // Add affected rows
2200 $edited = SQL_AFFECTEDROWS();
2201 $affected += $edited;
2203 // Load all data from that id
2204 $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`=%s LIMIT 1",
2209 ), __FUNCTION__, __LINE__);
2211 // Fetch the data and merge it into $content
2212 $content = merge_array($content, SQL_FETCHARRAY($result));
2214 // Prepare filter data array
2215 $filterData = array(
2217 'table_name' => $tableName,
2218 'content' => $content,
2220 'subject' => $subject,
2221 'userid_column' => $userIdColumn,
2222 'raw_userid' => $rawUserId,
2223 'affected' => $edited,
2227 // Send "build mail" out
2228 runFilterChain('send_build_mail', $filterData);
2231 SQL_FREERESULT($result);
2235 if ((count($cacheFiles) > 0) && (!empty($cacheFiles[0]))) {
2236 // Delete cache file(s)
2237 foreach ($cacheFiles as $cache) {
2238 // Skip any empty entries
2239 if (empty($cache)) {
2240 // This may cause trouble in loadCacheFile()
2244 // Is the cache file loadable?
2245 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
2247 $GLOBALS['cache_instance']->removeCacheFile();
2252 // Return affected rows
2256 // Delete rows by given id numbers
2257 function doGenericDeleteEntriesConfirm ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $deleteNow = array(FALSE), $idColumn = array('id'), $userIdColumn = array('userid'), $rawUserId = array('userid'), $cacheFiles = array()) {
2258 // The base SQL command:
2259 $sql = "DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s` IN (%s)";
2261 // Is a user id provided?
2262 //* BUG: */ die('<pre>'.print_r($rawUserId,TRUE).'</pre><pre>'.print_r($userIdColumn,TRUE).'</pre>');
2263 if ((isset($rawUserId[0])) && (isset($userIdColumn[0])) && (isPostRequestElementSet($rawUserId[0])) && (!is_array(postRequestElement($rawUserId[0])))) {
2264 // Add user id as well
2265 $sql .= ' AND `' . $userIdColumn[0] . '`=' . bigintval(postRequestElement($rawUserId[0]));
2268 // $idColumn[0] in POST must be an array again
2269 if (!is_array(postRequestElement($idColumn[0]))) {
2270 // This indicates that you have conflicting form field naming with XML names
2271 reportBug(__FUNCTION__, __LINE__, 'You have a wrong form field element, idColumn[0]=' . $idColumn[0]);
2275 //* BUG: */ die($sql.'<pre>'.print_r($tableName,TRUE).'</pre><pre>'.print_r($columns,TRUE).'</pre><pre>'.print_r($filterFunctions,TRUE).'</pre><pre>'.print_r($extraValues,TRUE).'</pre><pre>'.print_r($deleteNow,TRUE).'</pre><pre>'.print_r($idColumn,TRUE).'</pre>');
2277 foreach (postRequestElement($idColumn[0]) as $id => $sel) {
2284 // Is there a userid?
2285 if (isPostRequestElementSet($userIdColumn[0])) {
2286 // Load all data from that id
2287 $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`=%s LIMIT 1",
2292 ), __FUNCTION__, __LINE__);
2295 $content = SQL_FETCHARRAY($result);
2298 SQL_FREERESULT($result);
2300 // Send "build mails" out
2301 sendGenericBuildMails('delete', $tableName, $content, $id, '', $userIdColumn);
2305 $idList .= $id . ',';
2313 convertNullToZero(substr($idList, 0, -1))
2314 ), __FUNCTION__, __LINE__);
2316 // Return affected rows
2317 return SQL_AFFECTEDROWS();
2320 // Build a special template list
2321 // @TODO cacheFiles is not yet supported
2322 function doGenericListBuilder ($prefix, $listType, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId = array('userid'), $content = array()) {
2323 // $tableName and $idColumn must bove be arrays!
2324 if ((!is_array($tableName)) || (count($tableName) != 1)) {
2325 // $tableName is no array
2326 reportBug(__FUNCTION__, __LINE__, 'tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
2327 } elseif (!is_array($idColumn)) {
2328 // $idColumn is no array
2329 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
2330 } elseif ((!is_array($userIdColumn)) || (count($userIdColumn) != 1)) {
2331 // $tableName is no array
2332 reportBug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array: userIdColumn=' . $userIdColumn);
2338 // "Walk" through all entries
2339 //* DEBUG: */ reportBug(__FUNCTION__, __LINE__, 'listType=<pre>'.print_r($listType,TRUE).'</pre>,tableName<pre>'.print_r($tableName,TRUE).'</pre>,columns=<pre>'.print_r($columns,TRUE).'</pre>,filterFunctions=<pre>'.print_r($filterFunctions,TRUE).'</pre>,extraValues=<pre>'.print_r($extraValues,TRUE).'</pre>,idColumn=<pre>'.print_r($idColumn,TRUE).'</pre>,userIdColumn=<pre>'.print_r($userIdColumn,TRUE).'</pre>,rawUserId=<pre>'.print_r($rawUserId,TRUE).'</pre>');
2340 foreach (postRequestElement($idColumn[0]) as $id => $selected) {
2342 $id = bigintval($id);
2344 // Get result from a given column array and table name
2345 $result = SQL_RESULT_FROM_ARRAY($tableName[0], $columns, $idColumn[0], $id, __FUNCTION__, __LINE__);
2347 // Is there one entry?
2348 if (SQL_NUMROWS($result) == 1) {
2350 $row = SQL_FETCHARRAY($result);
2353 foreach ($row as $key => $value) {
2355 $idx = searchXmlArray($key, $columns, 'column');
2357 // Default name is NULL
2360 // Is the name there?
2361 if (isset($columns[$idx]['name'])) {
2363 $name = $columns[$idx]['name'];
2366 // Skip any missing entries
2367 if ($idx === FALSE) {
2369 //* DEBUG: */ reportBug(__FUNCTION__, __LINE__, 'key=' . $key . ' - SKIPPED!');
2373 // Is there a userid?
2374 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',userIdColumn=' . $userIdColumn[0]);
2375 if ($key == $userIdColumn[0]) {
2376 // Add it again as raw id
2377 //* DEBUG: */ reportBug(__FUNCTION__, __LINE__, 'key=' . $key . ',userIdColumn=' . $userIdColumn[0]);
2378 $row[$userIdColumn[0]] = convertZeroToNull($value);
2379 $row[$userIdColumn[0] . '_raw'] = $row[$userIdColumn[0]];
2382 // If the key matches the idColumn variable, we need to temporary remember it
2383 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',idColumn=' . $idColumn[0] . ',value=' . $value);
2384 if ($key == $idColumn[0]) {
2386 * Found, so remember it securely (to make sure only id
2387 * numbers can pass, don't use alpha-numerical values!)
2389 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'value=' . $value . ' - set as ' . $prefix . '_list_builder_id_value!');
2390 $GLOBALS[$prefix . '_list_builder_id_value'] = bigintval($value);
2393 // Try to handle call-back functions and/or extra values
2394 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'idx=' . $idx . ',row[' . $key . ']=' . $row[$key]);
2395 //if ($key == 'forced_campaign_created') die($idx.'=<pre>'.print_r($columns,true).'</pre><pre>'.print_r($extraValues,true).'</pre>');
2396 $row[$key] = doHandleExtraValues($filterFunctions, $extraValues, $idx, $row[$key], $userIdColumn, ((!is_null($name)) ? $name : $key), $id);
2400 $OUT .= loadTemplate(sprintf("%s_%s_%s_row",
2409 SQL_FREERESULT($result);
2412 // Is there an entry in $content?
2413 if ((is_array($content)) && (count($content) > 0)) {
2414 // Use generic 'rows'
2415 $content['rows'] = $OUT;
2417 // Use direct output
2421 // Load master template
2422 loadTemplate(sprintf("%s_%s_%s",
2430 // Checks whether given URL is blacklisted
2431 function isUrlBlacklisted ($url) {
2432 // Mark it as not listed by default
2435 // Is black-listing enbaled?
2436 if (!isUrlBlacklistEnabled()) {
2437 // No, then all URLs are not in this list
2439 } elseif (!isset($GLOBALS['blacklist_data'][$url])) {
2440 // Check black-list for given URL
2441 $result = SQL_QUERY_ESC("SELECT UNIX_TIMESTAMP(`timestamp`) AS `blist_timestamp` FROM `{?_MYSQL_PREFIX?}_url_blacklist` WHERE `url`='%s' LIMIT 1",
2442 array($url), __FILE__, __LINE__);
2444 // Is there an entry?
2445 if (SQL_NUMROWS($result) == 1) {
2446 // Jupp, we got one listed
2447 $GLOBALS['blacklist_data'][$url] = SQL_FETCHARRAY($result);
2449 // Mark it as listed
2454 SQL_FREERESULT($result);
2456 // Is found in cache -> black-listed
2464 // Adds key/value pair to a working SQL string together
2465 function addKeyValueSql ($key, $value) {
2470 if (($value == 'NULL') || (is_null($value))) {
2471 // Add key with NULL
2472 $sql .= sprintf(' `%s`=NULL,',
2475 } elseif ((is_double($value)) || (is_float($value)) || (is_int($value))) {
2476 // Is a number, so addd it directly
2477 $sql .= sprintf(" `%s`=%s,",
2482 // Else add the value escape'd
2483 $sql .= sprintf(" `%s`='%s',",
2489 // Return SQL string