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 - 2013 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, $accessLevel = 'deny') {
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 // Is ext-admins installed and version at least 0.3.0?
55 if (isExtensionInstalledAndNewer('admins', '0.3.0')) {
56 // Ok, let's create the admin login
57 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_admins` (`login`, `password`, `email`, `default_acl`) VALUES ('%s', '%s', '%s', '%s')",
63 ), __FUNCTION__, __LINE__);
65 // Ok, let's create the admin login
66 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_admins` (`login`, `password`, `email`) VALUES ('%s', '%s', '%s')",
71 ), __FUNCTION__, __LINE__);
79 SQL_FREERESULT($result);
85 // This function will be executed when the admin is not logged in and has submitted his login data
86 function ifAdminLoginDataIsValid ($adminLogin, $adminPassword) {
87 // First of all, no admin login is found, so the admin hash is null
91 // Get admin id from login
92 $adminId = getAdminId($adminLogin);
94 // Continue only with found admin ids
95 if (isValidId($adminId)) {
96 // Then we need to lookup the login name by getting the admin hash
97 $adminHash = getAdminHash($adminId);
99 // If this is fine, we can continue
100 if ($adminHash != '-1') {
101 // Get admin id and set it as current
102 setCurrentAdminId($adminId);
104 // Now, we need to encode the password in the same way the one is encoded in database
105 $testHash = generateHash($adminPassword, $adminHash);
107 // If they both match, the login data is valid
108 if ($testHash == $adminHash) {
118 // Prepare data array
121 'login' => $adminLogin,
122 'plain_pass' => $adminPassword,
123 'pass_hash' => $adminHash
126 // Run a special filter
127 runFilterChain('do_admin_login_' . $ret, $data);
133 // Only be executed on cookie checking
134 function ifAdminCookiesAreValid ($adminLogin, $passHash) {
135 // First of all, no admin login is found
138 // Then we need to lookup the login name by getting the admin hash
139 $adminHash = getAdminHash($adminLogin);
141 // If this is fine, we can continue
142 if ($adminHash != '-1') {
143 // Now, we need to encode the password in the same way the one is encoded in database
144 $testHash = encodeHashForCookie($adminHash);
145 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'adminLogin=' . $adminLogin . ',passHash='.$passHash.',adminHash='.$adminHash.',testHash='.$testHash);
147 // If they both match, the login data is valid
148 if ($testHash != $passHash) {
149 // Passwords don't match
151 } elseif (!isAdmin()) {
152 // Is not valid session
161 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret='.$ret);
165 // Do an admin action
166 function doAdminAction () {
167 // Determine correct 'what' value
168 $what = determineWhat();
171 $action = getActionFromModuleWhat(getModule(), $what);
173 // Load welcome template
174 if (isExtensionActive('admins')) {
175 // @TODO This and the next getCurrentAdminId() call might be moved into the templates?
176 $content['welcome'] = loadTemplate('admin_welcome_admins', TRUE, getCurrentAdminId());
178 $content['welcome'] = loadTemplate('admin_welcome', TRUE, getCurrentAdminId());
181 // Load header, footer, render menu
182 $content['header'] = loadTemplate('admin_header' , TRUE, $content);
183 $content['footer'] = loadTemplate('admin_footer' , TRUE, $content);
184 $content['menu'] = addAdminMenu($action, $what);
186 // Load main template
187 loadTemplate('admin_main', FALSE, $content);
189 // Check if action/what pair is valid
190 $result_action = SQL_QUERY_ESC("SELECT
193 `{?_MYSQL_PREFIX?}_admin_menu`
198 `what`='%s' AND `what` != 'welcome'
201 `what`='' OR `what` IS NULL
212 ), __FUNCTION__, __LINE__);
214 // Is there an entry?
215 if (SQL_NUMROWS($result_action) == 1) {
216 // Is valid but does the inlcude file exists?
217 $inc = sprintf("inc/modules/admin/action-%s.php", $action);
218 if ((isIncludeReadable($inc)) && (isMenuActionValid('admin', $action, $what)) && ($GLOBALS['acl_allow'] === TRUE)) {
219 // Ok, we finally load the admin action module
221 } elseif ($GLOBALS['acl_allow'] === FALSE) {
223 loadTemplate('admin_menu_failed', FALSE, '{%message,ADMIN_ACCESS_DENIED=' . $what . '%}');
225 // Include file not found :-(
226 loadTemplate('admin_menu_failed', FALSE, '{%message,ADMIN_ACTION_404=' . $action . '%}');
229 // Invalid action/what pair found
230 loadTemplate('admin_menu_failed', FALSE, '{%message,ADMIN_ACTION_INVALID=' . $action . '/' . $what . '%}');
234 SQL_FREERESULT($result_action);
237 loadTemplate('admin_main_footer', FALSE, $content);
241 * Checks whether current admin is allowed to access given action/what
242 * combination (only one is allowed to be null!).
244 function isAdminAllowedAccessMenu ($action, $what = NULL) {
246 if (!isset($GLOBALS[__FUNCTION__][$action][$what])) {
247 // ACL is always 'allow' when no ext-admins is installed
248 // @TODO This can be rewritten into a filter
249 $GLOBALS[__FUNCTION__][$action][$what] = ((!isExtensionInstalledAndNewer('admins', '0.2.0')) || ((isExtensionActive('admins')) && (isAdminsAllowedByAcl($action, $what))));
252 // Return the cached value
253 return $GLOBALS[__FUNCTION__][$action][$what];
256 // Adds an admin menu
257 function addAdminMenu ($action, $what) {
263 $GLOBALS['menu']['description'] = array();
264 $GLOBALS['menu']['title'] = array();
267 $result_main = SQL_QUERY("SELECT
268 `action` AS `main_action`,
269 `title` AS `main_title`,
270 `descr` AS `main_descr`
272 `{?_MYSQL_PREFIX?}_admin_menu`
274 (`what`='' OR `what` IS NULL)
277 `id` DESC", __FUNCTION__, __LINE__);
279 // Are there entries?
280 if (!SQL_HASZERONUMS($result_main)) {
281 $OUT .= '<ul class="admin_menu_main">';
283 // Load all 'action' menus
284 while ($mainContent = SQL_FETCHARRAY($result_main)) {
286 $inc = sprintf("inc/modules/admin/action-%s.php", $mainContent['main_action']);
288 // Is the current admin allowed to access this 'action' menu?
289 if (isAdminAllowedAccessMenu($mainContent['main_action'])) {
290 if ($SUB === FALSE) {
291 // Insert compiled menu title and description
292 $GLOBALS['menu']['title'][$mainContent['main_action']] = $mainContent['main_title'];
293 $GLOBALS['menu']['description'][$mainContent['main_action']] = $mainContent['main_descr'];
295 $OUT .= '<li class="admin_menu"' . addJavaScriptMenuContent('admin', $mainContent['main_action'], $action, $what) . '>
296 <div class="nobr"><strong>·</strong> ';
298 // Is the file readable?
299 if (isIncludeReadable($inc)) {
300 if (($mainContent['main_action'] == $action) && (empty($what))) {
303 $OUT .= '[<a href="{%url=modules.php?module=admin&action=' . $mainContent['main_action'] . '%}">';
306 $OUT .= '<span class="bad" style="cursor:help" title="{%message,ADMIN_MENU_ACTION_404_TITLE=' . $mainContent['main_action'] . '%}">';
309 $OUT .= $mainContent['main_title'];
311 // Is the file readable?
312 if (isIncludeReadable($inc)) {
313 if (($mainContent['main_action'] == $action) && (empty($what))) {
326 $OUT .= addAdminSubMenu($mainContent, $action, $what);
334 SQL_FREERESULT($result_main);
341 // Add admin sub menu
342 function addAdminSubMenu ($mainContent, $action, $what) {
346 // Check for menu entries
347 $result_what = SQL_QUERY_ESC("SELECT
348 `what` AS `sub_what`,
349 `title` AS `sub_title`,
350 `descr` AS `sub_descr`
352 `{?_MYSQL_PREFIX?}_admin_menu`
360 array($mainContent['main_action']), __FUNCTION__, __LINE__);
362 // Remember the count for later checks
363 setAdminMenuHasEntries($mainContent['main_action'], ((!SQL_HASZERONUMS($result_what)) && (($action == $mainContent['main_action']) || (isAdminMenuJavascriptEnabled()))));
365 // Start li-tag for sub menu content
366 $OUT .= '<li class="admin_menu_sub" id="action_menu_' . $mainContent['main_action'] . '"' . addStyleMenuContent('admin', $mainContent['main_action'], $action) . '>';
368 // Are there entries?
369 if (ifAdminMenuHasEntries($mainContent['main_action'])) {
370 // Sub menu has been called
373 // Are there entries?
374 if (!SQL_HASZERONUMS($result_what)) {
376 $OUT .= '<ul class="admin_menu_sub">';
379 while ($subContent = SQL_FETCHARRAY($result_what)) {
381 $inc = sprintf("inc/modules/admin/what-%s.php", $subContent['sub_what']);
383 // Is the current admin allowed to access this 'what' menu?
384 if (isAdminAllowedAccessMenu(NULL, $subContent['sub_what'])) {
385 // Insert compiled title and description
386 $GLOBALS['menu']['title'][$subContent['sub_what']] = $subContent['sub_title'];
387 $GLOBALS['menu']['description'][$subContent['sub_what']] = $subContent['sub_descr'];
388 $OUT .= '<li class="admin_menu">
389 <div class="nobr"><strong>--></strong> ';
391 // Is the file readable?
392 if (isIncludeReadable($inc)) {
393 if ($what == $subContent['sub_what']) {
396 $OUT .= '[<a href="{%url=modules.php?module=admin&what=' . $subContent['sub_what'] . '%}">';
399 $OUT .= '<span class="bad" style="cursor:help" title="{%message,ADMIN_MENU_WHAT_404_TITLE=' . $subContent['sub_what'] . '%}">';
402 $OUT .= $subContent['sub_title'];
404 // Is the file readable?
405 if (isIncludeReadable($inc)) {
406 if ($what == $subContent['sub_what']) {
419 // Finish HTML output
424 SQL_FREERESULT($result_what);
434 // Create an admin selection box form
435 function addAdminSelectionBox ($adminId = NULL, $special = '') {
436 // Default is email as "special column"
437 $ADD = ',`email` AS `special`';
439 // Is a special column given?
440 if (!empty($special)) {
441 // Additional column for SQL query
442 $ADD = ',`' . $special . '` AS `special`';
446 $result = SQL_QUERY('SELECT
451 `{?_MYSQL_PREFIX?}_admins`
453 `login` ASC', __FUNCTION__, __LINE__);
459 while ($content = SQL_FETCHARRAY($result)) {
461 $content['default'] = '';
463 // Is the id the same?
464 if ($content['id'] == $adminId) {
465 // Set this as default
466 $content['default'] = ' selected="selected"';
470 $OUT .= loadTemplate('select_admins_option', TRUE, $content);
474 SQL_FREERESULT($result);
476 // Add form to content
477 $content['form_selection'] = $OUT;
480 loadTemplate('select_admins_box', FALSE, $content);
483 // Create a member selection box
484 function addMemberSelectionBox ($userid = NULL, $add_all = FALSE, $return = FALSE, $none = FALSE, $field = 'userid', $whereStatement = " WHERE `surname` NOT LIKE '{?tester_user_surname_prefix?}%'") {
485 // Output selection form with all confirmed user accounts listed
486 $result = SQL_QUERY('SELECT
491 `{?_MYSQL_PREFIX?}_user_data`
492 ' . $whereStatement . '
494 `userid` ASC', __FUNCTION__, __LINE__);
499 // USe this only for adding points (e.g. adding refs really makes no sence ;-) )
500 if ($add_all === TRUE) {
501 $OUT = ' <option value="all">{--ALL_MEMBERS--}</option>';
502 } elseif ($none === TRUE) {
503 $OUT = ' <option value="0">{--SELECT_NONE--}</option>';
507 while ($content = SQL_FETCHARRAY($result)) {
508 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . intval($userid) . '/' . $content['userid']);
509 $OUT .= '<option value="' . bigintval($content['userid']) . '"';
510 if (bigintval($userid, FALSE, FALSE) === bigintval($content['userid'])) {
511 $OUT .= ' selected="selected"';
513 $OUT .= '>' . $content['surname'] . ' ' . $content['family'] . ' (' . bigintval($content['userid']) . ')</option>';
517 SQL_FREERESULT($result);
519 if ($return === FALSE) {
520 // Remeber options in constant
521 $content['form_selection'] = $OUT;
522 $content['what'] = '{%pipe,getWhat%}';
525 loadTemplate('admin_form_selection_box', FALSE, $content);
527 // Return content in selection frame
528 return '<select class="form_select" name="' . handleFieldWithBraces($field) . '" size="1">' . $OUT . '</select>';
532 // Create a menu selection box for given menu system
533 // @TODO Try to rewrite this to adminAddMenuSelectionBox()
535 function adminMenuSelectionBox_DEPRECATED ($mode, $default = '', $defid = '') {
536 $what = "`what` != '' AND `what` IS NOT NULL";
537 if ($mode == 'action') $what = "(`what`='' OR `what` IS NULL) AND `action` != 'login'";
539 $result = SQL_QUERY_ESC("SELECT `%s` AS `menu`, `title` FROM `{?_MYSQL_PREFIX?}_admin_menu` WHERE ".$what." ORDER BY `sort` ASC",
540 array($mode), __FUNCTION__, __LINE__);
541 if (!SQL_HASZERONUMS($result)) {
542 // Load menu as selection
543 $OUT = '<select name="' . $mode . '_menu';
544 if (!isValidId($defid)) $OUT .= '[' . intval($defid) . ']';
545 $OUT .= '" size="1" class="form_select">
546 <option value="">{--SELECT_NONE--}</option>';
548 while ($content = SQL_FETCHARRAY($result)) {
549 $OUT .= '<option value="' . $content['menu'] . '"';
550 if ((!empty($default)) && ($default == $content['menu'])) {
551 $OUT .= ' selected="selected"';
553 $OUT .= '>' . $content['title'] . '</option>';
557 SQL_FREERESULT($result);
559 // Add closing select-tag
563 $OUT = '{--ADMIN_PROBLEM_NO_MENU--}';
570 // Wrapper for $_POST and adminSaveSettings
571 function adminSaveSettingsFromPostData ($tableName = '_config', $whereStatement = '`config`=0', $translateComma = array(), $alwaysAdd = FALSE, $displayMessage = TRUE) {
573 $postData = postRequestArray();
575 // Call the lower function
576 adminSaveSettings($postData, $tableName, $whereStatement, $translateComma, $alwaysAdd, $displayMessage);
579 // Save settings to the database
580 function adminSaveSettings (&$postData, $tableName = '_config', $whereStatement = '`config`=0', $translateComma = array(), $alwaysAdd = FALSE, $displayMessage = TRUE) {
581 // Prepare all arrays, variables
582 $tableData = array();
585 // Now, walk through all entries and prepare them for saving
586 //* BUG: */ reportBug(__FUNCTION__, __LINE__, '<pre>'.print_r(postRequestArray(), TRUE).'</pre>');
587 foreach ($postData as $id => $val) {
588 // Process only formular field but not submit buttons ;)
589 if ($id == 'save_config') {
594 // Do not save the ok value
595 convertSelectionsToEpocheTime($postData, $tableData, $id, $skip);
597 // Shall we process this id? It muss not be empty, of course
598 if (($skip === FALSE) && (!empty($id)) && ((!isset($GLOBALS['skip_config'][$id]))) || ($tableName != '_config')) {
599 // Translate the value? (comma to dot!)
600 if ((is_array($translateComma)) && (in_array($id, $translateComma))) {
601 // Then do it here... :)
602 $val = convertCommaToDot($val);
605 // Test value on float
606 $test = (float) $val;
609 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'test=' . $test . ',val=' . $val . ',id=' . $id);
611 // Shall we add numbers or strings?
612 if ('' . $val . '' == '' . $test . '') {
614 array_push($tableData, sprintf("`%s`=%s", $id, $test));
615 } elseif (is_null($val)) {
617 array_push($tableData, sprintf("`%s`=NULL", $id));
620 array_push($tableData, sprintf("`%s`='%s'", $id, trim($val)));
623 // Do not add a config entry twice
624 $GLOBALS['skip_config'][$id] = TRUE;
626 // Update current configuration
627 setConfigEntry($id, $val);
631 // Check if entry does exist
633 if ($alwaysAdd === FALSE) {
634 if (!empty($whereStatement)) {
635 $result = SQL_QUERY("SELECT * FROM `{?_MYSQL_PREFIX?}" . $tableName . "` WHERE " . $whereStatement . " LIMIT 1", __FUNCTION__, __LINE__);
637 $result = SQL_QUERY("SELECT * FROM `{?_MYSQL_PREFIX?}" . $tableName . "` LIMIT 1", __FUNCTION__, __LINE__);
641 if (SQL_NUMROWS($result) == 1) {
642 // "Implode" all data to single string
643 $updatedData = implode(', ', $tableData);
645 // Generate SQL string
646 $sql = sprintf("UPDATE `{?_MYSQL_PREFIX?}%s` SET %s WHERE %s LIMIT 1",
652 // Add Line (does only work with AUTO_INCREMENT!
653 $keys = array(); $values = array();
654 foreach ($tableData as $entry) {
656 $line = explode('=', $entry);
657 array_push($keys , $line[0]);
658 array_push($values, $line[1]);
661 // Add both in one line
662 $keys = implode('`, `', $keys);
663 $values = implode(', ' , $values);
665 // Generate SQL string
666 $sql = sprintf("INSERT INTO `{?_MYSQL_PREFIX?}%s` (%s) VALUES (%s)",
674 SQL_FREERESULT($result);
676 // Simply run generated SQL string
677 SQL_QUERY($sql, __FUNCTION__, __LINE__);
679 // Remember affected rows
680 $affected = SQL_AFFECTEDROWS();
683 rebuildCache('config', 'config');
685 // Settings saved, so display message?
686 if ($displayMessage === TRUE) {
688 displayMessage('{--SETTINGS_SAVED--}');
691 // Return affected rows
695 // Generate a selection box
696 function adminAddMenuSelectionBox ($menu, $type, $name, $default = '') {
697 // Open the requested menu directory
698 $menuArray = getArrayFromDirectory(sprintf("inc/modules/%s/", $menu), $type . '-', FALSE, FALSE);
700 // Init the selection box
701 $OUT = '<select name="' . $name . '" class="form_select" size="1"><option value="">{--ADMIN_IS_TOP_MENU--}</option>';
703 // Walk through all files
704 foreach ($menuArray as $file) {
705 // Is this a PHP script?
706 if ((!isDirectory($file)) && (isInString('' . $type . '-', $file)) && (isInString('.php', $file))) {
707 // Then test if the file is readable
708 $test = sprintf("inc/modules/%s/%s", $menu, $file);
710 // Is the file there?
711 if (isIncludeReadable($test)) {
712 // Extract the value for what=xxx
713 $part = substr($file, (strlen($type) + 1));
714 $part = substr($part, 0, -4);
716 // Is that part different from the overview?
717 if ($part != 'welcome') {
718 $OUT .= '<option value="' . $part . '"';
719 if ($part == $default) {
720 $OUT .= ' selected="selected"';
722 $OUT .= '>' . $part . '</option>';
728 // Close selection box
735 // Creates a user-profile link for the admin. This function can also be used for many other purposes
736 function generateUserProfileLink ($userid, $title = '', $what = '') {
738 if (!isset($GLOBALS[__FUNCTION__][$userid][$title . '_' . $what])) {
739 // Is title empty and valid userid?
740 if (($title == '') && (isValidId($userid))) {
741 // Set userid as title
743 } elseif (!isValidId($userid)) {
744 // User id zero is invalid
745 return '<strong>' . convertNullToZero($userid) . '</strong>';
750 // Then get it to 'list_user'
754 if (($title == '0') && ($what == 'list_refs')) {
755 // Return title again
757 } elseif (!empty($title)) {
758 // Not empty, so skip next one
759 } elseif (isExtensionActive('nickname')) {
761 $nick = getNickname($userid);
763 // Is it not empty, use it as title else the userid
765 $title = $nick . '(' . $userid . ')';
772 $GLOBALS[__FUNCTION__][$userid][$title . '_' . $what] = '[<a href="{%url=modules.php?module=admin&what=' . $what . '&userid=' . $userid . '%}" title="{--ADMIN_USER_PROFILE_TITLE--}">' . $title . '</a>]';
776 return $GLOBALS[__FUNCTION__][$userid][$title . '_' . $what];
779 // Check "logical-area-mode"
780 function adminGetMenuMode () {
781 // Set the default menu mode as the mode for all admins
784 // If ext-sql_patches is up-to-date enough, use the configuration
785 if (isExtensionInstalledAndNewer('sql_patches', '0.3.2')) {
786 $mode = getAdminMenu();
793 $adminId = getCurrentAdminId();
795 // Check individual settings of current admin
796 if (isset($GLOBALS['cache_array']['admin']['la_mode'][$adminId])) {
798 $adminMode = $GLOBALS['cache_array']['admin']['la_mode'][$adminId];
799 incrementStatsEntry('cache_hits');
800 } elseif (isExtensionInstalledAndNewer('admins', '0.6.7')) {
801 // Load from database when version of 'admins' is enough
802 $result = SQL_QUERY_ESC("SELECT `la_mode` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
803 array($adminId), __FUNCTION__, __LINE__);
805 // Is there an entry?
806 if (SQL_NUMROWS($result) == 1) {
808 list($adminMode) = SQL_FETCHROW($result);
812 SQL_FREERESULT($result);
815 // Check what the admin wants and set it when it's not the default mode
816 if ($adminMode != 'global') {
820 // Return admin-menu's mode
824 // Change activation status
825 function adminChangeActivationStatus ($IDs, $table, $row, $idRow = 'id') {
827 if ((is_array($IDs)) && (count($IDs) > 0)) {
828 // "Walk" all through and count them
829 foreach ($IDs as $id => $selected) {
830 // Secure the id number
831 $id = bigintval($id);
833 // Should always be set... ;-)
834 if (!empty($selected)) {
835 // Determine new status
836 $result = SQL_QUERY_ESC("SELECT %s FROM `{?_MYSQL_PREFIX?}_%s` WHERE %s=%s LIMIT 1",
842 ), __FUNCTION__, __LINE__);
845 if (SQL_NUMROWS($result) == 1) {
847 list($currStatus) = SQL_FETCHROW($result);
849 // And switch it N<->Y
850 $newStatus = convertBooleanToYesNo(!($currStatus == 'Y'));
852 // Change this status
853 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s` SET %s='%s' WHERE %s=%s LIMIT 1",
860 ), __FUNCTION__, __LINE__);
862 // Count up affected rows
863 $count += SQL_AFFECTEDROWS();
867 SQL_FREERESULT($result);
872 displayMessage(sprintf(getMessage('ADMIN_STATUS_CHANGED'), $count, count($IDs)));
875 displayMessage('{--ADMIN_NOTHING_SELECTED_CHANGE--}');
879 // Build a special template list
880 // @TODO cacheFiles is not yet supported
881 function adminListBuilder ($listType, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId = array('userid'), $content = array()) {
882 // Call inner (general) function
883 doGenericListBuilder('admin', $listType, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId, $content);
886 // Change status of "build" list
887 function adminBuilderStatusHandler ($mode, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray, $rawUserId = array('userid'), $cacheFiles = array()) {
888 // $tableName must be an array
889 if ((!is_array($tableName)) || (count($tableName) != 1)) {
890 // No tableName specified
891 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
892 } elseif (!is_array($idColumn)) {
893 // $idColumn is no array
894 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
895 } elseif ((!is_array($userIdColumn)) || (count($userIdColumn) != 1)) {
896 // $tableName is no array
897 reportBug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array: userIdColumn=' . $userIdColumn);
900 // "Walk" through all entries
901 foreach (postRequestElement($idColumn[0]) as $id => $sel) {
902 // Construct SQL query
903 $sql = sprintf("UPDATE `{?_MYSQL_PREFIX?}_%s` SET", SQL_ESCAPE($tableName[0]));
905 // Load data of entry
906 $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`=%s LIMIT 1",
911 ), __FUNCTION__, __LINE__);
914 $content = SQL_FETCHARRAY($result);
917 SQL_FREERESULT($result);
919 // Add all status entries (e.g. status column last_updated or so)
920 $newStatus = 'UNKNOWN';
921 $oldStatus = 'UNKNOWN';
922 $statusColumn = 'unknown';
923 foreach ($statusArray as $column => $statusInfo) {
924 // Does the entry exist?
925 if ((isset($content[$column])) && (isset($statusInfo[$content[$column]]))) {
926 // Add these entries for update
927 $sql .= sprintf(" `%s`='%s',", SQL_ESCAPE($column), SQL_ESCAPE($statusInfo[$content[$column]]));
930 if ($statusColumn == 'unknown') {
931 // Always (!!!) change status column first!
932 $oldStatus = $content[$column];
933 $newStatus = $statusInfo[$oldStatus];
934 $statusColumn = $column;
936 } elseif (isset($content[$column])) {
938 reportBug(__FUNCTION__, __LINE__, ':UNFINISHED: id=' . $id . ',column=' . $column . '[' . gettype($statusInfo) . '] = ' . $content[$column]);
942 // Add other columns as well
943 foreach (postRequestArray() as $key => $entries) {
945 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Found entry: ' . $key);
947 // Skip id, raw userid and 'do_$mode'
948 if (!in_array($key, array($idColumn[0], $rawUserId[0], ('do_' . $mode)))) {
949 // Are there brackets () at the end?
950 if (substr($entries[$id], -2, 2) == '()') {
951 // Direct SQL command found
952 $sql .= sprintf(" `%s`=%s,", SQL_ESCAPE($key), SQL_ESCAPE($entries[$id]));
955 $sql .= sprintf(" `%s`='%s',", SQL_ESCAPE($key), SQL_ESCAPE($entries[$id]));
958 $content[$key] = $entries[$id];
960 } elseif (isDebugModeEnabled()) {
962 logDebugMessage(__FUNCTION__, __LINE__, 'Skipped: ' . $key);
966 // Finish SQL statement
967 $sql = substr($sql, 0, -1) . sprintf(" WHERE `%s`=%s AND `%s`='%s' LIMIT 1",
975 SQL_QUERY($sql, __FUNCTION__, __LINE__);
977 // Send "build mails" out
978 sendGenericBuildMails($mode, $tableName, $content, $id, $statusInfo[$content[$column]], $userIdColumn);
982 // Delete rows by given id numbers
983 function adminDeleteEntriesConfirm ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $deleteNow = array(FALSE), $idColumn = array('id'), $userIdColumn = array('userid'), $rawUserId = array('userid'), $cacheFiles = array(), $content = array()) {
984 // $tableName must be an array
985 if ((!is_array($tableName)) || (count($tableName) != 1)) {
986 // No tableName specified
987 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
988 } elseif (!is_array($idColumn)) {
989 // $idColumn is no array
990 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
991 } elseif (!is_array($userIdColumn)) {
992 // $userIdColumn is no array
993 reportBug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array: userIdColumn=' . $userIdColumn);
994 } elseif (!is_array($deleteNow)) {
995 // $deleteNow is no array
996 reportBug(__FUNCTION__, __LINE__, 'deleteNow[]=' . gettype($deleteNow) . '!=array: userIdColumn=' . $userIdColumn);
999 // Shall we delete here or list for deletion?
1000 if ($deleteNow[0] === TRUE) {
1001 // Call generic function
1002 $affected = doGenericDeleteEntriesConfirm($tableName, $columns, $filterFunctions, $extraValues, $deleteNow, $idColumn, $userIdColumn, $rawUserId, $cacheFiles);
1005 if ($affected == countPostSelection($idColumn[0])) {
1007 displayMessage('{--ADMIN_ALL_ENTRIES_REMOVED--}');
1009 // Some are still there :(
1010 displayMessage(sprintf(getMessage('ADMIN_SOME_ENTRIES_NOT_DELETED'), SQL_AFFECTEDROWS(), countPostSelection($idColumn[0])));
1013 // List for deletion confirmation
1014 adminListBuilder('delete', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId, $content);
1018 // Edit rows by given id numbers
1019 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(), $content = array()) {
1020 // $tableName must be an array
1021 if ((!is_array($tableName)) || (count($tableName) != 1)) {
1022 // No tableName specified
1023 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
1024 } elseif (!is_array($idColumn)) {
1025 // $idColumn is no array
1026 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
1027 } elseif (!is_array($userIdColumn)) {
1028 // $userIdColumn is no array
1029 reportBug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array: userIdColumn=' . $userIdColumn);
1030 } elseif (!is_array($editNow)) {
1031 // $editNow is no array
1032 reportBug(__FUNCTION__, __LINE__, 'editNow[]=' . gettype($editNow) . '!=array: userIdColumn=' . $userIdColumn);
1035 // Shall we change here or list for editing?
1036 if ($editNow[0] === TRUE) {
1037 // Call generic change method
1038 $affected = doGenericEditEntriesConfirm($tableName, $columns, $filterFunctions, $extraValues, $timeColumns, $editNow, $idColumn, $userIdColumn, $rawUserId, $cacheFiles);
1041 if ($affected == countPostSelection($idColumn[0])) {
1043 displayMessage('{--ADMIN_ALL_ENTRIES_EDITED--}');
1045 // Some are still there :(
1046 displayMessage(sprintf(getMessage('ADMIN_SOME_ENTRIES_NOT_EDITED'), $affected, countPostSelection($idColumn[0])));
1050 adminListBuilder('edit', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId, $content);
1054 // Un-/lock rows by given id numbers
1055 // @TODO rawUserId/content is not yet supported
1056 function adminLockEntriesConfirm ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $statusArray = array(), $lockNow = array(FALSE), $idColumn = array('id'), $userIdColumn = array('userid')) {
1057 // $tableName must be an array
1058 if ((!is_array($tableName)) || (count($tableName) != 1)) {
1059 // No tableName specified
1060 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
1061 } elseif (!is_array($idColumn)) {
1062 // $idColumn is no array
1063 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
1064 } elseif (!is_array($lockNow)) {
1065 // $lockNow is no array
1066 reportBug(__FUNCTION__, __LINE__, 'lockNow[]=' . gettype($lockNow) . '!=array: userIdColumn=' . $userIdColumn);
1069 // Shall we un-/lock here or list for locking?
1070 if ($lockNow[0] === TRUE) {
1072 adminBuilderStatusHandler('lock', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray);
1075 adminListBuilder('lock', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1079 // Undelete rows by given id numbers
1080 // @TODO rawUserId/cacheFiles/content is not yet supported
1081 function adminUndeleteEntriesConfirm ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $statusArray = array(), $undeleteNow = array(FALSE), $idColumn = array('id'), $userIdColumn = array('userid')) {
1082 // $tableName must be an array
1083 if ((!is_array($tableName)) || (count($tableName) != 1)) {
1084 // No tableName specified
1085 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
1086 } elseif (!is_array($idColumn)) {
1087 // $idColumn is no array
1088 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
1089 } elseif (!is_array($undeleteNow)) {
1090 // $undeleteNow is no array
1091 reportBug(__FUNCTION__, __LINE__, 'undeleteNow[]=' . gettype($undeleteNow) . '!=array: userIdColumn=' . $userIdColumn);
1094 // Shall we un-/lock here or list for locking?
1095 if ($undeleteNow[0] === TRUE) {
1097 adminBuilderStatusHandler('undelete', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray);
1100 adminListBuilder('undelete', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1104 // Adds a given entry to the database
1105 function adminAddEntries ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $timeColumns = array(), $columnIndex = NULL) {
1106 // Is the userid set?
1107 if (!isPostRequestElementSet('userid')) {
1108 // Then set NULL here
1109 setPostRequestElement('userid', NULL);
1112 // Call inner function
1113 doGenericAddEntries($tableName, $columns, $filterFunctions, $extraValues, $timeColumns, $columnIndex);
1115 // Entry has been added?
1116 if ((!SQL_HASZEROAFFECTED()) && ($GLOBALS['__XML_PARSE_RESULT'] === TRUE)) {
1117 // Display success message
1118 displayMessage('{--ADMIN_ENTRY_ADDED--}');
1120 // Display failed message
1121 displayMessage('{--ADMIN_ENTRY_NOT_ADDED--}');
1125 // Checks proxy settins by fetching check-updates3.php from mxchange.org
1126 function adminTestProxySettings ($settingsArray) {
1127 // Set temporary the new settings
1128 mergeConfig($settingsArray);
1130 // Now get the test URL
1131 $content = sendHttpGetRequest('check-updates3.php');
1133 // Is the first line with "200 OK"?
1134 $valid = isInString('200 OK', $content[0]);
1140 // Sends out a link to the given email adress so the admin can reset his/her password
1141 function sendAdminPasswordResetLink ($email) {
1145 //Â Look up administator login
1146 $result = SQL_QUERY_ESC("SELECT `id`, `login`, `password` FROM `{?_MYSQL_PREFIX?}_admins` WHERE '%s' REGEXP `email` LIMIT 1",
1147 array($email), __FUNCTION__, __LINE__);
1149 // Is there an account?
1150 if (SQL_HASZERONUMS($result)) {
1152 return '{--ADMIN_NO_LOGIN_WITH_EMAIL--}';
1156 $content = SQL_FETCHARRAY($result);
1159 SQL_FREERESULT($result);
1161 // Generate hash for reset link
1162 $content['hash'] = generateHash(getUrl() . getEncryptSeparator() . $content['id'] . getEncryptSeparator() . $content['login'] . getEncryptSeparator() . $content['password'], substr($content['password'], getSaltLength()));
1165 unset($content['id']);
1166 unset($content['password']);
1169 $mailText = loadEmailTemplate('admin_reset_password', $content);
1172 sendEmail($email, '{--ADMIN_RESET_PASSWORD_LINK_SUBJECT--}', $mailText);
1175 return '{--ADMIN_RESET_PASSWORD_LINK_SENT--}';
1178 // Validate hash and login for password reset
1179 function adminResetValidateHashLogin ($hash, $login) {
1180 // By default nothing validates... ;)
1183 // Then try to find that user
1184 $result = SQL_QUERY_ESC("SELECT `id`, `password`, `email` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
1185 array($login), __FUNCTION__, __LINE__);
1187 // Is an account here?
1188 if (SQL_NUMROWS($result) == 1) {
1190 $content = SQL_FETCHARRAY($result);
1192 // Generate hash again
1193 $hashFromData = generateHash(getUrl() . getEncryptSeparator() . $content['id'] . getEncryptSeparator() . $login . getEncryptSeparator() . $content['password'], substr($content['password'], getSaltLength()));
1196 $valid = ($hash == $hashFromData);
1200 SQL_FREERESULT($result);
1206 // Reset the password for the login. Do NOT call this function without calling above function first!
1207 function doResetAdminPassword ($login, $password) {
1208 // Generate hash (we already check for ext-sql_patches in generateHash())
1209 $passHash = generateHash($password);
1211 // Prepare fake POST data
1213 'login' => array(getAdminId($login) => $login),
1214 'password' => array(getAdminId($login) => $passHash),
1218 $message = adminsChangeAdminAccount($postData, '', FALSE);
1221 runFilterChain('post_form_reset_pass', array('login' => $login, 'hash' => $passHash, 'message' => $message));
1224 return '{--ADMIN_PASSWORD_RESET_DONE--}';
1227 // Solves a task by given id number
1228 function adminSolveTask ($id) {
1229 // Update the task data
1230 adminUpdateTaskData($id, 'status', 'SOLVED');
1233 // Marks a given task as deleted
1234 function adminDeleteTask ($id) {
1235 // Update the task data
1236 adminUpdateTaskData($id, 'status', 'DELETED');
1239 // Function to update task data
1240 function adminUpdateTaskData ($id, $row, $data) {
1241 // Should be admin and valid id
1243 // Not an admin so redirect better
1244 reportBug(__FUNCTION__, __LINE__, 'id=' . $id . ',row=' . $row . ',data=' . $data . ' - isAdmin()=false');
1245 } elseif ($id <= 0) {
1246 // Initiate backtrace
1247 reportBug(__FUNCTION__, __LINE__, sprintf("id is invalid: %s. row=%s, data=%s",
1255 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_task_system` SET `%s`='%s' WHERE `id`=%s LIMIT 1",
1260 ), __FUNCTION__, __LINE__);
1263 // Checks whether if the admin menu has entries
1264 function ifAdminMenuHasEntries ($action) {
1267 // Is the entry set?
1268 isset($GLOBALS['admin_menu_has_entries'][$action])
1270 // And do we have a menu for this action?
1271 $GLOBALS['admin_menu_has_entries'][$action] === TRUE
1273 // Login has always a menu
1279 // Setter for 'admin_menu_has_entries'
1280 function setAdminMenuHasEntries ($action, $hasEntries) {
1281 $GLOBALS['admin_menu_has_entries'][$action] = (bool) $hasEntries;
1284 // Creates a link to the user's admin-profile
1285 function adminCreateUserLink ($userid) {
1286 // Is the userid set correctly?
1287 if (isValidId($userid)) {
1288 // Create a link to that profile
1289 return '{%url=modules.php?module=admin&what=list_user&userid=' . bigintval($userid) . '%}';
1292 // Return a link to the user list
1293 return '{%url=modules.php?module=admin&what=list_user%}';
1296 // Generate a "link" for the given admin id (admin_id)
1297 function generateAdminLink ($adminId) {
1298 // No assigned admin is default
1299 $adminLink = '{--ADMIN_NO_ADMIN_ASSIGNED--}';
1301 // Zero? = Not assigned
1302 if (isValidId($adminId)) {
1303 // Load admin's login
1304 $login = getAdminLogin($adminId);
1306 // Is the login valid?
1307 if ($login != '***') {
1308 // Is the extension there?
1309 if (isExtensionActive('admins')) {
1311 $adminLink = '<a href="' . generateEmailLink(getAdminEmail($adminId), 'admins') . '" title="{--ADMIN_CONTACT_LINK_TITLE--}">' . $login . '</a>';
1313 // Extension not found
1314 $adminLink = '{%message,ADMIN_TASK_ROW_EXTENSION_NOT_INSTALLED=admins%}';
1318 $adminLink = '<div class="bad">{%message,ADMIN_ID_404=' . $adminId . '%}</div>';
1326 // Verifies if the current admin has confirmed to alter expert settings
1329 // 'failed' = Something goes wrong (default)
1330 // 'agreed' = Has verified and and confirmed it to see them
1331 // 'forbidden' = Has not the proper right to alter them
1332 // 'update' = Need to update extension 'admins'
1333 // 'ask' = A form was send to the admin
1334 function doVerifyExpertSettings () {
1335 // Default return status is failed
1338 // Is the extension installed and recent?
1339 if (isExtensionInstalledAndNewer('admins', '0.7.3')) {
1340 // Okay, load the status
1341 $expertSettings = getAminsExpertSettings();
1344 if ($expertSettings == 'Y') {
1345 // Okay, does he want to see them?
1346 if (isAdminsExpertWarningEnabled()) {
1348 if (isFormSent('save_expert')) {
1349 // Is the element set, then we need to change the admin
1350 if (isPostRequestElementSet('expert_settings')) {
1351 // Get it and prepare final post data array
1352 $postData['login'][getCurrentAdminId()] = getCurrentAdminLogin();
1353 $postData['expert_warning'][getCurrentAdminId()] = 'N';
1355 // Change it in the admin
1356 adminsChangeAdminAccount($postData, 'expert_warning');
1363 loadTemplate('admin_expert_settings_form');
1374 if ((isFormSent()) && (isPostRequestElementSet('expert_settings'))) {
1376 unsetPostRequestElement('ok');
1377 unsetPostRequestElement('expert_settings');
1381 $return = 'forbidden';
1384 // Out-dated extension or not installed
1388 // Output message for other status than ask/agreed
1389 if (($return != 'ask') && ($return != 'agreed')) {
1391 displayMessage('{--ADMIN_EXPERT_SETTINGS_STATUS_' . strtoupper($return) . '--}');
1398 // Generate link to unconfirmed mails for admin
1399 function generateUnconfirmedAdminLink ($id, $unconfirmed, $type) {
1401 $OUT = $unconfirmed;
1403 // Is there unconfirmed mails?
1404 if ($unconfirmed > 0) {
1405 // Add link to list_unconfirmed what-file
1406 $OUT = '<a href="{%url=modules.php?module=admin&what=list_unconfirmed&type=' . $type . '&id=' . $id . '%}">{%pipe,translateComma=' . $unconfirmed . '%}</a>';
1413 // Generates a navigation row for listing emails
1414 function addEmailNavigation ($numPages, $offset, $show_form, $colspan, $return=false) {
1415 // Don't do anything if $numPages is 1
1416 if ($numPages == 1) {
1417 // Abort here with empty content
1422 if ($show_form === FALSE) {
1427 for ($page = 1; $page <= $numPages; $page++) {
1428 // Is the page currently selected or shall we generate a link to it?
1429 if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
1430 // Is currently selected, so only highlight it
1431 $NAV .= '<strong>-';
1433 // Open anchor tag and add base URL
1434 $NAV .= '<a href="{%url=modules.php?module=admin&what=' . getWhat() . '&page=' . $page . '&offset=' . $offset;
1436 // Add userid when we shall show all mails from a single member
1437 if ((isGetRequestElementSet('userid')) && (isValidId(getRequestElement('userid')))) $NAV .= '&userid=' . bigintval(getRequestElement('userid'));
1439 // Close open anchor tag
1443 if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
1444 // Is currently selected, so only highlight it
1445 $NAV .= '-</strong>';
1451 // Add separator if total pages has not been reached
1452 if ($page < $numPages) {
1458 // Define constants only once
1459 $content['nav'] = $NAV;
1460 $content['span'] = $colspan;
1461 $content['top'] = $TOP;
1463 // Load navigation template
1464 $OUT = loadTemplate('admin_email_nav_row', TRUE, $content);
1466 if ($return === TRUE) {
1467 // Return generated HTML-Code
1475 // Process menu editing form
1476 function adminProcessMenuEditForm ($type, $subMenu) {
1477 // An action is done...
1478 foreach (postRequestElement('sel') as $sel => $menu) {
1479 $AND = "(`what` = '' OR `what` IS NULL)";
1481 $sel = bigintval($sel);
1483 if (!empty($subMenu)) {
1484 $AND = "`action`='" . $subMenu . "'";
1487 switch (postRequestElement('ok')) {
1488 case 'edit': // Edit menu
1489 // Shall we update a menu or sub menu?
1490 if (!isGetRequestElementSet('sub')) {
1491 // Update with 'what'=null
1492 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET `title`='%s',`action`='%s',`what`=NULL WHERE ".$AND." AND `id`=%s LIMIT 1",
1496 postRequestElement('sel_action', $sel),
1498 ), __FUNCTION__, __LINE__);
1500 // Update with selected 'what'
1501 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET `title`='%s',`action`='%s',`what`='%s' WHERE ".$AND." AND `id`=%s LIMIT 1",
1505 postRequestElement('sel_action', $sel),
1506 postRequestElement('sel_what', $sel),
1508 ), __FUNCTION__, __LINE__);
1512 case 'delete': // Delete menu
1513 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE ".$AND." AND `id`=%s LIMIT 1",
1517 ), __FUNCTION__, __LINE__);
1520 case 'status': // Change status of menus
1521 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET `visible`='%s',`locked`='%s' WHERE ".$AND." AND `id`=%s LIMIT 1",
1524 postRequestElement('visible', $sel),
1525 postRequestElement('locked', $sel),
1527 ), __FUNCTION__, __LINE__);
1530 default: // Unexpected action
1531 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unsupported action %s detected.", postRequestElement('ok')));
1532 displayMessage('{%message,ADMIN_UNKNOWN_OKAY=' . postRequestElement('ok') . '%}');
1538 displayMessage('{--SETTINGS_SAVED--}');
1541 // Handle weightning
1542 function doAdminProcessMenuWeightning ($type, $AND) {
1543 // Are there all required (generalized) GET parameter?
1544 if ((isGetRequestElementSet('act')) && (isGetRequestElementSet('tid')) && (isGetRequestElementSet('fid'))) {
1546 $tid = ''; $fid = '';
1549 if (isGetRequestElementSet('w')) {
1550 // Sub menus selected
1551 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `action`='%s' AND `sort`=%s LIMIT 1",
1554 getRequestElement('act'),
1555 bigintval(getRequestElement('tid'))
1556 ), __FUNCTION__, __LINE__);
1557 list($tid) = SQL_FETCHROW($result);
1558 SQL_FREERESULT($result);
1559 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `action`='%s' AND `sort`=%s LIMIT 1",
1562 getRequestElement('act'),
1563 bigintval(getRequestElement('fid'))
1564 ), __FUNCTION__, __LINE__);
1565 list($fid) = SQL_FETCHROW($result);
1566 SQL_FREERESULT($result);
1568 // Main menu selected
1569 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE (`what`='' OR `what` IS NULL) AND `sort`=%s LIMIT 1",
1572 bigintval(getRequestElement('tid'))
1573 ), __FUNCTION__, __LINE__);
1574 list($tid) = SQL_FETCHROW($result);
1575 SQL_FREERESULT($result);
1576 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE (`what`='' OR `what` IS NULL) AND `sort`=%s LIMIT 1",
1579 bigintval(getRequestElement('fid'))
1580 ), __FUNCTION__, __LINE__);
1581 list($fid) = SQL_FETCHROW($result);
1582 SQL_FREERESULT($result);
1585 if ((!empty($tid)) && (!empty($fid))) {
1587 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET `sort`=%s WHERE ".$AND." AND `id`=%s LIMIT 1",
1590 bigintval(getRequestElement('tid')),
1592 ), __FUNCTION__, __LINE__);
1593 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET `sort`=%s WHERE ".$AND." AND `id`=%s LIMIT 1",
1596 bigintval(getRequestElement('fid')),
1598 ), __FUNCTION__, __LINE__);
1603 // Function to register first admin
1604 function registerFirstAdmin () {
1605 // Make sure that no admin is registered
1606 assert(!isAdminRegistered());
1608 // Admin is not registered so we have to inform the user
1609 if ((isFormSent('add_first_admin')) && ((!isPostRequestElementSet('admin_login')) || (!isPostRequestElementSet('admin_password1')) || (strlen(postRequestElement('admin_password1')) < getConfig('minium_admin_pass_length')) || (!isPostRequestElementSet('admin_password2')) || (strlen(postRequestElement('admin_password2')) < getConfig('minium_admin_pass_length')) || (postRequestElement('admin_password1') != postRequestElement('admin_password2')))) {
1610 setPostRequestElement('add_first_admin', '***');
1613 // Clear error message
1617 // Is form for first admin sent?
1618 if ((isFormSent('add_first_admin')) && (postRequestElement('add_first_admin') != '***')) {
1619 // Hash the password with the old function because we are here in install mode
1620 $hashedPass = md5(postRequestElement('admin_password1'));
1622 // Kill maybe existing session variables
1623 destroyAdminSession();
1626 $ret = addAdminAccount(postRequestElement('admin_login'), $hashedPass, getWebmaster(), 'allow');
1628 // Check if registration wents fine
1631 // Change ADMIN_REGISTERED entry
1632 $done = changeDataInLocalConfigurationFile('ADMIN-SETUP', "setConfigEntry('ADMIN_REGISTERED', '", "');", 'Y', 0);
1634 // Was it successfull?
1635 if ($done === TRUE) {
1636 // Registering is done
1637 redirectToUrl('modules.php?module=admin&register=done');
1639 // Registration incomplete
1640 $errorMessage = '{--ADMIN_CANNOT_COMPLETE--}';
1642 // Set this to have our error message displayed
1643 setPostRequestElement('add_first_admin', '***');
1647 case 'failed': // Registration has failed
1648 $errorMessage = '{--ADMIN_REGISTER_FAILED--}';
1650 // Set this to have our error message displayed
1651 setPostRequestElement('add_first_admin', '***');
1654 case 'already': // Admin does already exists!
1655 $errorMessage = '{--ADMIN_LOGIN_ALREADY_REG--}';
1657 // Set this to have our error message displayed
1658 setPostRequestElement('add_first_admin', '***');
1662 // Any other kind will be logged
1663 $errorMessage = sprintf("Unknown return code %s from ifAdminLoginDataIsValid().", $ret);
1664 logDebugMessage(__FUNCTION__, __LINE__, $errorMessage);
1666 // Set this to have our error message displayed
1667 setPostRequestElement('add_first_admin', '***');
1672 // Whas that action okay?
1673 if ($ret != 'done') {
1675 $content['admin_login'] = '';
1676 if (isPostRequestElementSet('admin_login')) {
1677 $content['admin_login'] = postRequestElement('admin_login');
1680 // Init array elements
1681 $content['login_message'] = '';
1682 $content['password1_message'] = '';
1683 $content['password2_message'] = '';
1684 $content['error_message'] = '';
1686 // Yet-another notice-fix
1687 if ((isFormSent('add_first_admin')) && (postRequestElement('add_first_admin') == '***')) {
1690 $password1Message = '';
1691 $password2Message = '';
1693 // No login entered?
1694 if (empty($content['admin_login'])) {
1695 $loginMessage = '{--ADMIN_NO_LOGIN--}';
1698 // An error comes back from registration?
1699 if ((!empty($ret)) && ($ret != 'init')) {
1700 $loginMessage = $errorMessage;
1703 // No password 1 entered or to short?
1704 if (!isPostRequestElementSet('admin_password1')) {
1705 $password1Message = '{--ADMIN_NO_PASSWORD1--}';
1706 } elseif (strlen(postRequestElement('admin_password1')) < getConfig('minium_admin_pass_length')) {
1707 $password1Message = '{--ADMIN_SHORT_PASSWORD1--}';
1710 // No password 2 entered or to short?
1711 if (!isPostRequestElementSet('admin_password2')) {
1712 $password2Message = '{--ADMIN_NO_PASSWORD2--}';
1713 } elseif (strlen(postRequestElement('admin_password2')) < getConfig('minium_admin_pass_length')) {
1714 $password2Message = '{--ADMIN_SHORT_PASSWORD2--}';
1717 // Both didn't match?
1718 if (postRequestElement('admin_password1') != postRequestElement('admin_password2')) {
1720 if (empty($password1Message)) $password1Message = '{--ADMIN_PASSWORD1_MISMATCH--}';
1721 if (empty($password2Message)) $password2Message = '{--ADMIN_PASSWORD2_MISMATCH--}';
1724 // Output error messages
1725 $content['login_message'] = loadTemplate('admin_login_msg', TRUE, $loginMessage);
1726 $content['password1_message'] = loadTemplate('admin_login_msg', TRUE, $password1Message);
1727 $content['password2_message'] = loadTemplate('admin_login_msg', TRUE, $password2Message);
1728 $content['error_message'] = loadTemplate('admin_login_msg', TRUE, $errorMessage);
1731 // Output message in seperate template
1732 displayMessage('{--ADMIN_ACCOUNT_NOT_REGISTERED_YET--}');
1734 // Load register template
1735 loadTemplate('admin_reg_form', FALSE, $content);