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 * Needs to be in all Files and every File needs "svn propset *
18 * svn:keywords Date Revision" (autoprobset!) at least!!!!!! *
19 * -------------------------------------------------------------------- *
20 * Copyright (c) 2003 - 2009 by Roland Haeder *
21 * Copyright (c) 2009, 2010 by Mailer Developer Team *
22 * For more information visit: http://www.mxchange.org *
24 * This program is free software; you can redistribute it and/or modify *
25 * it under the terms of the GNU General Public License as published by *
26 * the Free Software Foundation; either version 2 of the License, or *
27 * (at your option) any later version. *
29 * This program is distributed in the hope that it will be useful, *
30 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
31 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
32 * GNU General Public License for more details. *
34 * You should have received a copy of the GNU General Public License *
35 * along with this program; if not, write to the Free Software *
36 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
38 ************************************************************************/
40 // Some security stuff...
41 if (!defined('__SECURITY')) {
45 // Register an administrator account
46 function addAdminAccount ($adminLogin, $passHash, $adminEmail) {
47 // Login does already exist
51 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
52 array($adminLogin), __FUNCTION__, __LINE__);
54 // Is the entry there?
55 if (SQL_HASZERONUMS($result)) {
56 // Ok, let's create the admin login
57 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_admins` (`login`, `password`, `email`) VALUES ('%s', '%s', '%s')",
62 ), __FUNCTION__, __LINE__);
69 SQL_FREERESULT($result);
75 // This function will be executed when the admin is not logged in and has submitted his login data
76 function ifAdminLoginDataIsValid ($adminLogin, $adminPassword) {
77 // First of all, no admin login is found
80 // Then we need to lookup the login name by getting the admin hash
81 $adminHash = getAdminHash($adminLogin);
83 // If this is fine, we can continue
84 if ($adminHash != '-1') {
85 // Get admin id and set it as current
86 setCurrentAdminId(getAdminId($adminLogin));
88 // Now, we need to encode the password in the same way the one is encoded in database
89 $testHash = generateHash($adminPassword, $adminHash);
91 // If they both match, the login data is valid
92 if ($testHash == $adminHash) {
101 // Prepare data array
103 'login' => $adminLogin,
104 'plain_pass' => $adminPassword,
105 'pass_hash' => $adminHash
108 // Run a special filter
109 runFilterChain('do_admin_login_' . $ret, $data);
115 // Only be executed on cookie checking
116 function ifAdminCookiesAreValid ($adminLogin, $passHash) {
117 // First of all, no admin login is found
120 // Then we need to lookup the login name by getting the admin hash
121 $adminHash = getAdminHash($adminLogin);
123 // If this is fine, we can continue
124 if ($adminHash != '-1') {
125 // Now, we need to encode the password in the same way the one is encoded in database
126 $testHash = encodeHashForCookie($adminHash);
127 //* DEBUG: */ outputHtml('adminLogin='.$adminLogin.',<br />passHash='.$passHash.',<br />adminHash='.$adminHash.',<br />testHash='.$testHash.'<br />');
129 // If they both match, the login data is valid
130 if ($testHash == $passHash) {
140 //* DEBUG: */ outputHtml('ret='.$ret);
144 // Do an admin action
145 function doAdminAction () {
149 //* DEBUG: */ outputHtml(__LINE__.'*'.$what.'/'.getModule().'/'.getAction().'/'.getWhat().'*<br />');
151 // Remove any spaces from variable
153 // Default admin action is the overview page
157 $what = secureString($what);
161 $action = getActionFromModuleWhat(getModule(), $what);
163 // Define admin login name and id number
164 $content['login'] = getSession('admin_login');
165 $content['id'] = getCurrentAdminId();
168 if (isExtensionActive('admins')) {
169 $content['welcome'] = loadTemplate('admin_welcome_admins', true, $content);
171 $content['welcome'] = loadTemplate('admin_welcome', true, $content);
173 $content['footer'] = loadTemplate('admin_footer' , true, $content);
174 $content['menu'] = addAdminMenu($action, $what, true);
177 loadTemplate('admin_main_header', false, $content);
179 // Check if action/what pair is valid
180 $result_action = SQL_QUERY_ESC("SELECT
183 `{?_MYSQL_PREFIX?}_admin_menu`
188 `what`='%s' AND `what` != 'overview'
191 `what`='' OR `what` IS NULL
202 ), __FUNCTION__, __LINE__);
204 // Do we have an entry?
205 if (SQL_NUMROWS($result_action) == 1) {
206 // Is valid but does the inlcude file exists?
207 $inc = sprintf("inc/modules/admin/action-%s.php", $action);
208 if ((isIncludeReadable($inc)) && (isMenuActionValid('admin', $action, $what)) && ($GLOBALS['acl_allow'] === true)) {
209 // Ok, we finally load the admin action module
211 } elseif ($GLOBALS['acl_allow'] === false) {
213 loadTemplate('admin_menu_failed', false, getMaskedMessage('ADMIN_ACCESS_DENIED', $what));
215 // Include file not found! :-(
216 loadTemplate('admin_menu_failed', false, getMaskedMessage('ADMIN_ACTION_404', $action));
219 // Invalid action/what pair found!
220 loadTemplate('admin_menu_failed', false, getMaskedMessage('ADMIN_ACTION_INVALID', $action . '/' . $what));
224 SQL_FREERESULT($result_action);
227 loadTemplate('admin_main_footer', false, $content);
230 // Adds an admin menu
231 function addAdminMenu ($action, $what, $return=false) {
237 $GLOBALS['menu']['description'] = array();
238 $GLOBALS['menu']['title'] = array();
241 $result_main = SQL_QUERY("SELECT
242 `action`, `title`, `descr`
244 `{?_MYSQL_PREFIX?}_admin_menu`
246 (`what`='' OR `what` IS NULL)
249 `id` DESC", __FUNCTION__, __LINE__);
251 // Do we have entries?
252 if (SQL_NUMROWS($result_main) > 0) {
253 $OUT .= '<ul class="admin_menu_main">';
254 // @TODO Rewrite this to $content = SQL_FETCHARRAY()
255 while (list($menu, $title, $descr) = SQL_FETCHROW($result_main)) {
256 if ((isExtensionActive('admins')) && (getExtensionVersion('admins') > '0.2.0')) {
257 $ACL = adminsCheckAdminAcl($menu, '');
259 // @TODO ACL is 'allow'... hmmm
264 $inc = sprintf("inc/modules/admin/action-%s.php", $menu);
266 // Is the file readable?
267 $readable = isIncludeReadable($inc);
270 if ($SUB === false) {
271 // Insert compiled menu title and description
272 $GLOBALS['menu']['title'][$menu] = $title;
273 $GLOBALS['menu']['description'][$menu] = $descr;
275 $OUT .= '<li class="admin_menu">
276 <div class="nobr"><strong>·</strong> ';
278 if ($readable === true) {
279 if (($menu == $action) && (empty($what))) {
282 $OUT .= '[<a href="{%url=modules.php?module=admin&action=' . $menu . '%}">';
285 $OUT .= '<em style="cursor:help" class="admin_note" title="{--MENU_ACTION_404--}">';
290 if ($readable === true) {
291 if (($menu == $action) && (empty($what))) {
303 // Check for menu entries
304 $result_what = SQL_QUERY_ESC("SELECT
305 `what`, `title`, `descr`
307 `{?_MYSQL_PREFIX?}_admin_menu`
315 array($menu), __FUNCTION__, __LINE__);
317 // Remember the count for later checks
318 setAdminMenuHasEntries($menu, ((SQL_NUMROWS($result_what) > 0) && ($action == $menu)));
320 // Do we have entries?
321 if ((ifAdminMenuHasEntries($menu)) && (SQL_NUMROWS($result_what) > 0)) {
322 $GLOBALS['menu']['description'] = array();
323 $GLOBALS['menu']['title'] = array(); $SUB = true;
324 $OUT .= '<li class="admin_menu_sub"><ul class="admin_menu_sub">';
325 // @TODO Rewrite this to $content = SQL_FETCHARRAY()
326 while (list($what_sub, $title_what, $desc_what) = SQL_FETCHROW($result_what)) {
327 // Check for access level
328 if ((isExtensionActive('admins')) && (getExtensionVersion('admins') > '0.2.0')) {
329 $ACL = adminsCheckAdminAcl('', $what_sub);
331 // @TODO ACL is 'allow'... hmmm
336 $inc = sprintf("inc/modules/admin/what-%s.php", $what_sub);
338 // Is the file readable?
339 $readable = isIncludeReadable($inc);
343 // Insert compiled title and description
344 $GLOBALS['menu']['title'][$what_sub] = $title_what;
345 $GLOBALS['menu']['description'][$what_sub] = $desc_what;
346 $OUT .= '<li class="admin_menu">
347 <div class="nobr"><strong>--></strong> ';
348 if ($readable === true) {
349 if ($what == $what_sub) {
352 $OUT .= '[<a href="{%url=modules.php?module=admin&what=' . $what_sub . '%}">';
355 $OUT .= '<em style="cursor:help" class="admin_note" title="{--MENU_WHAT_404--}">';
360 if ($readable === true) {
361 if ($what == $what_sub) {
375 SQL_FREERESULT($result_what);
383 SQL_FREERESULT($result_main);
387 // Is there a cache instance again?
388 // Return or output content?
389 if ($return === true) {
396 // Create member selection box
397 function addMemberSelectionBox ($def = 0, $add_all = false, $return = false, $none = false, $field = 'userid') {
398 // Output selection form with all confirmed user accounts listed
399 $result = SQL_QUERY("SELECT `userid`, `surname`, `family` FROM `{?_MYSQL_PREFIX?}_user_data` ORDER BY `userid` ASC", __FUNCTION__, __LINE__);
404 // USe this only for adding points (e.g. adding refs really makes no sence ;-) )
405 if ($add_all === true) $OUT = ' <option value="all">{--ALL_MEMBERS--}</option>';
406 elseif ($none === true) $OUT = ' <option value="0">{--SELECT_NONE--}</option>';
408 while ($content = SQL_FETCHARRAY($result)) {
409 $OUT .= '<option value="' . bigintval($content['userid']) . '"';
410 if ($def == $content['userid']) $OUT .= ' selected="selected"';
411 $OUT .= '>' . $content['surname'] . ' ' . $content['family'] . ' (' . bigintval($content['userid']) . ')</option>';
415 SQL_FREERESULT($result);
417 if ($return === false) {
418 // Remeber options in constant
419 $content['member_selection'] = $OUT;
420 $content['what'] = getWhat();
423 loadTemplate('admin_member_selection_box', false, $content);
425 // Return content in selection frame
426 return '<select class="admin_select" name="' . handleFieldWithBraces($field) . '" size="1">' . $OUT . '</select>';
430 // Create a menu selection box for given menu system
431 // @TODO Try to rewrite this to adminAddMenuSelectionBox()
433 function adminMenuSelectionBox_DEPRECATED ($mode, $default = '', $defid = '') {
434 $what = "`what` != ''";
435 if ($mode == 'action') $what = "(`what`='' OR `what` IS NULL) AND `action` !='login'";
437 $result = SQL_QUERY_ESC("SELECT `%s` AS `menu`, `title` FROM `{?_MYSQL_PREFIX?}_admin_menu` WHERE ".$what." ORDER BY `sort` ASC",
438 array($mode), __FUNCTION__, __LINE__);
439 if (SQL_NUMROWS($result) > 0) {
440 // Load menu as selection
441 $OUT = '<select name="' . $mode . '_menu';
442 if ((!empty($defid)) || ($defid == '0')) $OUT .= '[' . $defid . ']';
443 $OUT .= '" size="1" class="admin_select">
444 <option value="">{--SELECT_NONE--}</option>';
446 while ($content = SQL_FETCHARRAY($result)) {
447 $OUT .= '<option value="' . $content['menu'] . '"';
448 if ((!empty($default)) && ($default == $content['menu'])) $OUT .= ' selected="selected"';
449 $OUT .= '>' . $content['title'] . '</option>';
453 SQL_FREERESULT($result);
455 // Add closing select-tag
459 $OUT = getMessage('ADMIN_PROBLEM_NO_MENU');
466 // Wrapper for $_POST and adminSaveSettings
467 function adminSaveSettingsFromPostData ($tableName = '_config', $whereStatement = '`config`=0', $translateComma = array(), $alwaysAdd = false, $displayMessage = true) {
469 $postData = postRequestArray();
471 // Call the lower function
472 adminSaveSettings($postData, $tableName, $whereStatement, $translateComma, $alwaysAdd, $displayMessage);
475 // Save settings to the database
476 function adminSaveSettings (&$postData, $tableName = '_config', $whereStatement = '`config`=0', $translateComma = array(), $alwaysAdd = false, $displayMessage = true) {
477 // Prepare all arrays, variables
478 $tableData = array();
481 // Now, walk through all entries and prepare them for saving
482 foreach ($postData as $id => $val) {
483 // Process only formular field but not submit buttons ;)
485 // Do not save the ok value
486 convertSelectionsToTimestamp($postData, $tableData, $id, $skip);
488 // Shall we process this id? It muss not be empty, of course
489 if (($skip === false) && (!empty($id)) && ((!isset($GLOBALS['skip_config'][$id]))) || ($tableName != '_config')) {
490 // Translate the value? (comma to dot!)
491 if ((is_array($translateComma)) && (in_array($id, $translateComma))) {
492 // Then do it here... :)
493 $val = convertCommaToDot($val);
496 // Shall we add numbers or strings?
498 if ('' . $val . '' == '' . $test . '') {
500 $tableData[] = sprintf("`%s`=%s", $id, $test);
501 } elseif (is_null($val)) {
503 $tableData[] = sprintf("`%s`=NULL", $id);
506 $tableData[] = sprintf("`%s`='%s'", $id, trim($val));
509 // Do not add a config entry twice
510 $GLOBALS['skip_config'][$id] = true;
512 // Update current configuration
513 setConfigEntry($id, $val);
518 // Check if entry does exist
520 if ($alwaysAdd === false) {
521 if (!empty($whereStatement)) {
522 $result = SQL_QUERY("SELECT * FROM `{?_MYSQL_PREFIX?}" . $tableName . "` WHERE " . $whereStatement . " LIMIT 1", __FUNCTION__, __LINE__);
524 $result = SQL_QUERY("SELECT * FROM `{?_MYSQL_PREFIX?}" . $tableName . "` LIMIT 1", __FUNCTION__, __LINE__);
528 if (SQL_NUMROWS($result) == 1) {
529 // "Implode" all data to single string
530 $updatedData = implode(', ', $tableData);
532 // Generate SQL string
533 $sql = sprintf("UPDATE `{?_MYSQL_PREFIX?}%s` SET %s WHERE %s LIMIT 1",
539 // Add Line (does only work with auto_increment!
540 $keys = array(); $values = array();
541 foreach ($tableData as $entry) {
543 $line = explode('=', $entry);
545 $values[] = $line[1];
548 // Add both in one line
549 $keys = implode('`, `', $keys);
550 $values = implode(', ', $values);
552 // Generate SQL string
553 $sql = sprintf("INSERT INTO `{?_MYSQL_PREFIX?}%s` (%s) VALUES (%s)",
561 SQL_FREERESULT($result);
563 // Simply run generated SQL string
564 SQL_QUERY($sql, __FUNCTION__, __LINE__);
566 // Remember affected rows
567 $affected = SQL_AFFECTEDROWS();
570 rebuildCache('config', 'config');
572 // Settings saved, so display message?
573 if ($displayMessage === true) loadTemplate('admin_settings_saved', false, getMessage('SETTINGS_SAVED'));
575 // Return affected rows
579 // Generate a selection box
580 function adminAddMenuSelectionBox ($menu, $type, $name, $default = '') {
581 // Open the requested menu directory
582 $menuArray = getArrayFromDirectory(sprintf("inc/modules/%s/", $menu), '', false, false);
584 // Init the selection box
585 $OUT = '<select name="' . $name . '" class="admin_select" size="1"><option value="">{--IS_TOP_MENU--}</option>';
587 // Walk through all files
588 foreach ($menuArray as $file) {
589 // Is this a PHP script?
590 if ((!isDirectory($file)) && (strpos($file, '' . $type . '-') > -1) && (strpos($file, '.php') > 0)) {
591 // Then test if the file is readable
592 $test = sprintf("inc/modules/%s/%s", $menu, $file);
594 // Is the file there?
595 if (isIncludeReadable($test)) {
596 // Extract the value for what=xxx
597 $part = substr($file, (strlen($type) + 1));
598 $part = substr($part, 0, -4);
600 // Is that part different from the overview?
601 if ($part != 'overview') {
602 $OUT .= '<option value="' . $part . '"';
603 if ($part == $default) $OUT .= ' selected="selected"';
604 $OUT .= '>' . $part . '</option>';
610 // Close selection box
617 // Creates a user-profile link for the admin. This function can also be used for many other purposes
618 function generateUserProfileLink ($userid, $title = '', $what = 'list_user') {
619 if (($title == '') && ($userid > 0)) {
620 // Set userid as title
622 } elseif ($userid == 0) {
623 // User id zero is invalid
624 return '<strong>' . $userid . '</strong>';
627 if (($title == '0') && ($what == 'list_refs')) {
628 // Return title again
630 } elseif (isExtensionActive('nickname')) {
632 $nick = getNickname($userid);
634 // Is it not empty, use it as title else the userid
635 if (!empty($nick)) $title = $nick . '(' . $userid . ')'; else $title = $userid;
639 return '[<a href="{%url=modules.php?module=admin&what=' . $what . '&userid=' . $userid . '%}" title="{--ADMIN_USER_PROFILE_TITLE--}">' . $title . '</a>]';
642 // Check "logical-area-mode"
643 function adminGetMenuMode () {
644 // Set the default menu mode as the mode for all admins
645 $mode = getConfig('admin_menu');
649 $adminId = getCurrentAdminId();
651 // Check individual settings of current admin
652 if (isset($GLOBALS['cache_array']['admin']['la_mode'][$adminId])) {
654 $adminMode = $GLOBALS['cache_array']['admin']['la_mode'][$adminId];
655 incrementStatsEntry('cache_hits');
656 } elseif (isExtensionInstalledAndNewer('admins', '0.6.7')) {
657 // Load from database when version of 'admins' is enough
658 $result = SQL_QUERY_ESC("SELECT la_mode FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
659 array($adminId), __FUNCTION__, __LINE__);
661 // Do we have an entry?
662 if (SQL_NUMROWS($result) == 1) {
664 list($adminMode) = SQL_FETCHROW($result);
668 SQL_FREERESULT($result);
671 // Check what the admin wants and set it when it's not the default mode
672 if ($adminMode != 'global') $mode = $adminMode;
674 // Return admin-menu's mode
678 // Change activation status
679 function adminChangeActivationStatus ($IDs, $table, $row, $idRow = 'id') {
680 $cnt = '0'; $newStatus = 'Y';
681 if ((is_array($IDs)) && (count($IDs) > 0)) {
682 // "Walk" all through and count them
683 foreach ($IDs as $id => $selected) {
684 // Secure the id number
685 $id = bigintval($id);
687 // Should always be set... ;-)
688 if (!empty($selected)) {
689 // Determine new status
690 $result = SQL_QUERY_ESC("SELECT %s FROM `{?_MYSQL_PREFIX?}_%s` WHERE %s=%s LIMIT 1",
691 array($row, $table, $idRow, $id), __FUNCTION__, __LINE__);
694 if (SQL_NUMROWS($result) == 1) {
696 list($currStatus) = SQL_FETCHROW($result);
698 // And switch it N<->Y
699 if ($currStatus == 'Y') $newStatus = 'N'; else $newStatus = 'Y';
701 // Change this status
702 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s` SET %s='%s' WHERE %s=%s LIMIT 1",
703 array($table, $row, $newStatus, $idRow, $id), __FUNCTION__, __LINE__);
705 // Count up affected rows
706 $cnt += SQL_AFFECTEDROWS();
710 SQL_FREERESULT($result);
715 loadTemplate('admin_settings_saved', false, sprintf(getMessage('ADMIN_STATUS_CHANGED'), $cnt, count($IDs)));
718 loadTemplate('admin_settings_saved', false, getMessage('ADMIN_NOTHING_SELECTED_CHANGE'));
722 // Send mails for del/edit/lock build modes
723 function sendAdminBuildMails ($mode, $table, $content, $id, $subjectPart = '') {
724 // Default subject is the subject part
725 $subject = $subjectPart;
727 // Is the subject part not set?
728 if (empty($subjectPart)) {
729 // Then use it from the mode
730 $subject = strtoupper($mode);
733 // Is the raw userid set?
734 if (postRequestParameter('userid_raw', $id) > 0) {
736 $subjectLine = getMessage('MEMBER_'.strtoupper($subject).'_'.strtoupper($table).'_SUBJECT');
738 // Load email template
739 if (!empty($subjectPart)) {
740 $mail = loadEmailTemplate('member_' . $mode . '_' . strtolower($subjectPart) . '_' . $table, $content);
742 $mail = loadEmailTemplate('member_' . $mode . '_' . $table, $content);
746 sendEmail(postRequestParameter('userid_raw', $id), $subjectLine, $mail);
750 $subjectLine = getMessage('ADMIN_'.strtoupper($subject).'_'.strtoupper($table).'_SUBJECT');
752 // Send admin notification out
753 if (!empty($subjectPart)) {
754 sendAdminNotification($subjectLine, 'admin_' . $mode . '_' . strtolower($subjectPart) . '_' . $table, $content, postRequestParameter('userid_raw', $id));
756 sendAdminNotification($subjectLine, 'admin_' . $mode . '_' . $table, $content, postRequestParameter('userid_raw', $id));
760 // Build a special template list
761 function adminListBuilder ($listType, $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn) {
764 // "Walk"Â through all entries
765 foreach ($IDs as $id => $selected) {
767 $id = bigintval($id);
769 // Get result from a given column array and table name
770 $result = SQL_RESULT_FROM_ARRAY($table, $columns, $idColumn, $id, __FUNCTION__, __LINE__);
772 // Is there one entry?
773 if (SQL_NUMROWS($result) == 1) {
775 $content = SQL_FETCHARRAY($result);
778 foreach ($content as $key => $value) {
780 $idx = array_search($key, $columns, true);
782 //Â Do we have a userid?
783 if ($key == 'userid') {
784 // Add it again as raw id
785 $content['userid_raw'] = bigintval($value);
788 // If the key matches the idColumn variable, we need to temporary remember it
789 //* DEBUG: */ print 'key=' . $key . ',idColumn=' . $idColumn . ',value=' . $value . '<br />';
790 if ($key == $idColumn) {
791 // Found, so remember it
792 $GLOBALS['admin_list_builder_id_value'] = $value;
795 // Handle the call in external function
796 //* DEBUG: */ print 'key=' . $key . ',fucntion=' . $filterFunctions[$idx] . ',value=' . $value . '<br />';
797 $content[$key] = handleExtraValues($filterFunctions[$idx], $value, $extraValues[$idx]);
800 // Add color switching
801 $content['sw'] = $SW;
804 $OUT .= loadTemplate(sprintf("admin_%s_%s_row",
815 SQL_FREERESULT($result);
818 // Load master template
819 loadTemplate(sprintf("admin_%s_%s",
826 // Change status of "build" list
827 function adminBuilderStatusHandler ($mode, $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray) {
828 // All valid entries? (We hope so here!)
829 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues)) && (count($statusArray) > 0)) {
830 // "Walk" through all entries
831 foreach ($IDs as $id => $sel) {
832 // Construct SQL query
833 $sql = sprintf("UPDATE `{?_MYSQL_PREFIX?}_%s` SET", SQL_ESCAPE($table));
835 // Load data of entry
836 $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`=%s LIMIT 1",
837 array($table, $idColumn, $id), __FUNCTION__, __LINE__);
840 $content = SQL_FETCHARRAY($result);
843 SQL_FREERESULT($result);
845 // Add all status entries (e.g. status column last_updated or so)
846 $newStatus = 'UNKNOWN';
847 $oldStatus = 'UNKNOWN';
848 $statusColumn = 'unknown';
849 foreach ($statusArray as $column => $statusInfo) {
850 // Does the entry exist?
851 if ((isset($content[$column])) && (isset($statusInfo[$content[$column]]))) {
852 // Add these entries for update
853 $sql .= sprintf(" %s='%s',", SQL_ESCAPE($column), SQL_ESCAPE($statusInfo[$content[$column]]));
856 if ($statusColumn == 'unknown') {
857 // Always (!!!) change status column first!
858 $oldStatus = $content[$column];
859 $newStatus = $statusInfo[$oldStatus];
860 $statusColumn = $column;
862 } elseif (isset($content[$column])) {
864 app_die(__FUNCTION__, __LINE__, ":UNFINISHED: id={$id}/{$column}[".gettype($statusInfo)."] = {$content[$column]}");
868 // Add other columns as well
869 foreach (postRequestArray() as $key => $entries) {
871 logDebugMessage(__FUNCTION__, __LINE__, 'Found entry: ' . $key);
873 // Skip id, raw userid and 'do_$mode'
874 if (!in_array($key, array($idColumn, 'userid_raw', ('do_' . $mode)))) {
875 // Are there brackets () at the end?
876 if (substr($entries[$id], -2, 2) == '()') {
877 // Direct SQL command found
878 $sql .= sprintf(" %s=%s,", SQL_ESCAPE($key), SQL_ESCAPE($entries[$id]));
881 $sql .= sprintf(" %s='%s',", SQL_ESCAPE($key), SQL_ESCAPE($entries[$id]));
884 $content[$key] = $entries[$id];
888 logDebugMessage(__FUNCTION__, __LINE__, 'Skipped: ' . $key);
892 // Finish SQL statement
893 $sql = substr($sql, 0, -1) . sprintf(" WHERE `%s`=%s AND `%s`='%s' LIMIT 1",
901 SQL_QUERY($sql, __FUNCTION__, __LINE__);
903 // Do we have an URL?
904 if (isset($content['url'])) {
905 // Then add a framekiller test as well
906 $content['frametester'] = generateFrametesterUrl($content['url']);
909 // Send "build mails" out
910 sendAdminBuildMails($mode, $table, $content, $id, $statusInfo[$content[$column]]);
915 // Delete rows by given id numbers
916 function adminDeleteEntriesConfirm ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $deleteNow=false, $idColumn='id', $userIdColumn='userid') {
917 // All valid entries? (We hope so here!)
918 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues))) {
919 // Shall we delete here or list for deletion?
920 if ($deleteNow === true) {
921 // The base SQL command:
922 $sql = "DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_%s` WHERE %s IN (%s)";
926 foreach ($IDs as $id => $sel) {
927 // Is there a userid?
928 if (isPostRequestParameterSet('userid_raw', $id)) {
929 // Load all data from that id
930 $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_%s` WHERE %s=%s LIMIT 1",
931 array($table, $idColumn, $id), __FUNCTION__, __LINE__);
934 $content = SQL_FETCHARRAY($result);
937 SQL_FREERESULT($result);
939 // Send "build mails" out
940 sendAdminBuildMails('del', $table, $content, $id);
944 $idList .= $id . ',';
948 SQL_QUERY($sql, array($table, $idColumn, substr($idList, 0, -1)), __FUNCTION__, __LINE__);
951 if (SQL_AFFECTEDROWS() == count($IDs)) {
953 loadTemplate('admin_settings_saved', false, getMessage('ADMIN_ALL_ENTRIES_REMOVED'));
955 // Some are still there :(
956 loadTemplate('admin_settings_saved', false, sprintf(getMessage('ADMIN_SOME_ENTRIES_NOT_DELETED'), SQL_AFFECTEDROWS(), count($IDs)));
959 // List for deletion confirmation
960 adminListBuilder('del', $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
965 // Edit rows by given id numbers
966 function adminEditEntriesConfirm ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $editNow=false, $idColumn='id', $userIdColumn='userid') {
967 // All valid entries? (We hope so here!)
968 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues))) {
969 // Shall we change here or list for editing?
970 if ($editNow === true) {
973 foreach ($IDs as $id => $sel) {
974 // Prepare content array (new values)
977 // Prepare SQL for this row
978 $sql = sprintf("UPDATE `{?_MYSQL_PREFIX?}_%s` SET",
981 foreach (postRequestArray() as $key => $entries) {
982 // Skip raw userid which is always invalid
983 if ($key == 'userid_raw') {
984 // Continue with next field
988 // Is entries an array?
989 if (($key != $idColumn) && (is_array($entries)) && (isset($entries[$id]))) {
990 // Add this entry to content
991 $content[$key] = $entries[$id];
993 // Send data through the filter function if found
994 if ((isset($filterFunctions[$key])) && (isset($extraValues[$key]))) {
995 // Filter function set!
996 $entries[$id] = handleExtraValues($filterFunctions[$key], $entries[$id], $extraValues[$key]);
999 // Then add this value
1000 $sql .= sprintf(" `%s`='%s',",
1002 SQL_ESCAPE($entries[$id])
1004 } elseif (($key != $idColumn) && (!is_array($entries))) {
1005 // Add normal entries as well!
1006 $content[$key] = $entries;
1009 // Do we have an URL?
1010 if ($key == 'url') {
1011 // Then add a framekiller test as well
1012 $content['frametester'] = generateFrametesterUrl($content[$key]);
1016 // Finish SQL command
1017 $sql = substr($sql, 0, -1) . " WHERE `" . $idColumn . "`=" . bigintval($id) . " LIMIT 1";
1020 SQL_QUERY($sql, __FUNCTION__, __LINE__);
1022 // Add affected rows
1023 $affected += SQL_AFFECTEDROWS();
1025 // Load all data from that id
1026 $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`=%s LIMIT 1",
1027 array($table, $idColumn, $id), __FUNCTION__, __LINE__);
1029 // Fetch the data and merge it into $content
1030 $content = merge_array($content, SQL_FETCHARRAY($result));
1033 SQL_FREERESULT($result);
1035 // Send "build mails" out
1036 sendAdminBuildMails('edit', $table, $content, $id);
1040 if ($affected == count($IDs)) {
1042 loadTemplate('admin_settings_saved', false, getMessage('ADMIN_ALL_ENTRIES_EDITED'));
1044 // Some are still there :(
1045 loadTemplate('admin_settings_saved', false, sprintf(getMessage('ADMIN_SOME_ENTRIES_NOT_EDITED'), $affected, count($IDs)));
1049 adminListBuilder('edit', $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1054 // Un-/lock rows by given id numbers
1055 function adminLockEntriesConfirm ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $statusArray=array(), $lockNow=false, $idColumn='id', $userIdColumn='userid') {
1056 // All valid entries? (We hope so here!)
1057 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues)) && (($lockNow === false) || (count($statusArray) == 1))) {
1058 // Shall we un-/lock here or list for locking?
1059 if ($lockNow === true) {
1061 adminBuilderStatusHandler('lock', $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray);
1064 adminListBuilder('lock', $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1069 // Undelete rows by given id numbers
1070 function adminUndeleteEntriesConfirm ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $statusArray=array(), $undeleteNow=false, $idColumn='id', $userIdColumn='userid') {
1071 // All valid entries? (We hope so here!)
1072 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues)) && (($undeleteNow === false) || (count($statusArray) == 1))) {
1073 // Shall we un-/lock here or list for locking?
1074 if ($undeleteNow === true) {
1076 adminBuilderStatusHandler('undelete', $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray);
1079 adminListBuilder('undelete', $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1084 // Checks proxy settins by fetching check-updates3.php from www.mxchange.org
1085 function adminTestProxySettings ($settingsArray) {
1086 // Set temporary the new settings
1087 mergeConfig($settingsArray);
1089 // Now get the test URL
1090 $content = sendGetRequest('check-updates3.php');
1092 // Is the first line with "200 OK"?
1093 $valid = (strpos($content[0], '200 OK') !== false);
1099 // Sends out a link to the given email adress so the admin can reset his/her password
1100 function sendAdminPasswordResetLink ($email) {
1104 //Â Look up administator login
1105 $result = SQL_QUERY_ESC("SELECT `id`, `login`, `password` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `email`='%s' LIMIT 1",
1106 array($email), __FUNCTION__, __LINE__);
1108 // Is there an account?
1109 if (SQL_HASZERONUMS($result)) {
1110 // No account found!
1111 return getMessage('ADMIN_NO_LOGIN_WITH_EMAIL');
1115 $content = SQL_FETCHARRAY($result);
1118 SQL_FREERESULT($result);
1120 // Generate hash for reset link
1121 $content['hash'] = generateHash(getConfig('URL') . ':' . $content['id'] . ':' . $content['login'] . ':' . $content['password'], substr($content['password'], 10));
1124 unset($content['id']);
1125 unset($content['password']);
1128 $mailText = loadEmailTemplate('admin_reset_password', $content);
1131 sendEmail($email, getMessage('ADMIN_RESET_PASS_LINK_SUBJ'), $mailText);
1134 return getMessage('ADMIN_RESET_LINK_SENT');
1137 // Validate hash and login for password reset
1138 function adminResetValidateHashLogin ($hash, $login) {
1139 // By default nothing validates... ;)
1142 // Then try to find that user
1143 $result = SQL_QUERY_ESC("SELECT `id`, `password`, `email` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
1144 array($login), __FUNCTION__, __LINE__);
1146 // Is an account here?
1147 if (SQL_NUMROWS($result) == 1) {
1149 $content = SQL_FETCHARRAY($result);
1151 // Generate hash again
1152 $hashFromData = generateHash(getConfig('URL') . ':' . $content['id'] . ':' . $login . ':' . $content['password'], substr($content['password'], 10));
1155 $valid = ($hash == $hashFromData);
1159 SQL_FREERESULT($result);
1165 // Reset the password for the login. Do NOT call this function without calling above function first!
1166 function doResetAdminPassword ($login, $password) {
1167 // Generate hash (we already check for sql_patches in generateHash())
1168 $passHash = generateHash($password);
1171 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_admins` SET `password`='%s' WHERE `login`='%s' LIMIT 1",
1172 array($passHash, $login), __FUNCTION__, __LINE__);
1175 runFilterChain('post_admin_reset_pass', array('login' => $login, 'hash' => $passHash));
1178 return getMessage('ADMIN_PASSWORD_RESET_DONE');
1181 // Solves a task by given id number
1182 function adminSolveTask ($id) {
1183 // Update the task data
1184 adminUpdateTaskData($id, 'status', 'SOLVED');
1187 // Marks a given task as deleted
1188 function adminDeleteTask ($id) {
1189 // Update the task data
1190 adminUpdateTaskData($id, 'status', 'DELETED');
1193 // Function to update task data
1194 function adminUpdateTaskData ($id, $row, $data) {
1197 // Not an admin so redirect better
1198 redirectToUrl('modules.php?module=index');
1201 // Is the id not set, then we need a backtrace here... :(
1203 // Initiate backtrace
1204 debug_report_bug(sprintf("id is invalid: %s. row=%s, data=%s",
1212 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_task_system` SET `%s`='%s' WHERE `id`=%s LIMIT 1",
1217 ), __FUNCTION__, __LINE__);
1220 // Checks wether if the admin menu has entries
1221 function ifAdminMenuHasEntries ($action) {
1224 // Is the entry set?
1225 isset($GLOBALS['admin_menu_has_entries'][$action])
1227 // And do we have a menu for this action?
1228 $GLOBALS['admin_menu_has_entries'][$action] === true
1230 // Login has always a menu
1236 // Setter for 'admin_menu_has_entries'
1237 function setAdminMenuHasEntries ($action, $hasEntries) {
1238 $GLOBALS['admin_menu_has_entries'][$action] = (bool) $hasEntries;
1241 // Creates a link to the user's admin-profile
1242 function adminCreateUserLink ($userid) {
1243 // Is the userid set correctly?
1245 // Create a link to that profile
1246 return '{%url=modules.php?module=admin&what=list_user&userid=' . bigintval($userid) . '%}';
1249 // Return a link to the user list
1250 return '{%url=modules.php?module=admin&what=list_user%}';
1253 // Generate a "link" for the given admin id (admin_id)
1254 function generateAdminLink ($adminId) {
1255 // No assigned admin is default
1256 $adminLink = '<span class="admin_note">{--ADMIN_NO_ADMIN_ASSIGNED--}</span>';
1258 // Zero? = Not assigned
1259 if (bigintval($adminId) > 0) {
1260 // Load admin's login
1261 $login = getAdminLogin($adminId);
1263 // Is the login valid?
1264 if ($login != '***') {
1265 // Is the extension there?
1266 if (isExtensionActive('admins')) {
1268 $adminLink = '<a href="' . generateEmailLink(getAdminEmail($adminId), 'admins') . '" title="{--ADMIN_CONTACT_LINK_TITLE--}">' . $login . '</a>';
1270 // Extension not found
1271 $adminLink = getMaskedMessage('EXTENSION_PROBLEM_NOT_INSTALLED', 'admins');
1275 $adminLink = '<div class="admin_note">' . getMaskedMessage('ADMIN_ID_404', $adminId) . '</div>';
1283 // Verifies if the current admin has confirmed to alter expert settings
1286 // 'failed' = Something goes wrong (default)
1287 // 'agreed' = Has verified and and confirmed it to see them
1288 // 'forbidden' = Has not the proper right to alter them
1289 // 'update' = Need to update extension 'admins'
1290 // 'ask' = A form was send to the admin
1291 function doVerifyExpertSettings () {
1292 // Default return status is failed
1295 // Is the extension installed and recent?
1296 if (isExtensionInstalledAndNewer('admins', '0.7.3')) {
1297 // Okay, load the status
1298 $expertSettings = getAminsExpertSettings();
1301 if ($expertSettings == 'Y') {
1302 // Okay, does he want to see them?
1303 if (getAminsExpertWarning() == 'Y') {
1306 // Is the element set, then we need to change the admin
1307 if (isPostRequestParameterSet('expert_settings')) {
1308 // Get it and prepare final post data array
1309 $postData['login'][getCurrentAdminId()] = getAdminLogin(getCurrentAdminId());
1310 $postData['expert_warning'][getCurrentAdminId()] = 'N';
1312 // Change it in the admin
1313 adminsChangeAdminAccount($postData, 'expert_warning');
1316 unsetPostRequestParameter('ok');
1323 loadTemplate('admin_expert_settings_form');
1334 $return = 'forbidden';
1337 // Out-dated extension or not installed
1341 // Output message for other status than ask/agreed
1342 if (($return != 'ask') && ($return != 'agreed')) {
1344 loadTemplate('admin_settings_saved', false, getMessage('ADMIN_EXPERT_SETTINGS_STATUS_' . strtoupper($return)));