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 // Only let valid data pass
46 assert(in_array($accessLevel, array('allow', 'deny')));
48 // Login does already exist
52 $result = sqlQueryEscaped("SELECT `id` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
53 array($adminLogin), __FUNCTION__, __LINE__);
55 // Is the entry there?
56 if (ifSqlHasZeroNums($result)) {
57 // Is ext-admins installed and version at least 0.3.0?
58 if (isExtensionInstalledAndNewer('admins', '0.3.0')) {
59 // Ok, let's create the admin login
60 sqlQueryEscaped("INSERT INTO `{?_MYSQL_PREFIX?}_admins` (`login`, `password`, `email`, `default_acl`) VALUES ('%s', '%s', '%s', '%s')",
66 ), __FUNCTION__, __LINE__);
68 // Ok, let's create the admin login
69 sqlQueryEscaped("INSERT INTO `{?_MYSQL_PREFIX?}_admins` (`login`, `password`, `email`) VALUES ('%s', '%s', '%s')",
74 ), __FUNCTION__, __LINE__);
82 sqlFreeResult($result);
88 // This function will be executed when the admin is not logged in and has submitted his login data
89 function ifAdminLoginDataIsValid ($adminLogin, $adminPassword) {
90 // First of all, no admin login is found, so the admin hash is null
94 // Get admin id from login
95 $adminId = getAdminId($adminLogin);
97 // Continue only with found admin ids
98 if (isValidId($adminId)) {
99 // Then we need to lookup the login name by getting the admin hash
100 $adminHash = getAdminHash($adminId);
102 // If this is fine, we can continue
103 if ($adminHash != '-1') {
104 // Get admin id and set it as current
105 setCurrentAdminId($adminId);
107 // Now, we need to encode the password in the same way the one is encoded in database
108 $testHash = generateHash($adminPassword, $adminHash);
110 // If they both match, the login data is valid
111 if ($testHash == $adminHash) {
121 // Prepare data array
124 'login' => $adminLogin,
125 'plain_pass' => $adminPassword,
126 'pass_hash' => $adminHash
129 // Run a special filter
130 runFilterChain('do_admin_login_' . $ret, $data);
136 // Only be executed on cookie checking
137 function ifAdminCookiesAreValid ($adminLogin, $passHash) {
138 // First of all, no admin login is found
141 // Then we need to lookup the login name by getting the admin hash
142 $adminHash = getAdminHash($adminLogin);
144 // If this is fine, we can continue
145 if ($adminHash != '-1') {
146 // Now, we need to encode the password in the same way the one is encoded in database
147 $testHash = encodeHashForCookie($adminHash);
148 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'adminLogin=' . $adminLogin . ',passHash='.$passHash.',adminHash='.$adminHash.',testHash='.$testHash);
150 // If they both match, the login data is valid
151 if ($testHash != $passHash) {
152 // Passwords don't match
154 } elseif (!isAdmin()) {
155 // Is not valid session
164 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret='.$ret);
168 // Do an admin action
169 function doAdminAction () {
170 // Determine correct 'what' value
171 $what = determineWhat();
174 $action = getActionFromModuleWhat(getModule(), $what);
176 // Load welcome template
177 if (isExtensionActive('admins')) {
178 // @TODO This and the next getCurrentAdminId() call might be moved into the templates?
179 $content['welcome'] = loadTemplate('admin_welcome_admins', TRUE, getCurrentAdminId());
181 $content['welcome'] = loadTemplate('admin_welcome', TRUE, getCurrentAdminId());
184 // Load header, footer, render menu
185 $content['header'] = loadTemplate('admin_header' , TRUE, $content);
186 $content['footer'] = loadTemplate('admin_footer' , TRUE, $content);
187 $content['menu'] = addAdminMenu($action, $what);
189 // Load main template
190 loadTemplate('admin_main', FALSE, $content);
192 // Check if action/what pair is valid
193 $result_action = sqlQueryEscaped("SELECT
196 `{?_MYSQL_PREFIX?}_admin_menu`
201 `what`='%s' AND `what` != 'welcome'
204 `what`='' OR `what` IS NULL
215 ), __FUNCTION__, __LINE__);
217 // Is there an entry?
218 if (sqlNumRows($result_action) == 1) {
219 // Is valid but does the inlcude file exists?
220 $inc = sprintf('inc/modules/admin/action-%s.php', $action);
221 if ((isIncludeReadable($inc)) && (isMenuActionValid('admin', $action, $what)) && ($GLOBALS['acl_allow'] === TRUE)) {
222 // Ok, we finally load the admin action module
224 } elseif ($GLOBALS['acl_allow'] === FALSE) {
226 loadTemplate('admin_menu_failed', FALSE, '{%message,ADMIN_ACCESS_DENIED=' . $what . '%}');
228 // Include file not found :-(
229 loadTemplate('admin_menu_failed', FALSE, '{%message,ADMIN_ACTION_404=' . $action . '%}');
232 // Invalid action/what pair found
233 loadTemplate('admin_menu_failed', FALSE, '{%message,ADMIN_ACTION_INVALID=' . $action . '/' . $what . '%}');
237 sqlFreeResult($result_action);
240 loadTemplate('admin_main_footer', FALSE, $content);
244 * Checks whether current admin is allowed to access given action/what
245 * combination (only one is allowed to be null!).
247 function isAdminAllowedAccessMenu ($action, $what = NULL) {
249 if (!isset($GLOBALS[__FUNCTION__][$action][$what])) {
250 // ACL is always 'allow' when no ext-admins is installed
251 // @TODO This can be rewritten into a filter
252 $GLOBALS[__FUNCTION__][$action][$what] = ((!isExtensionInstalledAndNewer('admins', '0.2.0')) || ((isExtensionActive('admins')) && (isAdminsAllowedByAcl($action, $what))));
255 // Return the cached value
256 return $GLOBALS[__FUNCTION__][$action][$what];
259 // Adds an admin menu
260 function addAdminMenu ($action, $what) {
266 $GLOBALS['menu']['description'] = array();
267 $GLOBALS['menu']['title'] = array();
270 $result_main = sqlQuery("SELECT
271 `action` AS `main_action`,
272 `title` AS `main_title`,
273 `descr` AS `main_descr`
275 `{?_MYSQL_PREFIX?}_admin_menu`
277 (`what`='' OR `what` IS NULL)
280 `id` DESC", __FUNCTION__, __LINE__);
282 // Are there entries?
283 if (!ifSqlHasZeroNums($result_main)) {
284 $OUT .= '<ul class="admin_menu_main">';
286 // Load all 'action' menus
287 while ($mainContent = sqlFetchArray($result_main)) {
289 $inc = sprintf('inc/modules/admin/action-%s.php', $mainContent['main_action']);
291 // Is the current admin allowed to access this 'action' menu?
292 if (isAdminAllowedAccessMenu($mainContent['main_action'])) {
293 if ($SUB === FALSE) {
294 // Insert compiled menu title and description
295 $GLOBALS['menu']['title'][$mainContent['main_action']] = $mainContent['main_title'];
296 $GLOBALS['menu']['description'][$mainContent['main_action']] = $mainContent['main_descr'];
298 $OUT .= '<li class="admin_menu"' . addJavaScriptMenuContent('admin', $mainContent['main_action'], $action, $what) . '>
299 <div class="nobr"><strong>·</strong> ';
301 // Is the file readable?
302 if (isIncludeReadable($inc)) {
303 if (($mainContent['main_action'] == $action) && (empty($what))) {
306 $OUT .= '[<a href="{%url=modules.php?module=admin&action=' . $mainContent['main_action'] . '%}">';
309 $OUT .= '<span class="bad" style="cursor:help" title="{%message,ADMIN_MENU_ACTION_404_TITLE=' . $mainContent['main_action'] . '%}">';
312 $OUT .= $mainContent['main_title'];
314 // Is the file readable?
315 if (isIncludeReadable($inc)) {
316 if (($mainContent['main_action'] == $action) && (empty($what))) {
329 $OUT .= addAdminSubMenu($mainContent, $action, $what);
337 sqlFreeResult($result_main);
344 // Add admin sub menu
345 function addAdminSubMenu ($mainContent, $action, $what) {
349 // Check for menu entries
350 $result_what = sqlQueryEscaped("SELECT
351 `what` AS `sub_what`,
352 `title` AS `sub_title`,
353 `descr` AS `sub_descr`
355 `{?_MYSQL_PREFIX?}_admin_menu`
363 array($mainContent['main_action']), __FUNCTION__, __LINE__);
365 // Remember the count for later checks
366 setAdminMenuHasEntries($mainContent['main_action'], ((!ifSqlHasZeroNums($result_what)) && (($action == $mainContent['main_action']) || (isAdminMenuJavascriptEnabled()))));
368 // Start li-tag for sub menu content
369 $OUT .= '<li class="admin_menu_sub" id="action_menu_' . $mainContent['main_action'] . '"' . addStyleMenuContent('admin', $mainContent['main_action'], $action) . '>';
371 // Are there entries?
372 if (ifAdminMenuHasEntries($mainContent['main_action'])) {
373 // Sub menu has been called
376 // Are there entries?
377 if (!ifSqlHasZeroNums($result_what)) {
379 $OUT .= '<ul class="admin_menu_sub">';
382 while ($subContent = sqlFetchArray($result_what)) {
384 $inc = sprintf('inc/modules/admin/what-%s.php', $subContent['sub_what']);
386 // Is the current admin allowed to access this 'what' menu?
387 if (isAdminAllowedAccessMenu(NULL, $subContent['sub_what'])) {
388 // Insert compiled title and description
389 $GLOBALS['menu']['title'][$subContent['sub_what']] = $subContent['sub_title'];
390 $GLOBALS['menu']['description'][$subContent['sub_what']] = $subContent['sub_descr'];
391 $OUT .= '<li class="admin_menu">
392 <div class="nobr"><strong>--></strong> ';
394 // Is the file readable?
395 if (isIncludeReadable($inc)) {
396 if ($what == $subContent['sub_what']) {
399 $OUT .= '[<a href="{%url=modules.php?module=admin&what=' . $subContent['sub_what'] . '%}">';
402 $OUT .= '<span class="bad" style="cursor:help" title="{%message,ADMIN_MENU_WHAT_404_TITLE=' . $subContent['sub_what'] . '%}">';
405 $OUT .= $subContent['sub_title'];
407 // Is the file readable?
408 if (isIncludeReadable($inc)) {
409 if ($what == $subContent['sub_what']) {
422 // Finish HTML output
427 sqlFreeResult($result_what);
437 // Create an admin selection box form
438 function addAdminSelectionBox ($adminId = NULL, $special = '') {
439 // Default is email as "special column"
440 $ADD = ',`email` AS `special`';
442 // Is a special column given?
443 if (!empty($special)) {
444 // Additional column for SQL query
445 $ADD = ',`' . $special . '` AS `special`';
449 $result = sqlQuery('SELECT
454 `{?_MYSQL_PREFIX?}_admins`
456 `login` ASC', __FUNCTION__, __LINE__);
462 while ($content = sqlFetchArray($result)) {
464 $content['default'] = '';
466 // Is the id the same?
467 if ($content['id'] == $adminId) {
468 // Set this as default
469 $content['default'] = ' selected="selected"';
473 $OUT .= loadTemplate('select_admins_option', TRUE, $content);
477 sqlFreeResult($result);
479 // Add form to content
480 $content['form_selection'] = $OUT;
483 loadTemplate('select_admins_box', FALSE, $content);
486 // Create a member selection box
487 function addMemberSelectionBox ($userid = NULL, $add_all = FALSE, $return = FALSE, $none = FALSE, $field = 'userid', $whereStatement = " WHERE `surname` NOT LIKE '{?tester_user_surname_prefix?}%'") {
488 // Output selection form with all confirmed user accounts listed
489 $result = sqlQuery('SELECT
494 `{?_MYSQL_PREFIX?}_user_data`
495 ' . $whereStatement . '
497 `userid` ASC', __FUNCTION__, __LINE__);
502 // USe this only for adding points (e.g. adding refs really makes no sence ;-) )
503 if ($add_all === TRUE) {
504 $OUT = ' <option value="all">{--ALL_MEMBERS--}</option>';
505 } elseif ($none === TRUE) {
506 $OUT = ' <option value="0">{--SELECT_NONE--}</option>';
510 while ($content = sqlFetchArray($result)) {
511 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . intval($userid) . '/' . $content['userid']);
512 $OUT .= '<option value="' . bigintval($content['userid']) . '"';
513 if ($userid === $content['userid']) {
514 $OUT .= ' selected="selected"';
516 $OUT .= '>' . $content['surname'] . ' ' . $content['family'] . ' (' . $content['userid'] . ')</option>';
520 sqlFreeResult($result);
522 if ($return === FALSE) {
523 // Remeber options in constant
524 $content['form_selection'] = $OUT;
525 $content['what'] = '{%pipe,getWhat%}';
528 loadTemplate('admin_form_selection_box', FALSE, $content);
530 // Return content in selection frame
531 return '<select class="form_select" name="' . handleFieldWithBraces($field) . '" size="1">' . $OUT . '</select>';
535 // Create a menu selection box for given menu system
536 // @TODO Try to rewrite this to adminAddMenuSelectionBox()
538 function adminMenuSelectionBox_DEPRECATED ($mode, $default = '', $defid = '') {
539 $what = "`what` != '' AND `what` IS NOT NULL";
540 if ($mode == 'action') $what = "(`what`='' OR `what` IS NULL) AND `action` != 'login'";
542 $result = sqlQueryEscaped("SELECT `%s` AS `menu`, `title` FROM `{?_MYSQL_PREFIX?}_admin_menu` WHERE ".$what." ORDER BY `sort` ASC",
543 array($mode), __FUNCTION__, __LINE__);
544 if (!ifSqlHasZeroNums($result)) {
545 // Load menu as selection
546 $OUT = '<select name="' . $mode . '_menu';
547 if (!isValidId($defid)) $OUT .= '[' . intval($defid) . ']';
548 $OUT .= '" size="1" class="form_select">
549 <option value="">{--SELECT_NONE--}</option>';
551 while ($content = sqlFetchArray($result)) {
552 $OUT .= '<option value="' . $content['menu'] . '"';
553 if ((!empty($default)) && ($default == $content['menu'])) {
554 $OUT .= ' selected="selected"';
556 $OUT .= '>' . $content['title'] . '</option>';
560 sqlFreeResult($result);
562 // Add closing select-tag
566 $OUT = '{--ADMIN_PROBLEM_NO_MENU--}';
573 // Wrapper for $_POST and adminSaveSettings
574 function adminSaveSettingsFromPostData ($tableName = '_config', $whereStatement = '`config`=0', $translateComma = array(), $alwaysAdd = FALSE, $displayMessage = TRUE) {
576 $postData = postRequestArray();
578 // Call the lower function
579 adminSaveSettings($postData, $tableName, $whereStatement, $translateComma, $alwaysAdd, $displayMessage);
582 // Save settings to the database
583 function adminSaveSettings (&$postData, $tableName = '_config', $whereStatement = '`config`=0', $translateComma = array(), $alwaysAdd = FALSE, $displayMessage = TRUE) {
584 // Prepare all arrays, variables
585 $tableData = array();
588 // Now, walk through all entries and prepare them for saving
589 //* BUG: */ reportBug(__FUNCTION__, __LINE__, '<pre>'.print_r(postRequestArray(), TRUE).'</pre>');
590 foreach ($postData as $id => $val) {
591 // Process only formular field but not submit buttons ;)
592 if ($id == 'save_config') {
597 // Do not save the ok value
598 convertSelectionsToEpocheTime($postData, $tableData, $id, $skip);
600 // Shall we process this id? It muss not be empty, of course
601 if (($skip === FALSE) && (!empty($id)) && ((!isset($GLOBALS['skip_config'][$id]))) || ($tableName != '_config')) {
602 // Translate the value? (comma to dot!)
603 if ((is_array($translateComma)) && (in_array($id, $translateComma))) {
604 // Then do it here... :)
605 $val = convertCommaToDot($val);
608 // Test value on float
609 $test = (float) $val;
612 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'test=' . $test . ',val=' . $val . ',id=' . $id);
614 // Shall we add numbers or strings?
615 if ('' . $val . '' == '' . $test . '') {
617 array_push($tableData, sprintf('`%s`=%s', $id, $test));
618 } elseif (is_null($val)) {
620 array_push($tableData, sprintf('`%s`=NULL', $id));
623 array_push($tableData, sprintf("`%s`='%s'", $id, trim($val)));
626 // Do not add a config entry twice
627 $GLOBALS['skip_config'][$id] = TRUE;
629 // Update current configuration
630 setConfigEntry($id, $val);
634 // Check if entry does exist
636 if ($alwaysAdd === FALSE) {
637 if (!empty($whereStatement)) {
638 $result = sqlQuery('SELECT * FROM `{?_MYSQL_PREFIX?}' . $tableName . '` WHERE ' . $whereStatement . ' LIMIT 1', __FUNCTION__, __LINE__);
640 $result = sqlQuery('SELECT * FROM `{?_MYSQL_PREFIX?}' . $tableName . '` LIMIT 1', __FUNCTION__, __LINE__);
644 if (sqlNumRows($result) == 1) {
645 // "Implode" all data to single string
646 $updatedData = implode(', ', $tableData);
648 // Generate SQL string
649 $sql = sprintf('UPDATE `{?_MYSQL_PREFIX?}%s` SET %s WHERE %s LIMIT 1',
655 // Add Line (does only work with AUTO_INCREMENT!
656 $keys = array(); $values = array();
657 foreach ($tableData as $entry) {
659 $line = explode('=', $entry);
660 array_push($keys , $line[0]);
661 array_push($values, $line[1]);
664 // Add both in one line
665 $keys = implode('`, `', $keys);
666 $values = implode(', ' , $values);
668 // Generate SQL string
669 $sql = sprintf('INSERT INTO `{?_MYSQL_PREFIX?}%s` (%s) VALUES (%s)',
677 sqlFreeResult($result);
679 // Simply run generated SQL string
680 sqlQuery($sql, __FUNCTION__, __LINE__);
682 // Remember affected rows
683 $affected = sqlAffectedRows();
686 rebuildCache('config', 'config');
688 // Settings saved, so display message?
689 if ($displayMessage === TRUE) {
691 displayMessage('{--SETTINGS_SAVED--}');
694 // Return affected rows
698 // Generate a selection box
699 function adminAddMenuSelectionBox ($menu, $type, $name, $default = '') {
700 // Open the requested menu directory
701 $menuArray = getArrayFromDirectory(sprintf('inc/modules/%s/', $menu), $type . '-', FALSE, FALSE);
703 // Init the selection box
704 $OUT = '<select name="' . $name . '" class="form_select" size="1"><option value="">{--ADMIN_IS_TOP_MENU--}</option>';
706 // Walk through all files
707 foreach ($menuArray as $file) {
708 // Is this a PHP script?
709 if ((!isDirectory($file)) && (isInString('' . $type . '-', $file)) && (isInString('.php', $file))) {
710 // Then test if the file is readable
711 $test = sprintf('inc/modules/%s/%s', $menu, $file);
713 // Is the file there?
714 if (isIncludeReadable($test)) {
715 // Extract the value for what=xxx
716 $part = substr($file, (strlen($type) + 1));
717 $part = substr($part, 0, -4);
719 // Is that part different from the overview?
720 if ($part != 'welcome') {
721 $OUT .= '<option value="' . $part . '"';
722 if ($part == $default) {
723 $OUT .= ' selected="selected"';
725 $OUT .= '>' . $part . '</option>';
731 // Close selection box
738 // Creates a user-profile link for the admin. This function can also be used for many other purposes
739 function generateUserProfileLink ($userid, $title = '', $what = '') {
741 if (!isset($GLOBALS[__FUNCTION__][$userid][$title . '_' . $what])) {
742 // Is title empty and valid userid?
743 if (($title == '') && (isValidId($userid))) {
744 // Set userid as title
746 } elseif (!isValidId($userid)) {
747 // User id zero is invalid
748 return '<strong>' . convertNullToZero($userid) . '</strong>';
753 // Then get it to 'list_user'
757 if (($title == '0') && ($what == 'list_refs')) {
758 // Return title again
760 } elseif (!empty($title)) {
761 // Not empty, so skip next one
762 } elseif (isExtensionActive('nickname')) {
764 $nick = getNickname($userid);
766 // Is it not empty, use it as title else the userid
768 $title = $nick . '(' . $userid . ')';
775 $GLOBALS[__FUNCTION__][$userid][$title . '_' . $what] = '[<a href="{%url=modules.php?module=admin&what=' . $what . '&userid=' . $userid . '%}" title="{--ADMIN_USER_PROFILE_TITLE--}">' . $title . '</a>]';
779 return $GLOBALS[__FUNCTION__][$userid][$title . '_' . $what];
782 // Check "logical-area-mode"
783 function adminGetMenuMode () {
784 // Set the default menu mode as the mode for all admins
787 // If ext-sql_patches is up-to-date enough, use the configuration
788 if (isExtensionInstalledAndNewer('sql_patches', '0.3.2')) {
789 $mode = getAdminMenu();
796 $adminId = getCurrentAdminId();
798 // Check individual settings of current admin
799 if (isset($GLOBALS['cache_array']['admin']['la_mode'][$adminId])) {
801 $adminMode = $GLOBALS['cache_array']['admin']['la_mode'][$adminId];
802 incrementStatsEntry('cache_hits');
803 } elseif (isExtensionInstalledAndNewer('admins', '0.6.7')) {
804 // Load from database when version of 'admins' is enough
805 $result = sqlQueryEscaped('SELECT `la_mode` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1',
806 array($adminId), __FUNCTION__, __LINE__);
808 // Is there an entry?
809 if (sqlNumRows($result) == 1) {
811 list($adminMode) = sqlFetchRow($result);
815 sqlFreeResult($result);
818 // Check what the admin wants and set it when it's not the default mode
819 if ($adminMode != 'global') {
823 // Return admin-menu's mode
827 // Change activation status
828 function adminChangeActivationStatus ($IDs, $table, $row, $idRow = 'id') {
830 if ((is_array($IDs)) && (count($IDs) > 0)) {
831 // "Walk" all through and count them
832 foreach ($IDs as $id => $selected) {
833 // Secure the id number
834 $id = bigintval($id);
836 // Should always be set... ;-)
837 if (!empty($selected)) {
838 // Determine new status
839 $result = sqlQueryEscaped('SELECT %s FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`=%s LIMIT 1',
845 ), __FUNCTION__, __LINE__);
848 if (sqlNumRows($result) == 1) {
850 list($currStatus) = sqlFetchRow($result);
852 // And switch it N<->Y
853 $newStatus = convertBooleanToYesNo(!($currStatus == 'Y'));
855 // Change this status
856 sqlQueryEscaped("UPDATE `{?_MYSQL_PREFIX?}_%s` SET `%s`='%s' WHERE `%s`=%s LIMIT 1",
863 ), __FUNCTION__, __LINE__);
865 // Count up affected rows
866 $count += sqlAffectedRows();
870 sqlFreeResult($result);
875 displayMessage(sprintf(getMessage('ADMIN_STATUS_CHANGED'), $count, count($IDs)));
878 displayMessage('{--ADMIN_NOTHING_SELECTED_CHANGE--}');
882 // Build a special template list
883 // @TODO cacheFiles is not yet supported
884 function adminListBuilder ($listType, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId = array('userid'), $content = array()) {
885 // Call inner (general) function
886 doGenericListBuilder('admin', $listType, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId, $content);
889 // Change status of "build" list
890 function adminBuilderStatusHandler ($mode, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray, $rawUserId = array('userid'), $cacheFiles = array()) {
891 // $tableName must be an array
892 if ((!is_array($tableName)) || (count($tableName) != 1)) {
893 // No tableName specified
894 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
895 } elseif (!is_array($idColumn)) {
896 // $idColumn is no array
897 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
898 } elseif ((!is_array($userIdColumn)) || (count($userIdColumn) != 1)) {
899 // $tableName is no array
900 reportBug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array: userIdColumn=' . $userIdColumn);
903 // "Walk" through all entries
904 foreach (postRequestElement($idColumn[0]) as $id => $sel) {
905 // Construct SQL query
906 $sql = sprintf('UPDATE `{?_MYSQL_PREFIX?}_%s` SET', sqlEscapeString($tableName[0]));
908 // Load data of entry
909 $result = sqlQueryEscaped('SELECT * FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`=%s LIMIT 1',
914 ), __FUNCTION__, __LINE__);
917 $content = sqlFetchArray($result);
920 sqlFreeResult($result);
922 // Add all status entries (e.g. status column last_updated or so)
923 $newStatus = 'UNKNOWN';
924 $oldStatus = 'UNKNOWN';
925 $statusColumn = 'unknown';
926 foreach ($statusArray as $column => $statusInfo) {
927 // Does the entry exist?
928 if ((isset($content[$column])) && (isset($statusInfo[$content[$column]]))) {
929 // Add these entries for update
930 $sql .= sprintf(" `%s`='%s',", sqlEscapeString($column), sqlEscapeString($statusInfo[$content[$column]]));
933 if ($statusColumn == 'unknown') {
934 // Always (!!!) change status column first!
935 $oldStatus = $content[$column];
936 $newStatus = $statusInfo[$oldStatus];
937 $statusColumn = $column;
939 } elseif (isset($content[$column])) {
941 reportBug(__FUNCTION__, __LINE__, ':UNFINISHED: id=' . $id . ',column=' . $column . '[' . gettype($statusInfo) . '] = ' . $content[$column]);
945 // Add other columns as well
946 foreach (postRequestArray() as $key => $entries) {
948 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Found entry: ' . $key);
950 // Skip id, raw userid and 'do_$mode'
951 if (!in_array($key, array($idColumn[0], $rawUserId[0], ('do_' . $mode)))) {
952 // Are there brackets () at the end?
953 if (substr($entries[$id], -2, 2) == '()') {
954 // Direct SQL command found
955 $sql .= sprintf(' `%s`=%s,', sqlEscapeString($key), sqlEscapeString($entries[$id]));
958 $sql .= sprintf(" `%s`='%s',", sqlEscapeString($key), sqlEscapeString($entries[$id]));
961 $content[$key] = $entries[$id];
963 } elseif (isDebugModeEnabled()) {
965 logDebugMessage(__FUNCTION__, __LINE__, 'Skipped: ' . $key);
969 // Finish SQL statement
970 $sql = substr($sql, 0, -1) . sprintf(" WHERE `%s`=%s AND `%s`='%s' LIMIT 1",
978 sqlQuery($sql, __FUNCTION__, __LINE__);
980 // Send "build mails" out
981 sendGenericBuildMails($mode, $tableName, $content, $id, $statusInfo[$content[$column]], $userIdColumn);
985 // Delete rows by given id numbers
986 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()) {
987 // $tableName must be an array
988 if ((!is_array($tableName)) || (count($tableName) != 1)) {
989 // No tableName specified
990 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
991 } elseif (!is_array($idColumn)) {
992 // $idColumn is no array
993 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
994 } elseif (!is_array($userIdColumn)) {
995 // $userIdColumn is no array
996 reportBug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array: userIdColumn=' . $userIdColumn);
997 } elseif (!is_array($deleteNow)) {
998 // $deleteNow is no array
999 reportBug(__FUNCTION__, __LINE__, 'deleteNow[]=' . gettype($deleteNow) . '!=array: userIdColumn=' . $userIdColumn);
1002 // Shall we delete here or list for deletion?
1003 if ($deleteNow[0] === TRUE) {
1004 // Call generic function
1005 $affected = doGenericDeleteEntriesConfirm($tableName, $columns, $filterFunctions, $extraValues, $deleteNow, $idColumn, $userIdColumn, $rawUserId, $cacheFiles);
1008 if ($affected == countPostSelection($idColumn[0])) {
1010 displayMessage('{--ADMIN_ALL_ENTRIES_REMOVED--}');
1012 // Some are still there :(
1013 displayMessage(sprintf(getMessage('ADMIN_SOME_ENTRIES_NOT_DELETED'), sqlAffectedRows(), countPostSelection($idColumn[0])));
1016 // List for deletion confirmation
1017 adminListBuilder('delete', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId, $content);
1021 // Edit rows by given id numbers
1022 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()) {
1023 // $tableName must be an array
1024 if ((!is_array($tableName)) || (count($tableName) != 1)) {
1025 // No tableName specified
1026 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
1027 } elseif (!is_array($idColumn)) {
1028 // $idColumn is no array
1029 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
1030 } elseif (!is_array($userIdColumn)) {
1031 // $userIdColumn is no array
1032 reportBug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array: userIdColumn=' . $userIdColumn);
1033 } elseif (!is_array($editNow)) {
1034 // $editNow is no array
1035 reportBug(__FUNCTION__, __LINE__, 'editNow[]=' . gettype($editNow) . '!=array: userIdColumn=' . $userIdColumn);
1038 // Shall we change here or list for editing?
1039 if ($editNow[0] === TRUE) {
1040 // Call generic change method
1041 $affected = doGenericEditEntriesConfirm($tableName, $columns, $filterFunctions, $extraValues, $timeColumns, $editNow, $idColumn, $userIdColumn, $rawUserId, $cacheFiles);
1044 if ($affected == countPostSelection($idColumn[0])) {
1046 displayMessage('{--ADMIN_ALL_ENTRIES_EDITED--}');
1048 // Some are still there :(
1049 displayMessage(sprintf(getMessage('ADMIN_SOME_ENTRIES_NOT_EDITED'), $affected, countPostSelection($idColumn[0])));
1053 adminListBuilder('edit', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId, $content);
1057 // Un-/lock rows by given id numbers
1058 // @TODO rawUserId/content is not yet supported
1059 function adminLockEntriesConfirm ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $statusArray = array(), $lockNow = array(FALSE), $idColumn = array('id'), $userIdColumn = array('userid')) {
1060 // $tableName must be an array
1061 if ((!is_array($tableName)) || (count($tableName) != 1)) {
1062 // No tableName specified
1063 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
1064 } elseif (!is_array($idColumn)) {
1065 // $idColumn is no array
1066 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
1067 } elseif (!is_array($lockNow)) {
1068 // $lockNow is no array
1069 reportBug(__FUNCTION__, __LINE__, 'lockNow[]=' . gettype($lockNow) . '!=array: userIdColumn=' . $userIdColumn);
1072 // Shall we un-/lock here or list for locking?
1073 if ($lockNow[0] === TRUE) {
1075 adminBuilderStatusHandler('lock', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray);
1078 adminListBuilder('lock', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1082 // Undelete rows by given id numbers
1083 // @TODO rawUserId/cacheFiles/content is not yet supported
1084 function adminUndeleteEntriesConfirm ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $statusArray = array(), $undeleteNow = array(FALSE), $idColumn = array('id'), $userIdColumn = array('userid')) {
1085 // $tableName must be an array
1086 if ((!is_array($tableName)) || (count($tableName) != 1)) {
1087 // No tableName specified
1088 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
1089 } elseif (!is_array($idColumn)) {
1090 // $idColumn is no array
1091 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
1092 } elseif (!is_array($undeleteNow)) {
1093 // $undeleteNow is no array
1094 reportBug(__FUNCTION__, __LINE__, 'undeleteNow[]=' . gettype($undeleteNow) . '!=array: userIdColumn=' . $userIdColumn);
1097 // Shall we un-/lock here or list for locking?
1098 if ($undeleteNow[0] === TRUE) {
1100 adminBuilderStatusHandler('undelete', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray);
1103 adminListBuilder('undelete', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1107 // Adds a given entry to the database
1108 function adminAddEntries ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $timeColumns = array(), $columnIndex = NULL) {
1109 // Is the userid set?
1110 if (!isPostRequestElementSet('userid')) {
1111 // Then set NULL here
1112 setPostRequestElement('userid', NULL);
1115 // Call inner function
1116 doGenericAddEntries($tableName, $columns, $filterFunctions, $extraValues, $timeColumns, $columnIndex);
1118 // Entry has been added?
1119 if ((!ifSqlHasZeroAffectedRows()) && ($GLOBALS['__XML_PARSE_RESULT'] === TRUE)) {
1120 // Display success message
1121 displayMessage('{--ADMIN_ENTRY_ADDED--}');
1123 // Display failed message
1124 displayMessage('{--ADMIN_ENTRY_NOT_ADDED--}');
1128 // Checks proxy settins by fetching check-updates3.php from mxchange.org
1129 function adminTestProxySettings ($settingsArray) {
1130 // Set temporary the new settings
1131 mergeConfig($settingsArray);
1133 // Now get the test URL
1134 $content = sendHttpGetRequest('check-updates3.php');
1136 // Is the first line with "200 OK"?
1137 $valid = isInString('200 OK', $content[0]);
1143 // Sends out a link to the given email adress so the admin can reset his/her password
1144 function sendAdminPasswordResetLink ($email) {
1148 //Â Look up administator login
1149 $result = sqlQueryEscaped("SELECT `id`, `login`, `password` FROM `{?_MYSQL_PREFIX?}_admins` WHERE '%s' REGEXP `email` LIMIT 1",
1150 array($email), __FUNCTION__, __LINE__);
1152 // Is there an account?
1153 if (ifSqlHasZeroNums($result)) {
1155 return '{--ADMIN_NO_LOGIN_WITH_EMAIL--}';
1159 $content = sqlFetchArray($result);
1162 sqlFreeResult($result);
1164 // Generate hash for reset link
1165 $content['hash'] = generateHash(getUrl() . getEncryptSeparator() . $content['id'] . getEncryptSeparator() . $content['login'] . getEncryptSeparator() . $content['password'], substr($content['password'], getSaltLength()));
1168 unset($content['id']);
1169 unset($content['password']);
1172 $mailText = loadEmailTemplate('admin_reset_password', $content);
1175 sendEmail($email, '{--ADMIN_RESET_PASSWORD_LINK_SUBJECT--}', $mailText);
1178 return '{--ADMIN_RESET_PASSWORD_LINK_SENT--}';
1181 // Validate hash and login for password reset
1182 function adminResetValidateHashLogin ($hash, $login) {
1183 // By default nothing validates... ;)
1186 // Then try to find that user
1187 $result = sqlQueryEscaped("SELECT `id`, `password`, `email` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
1188 array($login), __FUNCTION__, __LINE__);
1190 // Is an account here?
1191 if (sqlNumRows($result) == 1) {
1193 $content = sqlFetchArray($result);
1195 // Generate hash again
1196 $hashFromData = generateHash(getUrl() . getEncryptSeparator() . $content['id'] . getEncryptSeparator() . $login . getEncryptSeparator() . $content['password'], substr($content['password'], getSaltLength()));
1199 $valid = ($hash == $hashFromData);
1203 sqlFreeResult($result);
1209 // Reset the password for the login. Do NOT call this function without calling above function first!
1210 function doResetAdminPassword ($login, $password) {
1211 // Generate hash (we already check for ext-sql_patches in generateHash())
1212 $passHash = generateHash($password);
1214 // Prepare fake POST data
1216 'login' => array(getAdminId($login) => $login),
1217 'password' => array(getAdminId($login) => $passHash),
1221 $message = adminsChangeAdminAccount($postData, '', FALSE);
1224 runFilterChain('post_form_reset_pass', array('login' => $login, 'hash' => $passHash, 'message' => $message));
1227 return '{--ADMIN_PASSWORD_RESET_DONE--}';
1230 // Solves a task by given id number
1231 function adminSolveTask ($id) {
1232 // Update the task data
1233 adminUpdateTaskData($id, 'status', 'SOLVED');
1236 // Marks a given task as deleted
1237 function adminDeleteTask ($id) {
1238 // Update the task data
1239 adminUpdateTaskData($id, 'status', 'DELETED');
1242 // Function to update task data
1243 function adminUpdateTaskData ($id, $row, $data) {
1244 // Should be admin and valid id
1246 // Not an admin so redirect better
1247 reportBug(__FUNCTION__, __LINE__, 'id=' . $id . ',row=' . $row . ',data=' . $data . ' - isAdmin()=false');
1248 } elseif ($id <= 0) {
1249 // Initiate backtrace
1250 reportBug(__FUNCTION__, __LINE__, sprintf('id is invalid: %s. row=%s, data=%s',
1258 sqlQueryEscaped("UPDATE `{?_MYSQL_PREFIX?}_task_system` SET `%s`='%s' WHERE `id`=%s LIMIT 1",
1263 ), __FUNCTION__, __LINE__);
1266 // Checks whether if the admin menu has entries
1267 function ifAdminMenuHasEntries ($action) {
1270 // Is the entry set?
1271 isset($GLOBALS['admin_menu_has_entries'][$action])
1273 // And do we have a menu for this action?
1274 $GLOBALS['admin_menu_has_entries'][$action] === TRUE
1276 // Login has always a menu
1282 // Setter for 'admin_menu_has_entries'
1283 function setAdminMenuHasEntries ($action, $hasEntries) {
1284 $GLOBALS['admin_menu_has_entries'][$action] = (bool) $hasEntries;
1287 // Creates a link to the user's admin-profile
1288 function adminCreateUserLink ($userid) {
1289 // Is the userid set correctly?
1290 if (isValidId($userid)) {
1291 // Create a link to that profile
1292 return '{%url=modules.php?module=admin&what=list_user&userid=' . bigintval($userid) . '%}';
1295 // Return a link to the user list
1296 return '{%url=modules.php?module=admin&what=list_user%}';
1299 // Generate a "link" for the given admin id (admin_id)
1300 function generateAdminLink ($adminId) {
1301 // No assigned admin is default
1302 $adminLink = '{--ADMIN_NO_ADMIN_ASSIGNED--}';
1304 // Zero? = Not assigned
1305 if (isValidId($adminId)) {
1306 // Load admin's login
1307 $login = getAdminLogin($adminId);
1309 // Is the login valid?
1310 if ($login != '***') {
1311 // Is the extension there?
1312 if (isExtensionActive('admins')) {
1314 $adminLink = '<a href="' . generateEmailLink(getAdminEmail($adminId), 'admins') . '" title="{--ADMIN_CONTACT_LINK_TITLE--}">' . $login . '</a>';
1316 // Extension not found
1317 $adminLink = '{%message,ADMIN_TASK_ROW_EXTENSION_NOT_INSTALLED=admins%}';
1321 $adminLink = '<div class="bad">{%message,ADMIN_ID_404=' . $adminId . '%}</div>';
1329 // Verifies if the current admin has confirmed to alter expert settings
1332 // 'failed' = Something goes wrong (default)
1333 // 'agreed' = Has verified and and confirmed it to see them
1334 // 'forbidden' = Has not the proper right to alter them
1335 // 'update' = Need to update extension 'admins'
1336 // 'ask' = A form was send to the admin
1337 function doVerifyExpertSettings () {
1338 // Default return status is failed
1341 // Is the extension installed and recent?
1342 if (isExtensionInstalledAndNewer('admins', '0.7.3')) {
1343 // Okay, load the status
1344 $expertSettings = getAminsExpertSettings();
1347 if ($expertSettings == 'Y') {
1348 // Okay, does he want to see them?
1349 if (isAdminsExpertWarningEnabled()) {
1351 if (isFormSent('save_expert')) {
1352 // Is the element set, then we need to change the admin
1353 if (isPostRequestElementSet('expert_settings')) {
1354 // Get it and prepare final post data array
1355 $postData['login'][getCurrentAdminId()] = getCurrentAdminLogin();
1356 $postData['expert_warning'][getCurrentAdminId()] = 'N';
1358 // Change it in the admin
1359 adminsChangeAdminAccount($postData, 'expert_warning');
1366 loadTemplate('admin_expert_settings_form');
1377 if ((isFormSent()) && (isPostRequestElementSet('expert_settings'))) {
1379 unsetPostRequestElement('ok');
1380 unsetPostRequestElement('expert_settings');
1384 $return = 'forbidden';
1387 // Out-dated extension or not installed
1391 // Output message for other status than ask/agreed
1392 if (($return != 'ask') && ($return != 'agreed')) {
1394 displayMessage('{--ADMIN_EXPERT_SETTINGS_STATUS_' . strtoupper($return) . '--}');
1401 // Generate link to unconfirmed mails for admin
1402 function generateUnconfirmedAdminLink ($id, $unconfirmed, $type) {
1404 $OUT = $unconfirmed;
1406 // Is there unconfirmed mails?
1407 if ($unconfirmed > 0) {
1408 // Add link to list_unconfirmed what-file
1409 $OUT = '<a href="{%url=modules.php?module=admin&what=list_unconfirmed&type=' . $type . '&id=' . $id . '%}">{%pipe,translateComma=' . $unconfirmed . '%}</a>';
1416 // Generates a navigation row for listing emails
1417 function addEmailNavigation ($numPages, $offset, $show_form, $colspan, $return=false) {
1418 // Don't do anything if $numPages is 1
1419 if ($numPages == 1) {
1420 // Abort here with empty content
1425 if ($show_form === FALSE) {
1430 for ($page = 1; $page <= $numPages; $page++) {
1431 // Is the page currently selected or shall we generate a link to it?
1432 if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
1433 // Is currently selected, so only highlight it
1434 $NAV .= '<strong>-';
1436 // Open anchor tag and add base URL
1437 $NAV .= '<a href="{%url=modules.php?module=admin&what=' . getWhat() . '&page=' . $page . '&offset=' . $offset;
1439 // Add userid when we shall show all mails from a single member
1440 if ((isGetRequestElementSet('userid')) && (isValidId(getRequestElement('userid')))) $NAV .= '&userid=' . bigintval(getRequestElement('userid'));
1442 // Close open anchor tag
1446 if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
1447 // Is currently selected, so only highlight it
1448 $NAV .= '-</strong>';
1454 // Add separator if total pages has not been reached
1455 if ($page < $numPages) {
1461 // Define constants only once
1462 $content['nav'] = $NAV;
1463 $content['span'] = $colspan;
1464 $content['top'] = $TOP;
1466 // Load navigation template
1467 $OUT = loadTemplate('admin_email_nav_row', TRUE, $content);
1469 if ($return === TRUE) {
1470 // Return generated HTML-Code
1478 // Process menu editing form
1479 function adminProcessMenuEditForm ($type, $subMenu) {
1480 // An action is done...
1481 foreach (postRequestElement('sel') as $sel => $menu) {
1482 $AND = "(`what` = '' OR `what` IS NULL)";
1484 $sel = bigintval($sel);
1486 if (!empty($subMenu)) {
1487 $AND = "`action`='" . $subMenu . "'";
1490 switch (postRequestElement('ok')) {
1491 case 'edit': // Edit menu
1492 // Shall we update a menu or sub menu?
1493 if (!isGetRequestElementSet('sub')) {
1494 // Update with 'what'=null
1495 sqlQueryEscaped("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET `title`='%s',`action`='%s',`what`=NULL WHERE ".$AND." AND `id`=%s LIMIT 1",
1499 postRequestElement('sel_action', $sel),
1501 ), __FUNCTION__, __LINE__);
1503 // Update with selected 'what'
1504 sqlQueryEscaped("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET `title`='%s',`action`='%s',`what`='%s' WHERE ".$AND." AND `id`=%s LIMIT 1",
1508 postRequestElement('sel_action', $sel),
1509 postRequestElement('sel_what', $sel),
1511 ), __FUNCTION__, __LINE__);
1515 case 'delete': // Delete menu
1516 sqlQueryEscaped("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE ".$AND." AND `id`=%s LIMIT 1",
1520 ), __FUNCTION__, __LINE__);
1523 case 'status': // Change status of menus
1524 sqlQueryEscaped("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET `visible`='%s',`locked`='%s' WHERE ".$AND." AND `id`=%s LIMIT 1",
1527 postRequestElement('visible', $sel),
1528 postRequestElement('locked', $sel),
1530 ), __FUNCTION__, __LINE__);
1533 default: // Unexpected action
1534 logDebugMessage(__FUNCTION__, __LINE__, sprintf('Unsupported action %s detected.', postRequestElement('ok')));
1535 displayMessage('{%message,ADMIN_UNKNOWN_OKAY=' . postRequestElement('ok') . '%}');
1541 displayMessage('{--SETTINGS_SAVED--}');
1544 // Handle weightning
1545 function doAdminProcessMenuWeightning ($type, $AND) {
1546 // Are there all required (generalized) GET parameter?
1547 if ((isGetRequestElementSet('act')) && (isGetRequestElementSet('tid')) && (isGetRequestElementSet('fid'))) {
1549 $tid = ''; $fid = '';
1552 if (isGetRequestElementSet('w')) {
1553 // Sub menus selected
1554 $result = sqlQueryEscaped("SELECT `id` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `action`='%s' AND `sort`=%s LIMIT 1",
1557 getRequestElement('act'),
1558 bigintval(getRequestElement('tid'))
1559 ), __FUNCTION__, __LINE__);
1560 list($tid) = sqlFetchRow($result);
1561 sqlFreeResult($result);
1562 $result = sqlQueryEscaped("SELECT `id` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `action`='%s' AND `sort`=%s LIMIT 1",
1565 getRequestElement('act'),
1566 bigintval(getRequestElement('fid'))
1567 ), __FUNCTION__, __LINE__);
1568 list($fid) = sqlFetchRow($result);
1569 sqlFreeResult($result);
1571 // Main menu selected
1572 $result = sqlQueryEscaped("SELECT `id` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE (`what`='' OR `what` IS NULL) AND `sort`=%s LIMIT 1",
1575 bigintval(getRequestElement('tid'))
1576 ), __FUNCTION__, __LINE__);
1577 list($tid) = sqlFetchRow($result);
1578 sqlFreeResult($result);
1579 $result = sqlQueryEscaped("SELECT `id` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE (`what`='' OR `what` IS NULL) AND `sort`=%s LIMIT 1",
1582 bigintval(getRequestElement('fid'))
1583 ), __FUNCTION__, __LINE__);
1584 list($fid) = sqlFetchRow($result);
1585 sqlFreeResult($result);
1588 if ((!empty($tid)) && (!empty($fid))) {
1590 sqlQueryEscaped("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET `sort`=%s WHERE ".$AND." AND `id`=%s LIMIT 1",
1593 bigintval(getRequestElement('tid')),
1595 ), __FUNCTION__, __LINE__);
1596 sqlQueryEscaped("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET `sort`=%s WHERE ".$AND." AND `id`=%s LIMIT 1",
1599 bigintval(getRequestElement('fid')),
1601 ), __FUNCTION__, __LINE__);
1606 // Function to register first admin
1607 function registerFirstAdmin () {
1608 // Make sure that no admin is registered
1609 assert(!isAdminRegistered());
1611 // Admin is not registered so we have to inform the user
1612 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')))) {
1613 setPostRequestElement('add_first_admin', '***');
1616 // Clear error message
1620 // Is form for first admin sent?
1621 if ((isFormSent('add_first_admin')) && (postRequestElement('add_first_admin') != '***')) {
1622 // Hash the password with the old function because we are here in install mode
1623 $hashedPass = md5(postRequestElement('admin_password1'));
1625 // Kill maybe existing session variables
1626 destroyAdminSession();
1629 $ret = addAdminAccount(postRequestElement('admin_login'), $hashedPass, getWebmaster(), 'allow');
1631 // Check if registration wents fine
1634 // Change ADMIN_REGISTERED entry
1635 $done = changeDataInLocalConfigurationFile('ADMIN-SETUP', "setConfigEntry('ADMIN_REGISTERED', '", "');", 'Y', 0);
1637 // Was it successfull?
1638 if ($done === TRUE) {
1639 // Registering is done
1640 redirectToUrl('modules.php?module=admin&register=done');
1642 // Registration incomplete
1643 $errorMessage = '{--ADMIN_CANNOT_COMPLETE--}';
1645 // Set this to have our error message displayed
1646 setPostRequestElement('add_first_admin', '***');
1650 case 'failed': // Registration has failed
1651 $errorMessage = '{--ADMIN_REGISTER_FAILED--}';
1653 // Set this to have our error message displayed
1654 setPostRequestElement('add_first_admin', '***');
1657 case 'already': // Admin does already exists!
1658 $errorMessage = '{--ADMIN_LOGIN_ALREADY_REG--}';
1660 // Set this to have our error message displayed
1661 setPostRequestElement('add_first_admin', '***');
1665 // Any other kind will be logged
1666 $errorMessage = sprintf('Unknown return code %s from ifAdminLoginDataIsValid().', $ret);
1667 logDebugMessage(__FUNCTION__, __LINE__, $errorMessage);
1669 // Set this to have our error message displayed
1670 setPostRequestElement('add_first_admin', '***');
1675 // Whas that action okay?
1676 if ($ret != 'done') {
1678 $content['admin_login'] = '';
1679 if (isPostRequestElementSet('admin_login')) {
1680 $content['admin_login'] = postRequestElement('admin_login');
1683 // Init array elements
1684 $content['login_message'] = '';
1685 $content['password1_message'] = '';
1686 $content['password2_message'] = '';
1687 $content['error_message'] = '';
1689 // Yet-another notice-fix
1690 if ((isFormSent('add_first_admin')) && (postRequestElement('add_first_admin') == '***')) {
1693 $password1Message = '';
1694 $password2Message = '';
1696 // No login entered?
1697 if (empty($content['admin_login'])) {
1698 $loginMessage = '{--ADMIN_NO_LOGIN--}';
1701 // An error comes back from registration?
1702 if ((!empty($ret)) && ($ret != 'init')) {
1703 $loginMessage = $errorMessage;
1706 // No password 1 entered or to short?
1707 if (!isPostRequestElementSet('admin_password1')) {
1708 $password1Message = '{--ADMIN_NO_PASSWORD1--}';
1709 } elseif (!isStrongPassword(postRequestElement('admin_password1'))) {
1710 $password1Message = '{--ADMIN_WEAK_PASSWORD1--}';
1713 // No password 2 entered or to short?
1714 if (!isPostRequestElementSet('admin_password2')) {
1715 $password2Message = '{--ADMIN_NO_PASSWORD2--}';
1716 } elseif (!isStrongPassword(postRequestElement('admin_password2'))) {
1717 $password2Message = '{--ADMIN_WEAK_PASSWORD2--}';
1720 // Both didn't match?
1721 if (postRequestElement('admin_password1') != postRequestElement('admin_password2')) {
1723 if (empty($password1Message)) $password1Message = '{--ADMIN_PASSWORD1_MISMATCH--}';
1724 if (empty($password2Message)) $password2Message = '{--ADMIN_PASSWORD2_MISMATCH--}';
1727 // Output error messages
1728 $content['login_message'] = loadTemplate('admin_login_msg', TRUE, $loginMessage);
1729 $content['password1_message'] = loadTemplate('admin_login_msg', TRUE, $password1Message);
1730 $content['password2_message'] = loadTemplate('admin_login_msg', TRUE, $password2Message);
1731 $content['error_message'] = loadTemplate('admin_login_msg', TRUE, $errorMessage);
1734 // Output message in seperate template
1735 displayMessage('{--ADMIN_ACCOUNT_NOT_REGISTERED_YET--}');
1737 // Load register template
1738 loadTemplate('admin_reg_form', FALSE, $content);