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 // Get admin id from login
81 $adminId = getAdminId($adminLogin);
83 // Continue only with found admin ids
85 // Then we need to lookup the login name by getting the admin hash
86 $adminHash = getAdminHash($adminId);
88 // If this is fine, we can continue
89 if ($adminHash != '-1') {
90 // Get admin id and set it as current
91 setCurrentAdminId($adminId);
93 // Now, we need to encode the password in the same way the one is encoded in database
94 $testHash = generateHash($adminPassword, $adminHash);
96 // If they both match, the login data is valid
97 if ($testHash == $adminHash) {
107 // Prepare data array
110 'login' => $adminLogin,
111 'plain_pass' => $adminPassword,
112 'pass_hash' => $adminHash
115 // Run a special filter
116 runFilterChain('do_admin_login_' . $ret, $data);
122 // Only be executed on cookie checking
123 function ifAdminCookiesAreValid ($adminLogin, $passHash) {
124 // First of all, no admin login is found
127 // Then we need to lookup the login name by getting the admin hash
128 $adminHash = getAdminHash($adminLogin);
130 // If this is fine, we can continue
131 if ($adminHash != '-1') {
132 // Now, we need to encode the password in the same way the one is encoded in database
133 $testHash = encodeHashForCookie($adminHash);
134 //* DEBUG: */ debugOutput('adminLogin=' . $adminLogin . ',passHash='.$passHash.',adminHash='.$adminHash.',testHash='.$testHash);
136 // If they both match, the login data is valid
137 if ($testHash == $passHash) {
147 //* DEBUG: */ debugOutput('ret='.$ret);
151 // Do an admin action
152 function doAdminAction () {
156 //* DEBUG: */ debugOutput(__LINE__.'*'.$what.'/'.getModule().'/'.getAction().'/'.getWhat().'*');
158 // Remove any spaces from variable
160 // Default admin action is the overview page
164 $what = secureString($what);
168 $action = getActionFromModuleWhat(getModule(), $what);
170 // Define admin login name and id number
171 $content['login'] = getAdminLogin(getSession('admin_id'));
172 $content['id'] = getCurrentAdminId();
175 if (isExtensionActive('admins')) {
176 $content['welcome'] = loadTemplate('admin_welcome_admins', true, $content);
178 $content['welcome'] = loadTemplate('admin_welcome', true, $content);
180 $content['footer'] = loadTemplate('admin_footer' , true, $content);
181 $content['menu'] = addAdminMenu($action, $what, true);
184 loadTemplate('admin_main_header', false, $content);
186 // Check if action/what pair is valid
187 $result_action = SQL_QUERY_ESC("SELECT
190 `{?_MYSQL_PREFIX?}_admin_menu`
195 `what`='%s' AND `what` != 'overview'
198 `what`='' OR `what` IS NULL
209 ), __FUNCTION__, __LINE__);
211 // Do we have an entry?
212 if (SQL_NUMROWS($result_action) == 1) {
213 // Is valid but does the inlcude file exists?
214 $inc = sprintf("inc/modules/admin/action-%s.php", $action);
215 if ((isIncludeReadable($inc)) && (isMenuActionValid('admin', $action, $what)) && ($GLOBALS['acl_allow'] === true)) {
216 // Ok, we finally load the admin action module
218 } elseif ($GLOBALS['acl_allow'] === false) {
220 loadTemplate('admin_menu_failed', false, getMaskedMessage('ADMIN_ACCESS_DENIED', $what));
222 // Include file not found! :-(
223 loadTemplate('admin_menu_failed', false, getMaskedMessage('ADMIN_ACTION_404', $action));
226 // Invalid action/what pair found!
227 loadTemplate('admin_menu_failed', false, getMaskedMessage('ADMIN_ACTION_INVALID', $action . '/' . $what));
231 SQL_FREERESULT($result_action);
234 loadTemplate('admin_main_footer', false, $content);
237 // Adds an admin menu
238 function addAdminMenu ($action, $what, $return=false) {
244 $GLOBALS['menu']['description'] = array();
245 $GLOBALS['menu']['title'] = array();
248 $result_main = SQL_QUERY("SELECT
249 `action`, `title`, `descr`
251 `{?_MYSQL_PREFIX?}_admin_menu`
253 (`what`='' OR `what` IS NULL)
256 `id` DESC", __FUNCTION__, __LINE__);
258 // Do we have entries?
259 if (SQL_NUMROWS($result_main) > 0) {
260 $OUT .= '<ul class="admin_menu_main">';
261 // @TODO Rewrite this to $content = SQL_FETCHARRAY()
262 while (list($menu, $title, $descr) = SQL_FETCHROW($result_main)) {
263 if (isExtensionInstalledAndNewer('admins', '0.2.0')) {
264 $ACL = adminsCheckAdminAcl($menu, '');
266 // @TODO ACL is 'allow'... hmmm
271 $inc = sprintf("inc/modules/admin/action-%s.php", $menu);
273 // Is the file readable?
274 $readable = isIncludeReadable($inc);
277 if ($SUB === false) {
278 // Insert compiled menu title and description
279 $GLOBALS['menu']['title'][$menu] = $title;
280 $GLOBALS['menu']['description'][$menu] = $descr;
282 $OUT .= '<li class="admin_menu">
283 <div class="nobr"><strong>·</strong> ';
285 if ($readable === true) {
286 if (($menu == $action) && (empty($what))) {
289 $OUT .= '[<a href="{%url=modules.php?module=admin&action=' . $menu . '%}">';
292 $OUT .= '<em style="cursor:help" class="admin_note" title="{--MENU_ACTION_404--}">';
297 if ($readable === true) {
298 if (($menu == $action) && (empty($what))) {
310 // Check for menu entries
311 $result_what = SQL_QUERY_ESC("SELECT
312 `what`, `title`, `descr`
314 `{?_MYSQL_PREFIX?}_admin_menu`
322 array($menu), __FUNCTION__, __LINE__);
324 // Remember the count for later checks
325 setAdminMenuHasEntries($menu, ((SQL_NUMROWS($result_what) > 0) && ($action == $menu)));
327 // Do we have entries?
328 if ((ifAdminMenuHasEntries($menu)) && (SQL_NUMROWS($result_what) > 0)) {
329 $GLOBALS['menu']['description'] = array();
330 $GLOBALS['menu']['title'] = array(); $SUB = true;
331 $OUT .= '<li class="admin_menu_sub"><ul class="admin_menu_sub">';
332 // @TODO Rewrite this to $content = SQL_FETCHARRAY()
333 while (list($what_sub, $title_what, $desc_what) = SQL_FETCHROW($result_what)) {
334 // Check for access level
335 if (isExtensionInstalledAndNewer('admins', '0.2.0')) {
336 $ACL = adminsCheckAdminAcl('', $what_sub);
338 // @TODO ACL is 'allow'... hmmm
343 $inc = sprintf("inc/modules/admin/what-%s.php", $what_sub);
345 // Is the file readable?
346 $readable = isIncludeReadable($inc);
350 // Insert compiled title and description
351 $GLOBALS['menu']['title'][$what_sub] = $title_what;
352 $GLOBALS['menu']['description'][$what_sub] = $desc_what;
353 $OUT .= '<li class="admin_menu">
354 <div class="nobr"><strong>--></strong> ';
355 if ($readable === true) {
356 if ($what == $what_sub) {
359 $OUT .= '[<a href="{%url=modules.php?module=admin&what=' . $what_sub . '%}">';
362 $OUT .= '<em style="cursor:help" class="admin_note" title="{--MENU_WHAT_404--}">';
367 if ($readable === true) {
368 if ($what == $what_sub) {
382 SQL_FREERESULT($result_what);
390 SQL_FREERESULT($result_main);
394 // Is there a cache instance again?
395 // Return or output content?
396 if ($return === true) {
403 // Create member selection box
404 function addMemberSelectionBox ($def = 0, $add_all = false, $return = false, $none = false, $field = 'userid') {
405 // Output selection form with all confirmed user accounts listed
406 $result = SQL_QUERY("SELECT `userid`, `surname`, `family` FROM `{?_MYSQL_PREFIX?}_user_data` ORDER BY `userid` ASC", __FUNCTION__, __LINE__);
411 // USe this only for adding points (e.g. adding refs really makes no sence ;-) )
412 if ($add_all === true) $OUT = ' <option value="all">{--ALL_MEMBERS--}</option>';
413 elseif ($none === true) $OUT = ' <option value="0">{--SELECT_NONE--}</option>';
415 while ($content = SQL_FETCHARRAY($result)) {
416 $OUT .= '<option value="' . bigintval($content['userid']) . '"';
417 if ($def == $content['userid']) $OUT .= ' selected="selected"';
418 $OUT .= '>' . $content['surname'] . ' ' . $content['family'] . ' (' . bigintval($content['userid']) . ')</option>';
422 SQL_FREERESULT($result);
424 if ($return === false) {
425 // Remeber options in constant
426 $content['member_selection'] = $OUT;
427 $content['what'] = getWhat();
430 loadTemplate('admin_member_selection_box', false, $content);
432 // Return content in selection frame
433 return '<select class="admin_select" name="' . handleFieldWithBraces($field) . '" size="1">' . $OUT . '</select>';
437 // Create a menu selection box for given menu system
438 // @TODO Try to rewrite this to adminAddMenuSelectionBox()
440 function adminMenuSelectionBox_DEPRECATED ($mode, $default = '', $defid = '') {
441 $what = "`what` != ''";
442 if ($mode == 'action') $what = "(`what`='' OR `what` IS NULL) AND `action` !='login'";
444 $result = SQL_QUERY_ESC("SELECT `%s` AS `menu`, `title` FROM `{?_MYSQL_PREFIX?}_admin_menu` WHERE ".$what." ORDER BY `sort` ASC",
445 array($mode), __FUNCTION__, __LINE__);
446 if (SQL_NUMROWS($result) > 0) {
447 // Load menu as selection
448 $OUT = '<select name="' . $mode . '_menu';
449 if ((!empty($defid)) || ($defid == '0')) $OUT .= '[' . $defid . ']';
450 $OUT .= '" size="1" class="admin_select">
451 <option value="">{--SELECT_NONE--}</option>';
453 while ($content = SQL_FETCHARRAY($result)) {
454 $OUT .= '<option value="' . $content['menu'] . '"';
455 if ((!empty($default)) && ($default == $content['menu'])) $OUT .= ' selected="selected"';
456 $OUT .= '>' . $content['title'] . '</option>';
460 SQL_FREERESULT($result);
462 // Add closing select-tag
466 $OUT = '{--ADMIN_PROBLEM_NO_MENU--}';
473 // Wrapper for $_POST and adminSaveSettings
474 function adminSaveSettingsFromPostData ($tableName = '_config', $whereStatement = '`config`=0', $translateComma = array(), $alwaysAdd = false, $displayMessage = true) {
476 $postData = postRequestArray();
478 // Call the lower function
479 adminSaveSettings($postData, $tableName, $whereStatement, $translateComma, $alwaysAdd, $displayMessage);
482 // Save settings to the database
483 function adminSaveSettings (&$postData, $tableName = '_config', $whereStatement = '`config`=0', $translateComma = array(), $alwaysAdd = false, $displayMessage = true) {
484 // Prepare all arrays, variables
485 $tableData = array();
488 // Now, walk through all entries and prepare them for saving
489 foreach ($postData as $id => $val) {
490 // Process only formular field but not submit buttons ;)
492 // Do not save the ok value
493 convertSelectionsToTimestamp($postData, $tableData, $id, $skip);
495 // Shall we process this id? It muss not be empty, of course
496 if (($skip === false) && (!empty($id)) && ((!isset($GLOBALS['skip_config'][$id]))) || ($tableName != '_config')) {
497 // Translate the value? (comma to dot!)
498 if ((is_array($translateComma)) && (in_array($id, $translateComma))) {
499 // Then do it here... :)
500 $val = convertCommaToDot($val);
503 // Shall we add numbers or strings?
505 if ('' . $val . '' == '' . $test . '') {
507 $tableData[] = sprintf("`%s`=%s", $id, $test);
508 } elseif (is_null($val)) {
510 $tableData[] = sprintf("`%s`=NULL", $id);
513 $tableData[] = sprintf("`%s`='%s'", $id, trim($val));
516 // Do not add a config entry twice
517 $GLOBALS['skip_config'][$id] = true;
519 // Update current configuration
520 setConfigEntry($id, $val);
525 // Check if entry does exist
527 if ($alwaysAdd === false) {
528 if (!empty($whereStatement)) {
529 $result = SQL_QUERY("SELECT * FROM `{?_MYSQL_PREFIX?}" . $tableName . "` WHERE " . $whereStatement . " LIMIT 1", __FUNCTION__, __LINE__);
531 $result = SQL_QUERY("SELECT * FROM `{?_MYSQL_PREFIX?}" . $tableName . "` LIMIT 1", __FUNCTION__, __LINE__);
535 if (SQL_NUMROWS($result) == 1) {
536 // "Implode" all data to single string
537 $updatedData = implode(', ', $tableData);
539 // Generate SQL string
540 $sql = sprintf("UPDATE `{?_MYSQL_PREFIX?}%s` SET %s WHERE %s LIMIT 1",
546 // Add Line (does only work with auto_increment!
547 $keys = array(); $values = array();
548 foreach ($tableData as $entry) {
550 $line = explode('=', $entry);
552 $values[] = $line[1];
555 // Add both in one line
556 $keys = implode('`, `', $keys);
557 $values = implode(', ', $values);
559 // Generate SQL string
560 $sql = sprintf("INSERT INTO `{?_MYSQL_PREFIX?}%s` (%s) VALUES (%s)",
568 SQL_FREERESULT($result);
570 // Simply run generated SQL string
571 SQL_QUERY($sql, __FUNCTION__, __LINE__);
573 // Remember affected rows
574 $affected = SQL_AFFECTEDROWS();
577 rebuildCache('config', 'config');
579 // Settings saved, so display message?
580 if ($displayMessage === true) loadTemplate('admin_settings_saved', false, '{--SETTINGS_SAVED--}');
582 // Return affected rows
586 // Generate a selection box
587 function adminAddMenuSelectionBox ($menu, $type, $name, $default = '') {
588 // Open the requested menu directory
589 $menuArray = getArrayFromDirectory(sprintf("inc/modules/%s/", $menu), '', false, false);
591 // Init the selection box
592 $OUT = '<select name="' . $name . '" class="admin_select" size="1"><option value="">{--IS_TOP_MENU--}</option>';
594 // Walk through all files
595 foreach ($menuArray as $file) {
596 // Is this a PHP script?
597 if ((!isDirectory($file)) && (strpos($file, '' . $type . '-') > -1) && (strpos($file, '.php') > 0)) {
598 // Then test if the file is readable
599 $test = sprintf("inc/modules/%s/%s", $menu, $file);
601 // Is the file there?
602 if (isIncludeReadable($test)) {
603 // Extract the value for what=xxx
604 $part = substr($file, (strlen($type) + 1));
605 $part = substr($part, 0, -4);
607 // Is that part different from the overview?
608 if ($part != 'overview') {
609 $OUT .= '<option value="' . $part . '"';
610 if ($part == $default) $OUT .= ' selected="selected"';
611 $OUT .= '>' . $part . '</option>';
617 // Close selection box
624 // Creates a user-profile link for the admin. This function can also be used for many other purposes
625 function generateUserProfileLink ($userid, $title = '', $what = 'list_user') {
626 if (($title == '') && ($userid > 0)) {
627 // Set userid as title
629 } elseif ($userid == 0) {
630 // User id zero is invalid
631 return '<strong>' . $userid . '</strong>';
634 if (($title == '0') && ($what == 'list_refs')) {
635 // Return title again
637 } elseif (isExtensionActive('nickname')) {
639 $nick = getNickname($userid);
641 // Is it not empty, use it as title else the userid
642 if (!empty($nick)) $title = $nick . '(' . $userid . ')'; else $title = $userid;
646 return '[<a href="{%url=modules.php?module=admin&what=' . $what . '&userid=' . $userid . '%}" title="{--ADMIN_USER_PROFILE_TITLE--}">' . $title . '</a>]';
649 // Check "logical-area-mode"
650 function adminGetMenuMode () {
651 // Set the default menu mode as the mode for all admins
652 $mode = getConfig('admin_menu');
656 $adminId = getCurrentAdminId();
658 // Check individual settings of current admin
659 if (isset($GLOBALS['cache_array']['admin']['la_mode'][$adminId])) {
661 $adminMode = $GLOBALS['cache_array']['admin']['la_mode'][$adminId];
662 incrementStatsEntry('cache_hits');
663 } elseif (isExtensionInstalledAndNewer('admins', '0.6.7')) {
664 // Load from database when version of 'admins' is enough
665 $result = SQL_QUERY_ESC("SELECT la_mode FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
666 array($adminId), __FUNCTION__, __LINE__);
668 // Do we have an entry?
669 if (SQL_NUMROWS($result) == 1) {
671 list($adminMode) = SQL_FETCHROW($result);
675 SQL_FREERESULT($result);
678 // Check what the admin wants and set it when it's not the default mode
679 if ($adminMode != 'global') $mode = $adminMode;
681 // Return admin-menu's mode
685 // Change activation status
686 function adminChangeActivationStatus ($IDs, $table, $row, $idRow = 'id') {
687 $cnt = '0'; $newStatus = 'Y';
688 if ((is_array($IDs)) && (count($IDs) > 0)) {
689 // "Walk" all through and count them
690 foreach ($IDs as $id => $selected) {
691 // Secure the id number
692 $id = bigintval($id);
694 // Should always be set... ;-)
695 if (!empty($selected)) {
696 // Determine new status
697 $result = SQL_QUERY_ESC("SELECT %s FROM `{?_MYSQL_PREFIX?}_%s` WHERE %s=%s LIMIT 1",
698 array($row, $table, $idRow, $id), __FUNCTION__, __LINE__);
701 if (SQL_NUMROWS($result) == 1) {
703 list($currStatus) = SQL_FETCHROW($result);
705 // And switch it N<->Y
706 if ($currStatus == 'Y') $newStatus = 'N'; else $newStatus = 'Y';
708 // Change this status
709 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s` SET %s='%s' WHERE %s=%s LIMIT 1",
710 array($table, $row, $newStatus, $idRow, $id), __FUNCTION__, __LINE__);
712 // Count up affected rows
713 $cnt += SQL_AFFECTEDROWS();
717 SQL_FREERESULT($result);
722 loadTemplate('admin_settings_saved', false, sprintf(getMessage('ADMIN_STATUS_CHANGED'), $cnt, count($IDs)));
725 loadTemplate('admin_settings_saved', false, '{--ADMIN_NOTHING_SELECTED_CHANGE--}');
729 // Send mails for del/edit/lock build modes
730 function sendAdminBuildMails ($mode, $table, $content, $id, $subjectPart = '', $userid = 'userid') {
731 // Default subject is the subject part
732 $subject = $subjectPart;
734 // Is the subject part not set?
735 if (empty($subjectPart)) {
736 // Then use it from the mode
737 $subject = strtoupper($mode);
740 // Is the raw userid set?
741 if (postRequestParameter($userid, $id) > 0) {
743 $subject = '{--MEMBER_' . strtoupper($subject) . '_' . strtoupper($table) . '_SUBJECT--}';
745 // Load email template
746 if (!empty($subjectPart)) {
747 $mail = loadEmailTemplate('member_' . $mode . '_' . strtolower($subjectPart) . '_' . $table, $content);
749 $mail = loadEmailTemplate('member_' . $mode . '_' . $table, $content);
753 sendEmail(postRequestParameter($userid, $id), $subject, $mail);
757 $subject = '{--ADMIN_' . strtoupper($subject) . '_' . strtoupper($table) . '_SUBJECT--}';
759 // Send admin notification out
760 if (!empty($subjectPart)) {
761 sendAdminNotification($subject, 'admin_' . $mode . '_' . strtolower($subjectPart) . '_' . $table, $content, postRequestParameter($userid, $id));
763 sendAdminNotification($subject, 'admin_' . $mode . '_' . $table, $content, postRequestParameter($userid, $id));
767 // Build a special template list
768 function adminListBuilder ($listType, $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $userid = 'userid') {
771 // "Walk"Â through all entries
772 foreach ($IDs as $id => $selected) {
774 $id = bigintval($id);
776 // Get result from a given column array and table name
777 $result = SQL_RESULT_FROM_ARRAY($table, $columns, $idColumn, $id, __FUNCTION__, __LINE__);
779 // Is there one entry?
780 if (SQL_NUMROWS($result) == 1) {
782 $content = SQL_FETCHARRAY($result);
785 foreach ($content as $key => $value) {
787 $idx = array_search($key, $columns, true);
789 //Â Do we have a userid?
790 if ($key == $userIdColumn) {
791 // Add it again as raw id
792 $content[$userIdColumn] = bigintval($value);
793 $content[$userIdColumn . '_raw'] = $content[$userIdColumn];
796 // If the key matches the idColumn variable, we need to temporary remember it
797 //* DEBUG: */ debugOutput('key=' . $key . ',idColumn=' . $idColumn . ',value=' . $value);
798 if ($key == $idColumn) {
799 // Found, so remember it
800 $GLOBALS['admin_list_builder_id_value'] = $value;
803 // Handle the call in external function
804 //* DEBUG: */ debugOutput('key=' . $key . ',fucntion=' . $filterFunctions[$idx] . ',value=' . $value);
805 $content[$key] = handleExtraValues($filterFunctions[$idx], $value, $extraValues[$idx]);
808 // Add color switching
809 $content['sw'] = $SW;
812 $OUT .= loadTemplate(sprintf("admin_%s_%s_row",
823 SQL_FREERESULT($result);
826 // Load master template
827 loadTemplate(sprintf("admin_%s_%s",
834 // Change status of "build" list
835 function adminBuilderStatusHandler ($mode, $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray, $userid = 'userid') {
836 // All valid entries? (We hope so here!)
837 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues)) && (count($statusArray) > 0)) {
838 // "Walk" through all entries
839 foreach ($IDs as $id => $sel) {
840 // Construct SQL query
841 $sql = sprintf("UPDATE `{?_MYSQL_PREFIX?}_%s` SET", SQL_ESCAPE($table));
843 // Load data of entry
844 $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`=%s LIMIT 1",
845 array($table, $idColumn, $id), __FUNCTION__, __LINE__);
848 $content = SQL_FETCHARRAY($result);
851 SQL_FREERESULT($result);
853 // Add all status entries (e.g. status column last_updated or so)
854 $newStatus = 'UNKNOWN';
855 $oldStatus = 'UNKNOWN';
856 $statusColumn = 'unknown';
857 foreach ($statusArray as $column => $statusInfo) {
858 // Does the entry exist?
859 if ((isset($content[$column])) && (isset($statusInfo[$content[$column]]))) {
860 // Add these entries for update
861 $sql .= sprintf(" %s='%s',", SQL_ESCAPE($column), SQL_ESCAPE($statusInfo[$content[$column]]));
864 if ($statusColumn == 'unknown') {
865 // Always (!!!) change status column first!
866 $oldStatus = $content[$column];
867 $newStatus = $statusInfo[$oldStatus];
868 $statusColumn = $column;
870 } elseif (isset($content[$column])) {
872 debug_report_bug(__FUNCTION__, __LINE__, ":UNFINISHED: id={$id}/{$column}[".gettype($statusInfo)."] = {$content[$column]}");
876 // Add other columns as well
877 foreach (postRequestArray() as $key => $entries) {
879 logDebugMessage(__FUNCTION__, __LINE__, 'Found entry: ' . $key);
881 // Skip id, raw userid and 'do_$mode'
882 if (!in_array($key, array($idColumn, $userid, ('do_' . $mode)))) {
883 // Are there brackets () at the end?
884 if (substr($entries[$id], -2, 2) == '()') {
885 // Direct SQL command found
886 $sql .= sprintf(" %s=%s,", SQL_ESCAPE($key), SQL_ESCAPE($entries[$id]));
889 $sql .= sprintf(" %s='%s',", SQL_ESCAPE($key), SQL_ESCAPE($entries[$id]));
892 $content[$key] = $entries[$id];
896 logDebugMessage(__FUNCTION__, __LINE__, 'Skipped: ' . $key);
900 // Finish SQL statement
901 $sql = substr($sql, 0, -1) . sprintf(" WHERE `%s`=%s AND `%s`='%s' LIMIT 1",
909 SQL_QUERY($sql, __FUNCTION__, __LINE__);
911 // Do we have an URL?
912 if (isset($content['url'])) {
913 // Then add a framekiller test as well
914 $content['frametester'] = generateFrametesterUrl($content['url']);
917 // Send "build mails" out
918 sendAdminBuildMails($mode, $table, $content, $id, $statusInfo[$content[$column]]);
923 // Delete rows by given id numbers
924 function adminDeleteEntriesConfirm ($IDs, $table, $columns = array(), $filterFunctions = array(), $extraValues = array(), $deleteNow = false, $idColumn = 'id', $userIdColumn = 'userid', $userid = 'userid') {
925 // All valid entries? (We hope so here!)
926 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues))) {
927 // Shall we delete here or list for deletion?
928 if ($deleteNow === true) {
929 // The base SQL command:
930 $sql = "DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s` IN (%s)";
934 foreach ($IDs as $id => $sel) {
935 // Is there a userid?
936 if (isPostRequestParameterSet($userid, $id)) {
937 // Load all data from that id
938 $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`=%s LIMIT 1",
943 ), __FUNCTION__, __LINE__);
946 $content = SQL_FETCHARRAY($result);
949 SQL_FREERESULT($result);
951 // Send "build mails" out
952 sendAdminBuildMails('del', $table, $content, $id);
956 $idList .= $id . ',';
960 SQL_QUERY_ESC($sql, array($table, $idColumn, substr($idList, 0, -1)), __FUNCTION__, __LINE__);
963 if (SQL_AFFECTEDROWS() == count($IDs)) {
965 loadTemplate('admin_settings_saved', false, '{--ADMIN_ALL_ENTRIES_REMOVED--}');
967 // Some are still there :(
968 loadTemplate('admin_settings_saved', false, sprintf(getMessage('ADMIN_SOME_ENTRIES_NOT_DELETED'), SQL_AFFECTEDROWS(), count($IDs)));
971 // List for deletion confirmation
972 adminListBuilder('del', $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
977 // Edit rows by given id numbers
978 function adminEditEntriesConfirm ($IDs, $table, $columns = array(), $filterFunctions = array(), $extraValues = array(), $editNow = false, $idColumn = 'id', $userIdColumn = 'userid', $userid = 'userid') {
979 // All valid entries? (We hope so here!)
980 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues))) {
981 // Shall we change here or list for editing?
982 if ($editNow === true) {
985 foreach ($IDs as $id => $sel) {
986 // Prepare content array (new values)
989 // Prepare SQL for this row
990 $sql = sprintf("UPDATE `{?_MYSQL_PREFIX?}_%s` SET",
993 foreach (postRequestArray() as $key => $entries) {
994 // Skip raw userid which is always invalid
995 if ($key == $userid) {
996 // Continue with next field
1000 // Is entries an array?
1001 if (($key != $idColumn) && (is_array($entries)) && (isset($entries[$id]))) {
1002 // Add this entry to content
1003 $content[$key] = $entries[$id];
1005 // Send data through the filter function if found
1006 if ((isset($filterFunctions[$key])) && (isset($extraValues[$key]))) {
1007 // Filter function set!
1008 $entries[$id] = handleExtraValues($filterFunctions[$key], $entries[$id], $extraValues[$key]);
1011 // Then add this value
1012 $sql .= sprintf(" `%s`='%s',",
1014 SQL_ESCAPE($entries[$id])
1016 } elseif (($key != $idColumn) && (!is_array($entries))) {
1017 // Add normal entries as well!
1018 $content[$key] = $entries;
1021 // Do we have an URL?
1022 if ($key == 'url') {
1023 // Then add a framekiller test as well
1024 $content['frametester'] = generateFrametesterUrl($content[$key]);
1028 // Finish SQL command
1029 $sql = substr($sql, 0, -1) . " WHERE `" . $idColumn . "`=" . bigintval($id) . " LIMIT 1";
1032 SQL_QUERY($sql, __FUNCTION__, __LINE__);
1034 // Add affected rows
1035 $affected += SQL_AFFECTEDROWS();
1037 // Load all data from that id
1038 $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`=%s LIMIT 1",
1039 array($table, $idColumn, $id), __FUNCTION__, __LINE__);
1041 // Fetch the data and merge it into $content
1042 $content = merge_array($content, SQL_FETCHARRAY($result));
1045 SQL_FREERESULT($result);
1047 // Send "build mails" out
1048 sendAdminBuildMails('edit', $table, $content, $id);
1052 if ($affected == count($IDs)) {
1054 loadTemplate('admin_settings_saved', false, '{--ADMIN_ALL_ENTRIES_EDITED--}');
1056 // Some are still there :(
1057 loadTemplate('admin_settings_saved', false, sprintf(getMessage('ADMIN_SOME_ENTRIES_NOT_EDITED'), $affected, count($IDs)));
1061 adminListBuilder('edit', $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1066 // Un-/lock rows by given id numbers
1067 function adminLockEntriesConfirm ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $statusArray=array(), $lockNow=false, $idColumn='id', $userIdColumn='userid') {
1068 // All valid entries? (We hope so here!)
1069 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues)) && (($lockNow === false) || (count($statusArray) == 1))) {
1070 // Shall we un-/lock here or list for locking?
1071 if ($lockNow === true) {
1073 adminBuilderStatusHandler('lock', $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray);
1076 adminListBuilder('lock', $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1081 // Undelete rows by given id numbers
1082 function adminUndeleteEntriesConfirm ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $statusArray=array(), $undeleteNow=false, $idColumn='id', $userIdColumn='userid') {
1083 // All valid entries? (We hope so here!)
1084 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues)) && (($undeleteNow === false) || (count($statusArray) == 1))) {
1085 // Shall we un-/lock here or list for locking?
1086 if ($undeleteNow === true) {
1088 adminBuilderStatusHandler('undelete', $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray);
1091 adminListBuilder('undelete', $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1096 // Checks proxy settins by fetching check-updates3.php from www.mxchange.org
1097 function adminTestProxySettings ($settingsArray) {
1098 // Set temporary the new settings
1099 mergeConfig($settingsArray);
1101 // Now get the test URL
1102 $content = sendGetRequest('check-updates3.php');
1104 // Is the first line with "200 OK"?
1105 $valid = (strpos($content[0], '200 OK') !== false);
1111 // Sends out a link to the given email adress so the admin can reset his/her password
1112 function sendAdminPasswordResetLink ($email) {
1116 //Â Look up administator login
1117 $result = SQL_QUERY_ESC("SELECT `id`, `login`, `password` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `email`='%s' LIMIT 1",
1118 array($email), __FUNCTION__, __LINE__);
1120 // Is there an account?
1121 if (SQL_HASZERONUMS($result)) {
1122 // No account found!
1123 return getMessage('ADMIN_NO_LOGIN_WITH_EMAIL');
1127 $content = SQL_FETCHARRAY($result);
1130 SQL_FREERESULT($result);
1132 // Generate hash for reset link
1133 $content['hash'] = generateHash(getConfig('URL') . ':' . $content['id'] . ':' . $content['login'] . ':' . $content['password'], substr($content['password'], 10));
1136 unset($content['id']);
1137 unset($content['password']);
1140 $mailText = loadEmailTemplate('admin_reset_password', $content);
1143 sendEmail($email, '{--ADMIN_RESET_PASS_LINK_SUBJECT--}', $mailText);
1146 return getMessage('ADMIN_RESET_LINK_SENT');
1149 // Validate hash and login for password reset
1150 function adminResetValidateHashLogin ($hash, $login) {
1151 // By default nothing validates... ;)
1154 // Then try to find that user
1155 $result = SQL_QUERY_ESC("SELECT `id`, `password`, `email` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
1156 array($login), __FUNCTION__, __LINE__);
1158 // Is an account here?
1159 if (SQL_NUMROWS($result) == 1) {
1161 $content = SQL_FETCHARRAY($result);
1163 // Generate hash again
1164 $hashFromData = generateHash(getConfig('URL') . ':' . $content['id'] . ':' . $login . ':' . $content['password'], substr($content['password'], 10));
1167 $valid = ($hash == $hashFromData);
1171 SQL_FREERESULT($result);
1177 // Reset the password for the login. Do NOT call this function without calling above function first!
1178 function doResetAdminPassword ($login, $password) {
1179 // Generate hash (we already check for sql_patches in generateHash())
1180 $passHash = generateHash($password);
1183 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_admins` SET `password`='%s' WHERE `login`='%s' LIMIT 1",
1184 array($passHash, $login), __FUNCTION__, __LINE__);
1187 runFilterChain('post_admin_reset_pass', array('login' => $login, 'hash' => $passHash));
1190 return getMessage('ADMIN_PASSWORD_RESET_DONE');
1193 // Solves a task by given id number
1194 function adminSolveTask ($id) {
1195 // Update the task data
1196 adminUpdateTaskData($id, 'status', 'SOLVED');
1199 // Marks a given task as deleted
1200 function adminDeleteTask ($id) {
1201 // Update the task data
1202 adminUpdateTaskData($id, 'status', 'DELETED');
1205 // Function to update task data
1206 function adminUpdateTaskData ($id, $row, $data) {
1209 // Not an admin so redirect better
1210 redirectToUrl('modules.php?module=index');
1213 // Is the id not set, then we need a backtrace here... :(
1215 // Initiate backtrace
1216 debug_report_bug(__FUNCTION__, __LINE__, sprintf("id is invalid: %s. row=%s, data=%s",
1224 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_task_system` SET `%s`='%s' WHERE `id`=%s LIMIT 1",
1229 ), __FUNCTION__, __LINE__);
1232 // Checks wether if the admin menu has entries
1233 function ifAdminMenuHasEntries ($action) {
1236 // Is the entry set?
1237 isset($GLOBALS['admin_menu_has_entries'][$action])
1239 // And do we have a menu for this action?
1240 $GLOBALS['admin_menu_has_entries'][$action] === true
1242 // Login has always a menu
1248 // Setter for 'admin_menu_has_entries'
1249 function setAdminMenuHasEntries ($action, $hasEntries) {
1250 $GLOBALS['admin_menu_has_entries'][$action] = (bool) $hasEntries;
1253 // Creates a link to the user's admin-profile
1254 function adminCreateUserLink ($userid) {
1255 // Is the userid set correctly?
1257 // Create a link to that profile
1258 return '{%url=modules.php?module=admin&what=list_user&userid=' . bigintval($userid) . '%}';
1261 // Return a link to the user list
1262 return '{%url=modules.php?module=admin&what=list_user%}';
1265 // Generate a "link" for the given admin id (admin_id)
1266 function generateAdminLink ($adminId) {
1267 // No assigned admin is default
1268 $adminLink = '<span class="admin_note">{--ADMIN_NO_ADMIN_ASSIGNED--}</span>';
1270 // Zero? = Not assigned
1271 if (bigintval($adminId) > 0) {
1272 // Load admin's login
1273 $login = getAdminLogin($adminId);
1275 // Is the login valid?
1276 if ($login != '***') {
1277 // Is the extension there?
1278 if (isExtensionActive('admins')) {
1280 $adminLink = '<a href="' . generateEmailLink(getAdminEmail($adminId), 'admins') . '" title="{--ADMIN_CONTACT_LINK_TITLE--}">' . $login . '</a>';
1282 // Extension not found
1283 $adminLink = getMaskedMessage('EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED', 'admins');
1287 $adminLink = '<div class="admin_note">' . getMaskedMessage('ADMIN_ID_404', $adminId) . '</div>';
1295 // Verifies if the current admin has confirmed to alter expert settings
1298 // 'failed' = Something goes wrong (default)
1299 // 'agreed' = Has verified and and confirmed it to see them
1300 // 'forbidden' = Has not the proper right to alter them
1301 // 'update' = Need to update extension 'admins'
1302 // 'ask' = A form was send to the admin
1303 function doVerifyExpertSettings () {
1304 // Default return status is failed
1307 // Is the extension installed and recent?
1308 if (isExtensionInstalledAndNewer('admins', '0.7.3')) {
1309 // Okay, load the status
1310 $expertSettings = getAminsExpertSettings();
1313 if ($expertSettings == 'Y') {
1314 // Okay, does he want to see them?
1315 if (getAminsExpertWarning() == 'Y') {
1318 // Is the element set, then we need to change the admin
1319 if (isPostRequestParameterSet('expert_settings')) {
1320 // Get it and prepare final post data array
1321 $postData['login'][getCurrentAdminId()] = getAdminLogin(getCurrentAdminId());
1322 $postData['expert_warning'][getCurrentAdminId()] = 'N';
1324 // Change it in the admin
1325 adminsChangeAdminAccount($postData, 'expert_warning');
1328 unsetPostRequestParameter('ok');
1335 loadTemplate('admin_expert_settings_form');
1346 $return = 'forbidden';
1349 // Out-dated extension or not installed
1353 // Output message for other status than ask/agreed
1354 if (($return != 'ask') && ($return != 'agreed')) {
1356 loadTemplate('admin_settings_saved', false, '{--ADMIN_EXPERT_SETTINGS_STATUS_' . strtoupper($return) . '--}');
1363 // Generate link to unconfirmed mails for admin
1364 function generateUnconfirmedAdminLink ($id, $unconfirmed, $type = 'bid') {
1366 $OUT = $unconfirmed;
1368 // Do we have unconfirmed mails?
1369 if ($unconfirmed > 0) {
1370 // Add link to list_unconfirmed what-file
1371 $OUT = '<a href="{%url=modules.php?module=admin&what=list_unconfirmed&' . $type . '=' . $id . '%}">' . translateComma($unconfirmed) . '</a>';
1378 // Generates a navigation row for listing emails
1379 function addEmailNavigation ($numPages, $offset, $show_form, $colspan, $return=false) {
1380 // Don't do anything if $numPages is 1
1381 if ($numPages == 1) {
1382 // Abort here with empty content
1387 if ($show_form === false) {
1392 for ($page = 1; $page <= $numPages; $page++) {
1393 // Is the page currently selected or shall we generate a link to it?
1394 if (($page == getRequestParameter('page')) || ((!isGetRequestParameterSet('page')) && ($page == 1))) {
1395 // Is currently selected, so only highlight it
1396 $NAV .= '<strong>-';
1398 // Open anchor tag and add base URL
1399 $NAV .= '<a href="{%url=modules.php?module=admin&what=' . getWhat() . '&page=' . $page . '&offset=' . $offset;
1401 // Add userid when we shall show all mails from a single member
1402 if ((isGetRequestParameterSet('userid')) && (bigintval(getRequestParameter('userid')) > 0)) $NAV .= '&userid=' . bigintval(getRequestParameter('userid'));
1404 // Close open anchor tag
1408 if (($page == getRequestParameter('page')) || ((!isGetRequestParameterSet('page')) && ($page == 1))) {
1409 // Is currently selected, so only highlight it
1410 $NAV .= '-</strong>';
1416 // Add seperator if we have not yet reached total pages
1417 if ($page < $numPages) {
1423 // Define constants only once
1424 $content['nav'] = $NAV;
1425 $content['span'] = $colspan;
1426 $content['top'] = $TOP;
1428 // Load navigation template
1429 $OUT = loadTemplate('admin_email_nav_row', true, $content);
1431 if ($return === true) {
1432 // Return generated HTML-Code