2 /************************************************************************
3 * Mailer v0.2.1-FINAL Start: 08/31/2003 *
4 * =================== Last change: 11/23/2004 *
6 * -------------------------------------------------------------------- *
7 * File : admin-inc.php *
8 * -------------------------------------------------------------------- *
9 * Short description : Administrative related functions *
10 * -------------------------------------------------------------------- *
11 * Kurzbeschreibung : Fuer die Administration benoetigte 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 // Register an administrator account
44 function addAdminAccount ($adminLogin, $passHash, $adminEmail) {
45 // Login does already exist
49 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
50 array($adminLogin), __FUNCTION__, __LINE__);
52 // Is the entry there?
53 if (SQL_HASZERONUMS($result)) {
54 // Ok, let's create the admin login
55 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_admins` (`login`,`password`,`email`) VALUES ('%s', '%s', '%s')",
60 ), __FUNCTION__, __LINE__);
67 SQL_FREERESULT($result);
73 // This function will be executed when the admin is not logged in and has submitted his login data
74 function ifAdminLoginDataIsValid ($adminLogin, $adminPassword) {
75 // First of all, no admin login is found, so the admin hash is null
79 // Get admin id from login
80 $adminId = getAdminId($adminLogin);
82 // Continue only with found admin ids
84 // Then we need to lookup the login name by getting the admin hash
85 $adminHash = getAdminHash($adminId);
87 // If this is fine, we can continue
88 if ($adminHash != '-1') {
89 // Get admin id and set it as current
90 setCurrentAdminId($adminId);
92 // Now, we need to encode the password in the same way the one is encoded in database
93 $testHash = generateHash($adminPassword, $adminHash);
95 // If they both match, the login data is valid
96 if ($testHash == $adminHash) {
106 // Prepare data array
109 'login' => $adminLogin,
110 'plain_pass' => $adminPassword,
111 'pass_hash' => $adminHash
114 // Run a special filter
115 runFilterChain('do_admin_login_' . $ret, $data);
121 // Only be executed on cookie checking
122 function ifAdminCookiesAreValid ($adminLogin, $passHash) {
123 // First of all, no admin login is found
126 // Then we need to lookup the login name by getting the admin hash
127 $adminHash = getAdminHash($adminLogin);
129 // If this is fine, we can continue
130 if ($adminHash != '-1') {
131 // Now, we need to encode the password in the same way the one is encoded in database
132 $testHash = encodeHashForCookie($adminHash);
133 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'adminLogin=' . $adminLogin . ',passHash='.$passHash.',adminHash='.$adminHash.',testHash='.$testHash);
135 // If they both match, the login data is valid
136 if ($testHash == $passHash) {
146 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret='.$ret);
150 // Do an admin action
151 function doAdminAction () {
152 // Determine correct 'what' value
153 $what = determineWhat();
156 $action = getActionFromModuleWhat(getModule(), $what);
158 // Load welcome template
159 if (isExtensionActive('admins')) {
160 // @TODO This and the next getCurrentAdminId() call might be moved into the templates?
161 $content['welcome'] = loadTemplate('admin_welcome_admins', true, getCurrentAdminId());
163 $content['welcome'] = loadTemplate('admin_welcome', true, getCurrentAdminId());
166 // Load header, footer, render menu
167 $content['header'] = loadTemplate('admin_header' , true, $content);
168 $content['footer'] = loadTemplate('admin_footer' , true, $content);
169 $content['menu'] = addAdminMenu($action, $what);
171 // Load main template
172 loadTemplate('admin_main', false, $content);
174 // Check if action/what pair is valid
175 $result_action = SQL_QUERY_ESC("SELECT
178 `{?_MYSQL_PREFIX?}_admin_menu`
183 `what`='%s' AND `what` != 'welcome'
186 `what`='' OR `what` IS NULL
197 ), __FUNCTION__, __LINE__);
199 // Do we have an entry?
200 if (SQL_NUMROWS($result_action) == 1) {
201 // Is valid but does the inlcude file exists?
202 $inc = sprintf("inc/modules/admin/action-%s.php", $action);
203 if ((isIncludeReadable($inc)) && (isMenuActionValid('admin', $action, $what)) && ($GLOBALS['acl_allow'] === true)) {
204 // Ok, we finally load the admin action module
206 } elseif ($GLOBALS['acl_allow'] === false) {
208 loadTemplate('admin_menu_failed', false, '{%message,ADMIN_ACCESS_DENIED=' . $what . '%}');
210 // Include file not found :-(
211 loadTemplate('admin_menu_failed', false, '{%message,ADMIN_ACTION_404=' . $action . '%}');
214 // Invalid action/what pair found
215 loadTemplate('admin_menu_failed', false, '{%message,ADMIN_ACTION_INVALID=' . $action . '/' . $what . '%}');
219 SQL_FREERESULT($result_action);
222 loadTemplate('admin_main_footer', false, $content);
226 * Checks whether current admin is allowed to access given action/what
227 * combination (only one is allowed to be null!).
229 function isAdminAllowedAccessMenu ($action, $what = NULL) {
231 if (!isset($GLOBALS[__FUNCTION__][$action][$what])) {
232 // ACL is always 'allow' when no ext-admins is installed
233 // @TODO This can be rewritten into a filter
234 $GLOBALS[__FUNCTION__][$action][$what] = ((!isExtensionInstalledAndNewer('admins', '0.2.0')) || ((isExtensionActive('admins')) && (isAdminsAllowedByAcl($action, $what))));
237 // Return the cached value
238 return $GLOBALS[__FUNCTION__][$action][$what];
241 // Adds an admin menu
242 function addAdminMenu ($action, $what) {
248 $GLOBALS['menu']['description'] = array();
249 $GLOBALS['menu']['title'] = array();
252 $result_main = SQL_QUERY("SELECT
253 `action` AS `main_action`,
254 `title` AS `main_title`,
255 `descr` AS `main_descr`
257 `{?_MYSQL_PREFIX?}_admin_menu`
259 (`what`='' OR `what` IS NULL)
262 `id` DESC", __FUNCTION__, __LINE__);
264 // Do we have entries?
265 if (!SQL_HASZERONUMS($result_main)) {
266 $OUT .= '<ul class="admin_menu_main">';
268 // Load all 'action' menus
269 while ($mainContent = SQL_FETCHARRAY($result_main)) {
271 $inc = sprintf("inc/modules/admin/action-%s.php", $mainContent['main_action']);
273 // Is the current admin allowed to access this 'action' menu?
274 if (isAdminAllowedAccessMenu($mainContent['main_action'])) {
275 if ($SUB === false) {
276 // Insert compiled menu title and description
277 $GLOBALS['menu']['title'][$mainContent['main_action']] = $mainContent['main_title'];
278 $GLOBALS['menu']['description'][$mainContent['main_action']] = $mainContent['main_descr'];
280 $OUT .= '<li class="admin_menu"' . addJavaScriptMenuContent('admin', $mainContent['main_action'], $action, $what) . '>
281 <div class="nobr"><strong>·</strong> ';
283 // Is the file readable?
284 if (isIncludeReadable($inc)) {
285 if (($mainContent['main_action'] == $action) && (empty($what))) {
288 $OUT .= '[<a href="{%url=modules.php?module=admin&action=' . $mainContent['main_action'] . '%}">';
291 $OUT .= '<span class="bad" style="cursor:help" title="{%message,ADMIN_MENU_ACTION_404_TITLE=' . $mainContent['main_action'] . '%}">';
294 $OUT .= $mainContent['main_title'];
296 // Is the file readable?
297 if (isIncludeReadable($inc)) {
298 if (($mainContent['main_action'] == $action) && (empty($what))) {
311 $OUT .= addAdminSubMenu($mainContent, $action, $what);
319 SQL_FREERESULT($result_main);
326 // Add admin sub menu
327 function addAdminSubMenu ($mainContent, $action, $what) {
331 // Check for menu entries
332 $result_what = SQL_QUERY_ESC("SELECT
333 `what` AS `sub_what`,
334 `title` AS `sub_title`,
335 `descr` AS `sub_descr`
337 `{?_MYSQL_PREFIX?}_admin_menu`
345 array($mainContent['main_action']), __FUNCTION__, __LINE__);
347 // Remember the count for later checks
348 setAdminMenuHasEntries($mainContent['main_action'], ((!SQL_HASZERONUMS($result_what)) && (($action == $mainContent['main_action']) || (isAdminMenuJavascriptEnabled()))));
350 // Start li-tag for sub menu content
351 $OUT .= '<li class="admin_menu_sub" id="action_menu_' . $mainContent['main_action'] . '"' . addStyleMenuContent('admin', $mainContent['main_action'], $action) . '>';
353 // Do we have entries?
354 if (ifAdminMenuHasEntries($mainContent['main_action'])) {
355 // Sub menu has been called
358 // Do we have entries?
359 if (!SQL_HASZERONUMS($result_what)) {
361 $OUT .= '<ul class="admin_menu_sub">';
364 while ($subContent = SQL_FETCHARRAY($result_what)) {
366 $inc = sprintf("inc/modules/admin/what-%s.php", $subContent['sub_what']);
368 // Is the current admin allowed to access this 'what' menu?
369 if (isAdminAllowedAccessMenu(NULL, $subContent['sub_what'])) {
370 // Insert compiled title and description
371 $GLOBALS['menu']['title'][$subContent['sub_what']] = $subContent['sub_title'];
372 $GLOBALS['menu']['description'][$subContent['sub_what']] = $subContent['sub_descr'];
373 $OUT .= '<li class="admin_menu">
374 <div class="nobr"><strong>--></strong> ';
376 // Is the file readable?
377 if (isIncludeReadable($inc)) {
378 if ($what == $subContent['sub_what']) {
381 $OUT .= '[<a href="{%url=modules.php?module=admin&what=' . $subContent['sub_what'] . '%}">';
384 $OUT .= '<span class="bad" style="cursor:help" title="{%message,ADMIN_MENU_WHAT_404_TITLE=' . $subContent['sub_what'] . '%}">';
387 $OUT .= $subContent['sub_title'];
389 // Is the file readable?
390 if (isIncludeReadable($inc)) {
391 if ($what == $subContent['sub_what']) {
404 // Finish HTML output
409 SQL_FREERESULT($result_what);
419 // Create an admin selection box form
420 function addAdminSelectionBox ($adminId = NULL, $special = '') {
421 // Default is email as "special column"
422 $ADD = ',`email` AS `special`';
424 // Is a special column given?
425 if (!empty($special)) {
426 // Additional column for SQL query
427 $ADD = ',`' . $special . '` AS `special`';
431 $result = SQL_QUERY('SELECT
436 `{?_MYSQL_PREFIX?}_admins`
438 `login` ASC', __FUNCTION__, __LINE__);
444 while ($content = SQL_FETCHARRAY($result)) {
446 $OUT .= loadTemplate('select_admins_option', true, $content);
450 SQL_FREERESULT($result);
452 // Add form to content
453 $content['form_selection'] = $OUT;
456 loadTemplate('select_admins_box', false, $content);
459 // Create a member selection box
460 function addMemberSelectionBox ($userid = NULL, $add_all = false, $return = false, $none = false, $field = 'userid', $whereStatement = " WHERE `surname` NOT LIKE '{?tester_user_surname_prefix?}%'") {
461 // Output selection form with all confirmed user accounts listed
462 $result = SQL_QUERY('SELECT
467 `{?_MYSQL_PREFIX?}_user_data`
468 ' . $whereStatement . '
470 `userid` ASC', __FUNCTION__, __LINE__);
475 // USe this only for adding points (e.g. adding refs really makes no sence ;-) )
476 if ($add_all === true) {
477 $OUT = ' <option value="all">{--ALL_MEMBERS--}</option>';
478 } elseif ($none === true) {
479 $OUT = ' <option value="0">{--SELECT_NONE--}</option>';
483 while ($content = SQL_FETCHARRAY($result)) {
484 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . intval($userid) . '/' . $content['userid']);
485 $OUT .= '<option value="' . bigintval($content['userid']) . '"';
486 if (bigintval($userid) === bigintval($content['userid'])) {
487 $OUT .= ' selected="selected"';
489 $OUT .= '>' . $content['surname'] . ' ' . $content['family'] . ' (' . bigintval($content['userid']) . ')</option>';
493 SQL_FREERESULT($result);
495 if ($return === false) {
496 // Remeber options in constant
497 $content['form_selection'] = $OUT;
498 $content['what'] = '{%pipe,getWhat%}';
501 loadTemplate('admin_form_selection_box', false, $content);
503 // Return content in selection frame
504 return '<select class="form_select" name="' . handleFieldWithBraces($field) . '" size="1">' . $OUT . '</select>';
508 // Create a menu selection box for given menu system
509 // @TODO Try to rewrite this to adminAddMenuSelectionBox()
511 function adminMenuSelectionBox_DEPRECATED ($mode, $default = '', $defid = '') {
512 $what = "`what` != '' AND `what` IS NOT NULL";
513 if ($mode == 'action') $what = "(`what`='' OR `what` IS NULL) AND `action` != 'login'";
515 $result = SQL_QUERY_ESC("SELECT `%s` AS `menu`,`title` FROM `{?_MYSQL_PREFIX?}_admin_menu` WHERE ".$what." ORDER BY `sort` ASC",
516 array($mode), __FUNCTION__, __LINE__);
517 if (!SQL_HASZERONUMS($result)) {
518 // Load menu as selection
519 $OUT = '<select name="' . $mode . '_menu';
520 if ((!empty($defid)) || ($defid == '0')) $OUT .= '[' . $defid . ']';
521 $OUT .= '" size="1" class="form_select">
522 <option value="">{--SELECT_NONE--}</option>';
524 while ($content = SQL_FETCHARRAY($result)) {
525 $OUT .= '<option value="' . $content['menu'] . '"';
526 if ((!empty($default)) && ($default == $content['menu'])) {
527 $OUT .= ' selected="selected"';
529 $OUT .= '>' . $content['title'] . '</option>';
533 SQL_FREERESULT($result);
535 // Add closing select-tag
539 $OUT = '{--ADMIN_PROBLEM_NO_MENU--}';
546 // Wrapper for $_POST and adminSaveSettings
547 function adminSaveSettingsFromPostData ($tableName = '_config', $whereStatement = '`config`=0', $translateComma = array(), $alwaysAdd = false, $displayMessage = true) {
549 $postData = postRequestArray();
551 // Call the lower function
552 adminSaveSettings($postData, $tableName, $whereStatement, $translateComma, $alwaysAdd, $displayMessage);
555 // Save settings to the database
556 function adminSaveSettings (&$postData, $tableName = '_config', $whereStatement = '`config`=0', $translateComma = array(), $alwaysAdd = false, $displayMessage = true) {
557 // Prepare all arrays, variables
558 $tableData = array();
561 // Now, walk through all entries and prepare them for saving
562 foreach ($postData as $id => $val) {
563 // Process only formular field but not submit buttons ;)
569 // Do not save the ok value
570 convertSelectionsToEpocheTime($postData, $tableData, $id, $skip);
572 // Shall we process this id? It muss not be empty, of course
573 if (($skip === false) && (!empty($id)) && ((!isset($GLOBALS['skip_config'][$id]))) || ($tableName != '_config')) {
574 // Translate the value? (comma to dot!)
575 if ((is_array($translateComma)) && (in_array($id, $translateComma))) {
576 // Then do it here... :)
577 $val = convertCommaToDot($val);
580 // Shall we add numbers or strings?
581 $test = (float) $val;
582 if ('' . $val . '' == '' . $test . '') {
584 array_push($tableData, sprintf("`%s`=%s", $id, $test));
585 } elseif (is_null($val)) {
587 array_push($tableData, sprintf("`%s`=NULL", $id));
590 array_push($tableData, sprintf("`%s`='%s'", $id, trim($val)));
593 // Do not add a config entry twice
594 $GLOBALS['skip_config'][$id] = true;
596 // Update current configuration
597 setConfigEntry($id, $val);
601 // Check if entry does exist
603 if ($alwaysAdd === false) {
604 if (!empty($whereStatement)) {
605 $result = SQL_QUERY("SELECT * FROM `{?_MYSQL_PREFIX?}" . $tableName . "` WHERE " . $whereStatement . " LIMIT 1", __FUNCTION__, __LINE__);
607 $result = SQL_QUERY("SELECT * FROM `{?_MYSQL_PREFIX?}" . $tableName . "` LIMIT 1", __FUNCTION__, __LINE__);
611 if (SQL_NUMROWS($result) == 1) {
612 // "Implode" all data to single string
613 $updatedData = implode(', ', $tableData);
615 // Generate SQL string
616 $sql = sprintf("UPDATE `{?_MYSQL_PREFIX?}%s` SET %s WHERE %s LIMIT 1",
622 // Add Line (does only work with AUTO_INCREMENT!
623 $keys = array(); $values = array();
624 foreach ($tableData as $entry) {
626 $line = explode('=', $entry);
627 array_push($keys , $line[0]);
628 array_push($values, $line[1]);
631 // Add both in one line
632 $keys = implode('`,`', $keys);
633 $values = implode(', ' , $values);
635 // Generate SQL string
636 $sql = sprintf("INSERT INTO `{?_MYSQL_PREFIX?}%s` (%s) VALUES (%s)",
644 SQL_FREERESULT($result);
646 // Simply run generated SQL string
647 SQL_QUERY($sql, __FUNCTION__, __LINE__);
649 // Remember affected rows
650 $affected = SQL_AFFECTEDROWS();
653 rebuildCache('config', 'config');
655 // Settings saved, so display message?
656 if ($displayMessage === true) displayMessage('{--SETTINGS_SAVED--}');
658 // Return affected rows
662 // Generate a selection box
663 function adminAddMenuSelectionBox ($menu, $type, $name, $default = '') {
664 // Open the requested menu directory
665 $menuArray = getArrayFromDirectory(sprintf("inc/modules/%s/", $menu), $type . '-', false, false);
667 // Init the selection box
668 $OUT = '<select name="' . $name . '" class="form_select" size="1"><option value="">{--ADMIN_IS_TOP_MENU--}</option>';
670 // Walk through all files
671 foreach ($menuArray as $file) {
672 // Is this a PHP script?
673 if ((!isDirectory($file)) && (isInString('' . $type . '-', $file)) && (isInString('.php', $file))) {
674 // Then test if the file is readable
675 $test = sprintf("inc/modules/%s/%s", $menu, $file);
677 // Is the file there?
678 if (isIncludeReadable($test)) {
679 // Extract the value for what=xxx
680 $part = substr($file, (strlen($type) + 1));
681 $part = substr($part, 0, -4);
683 // Is that part different from the overview?
684 if ($part != 'welcome') {
685 $OUT .= '<option value="' . $part . '"';
686 if ($part == $default) {
687 $OUT .= ' selected="selected"';
689 $OUT .= '>' . $part . '</option>';
695 // Close selection box
702 // Creates a user-profile link for the admin. This function can also be used for many other purposes
703 function generateUserProfileLink ($userid, $title = '', $what = 'list_user') {
704 if (($title == '') && (isValidUserId($userid))) {
705 // Set userid as title
707 } elseif (!isValidUserId($userid)) {
708 // User id zero is invalid
709 return '<strong>' . convertNullToZero($userid) . '</strong>';
712 if (($title == '0') && ($what == 'list_refs')) {
713 // Return title again
715 } elseif (!empty($title)) {
716 // Not empty, so skip next one
717 } elseif (isExtensionActive('nickname')) {
719 $nick = getNickname($userid);
721 // Is it not empty, use it as title else the userid
723 $title = $nick . '(' . $userid . ')';
730 return '[<a href="{%url=modules.php?module=admin&what=' . $what . '&userid=' . $userid . '%}" title="{--ADMIN_USER_PROFILE_TITLE--}">' . $title . '</a>]';
733 // Check "logical-area-mode"
734 function adminGetMenuMode () {
735 // Set the default menu mode as the mode for all admins
738 // If sql_patches is up-to-date enough, use the configuration
739 if (isExtensionInstalledAndNewer('sql_patches', '0.3.2')) {
740 $mode = getAdminMenu();
747 $adminId = getCurrentAdminId();
749 // Check individual settings of current admin
750 if (isset($GLOBALS['cache_array']['admin']['la_mode'][$adminId])) {
752 $adminMode = $GLOBALS['cache_array']['admin']['la_mode'][$adminId];
753 incrementStatsEntry('cache_hits');
754 } elseif (isExtensionInstalledAndNewer('admins', '0.6.7')) {
755 // Load from database when version of 'admins' is enough
756 $result = SQL_QUERY_ESC("SELECT `la_mode` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
757 array($adminId), __FUNCTION__, __LINE__);
759 // Do we have an entry?
760 if (SQL_NUMROWS($result) == 1) {
762 list($adminMode) = SQL_FETCHROW($result);
766 SQL_FREERESULT($result);
769 // Check what the admin wants and set it when it's not the default mode
770 if ($adminMode != 'global') {
774 // Return admin-menu's mode
778 // Change activation status
779 function adminChangeActivationStatus ($IDs, $table, $row, $idRow = 'id') {
781 if ((is_array($IDs)) && (count($IDs) > 0)) {
782 // "Walk" all through and count them
783 foreach ($IDs as $id => $selected) {
784 // Secure the id number
785 $id = bigintval($id);
787 // Should always be set... ;-)
788 if (!empty($selected)) {
789 // Determine new status
790 $result = SQL_QUERY_ESC("SELECT %s FROM `{?_MYSQL_PREFIX?}_%s` WHERE %s=%s LIMIT 1",
796 ), __FUNCTION__, __LINE__);
799 if (SQL_NUMROWS($result) == 1) {
801 list($currStatus) = SQL_FETCHROW($result);
803 // And switch it N<->Y
804 $newStatus = convertBooleanToYesNo(!($currStatus == 'Y'));
806 // Change this status
807 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s` SET %s='%s' WHERE %s=%s LIMIT 1",
814 ), __FUNCTION__, __LINE__);
816 // Count up affected rows
817 $count += SQL_AFFECTEDROWS();
821 SQL_FREERESULT($result);
826 displayMessage(sprintf(getMessage('ADMIN_STATUS_CHANGED'), $count, count($IDs)));
829 displayMessage('{--ADMIN_NOTHING_SELECTED_CHANGE--}');
833 // Send mails for del/edit/lock build modes
834 function sendAdminBuildMails ($mode, $tableName, $content, $id, $subjectPart = '', $userIdColumn = array('userid')) {
835 // $tableName must be an array
836 if ((!is_array($tableName)) || (count($tableName) != 1)) {
837 // $tableName is no array
838 reportBug(__FUNCTION__, __LINE__, 'tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
839 } elseif ((!is_array($userIdColumn)) || (count($userIdColumn) != 1)) {
840 // $tableName is no array
841 reportBug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array: userIdColumn=' . $userIdColumn);
844 // Default subject is the subject part
845 $subject = $subjectPart;
847 // Is the subject part not set?
848 if (empty($subjectPart)) {
849 // Then use it from the mode
850 $subject = strtoupper($mode);
853 // Is the raw userid set?
854 if (postRequestElement($userIdColumn[0], $id) > 0) {
855 // Load email template
856 if (!empty($subjectPart)) {
857 $mail = loadEmailTemplate('member_' . $mode . '_' . strtolower($subjectPart) . '_' . $tableName[0], $content);
859 $mail = loadEmailTemplate('member_' . $mode . '_' . $tableName[0], $content);
863 sendEmail(postRequestElement($userIdColumn[0], $id), strtoupper('{--MEMBER_' . $subject . '_' . $tableName[0] . '_SUBJECT--}'), $mail);
867 $subject = strtoupper('{--ADMIN_' . $subject . '_' . $tableName[0] . '_SUBJECT--}');
869 // Send admin notification out
870 if (!empty($subjectPart)) {
871 sendAdminNotification($subject, 'admin_' . $mode . '_' . strtolower($subjectPart) . '_' . $tableName[0], $content, postRequestElement($userIdColumn[0], $id));
873 sendAdminNotification($subject, 'admin_' . $mode . '_' . $tableName[0], $content, postRequestElement($userIdColumn[0], $id));
877 // Build a special template list
878 function adminListBuilder ($listType, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId = array('userid')) {
879 // $tableName and $idColumn must bove be arrays!
880 if ((!is_array($tableName)) || (count($tableName) != 1)) {
881 // $tableName is no array
882 reportBug(__FUNCTION__, __LINE__, 'tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
883 } elseif (!is_array($idColumn)) {
884 // $idColumn is no array
885 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
886 } elseif ((!is_array($userIdColumn)) || (count($userIdColumn) != 1)) {
887 // $tableName is no array
888 reportBug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array: userIdColumn=' . $userIdColumn);
894 // "Walk"Â through all entries
895 //* 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>');
896 foreach (postRequestElement($idColumn[0]) as $id => $selected) {
898 $id = bigintval($id);
900 // Get result from a given column array and table name
901 $result = SQL_RESULT_FROM_ARRAY($tableName[0], $columns, $idColumn[0], $id, __FUNCTION__, __LINE__);
903 // Is there one entry?
904 if (SQL_NUMROWS($result) == 1) {
906 $content = SQL_FETCHARRAY($result);
909 foreach ($content as $key => $value) {
911 $idx = searchXmlArray($key, $columns, 'column');
913 // Skip any missing entries
914 if ($idx === false) {
916 //* DEBUG: */ reportBug(__FUNCTION__, __LINE__, 'key=' . $key . ' - SKIPPED!');
920 //Â Do we have a userid?
921 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',userIdColumn=' . $userIdColumn[0]);
922 if ($key == $userIdColumn[0]) {
923 // Add it again as raw id
924 //* DEBUG: */ reportBug(__FUNCTION__, __LINE__, 'key=' . $key . ',userIdColumn=' . $userIdColumn[0]);
925 $content[$userIdColumn[0]] = convertZeroToNull($value);
926 $content[$userIdColumn[0] . '_raw'] = $content[$userIdColumn[0]];
929 // If the key matches the idColumn variable, we need to temporary remember it
930 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',idColumn=' . $idColumn[0] . ',value=' . $value);
931 if ($key == $idColumn[0]) {
933 * Found, so remember it securely (to make sure only id
934 * numbers can pass, don't use alpha-numerical values!)
936 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'value=' . $value . ' - set as admin_list_builder_id_value!');
937 $GLOBALS['admin_list_builder_id_value'] = bigintval($value);
940 // Do we have a call-back function and extra-value pair?
941 if ((isset($filterFunctions[$idx])) && (isset($extraValues[$idx]))) {
942 // Handle the call in external function
943 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',fucntion=' . $filterFunctions[$idx] . ',value=' . $value);
944 $content[$key] = handleExtraValues(
945 $filterFunctions[$idx],
949 } elseif ((isset($columns[$idx]['name'])) && (isset($filterFunctions[$columns[$idx]['name']])) && (isset($extraValues[$columns[$idx]['name']]))) {
950 // Handle the call in external function
951 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',fucntion=' . $filterFunctions[$columns[$idx]['name']] . ',value=' . $value);
952 $content[$key] = handleExtraValues(
953 $filterFunctions[$columns[$idx]['name']],
955 $extraValues[$columns[$idx]['name']]
961 $OUT .= loadTemplate(sprintf("admin_%s_%s_row",
969 SQL_FREERESULT($result);
972 // Load master template
973 loadTemplate(sprintf("admin_%s_%s",
980 // Change status of "build" list
981 function adminBuilderStatusHandler ($mode, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray, $rawUserId = array('userid'), $cacheFiles = array()) {
982 // $tableName must be an array
983 if ((!is_array($tableName)) || (count($tableName) != 1)) {
984 // No tableName specified
985 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
986 } elseif (!is_array($idColumn)) {
987 // $idColumn is no array
988 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
989 } elseif ((!is_array($userIdColumn)) || (count($userIdColumn) != 1)) {
990 // $tableName is no array
991 reportBug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array: userIdColumn=' . $userIdColumn);
994 // "Walk" through all entries
995 foreach (postRequestElement($idColumn[0]) as $id => $sel) {
996 // Construct SQL query
997 $sql = sprintf("UPDATE `{?_MYSQL_PREFIX?}_%s` SET", SQL_ESCAPE($tableName[0]));
999 // Load data of entry
1000 $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`=%s LIMIT 1",
1005 ), __FUNCTION__, __LINE__);
1008 $content = SQL_FETCHARRAY($result);
1011 SQL_FREERESULT($result);
1013 // Add all status entries (e.g. status column last_updated or so)
1014 $newStatus = 'UNKNOWN';
1015 $oldStatus = 'UNKNOWN';
1016 $statusColumn = 'unknown';
1017 foreach ($statusArray as $column => $statusInfo) {
1018 // Does the entry exist?
1019 if ((isset($content[$column])) && (isset($statusInfo[$content[$column]]))) {
1020 // Add these entries for update
1021 $sql .= sprintf(" `%s`='%s',", SQL_ESCAPE($column), SQL_ESCAPE($statusInfo[$content[$column]]));
1024 if ($statusColumn == 'unknown') {
1025 // Always (!!!) change status column first!
1026 $oldStatus = $content[$column];
1027 $newStatus = $statusInfo[$oldStatus];
1028 $statusColumn = $column;
1030 } elseif (isset($content[$column])) {
1032 reportBug(__FUNCTION__, __LINE__, ':UNFINISHED: id=' . $id . ',column=' . $column . '[' . gettype($statusInfo) . '] = ' . $content[$column]);
1036 // Add other columns as well
1037 foreach (postRequestArray() as $key => $entries) {
1039 logDebugMessage(__FUNCTION__, __LINE__, 'Found entry: ' . $key);
1041 // Skip id, raw userid and 'do_$mode'
1042 if (!in_array($key, array($idColumn[0], $rawUserId[0], ('do_' . $mode)))) {
1043 // Are there brackets () at the end?
1044 if (substr($entries[$id], -2, 2) == '()') {
1045 // Direct SQL command found
1046 $sql .= sprintf(" `%s`=%s,", SQL_ESCAPE($key), SQL_ESCAPE($entries[$id]));
1048 // Add regular entry
1049 $sql .= sprintf(" `%s`='%s',", SQL_ESCAPE($key), SQL_ESCAPE($entries[$id]));
1052 $content[$key] = $entries[$id];
1056 logDebugMessage(__FUNCTION__, __LINE__, 'Skipped: ' . $key);
1060 // Finish SQL statement
1061 $sql = substr($sql, 0, -1) . sprintf(" WHERE `%s`=%s AND `%s`='%s' LIMIT 1",
1069 SQL_QUERY($sql, __FUNCTION__, __LINE__);
1071 // Send "build mails" out
1072 sendAdminBuildMails($mode, $tableName, $content, $id, $statusInfo[$content[$column]], $userIdColumn);
1076 // Delete rows by given id numbers
1077 function adminDeleteEntriesConfirm ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $deleteNow = array(false), $idColumn = array('id'), $userIdColumn = array('userid'), $rawUserId = array('userid'), $cacheFiles = array()) {
1078 // $tableName must be an array
1079 if ((!is_array($tableName)) || (count($tableName) != 1)) {
1080 // No tableName specified
1081 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
1082 } elseif (!is_array($idColumn)) {
1083 // $idColumn is no array
1084 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
1085 } elseif (!is_array($userIdColumn)) {
1086 // $userIdColumn is no array
1087 reportBug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array: userIdColumn=' . $userIdColumn);
1088 } elseif (!is_array($deleteNow)) {
1089 // $deleteNow is no array
1090 reportBug(__FUNCTION__, __LINE__, 'deleteNow[]=' . gettype($deleteNow) . '!=array: userIdColumn=' . $userIdColumn);
1093 // Shall we delete here or list for deletion?
1094 if ($deleteNow[0] === true) {
1095 // The base SQL command:
1096 $sql = "DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s` IN (%s)";
1100 foreach (postRequestElement($idColumn[0]) as $id => $sel) {
1101 // Is there a userid?
1102 if (isPostRequestElementSet($rawUserId[0], $id)) {
1103 // Load all data from that id
1104 $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`=%s LIMIT 1",
1109 ), __FUNCTION__, __LINE__);
1112 $content = SQL_FETCHARRAY($result);
1115 SQL_FREERESULT($result);
1117 // Send "build mails" out
1118 sendAdminBuildMails('delete', $tableName, $content, $id, '', $userIdColumn);
1122 $idList .= $id . ',';
1126 SQL_QUERY_ESC($sql, array($tableName[0], $idColumn[0], substr($idList, 0, -1)), __FUNCTION__, __LINE__);
1129 if (SQL_AFFECTEDROWS() == countPostSelection($idColumn[0])) {
1131 displayMessage('{--ADMIN_ALL_ENTRIES_REMOVED--}');
1133 // Some are still there :(
1134 displayMessage(sprintf(getMessage('ADMIN_SOME_ENTRIES_NOT_DELETED'), SQL_AFFECTEDROWS(), countPostSelection($idColumn[0])));
1137 // List for deletion confirmation
1138 adminListBuilder('delete', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1142 // Edit rows by given id numbers
1143 function adminEditEntriesConfirm ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $timeColumns = array(), $editNow = array(false), $idColumn = array('id'), $userIdColumn = array('userid'), $rawUserId = array('userid'), $cacheFiles = array()) {
1144 // $tableName must be an array
1145 if ((!is_array($tableName)) || (count($tableName) != 1)) {
1146 // No tableName specified
1147 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
1148 } elseif (!is_array($idColumn)) {
1149 // $idColumn is no array
1150 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
1151 } elseif (!is_array($userIdColumn)) {
1152 // $userIdColumn is no array
1153 reportBug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array: userIdColumn=' . $userIdColumn);
1154 } elseif (!is_array($editNow)) {
1155 // $editNow is no array
1156 reportBug(__FUNCTION__, __LINE__, 'editNow[]=' . gettype($editNow) . '!=array: userIdColumn=' . $userIdColumn);
1159 // Shall we change here or list for editing?
1160 if ($editNow[0] === true) {
1163 foreach (postRequestElement($idColumn[0]) as $id => $sel) {
1164 // Prepare content array (new values)
1167 // Prepare SQL for this row
1168 $sql = sprintf("UPDATE `{?_MYSQL_PREFIX?}_%s` SET",
1169 SQL_ESCAPE($tableName[0])
1172 // "Walk" through all entries
1173 foreach (postRequestArray() as $key => $entries) {
1174 // Skip raw userid which is always invalid
1175 if ($key == $rawUserId[0]) {
1176 // Continue with next field
1177 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',idColumn[0]=' . $idColumn[0] . ',rawUserId=' . $rawUserId[0]);
1182 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',idColumn[0]=' . $idColumn[0] . ',entries=<pre>'.print_r($entries,true).'</pre>');
1184 // Is entries an array?
1185 if (($key != $idColumn[0]) && (is_array($entries)) && (isset($entries[$id]))) {
1186 // Add this entry to content
1187 $content[$key] = $entries[$id];
1189 // Send data through the filter function if found
1190 if ($key == $userIdColumn[0]) {
1191 // Is the userid, we have to process it with convertZeroToNull()
1192 $entries[$id] = convertZeroToNull($entries[$id]);
1193 } elseif ((isset($filterFunctions[$key])) && (isset($extraValues[$key]))) {
1194 // Filter function set!
1195 $entries[$id] = handleExtraValues($filterFunctions[$key], $entries[$id], $extraValues[$key]);
1198 // Is the value NULL?
1199 if ($entries[$id] == 'NULL') {
1201 $sql .= sprintf(' `%s`=NULL,',
1205 // Else add the value covered
1206 $sql .= sprintf(" `%s`='%s',",
1208 SQL_ESCAPE($entries[$id])
1211 } elseif (($key != $idColumn[0]) && (!is_array($entries))) {
1212 // Add normal entries as well!
1213 $content[$key] = $entries;
1217 // Finish SQL command
1218 $sql = substr($sql, 0, -1) . " WHERE `" . SQL_ESCAPE($idColumn[0]) . "`=" . bigintval($id) . " LIMIT 1";
1221 SQL_QUERY($sql, __FUNCTION__, __LINE__);
1223 // Add affected rows
1224 $affected += SQL_AFFECTEDROWS();
1226 // Load all data from that id
1227 $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`=%s LIMIT 1",
1232 ), __FUNCTION__, __LINE__);
1234 // Fetch the data and merge it into $content
1235 $content = merge_array($content, SQL_FETCHARRAY($result));
1238 SQL_FREERESULT($result);
1240 // Send "build mails" out
1241 sendAdminBuildMails('edit', $tableName, $content, $id, '', $userIdColumn);
1245 if ((count($cacheFiles) > 0) && (!empty($cacheFiles[0]))) {
1246 // Delete cache file(s)
1247 foreach ($cacheFiles as $cacheFile) {
1248 // Skip any empty entries
1249 if (empty($cacheFile)) {
1250 // This may cause trouble in loadCacheFile()
1254 // Is the cache file loadable?
1255 if ($GLOBALS['cache_instance']->loadCacheFile($cacheFile)) {
1257 $GLOBALS['cache_instance']->removeCacheFile();
1263 if ($affected == countPostSelection($idColumn[0])) {
1265 displayMessage('{--ADMIN_ALL_ENTRIES_EDITED--}');
1267 // Some are still there :(
1268 displayMessage(sprintf(getMessage('ADMIN_SOME_ENTRIES_NOT_EDITED'), $affected, countPostSelection($idColumn[0])));
1272 adminListBuilder('edit', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1276 // Un-/lock rows by given id numbers
1277 function adminLockEntriesConfirm ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $statusArray = array(), $lockNow = array(false), $idColumn = array('id'), $userIdColumn = array('userid')) {
1278 // $tableName must be an array
1279 if ((!is_array($tableName)) || (count($tableName) != 1)) {
1280 // No tableName specified
1281 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
1282 } elseif (!is_array($idColumn)) {
1283 // $idColumn is no array
1284 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
1285 } elseif (!is_array($lockNow)) {
1286 // $lockNow is no array
1287 reportBug(__FUNCTION__, __LINE__, 'lockNow[]=' . gettype($lockNow) . '!=array: userIdColumn=' . $userIdColumn);
1290 // Shall we un-/lock here or list for locking?
1291 if ($lockNow[0] === true) {
1293 adminBuilderStatusHandler('lock', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray);
1296 adminListBuilder('lock', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1300 // Undelete rows by given id numbers
1301 function adminUndeleteEntriesConfirm ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $statusArray = array(), $undeleteNow = array(false), $idColumn = array('id'), $userIdColumn = array('userid')) {
1302 // $tableName must be an array
1303 if ((!is_array($tableName)) || (count($tableName) != 1)) {
1304 // No tableName specified
1305 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
1306 } elseif (!is_array($idColumn)) {
1307 // $idColumn is no array
1308 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
1309 } elseif (!is_array($undeleteNow)) {
1310 // $undeleteNow is no array
1311 reportBug(__FUNCTION__, __LINE__, 'undeleteNow[]=' . gettype($undeleteNow) . '!=array: userIdColumn=' . $userIdColumn);
1314 // Shall we un-/lock here or list for locking?
1315 if ($undeleteNow[0] === true) {
1317 adminBuilderStatusHandler('undelete', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray);
1320 adminListBuilder('undelete', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1324 // Adds a given entry to the database
1325 function adminAddEntries ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $timeColumns = array(), $columnIndex = NULL) {
1326 //* DEBUG: */ die('columns=<pre>'.print_r($columns,true).'</pre>,filterFunctions=<pre>'.print_r($filterFunctions,true).'</pre>,extraValues=<pre>'.print_r($extraValues,true).'</pre>,POST=<pre>'.print_r($_POST,true).'</pre>');
1327 // Verify that tableName and columns are not empty
1328 if ((!is_array($tableName)) || (count($tableName) != 1)) {
1329 // No tableName specified
1330 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
1331 } elseif (count($columns) == 0) {
1332 // No columns specified
1333 reportBug(__FUNCTION__, __LINE__, 'columns is not given. Please fix your XML.');
1336 // Init columns and value elements
1337 $sqlColumns = array();
1338 $sqlValues = array();
1340 // Do we have "time columns"?
1341 if (count($timeColumns) > 0) {
1342 // Then "walk" through all entries
1343 foreach ($timeColumns as $column) {
1344 // Convert all (possible) selections
1345 convertSelectionsToEpocheTimeInPostData($column . '_ye');
1349 // Add columns and values
1350 foreach ($columns as $key => $columnName) {
1351 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',columnName=' . $columnName);
1352 // Is columnIndex set?
1353 if (!is_null($columnIndex)) {
1355 //* DEBUG: */ die('columnIndex=<pre>'.print_r($columnIndex,true).'</pre>'.debug_get_printable_backtrace());
1356 assert((is_array($columnName)) && (isset($columnName[$columnIndex])));
1358 // Then use that index "blindly"
1359 $columnName = $columnName[$columnIndex];
1363 /* 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'])) . '<br />');
1365 // Copy entry securely to the final arrays
1366 $sqlColumns[$key] = SQL_ESCAPE($columnName);
1367 $sqlValues[$key] = SQL_ESCAPE(postRequestElement($columnName));
1369 // Send data through the filter function if found
1370 if ((isset($filterFunctions[$key])) && (isset($extraValues[$key . '_list']))) {
1371 // Filter function set!
1372 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sqlValues[' . $key . '][' . gettype($sqlValues[$key]) . ']=' . $sqlValues[$key] . ' - BEFORE!');
1373 $sqlValues[$key] = call_user_func_array($filterFunctions[$key], merge_array(array($columnName), $extraValues[$key . '_list']));
1374 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sqlValues[' . $key . '][' . gettype($sqlValues[$key]) . ']=' . $sqlValues[$key] . ' - AFTER!');
1375 } elseif ((isset($filterFunctions[$key])) && (!empty($filterFunctions[$key]))) {
1376 // Run through an extra filter
1377 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sqlValues[' . $key . '][' . gettype($sqlValues[$key]) . ']=' . $sqlValues[$key] . ' - BEFORE!');
1378 $sqlValues[$key] = handleExtraValues($filterFunctions[$key], $sqlValues[$key], '');
1379 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sqlValues[' . $key . '][' . gettype($sqlValues[$key]) . ']=' . $sqlValues[$key] . ' - AFTER!');
1382 // Is the value not a number?
1383 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'sqlValues[' . $key . '][' . gettype($sqlValues[$key]) . ']=' . $sqlValues[$key]);
1384 if (($sqlValues[$key] != 'NULL') && (is_string($sqlValues[$key]))) {
1385 // Add quotes around it
1386 $sqlValues[$key] = chr(39) . $sqlValues[$key] . chr(39);
1390 // Build the SQL query
1391 $SQL = 'INSERT INTO `{?_MYSQL_PREFIX?}_' . $tableName[0] . '` (`' . implode('`,`', $sqlColumns) . "`) VALUES (" . implode(',', $sqlValues) . ')';
1393 // Run the SQL query
1394 SQL_QUERY($SQL, __FUNCTION__, __LINE__);
1396 // Entry has been added?
1397 if (!SQL_HASZEROAFFECTED()) {
1398 // Display success message
1399 displayMessage('{--ADMIN_ENTRY_ADDED--}');
1401 // Display failed message
1402 displayMessage('{--ADMIN_ENTRY_NOT_ADDED--}');
1406 // List all given rows (callback function from XML)
1407 function adminListEntries ($tableTemplate, $rowTemplate, $noEntryMessageId, $tableName, $columns, $whereColumns, $orderByColumns, $callbackColumns, $extraParameters = array(), $conditions = array()) {
1408 // Verify that tableName and columns are not empty
1409 if ((!is_array($tableName)) || (count($tableName) != 1)) {
1410 // No tableName specified
1411 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array,tableTemplate=' . $tableTemplate . ',rowTemplate=' . $rowTemplate);
1412 } elseif (count($columns) == 0) {
1413 // No columns specified
1414 reportBug(__FUNCTION__, __LINE__, 'columns is not given. Please fix your XML,tableTemplate=' . $tableTemplate . ',rowTemplate=' . $rowTemplate . ',tableName[0]=' . $tableName[0]);
1417 // This is the minimum query, so at least columns and tableName must have entries
1420 // Get the sql part back from given array
1421 $SQL .= getSqlPartFromXmlArray($columns);
1423 // Remove last commata and add FROM statement
1424 $SQL .= ' FROM `{?_MYSQL_PREFIX?}_' . $tableName[0] . '`';
1426 // Do we have entries from whereColumns to add?
1427 if (count($whereColumns) > 0) {
1428 // Then add these as well
1429 if (count($whereColumns) == 1) {
1433 // Table/alias included?
1434 if (!empty($whereColumns[0]['table'])) {
1436 $SQL .= $whereColumns[0]['table'] . '.';
1440 $SQL .= '`' . $whereColumns[0]['column'] . '`' . $whereColumns[0]['condition'] . chr(39) . $whereColumns[0]['look_for'] . chr(39);
1441 } elseif ((count($whereColumns > 1)) && (count($conditions) > 0)) {
1442 // More than one "WHERE" + condition found
1443 foreach ($whereColumns as $idx => $columnArray) {
1445 $condition = 'WHERE';
1447 // Is the condition element there?
1448 if (isset($conditions[$columnArray['column']])) {
1449 // Assume the condition
1450 $condition = $conditions[$columnArray['column']];
1454 $SQL .= ' ' . $condition;
1456 // Table/alias included?
1457 if (!empty($whereColumns[$idx]['table'])) {
1459 $SQL .= $whereColumns[$idx]['table'] . '.';
1463 $SQL .= '`' . $whereColumns[$idx]['column'] . '`' . $whereColumns[$idx]['condition'] . chr(39) . convertDollarDataToGetElement($whereColumns[$idx]['look_for']) . chr(39);
1466 // Did not set $conditions
1467 reportBug(__FUNCTION__, __LINE__, 'Supplied more than "whereColumns" entries but no conditions! Please fix your XML template.');
1471 // Do we have entries from orderByColumns to add?
1472 if (count($orderByColumns) > 0) {
1474 $SQL .= ' ORDER BY ';
1475 foreach ($orderByColumns as $orderByColumn => $array) {
1476 // Get keys (table/alias) and values (sorting itself)
1477 $table = trim(implode('', array_keys($array)));
1478 $sorting = trim(implode('', array_keys($array)));
1480 // table/alias can be omitted
1481 if (!empty($table)) {
1482 // table/alias is given
1483 $SQL .= $table . '.';
1486 // Add order-by column
1487 $SQL .= '`' . $orderByColumn . '` ' . $sorting . ',';
1490 // Remove last column
1491 $SQL = substr($SQL, 0, -1);
1494 // Now handle all over to the inner function which will execute the listing
1495 doAdminListEntries($SQL, $tableTemplate, $noEntryMessageId, $rowTemplate, $callbackColumns, $extraParameters);
1498 // Do the listing of entries
1499 function doAdminListEntries ($SQL, $tableTemplate, $noEntryMessageId, $rowTemplate, $callbackColumns, $extraParameters = array()) {
1500 // Run the SQL query
1501 $result = SQL_QUERY($SQL, __FUNCTION__, __LINE__);
1503 // Do we have some URLs left?
1504 if (!SQL_HASZERONUMS($result)) {
1507 while ($content = SQL_FETCHARRAY($result)) {
1508 // "Translate" content
1509 foreach ($callbackColumns as $columnName => $callbackName) {
1510 // Fill the callback arguments
1511 $args = array($content[$columnName]);
1513 // Do we have more to add?
1514 if (isset($extraParameters[$columnName])) {
1516 $args = merge_array($args, $extraParameters[$columnName]);
1519 // Call the callback-function
1520 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'callbackFunction=' . $callbackName . ',args=<pre>'.print_r($args, true).'</pre>');
1521 // @TODO If we can rewrite the EL sub-system to support more than one parameter, this call_user_func_array() can be avoided
1522 $content[$columnName] = call_user_func_array($callbackName, $args);
1525 // Load row template
1526 $OUT .= loadTemplate(trim($rowTemplate[0]), true, $content);
1529 // Load main template
1530 loadTemplate(trim($tableTemplate[0]), false, $OUT);
1532 // No URLs in surfbar
1533 displayMessage('{--' .$noEntryMessageId[0] . '--}');
1537 SQL_FREERESULT($result);
1540 // Checks proxy settins by fetching check-updates3.php from mxchange.org
1541 function adminTestProxySettings ($settingsArray) {
1542 // Set temporary the new settings
1543 mergeConfig($settingsArray);
1545 // Now get the test URL
1546 $content = sendGetRequest('check-updates3.php');
1548 // Is the first line with "200 OK"?
1549 $valid = isInString('200 OK', $content[0]);
1555 // Sends out a link to the given email adress so the admin can reset his/her password
1556 function sendAdminPasswordResetLink ($email) {
1560 //Â Look up administator login
1561 $result = SQL_QUERY_ESC("SELECT `id`,`login`,`password` FROM `{?_MYSQL_PREFIX?}_admins` WHERE '%s' REGEXP `email` LIMIT 1",
1562 array($email), __FUNCTION__, __LINE__);
1564 // Is there an account?
1565 if (SQL_HASZERONUMS($result)) {
1567 return '{--ADMIN_NO_LOGIN_WITH_EMAIL--}';
1571 $content = SQL_FETCHARRAY($result);
1574 SQL_FREERESULT($result);
1576 // Generate hash for reset link
1577 $content['hash'] = generateHash(getUrl() . getEncryptSeparator() . $content['id'] . getEncryptSeparator() . $content['login'] . getEncryptSeparator() . $content['password'], substr($content['password'], getSaltLength()));
1580 unset($content['id']);
1581 unset($content['password']);
1584 $mailText = loadEmailTemplate('admin_reset_password', $content);
1587 sendEmail($email, '{--ADMIN_RESET_PASSWORD_LINK_SUBJECT--}', $mailText);
1590 return '{--ADMIN_RESET_PASSWORD_LINK_SENT--}';
1593 // Validate hash and login for password reset
1594 function adminResetValidateHashLogin ($hash, $login) {
1595 // By default nothing validates... ;)
1598 // Then try to find that user
1599 $result = SQL_QUERY_ESC("SELECT `id`,`password`,`email` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
1600 array($login), __FUNCTION__, __LINE__);
1602 // Is an account here?
1603 if (SQL_NUMROWS($result) == 1) {
1605 $content = SQL_FETCHARRAY($result);
1607 // Generate hash again
1608 $hashFromData = generateHash(getUrl() . getEncryptSeparator() . $content['id'] . getEncryptSeparator() . $login . getEncryptSeparator() . $content['password'], substr($content['password'], getSaltLength()));
1611 $valid = ($hash == $hashFromData);
1615 SQL_FREERESULT($result);
1621 // Reset the password for the login. Do NOT call this function without calling above function first!
1622 function doResetAdminPassword ($login, $password) {
1623 // Generate hash (we already check for sql_patches in generateHash())
1624 $passHash = generateHash($password);
1626 // Prepare fake POST data
1628 'login' => array(getAdminId($login) => $login),
1629 'password' => array(getAdminId($login) => $passHash),
1633 $message = adminsChangeAdminAccount($postData, '', false);
1636 runFilterChain('post_form_reset_pass', array('login' => $login, 'hash' => $passHash, 'message' => $message));
1639 return '{--ADMIN_PASSWORD_RESET_DONE--}';
1642 // Solves a task by given id number
1643 function adminSolveTask ($id) {
1644 // Update the task data
1645 adminUpdateTaskData($id, 'status', 'SOLVED');
1648 // Marks a given task as deleted
1649 function adminDeleteTask ($id) {
1650 // Update the task data
1651 adminUpdateTaskData($id, 'status', 'DELETED');
1654 // Function to update task data
1655 function adminUpdateTaskData ($id, $row, $data) {
1656 // Should be admin and valid id
1658 // Not an admin so redirect better
1659 reportBug(__FUNCTION__, __LINE__, 'id=' . $id . ',row=' . $row . ',data=' . $data . ' - isAdmin()=false');
1660 } elseif ($id <= 0) {
1661 // Initiate backtrace
1662 reportBug(__FUNCTION__, __LINE__, sprintf("id is invalid: %s. row=%s, data=%s",
1670 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_task_system` SET `%s`='%s' WHERE `id`=%s LIMIT 1",
1675 ), __FUNCTION__, __LINE__);
1678 // Checks whether if the admin menu has entries
1679 function ifAdminMenuHasEntries ($action) {
1682 // Is the entry set?
1683 isset($GLOBALS['admin_menu_has_entries'][$action])
1685 // And do we have a menu for this action?
1686 $GLOBALS['admin_menu_has_entries'][$action] === true
1688 // Login has always a menu
1694 // Setter for 'admin_menu_has_entries'
1695 function setAdminMenuHasEntries ($action, $hasEntries) {
1696 $GLOBALS['admin_menu_has_entries'][$action] = (bool) $hasEntries;
1699 // Creates a link to the user's admin-profile
1700 function adminCreateUserLink ($userid) {
1701 // Is the userid set correctly?
1702 if (isValidUserId($userid)) {
1703 // Create a link to that profile
1704 return '{%url=modules.php?module=admin&what=list_user&userid=' . bigintval($userid) . '%}';
1707 // Return a link to the user list
1708 return '{%url=modules.php?module=admin&what=list_user%}';
1711 // Generate a "link" for the given admin id (admin_id)
1712 function generateAdminLink ($adminId) {
1713 // No assigned admin is default
1714 $adminLink = '{--ADMIN_NO_ADMIN_ASSIGNED--}';
1716 // Zero? = Not assigned
1717 if (isValidUserId($adminId)) {
1718 // Load admin's login
1719 $login = getAdminLogin($adminId);
1721 // Is the login valid?
1722 if ($login != '***') {
1723 // Is the extension there?
1724 if (isExtensionActive('admins')) {
1726 $adminLink = '<a href="' . generateEmailLink(getAdminEmail($adminId), 'admins') . '" title="{--ADMIN_CONTACT_LINK_TITLE--}">' . $login . '</a>';
1728 // Extension not found
1729 $adminLink = '{%message,ADMIN_TASK_ROW_EXTENSION_NOT_INSTALLED=admins%}';
1733 $adminLink = '<div class="bad">{%message,ADMIN_ID_404=' . $adminId . '%}</div>';
1741 // Verifies if the current admin has confirmed to alter expert settings
1744 // 'failed' = Something goes wrong (default)
1745 // 'agreed' = Has verified and and confirmed it to see them
1746 // 'forbidden' = Has not the proper right to alter them
1747 // 'update' = Need to update extension 'admins'
1748 // 'ask' = A form was send to the admin
1749 function doVerifyExpertSettings () {
1750 // Default return status is failed
1753 // Is the extension installed and recent?
1754 if (isExtensionInstalledAndNewer('admins', '0.7.3')) {
1755 // Okay, load the status
1756 $expertSettings = getAminsExpertSettings();
1759 if ($expertSettings == 'Y') {
1760 // Okay, does he want to see them?
1761 if (isAdminsExpertWarningEnabled()) {
1764 // Is the element set, then we need to change the admin
1765 if (isPostRequestElementSet('expert_settings')) {
1766 // Get it and prepare final post data array
1767 $postData['login'][getCurrentAdminId()] = getCurrentAdminLogin();
1768 $postData['expert_warning'][getCurrentAdminId()] = 'N';
1770 // Change it in the admin
1771 adminsChangeAdminAccount($postData, 'expert_warning');
1774 unsetPostRequestElement('ok');
1781 loadTemplate('admin_expert_settings_form');
1792 $return = 'forbidden';
1795 // Out-dated extension or not installed
1799 // Output message for other status than ask/agreed
1800 if (($return != 'ask') && ($return != 'agreed')) {
1802 displayMessage('{--ADMIN_EXPERT_SETTINGS_STATUS_' . strtoupper($return) . '--}');
1809 // Generate link to unconfirmed mails for admin
1810 function generateUnconfirmedAdminLink ($id, $unconfirmed, $type = 'bid') {
1812 $OUT = $unconfirmed;
1814 // Do we have unconfirmed mails?
1815 if ($unconfirmed > 0) {
1816 // Add link to list_unconfirmed what-file
1817 $OUT = '<a href="{%url=modules.php?module=admin&what=list_unconfirmed&' . $type . '=' . $id . '%}">{%pipe,translateComma=' . $unconfirmed . '%}</a>';
1824 // Generates a navigation row for listing emails
1825 function addEmailNavigation ($numPages, $offset, $show_form, $colspan, $return=false) {
1826 // Don't do anything if $numPages is 1
1827 if ($numPages == 1) {
1828 // Abort here with empty content
1833 if ($show_form === false) {
1838 for ($page = 1; $page <= $numPages; $page++) {
1839 // Is the page currently selected or shall we generate a link to it?
1840 if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
1841 // Is currently selected, so only highlight it
1842 $NAV .= '<strong>-';
1844 // Open anchor tag and add base URL
1845 $NAV .= '<a href="{%url=modules.php?module=admin&what=' . getWhat() . '&page=' . $page . '&offset=' . $offset;
1847 // Add userid when we shall show all mails from a single member
1848 if ((isGetRequestElementSet('userid')) && (isValidUserId(getRequestElement('userid')))) $NAV .= '&userid=' . bigintval(getRequestElement('userid'));
1850 // Close open anchor tag
1854 if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
1855 // Is currently selected, so only highlight it
1856 $NAV .= '-</strong>';
1862 // Add separator if we have not yet reached total pages
1863 if ($page < $numPages) {
1869 // Define constants only once
1870 $content['nav'] = $NAV;
1871 $content['span'] = $colspan;
1872 $content['top'] = $TOP;
1874 // Load navigation template
1875 $OUT = loadTemplate('admin_email_nav_row', true, $content);
1877 if ($return === true) {
1878 // Return generated HTML-Code
1886 // Process menu editing form
1887 function adminProcessMenuEditForm ($type, $subMenu) {
1888 // An action is done...
1889 foreach (postRequestElement('sel') as $sel => $menu) {
1890 $AND = "(`what` = '' OR `what` IS NULL)";
1892 $sel = bigintval($sel);
1894 if (!empty($subMenu)) {
1895 $AND = "`action`='" . $subMenu . "'";
1898 switch (postRequestElement('ok')) {
1899 case 'edit': // Edit menu
1900 // Shall we update a menu or sub menu?
1901 if (!isGetRequestElementSet('sub')) {
1902 // Update with 'what'=null
1903 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET `title`='%s',`action`='%s',`what`=NULL WHERE ".$AND." AND `id`=%s LIMIT 1",
1907 postRequestElement('sel_action', $sel),
1909 ), __FUNCTION__, __LINE__);
1911 // Update with selected 'what'
1912 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET `title`='%s',`action`='%s',`what`='%s' WHERE ".$AND." AND `id`=%s LIMIT 1",
1916 postRequestElement('sel_action', $sel),
1917 postRequestElement('sel_what', $sel),
1919 ), __FUNCTION__, __LINE__);
1923 case 'delete': // Delete menu
1924 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE ".$AND." AND `id`=%s LIMIT 1",
1928 ), __FUNCTION__, __LINE__);
1931 case 'status': // Change status of menus
1932 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET `visible`='%s',`locked`='%s' WHERE ".$AND." AND `id`=%s LIMIT 1",
1935 postRequestElement('visible', $sel),
1936 postRequestElement('locked', $sel),
1938 ), __FUNCTION__, __LINE__);
1941 default: // Unexpected action
1942 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unsupported action %s detected.", postRequestElement('ok')));
1943 displayMessage('{%message,ADMIN_UNKNOWN_OKAY=' . postRequestElement('ok') . '%}');
1949 displayMessage('{--SETTINGS_SAVED--}');
1952 // Handle weightning
1953 function doAdminProcessMenuWeightning ($type, $AND) {
1954 // Are there all required (generalized) GET parameter?
1955 if ((isGetRequestElementSet('act')) && (isGetRequestElementSet('tid')) && (isGetRequestElementSet('fid'))) {
1957 $tid = ''; $fid = '';
1960 if (isGetRequestElementSet('w')) {
1961 // Sub menus selected
1962 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `action`='%s' AND `sort`=%s LIMIT 1",
1965 getRequestElement('act'),
1966 bigintval(getRequestElement('tid'))
1967 ), __FUNCTION__, __LINE__);
1968 list($tid) = SQL_FETCHROW($result);
1969 SQL_FREERESULT($result);
1970 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `action`='%s' AND `sort`=%s LIMIT 1",
1973 getRequestElement('act'),
1974 bigintval(getRequestElement('fid'))
1975 ), __FUNCTION__, __LINE__);
1976 list($fid) = SQL_FETCHROW($result);
1977 SQL_FREERESULT($result);
1979 // Main menu selected
1980 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE (`what`='' OR `what` IS NULL) AND `sort`=%s LIMIT 1",
1983 bigintval(getRequestElement('tid'))
1984 ), __FUNCTION__, __LINE__);
1985 list($tid) = SQL_FETCHROW($result);
1986 SQL_FREERESULT($result);
1987 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE (`what`='' OR `what` IS NULL) AND `sort`=%s LIMIT 1",
1990 bigintval(getRequestElement('fid'))
1991 ), __FUNCTION__, __LINE__);
1992 list($fid) = SQL_FETCHROW($result);
1993 SQL_FREERESULT($result);
1996 if ((!empty($tid)) && (!empty($fid))) {
1998 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET `sort`=%s WHERE ".$AND." AND `id`=%s LIMIT 1",
2001 bigintval(getRequestElement('tid')),
2003 ), __FUNCTION__, __LINE__);
2004 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET `sort`=%s WHERE ".$AND." AND `id`=%s LIMIT 1",
2007 bigintval(getRequestElement('fid')),
2009 ), __FUNCTION__, __LINE__);