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 * For more information visit: http://www.mxchange.org *
23 * This program is free software; you can redistribute it and/or modify *
24 * it under the terms of the GNU General Public License as published by *
25 * the Free Software Foundation; either version 2 of the License, or *
26 * (at your option) any later version. *
28 * This program is distributed in the hope that it will be useful, *
29 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
30 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
31 * GNU General Public License for more details. *
33 * You should have received a copy of the GNU General Public License *
34 * along with this program; if not, write to the Free Software *
35 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
37 ************************************************************************/
39 // Some security stuff...
40 if (!defined('__SECURITY')) {
44 // Register an administrator account
45 function addAdminAccount ($adminLogin, $passHash, $adminEmail) {
46 // Login does already exist
50 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
51 array($adminLogin), __FUNCTION__, __LINE__);
53 // Is the entry there?
54 if (SQL_NUMROWS($result) == '0') {
55 // Ok, let's create the admin login
56 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_admins` (`login`, `password`, `email`) VALUES ('%s', '%s', '%s')",
61 ), __FUNCTION__, __LINE__);
68 SQL_FREERESULT($result);
74 // This function will be executed when the admin is not logged in and has submitted his login data
75 function ifAdminLoginDataIsValid ($adminLogin, $adminPassword) {
76 // First of all, no admin login is found
79 // Then we need to lookup the login name by getting the admin hash
80 $adminHash = getAdminHash($adminLogin);
82 // If this is fine, we can continue
83 if ($adminHash != '-1') {
84 // Get admin id and set it as current
85 setCurrentAdminId(getAdminId($adminLogin));
87 // Now, we need to encode the password in the same way the one is encoded in database
88 $testHash = generateHash($adminPassword, $adminHash);
90 // If they both match, the login data is valid
91 if ($testHash == $adminHash) {
100 // Prepare data array
102 'login' => $adminLogin,
103 'plain_pass' => $adminPassword,
104 'pass_hash' => $adminHash
107 // Run a special filter
108 runFilterChain('do_admin_login_' . $ret, $data);
114 // Only be executed on cookie checking
115 function ifAdminCookiesAreValid ($adminLogin, $passHash) {
116 // First of all, no admin login is found
119 // Then we need to lookup the login name by getting the admin hash
120 $adminHash = getAdminHash($adminLogin);
122 // If this is fine, we can continue
123 if ($adminHash != '-1') {
124 // Now, we need to encode the password in the same way the one is encoded in database
125 $testHash = encodeHashForCookie($adminHash);
126 //* DEBUG: */ outputHtml('adminLogin='.$adminLogin.',<br />passHash='.$passHash.',<br />adminHash='.$adminHash.',<br />testHash='.$testHash.'<br />');
128 // If they both match, the login data is valid
129 if ($testHash == $passHash) {
139 //* DEBUG: */ outputHtml('ret='.$ret);
143 // Do an admin action
144 function doAdminAction () {
148 //* DEBUG: */ outputHtml(__LINE__.'*'.$what.'/'.getModule().'/'.getAction().'/'.getWhat().'*<br />');
150 // Remove any spaces from variable
152 // Default admin action is the overview page
156 $what = secureString($what);
160 $action = getActionFromModuleWhat(getModule(), $what);
162 // Define admin login name and id number
163 $content['login'] = getSession('admin_login');
164 $content['id'] = getCurrentAdminId();
167 if (isExtensionActive('admins')) {
168 $content['welcome'] = loadTemplate('admin_welcome_admins', true, $content);
170 $content['welcome'] = loadTemplate('admin_welcome', true, $content);
172 $content['footer'] = loadTemplate('admin_footer' , true, $content);
173 $content['menu'] = addAdminMenu($action, $what, true);
176 loadTemplate('admin_main_header', false, $content);
178 // Check if action/what pair is valid
179 $result_action = SQL_QUERY_ESC("SELECT
182 `{?_MYSQL_PREFIX?}_admin_menu`
187 `what`='%s' AND `what` != 'overview'
190 `what`='' OR `what` IS NULL
201 ), __FUNCTION__, __LINE__);
203 // Do we have an entry?
204 if (SQL_NUMROWS($result_action) == 1) {
205 // Is valid but does the inlcude file exists?
206 $inc = sprintf("inc/modules/admin/action-%s.php", $action);
207 if ((isIncludeReadable($inc)) && (isMenuActionValid('admin', $action, $what)) && ($GLOBALS['acl_allow'] === true)) {
208 // Ok, we finally load the admin action module
210 } elseif ($GLOBALS['acl_allow'] === false) {
212 loadTemplate('admin_menu_failed', false, getMaskedMessage('ADMIN_ACCESS_DENIED', $what));
214 // Include file not found! :-(
215 loadTemplate('admin_menu_failed', false, getMaskedMessage('ADMIN_ACTION_404', $action));
218 // Invalid action/what pair found!
219 loadTemplate('admin_menu_failed', false, getMaskedMessage('ADMIN_ACTION_INVALID', $action . '/' . $what));
223 SQL_FREERESULT($result_action);
226 loadTemplate('admin_main_footer', false, $content);
229 // Adds an admin menu
230 function addAdminMenu ($action, $what, $return=false) {
236 $GLOBALS['menu']['description'] = array();
237 $GLOBALS['menu']['title'] = array();
240 $result_main = SQL_QUERY("SELECT
241 `action`, `title`, `descr`
243 `{?_MYSQL_PREFIX?}_admin_menu`
245 (`what`='' OR `what` IS NULL)
248 `id` DESC", __FUNCTION__, __LINE__);
250 // Do we have entries?
251 if (SQL_NUMROWS($result_main) > 0) {
252 $OUT .= '<ul class="admin_menu_main">';
253 // @TODO Rewrite this to $content = SQL_FETCHARRAY()
254 while (list($menu, $title, $descr) = SQL_FETCHROW($result_main)) {
255 if ((isExtensionActive('admins')) && (getExtensionVersion('admins') > '0.2.0')) {
256 $ACL = adminsCheckAdminAcl($menu, '');
258 // @TODO ACL is 'allow'... hmmm
263 $inc = sprintf("inc/modules/admin/action-%s.php", $menu);
265 // Is the file readable?
266 $readable = isIncludeReadable($inc);
269 if ($SUB === false) {
270 // Insert compiled menu title and description
271 $GLOBALS['menu']['title'][$menu] = $title;
272 $GLOBALS['menu']['description'][$menu] = $descr;
274 $OUT .= '<li class="admin_menu">
275 <div class="nobr"><strong>·</strong> ';
277 if ($readable === true) {
278 if (($menu == $action) && (empty($what))) {
281 $OUT .= '[<a href="{%url=modules.php?module=admin&action=' . $menu . '%}">';
284 $OUT .= '<em style="cursor:help" class="admin_note" title="{--MENU_ACTION_404--}">';
289 if ($readable === true) {
290 if (($menu == $action) && (empty($what))) {
302 // Check for menu entries
303 $result_what = SQL_QUERY_ESC("SELECT
304 `what`, `title`, `descr`
306 `{?_MYSQL_PREFIX?}_admin_menu`
314 array($menu), __FUNCTION__, __LINE__);
316 // Remember the count for later checks
317 setAdminMenuHasEntries($menu, ((SQL_NUMROWS($result_what) > 0) && ($action == $menu)));
319 // Do we have entries?
320 if ((ifAdminMenuHasEntries($menu)) && (SQL_NUMROWS($result_what) > 0)) {
321 $GLOBALS['menu']['description'] = array();
322 $GLOBALS['menu']['title'] = array(); $SUB = true;
323 $OUT .= '<li class="admin_menu_sub"><ul class="admin_menu_sub">';
324 // @TODO Rewrite this to $content = SQL_FETCHARRAY()
325 while (list($what_sub, $title_what, $desc_what) = SQL_FETCHROW($result_what)) {
326 // Check for access level
327 if ((isExtensionActive('admins')) && (getExtensionVersion('admins') > '0.2.0')) {
328 $ACL = adminsCheckAdminAcl('', $what_sub);
330 // @TODO ACL is 'allow'... hmmm
335 $inc = sprintf("inc/modules/admin/what-%s.php", $what_sub);
337 // Is the file readable?
338 $readable = isIncludeReadable($inc);
342 // Insert compiled title and description
343 $GLOBALS['menu']['title'][$what_sub] = $title_what;
344 $GLOBALS['menu']['description'][$what_sub] = $desc_what;
345 $OUT .= '<li class="admin_menu">
346 <div class="nobr"><strong>--></strong> ';
347 if ($readable === true) {
348 if ($what == $what_sub) {
351 $OUT .= '[<a href="{%url=modules.php?module=admin&what=' . $what_sub . '%}">';
354 $OUT .= '<em style="cursor:help" class="admin_note" title="{--MENU_WHAT_404--}">';
359 if ($readable === true) {
360 if ($what == $what_sub) {
374 SQL_FREERESULT($result_what);
382 SQL_FREERESULT($result_main);
386 // Is there a cache instance again?
387 // Return or output content?
388 if ($return === true) {
395 // Create member selection box
396 function addMemberSelectionBox ($def=0, $add_all=false, $return=false, $none=false, $field='userid') {
397 // Output selection form with all confirmed user accounts listed
398 $result = SQL_QUERY("SELECT `userid`, `surname`, `family` FROM `{?_MYSQL_PREFIX?}_user_data` ORDER BY `userid` ASC", __FUNCTION__, __LINE__);
403 // USe this only for adding points (e.g. adding refs really makes no sence ;-) )
404 if ($add_all === true) $OUT = ' <option value="all">{--ALL_MEMBERS--}</option>';
405 elseif ($none === true) $OUT = ' <option value="0">{--SELECT_NONE--}</option>';
407 while ($content = SQL_FETCHARRAY($result)) {
408 $OUT .= ' <option value="' . bigintval($content['userid']) . '"';
409 if ($def == $content['userid']) $OUT .= ' selected="selected"';
410 $OUT .= '>' . $content['surname'] . ' ' . $content['family'] . ' (' . bigintval($content['userid']) . ')</option>';
414 SQL_FREERESULT($result);
416 if ($return === false) {
417 // Remeber options in constant
418 $content['member_selection'] = $OUT;
419 $content['what'] = getWhat();
422 loadTemplate('admin_member_selection_box', false, $content);
424 // Return content in selection frame
425 return '<select class="admin_select" name="' . $field . '" size="1">' . $OUT . '</select>';
429 // Create a menu selection box for given menu system
430 // @TODO Try to rewrite this to adminAddMenuSelectionBox()
432 function adminMenuSelectionBox_DEPRECATED ($mode, $default = '', $defid = '') {
433 $what = "`what` != ''";
434 if ($mode == 'action') $what = "(`what`='' OR `what` IS NULL) AND `action` !='login'";
436 $result = SQL_QUERY_ESC("SELECT %s, `title` FROM `{?_MYSQL_PREFIX?}_admin_menu` WHERE ".$what." ORDER BY `sort` ASC",
437 array($mode), __FUNCTION__, __LINE__);
438 if (SQL_NUMROWS($result) > 0) {
439 // Load menu as selection
440 $OUT = "<select name=\"".$mode."_menu";
441 if ((!empty($defid)) || ($defid == '0')) $OUT .= "[".$defid."]";
442 $OUT .= "\" size=\"1\" class=\"admin_select\">
443 <option value=\"\">{--SELECT_NONE--}</option>\n";
444 // @TODO Try to rewrite this to $content = SQL_FETCHARRAY(). Please look some lines above for the dynamic query
445 while (list($menu, $title) = SQL_FETCHROW($result)) {
446 $OUT .= " <option value=\"".$menu."\"";
447 if ((!empty($default)) && ($default == $menu)) $OUT .= ' selected="selected"';
448 $OUT .= ">".$title."</option>\n";
452 SQL_FREERESULT($result);
453 $OUT .= "</select>\n";
456 $OUT = getMessage('ADMIN_PROBLEM_NO_MENU');
463 // Wrapper for $_POST and adminSaveSettings
464 function adminSaveSettingsFromPostData ($tableName = '_config', $whereStatement = '`config`=0', $translateComma = array(), $alwaysAdd = false, $displayMessage = true) {
466 $postData = postRequestArray();
468 // Call the lower function
469 adminSaveSettings($postData, $tableName, $whereStatement, $translateComma, $alwaysAdd, $displayMessage);
472 // Save settings to the database
473 function adminSaveSettings (&$postData, $tableName = '_config', $whereStatement = '`config`=0', $translateComma = array(), $alwaysAdd = false, $displayMessage = true) {
474 // Prepare all arrays, variables
475 $tableData = array();
478 // Now, walk through all entries and prepare them for saving
479 foreach ($postData as $id => $val) {
480 // Process only formular field but not submit buttons ;)
482 // Do not save the ok value
483 convertSelectionsToTimestamp($postData, $tableData, $id, $skip);
485 // Shall we process this id? It muss not be empty, of course
486 if (($skip === false) && (!empty($id)) && ((!isset($GLOBALS['skip_config'][$id]))) || ($tableName != '_config')) {
487 // Translate the value? (comma to dot!)
488 if ((is_array($translateComma)) && (in_array($id, $translateComma))) {
489 // Then do it here... :)
490 $val = convertCommaToDot($val);
493 // Shall we add numbers or strings?
495 if ('' . $val . '' == '' . $test . '') {
497 $tableData[] = sprintf("`%s`=%s", $id, $test);
500 $tableData[] = sprintf("`%s`='%s'", $id, trim($val));
503 // Do not add a config entry twice
504 $GLOBALS['skip_config'][$id] = true;
506 // Update current configuration
507 setConfigEntry($id, $val);
512 // Check if entry does exist
514 if ($alwaysAdd === false) {
515 if (!empty($whereStatement)) {
516 $result = SQL_QUERY("SELECT * FROM `{?_MYSQL_PREFIX?}" . $tableName . "` WHERE " . $whereStatement . " LIMIT 1", __FUNCTION__, __LINE__);
518 $result = SQL_QUERY("SELECT * FROM `{?_MYSQL_PREFIX?}" . $tableName . "` LIMIT 1", __FUNCTION__, __LINE__);
522 if (SQL_NUMROWS($result) == 1) {
523 // "Implode" all data to single string
524 $updatedData = implode(', ', $tableData);
526 // Generate SQL string
527 $sql = sprintf("UPDATE `{?_MYSQL_PREFIX?}%s` SET %s WHERE %s LIMIT 1",
533 // Add Line (does only work with auto_increment!
534 $keys = array(); $values = array();
535 foreach ($tableData as $entry) {
537 $line = explode('=', $entry);
539 $values[] = $line[1];
542 // Add both in one line
543 $keys = implode('`, `', $keys);
544 $values = implode(', ', $values);
546 // Generate SQL string
547 $sql = sprintf("INSERT INTO `{?_MYSQL_PREFIX?}%s` (%s) VALUES (%s)",
555 SQL_FREERESULT($result);
557 // Simply run generated SQL string
558 SQL_QUERY($sql, __FUNCTION__, __LINE__);
560 // Remember affected rows
561 $affected = SQL_AFFECTEDROWS();
564 rebuildCache('config', 'config');
566 // Settings saved, so display message?
567 if ($displayMessage === true) loadTemplate('admin_settings_saved', false, getMessage('SETTINGS_SAVED'));
569 // Return affected rows
573 // Generate a selection box
574 function adminAddMenuSelectionBox ($menu, $type, $name, $default = '') {
575 // Open the requested menu directory
576 $menuArray = getArrayFromDirectory(sprintf("inc/modules/%s/", $menu), '', false, false);
578 // Init the selection box
579 $OUT = "<select name=\"".$name."\" class=\"admin_select\" size=\"1\">
580 <option value=\"\">{--IS_TOP_MENU--}</option>\n";
582 // Walk through all files
583 foreach ($menuArray as $file) {
584 // Is this a PHP script?
585 if ((!isDirectory($file)) && (strpos($file, "".$type.'-') > -1) && (strpos($file, '.php') > 0)) {
586 // Then test if the file is readable
587 $test = sprintf("inc/modules/%s/%s", $menu, $file);
589 // Is the file there?
590 if (isIncludeReadable($test)) {
591 // Extract the value for what=xxx
592 $part = substr($file, (strlen($type) + 1));
593 $part = substr($part, 0, -4);
595 // Is that part different from the overview?
596 if ($part != 'overview') {
597 $OUT .= " <option value=\"".$part."\"";
598 if ($part == $default) $OUT .= ' selected="selected"';
599 $OUT .= ">".$part."</option>\n";
605 // Close selection box
606 $OUT .= "</select>\n";
612 // Creates a user-profile link for the admin. This function can also be used for many other purposes
613 function generateUserProfileLink ($userid, $title = '', $what = 'list_user') {
614 if (($title == '') && ($userid > 0)) {
615 // Set userid as title
617 } elseif ($userid == 0) {
618 // User id zero is invalid
619 return '<strong>' . $userid . '</strong>';
622 if (($title == '0') && ($what == 'list_refs')) {
623 // Return title again
625 } elseif (isExtensionActive('nickname')) {
627 $nick = getNickname($userid);
629 // Is it not empty, use it as title else the userid
630 if (!empty($nick)) $title = $nick . '(' . $userid . ')'; else $title = $userid;
634 return '[<a href="{%url=modules.php?module=admin&what=' . $what . '&userid=' . $userid . '%}" title="{--ADMIN_USER_PROFILE_TITLE--}">' . $title . '</a>]';
637 // Check "logical-area-mode"
638 function adminGetMenuMode () {
639 // Set the default menu mode as the mode for all admins
640 $mode = getConfig('admin_menu');
644 $adminId = getCurrentAdminId();
646 // Check individual settings of current admin
647 if (isset($GLOBALS['cache_array']['admin']['la_mode'][$adminId])) {
649 $adminMode = $GLOBALS['cache_array']['admin']['la_mode'][$adminId];
650 incrementStatsEntry('cache_hits');
651 } elseif (isExtensionInstalledAndNewer('admins', '0.6.7')) {
652 // Load from database when version of 'admins' is enough
653 $result = SQL_QUERY_ESC("SELECT la_mode FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
654 array($adminId), __FUNCTION__, __LINE__);
656 // Do we have an entry?
657 if (SQL_NUMROWS($result) == 1) {
659 list($adminMode) = SQL_FETCHROW($result);
663 SQL_FREERESULT($result);
666 // Check what the admin wants and set it when it's not the default mode
667 if ($adminMode != 'global') $mode = $adminMode;
669 // Return admin-menu's mode
673 // Change activation status
674 function adminChangeActivationStatus ($IDs, $table, $row, $idRow = 'id') {
675 $cnt = '0'; $newStatus = 'Y';
676 if ((is_array($IDs)) && (count($IDs) > 0)) {
677 // "Walk" all through and count them
678 foreach ($IDs as $id => $selected) {
679 // Secure the id number
680 $id = bigintval($id);
682 // Should always be set... ;-)
683 if (!empty($selected)) {
684 // Determine new status
685 $result = SQL_QUERY_ESC("SELECT %s FROM `{?_MYSQL_PREFIX?}_%s` WHERE %s=%s LIMIT 1",
686 array($row, $table, $idRow, $id), __FUNCTION__, __LINE__);
689 if (SQL_NUMROWS($result) == 1) {
691 list($currStatus) = SQL_FETCHROW($result);
693 // And switch it N<->Y
694 if ($currStatus == 'Y') $newStatus = 'N'; else $newStatus = 'Y';
696 // Change this status
697 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s` SET %s='%s' WHERE %s=%s LIMIT 1",
698 array($table, $row, $newStatus, $idRow, $id), __FUNCTION__, __LINE__);
700 // Count up affected rows
701 $cnt += SQL_AFFECTEDROWS();
705 SQL_FREERESULT($result);
710 loadTemplate('admin_settings_saved', false, sprintf(getMessage('ADMIN_STATUS_CHANGED'), $cnt, count($IDs)));
713 loadTemplate('admin_settings_saved', false, getMessage('ADMIN_NOTHING_SELECTED_CHANGE'));
717 // Send mails for del/edit/lock build modes
718 function sendAdminBuildMails ($mode, $table, $content, $id, $subjectPart = '') {
719 // Default subject is the subject part
720 $subject = $subjectPart;
722 // Is the subject part not set?
723 if (empty($subjectPart)) {
724 // Then use it from the mode
725 $subject = strtoupper($mode);
728 // Is the raw userid set?
729 if (postRequestParameter('userid_raw', $id) > 0) {
731 $subjectLine = getMessage('MEMBER_'.strtoupper($subject).'_'.strtoupper($table).'_SUBJECT');
733 // Load email template
734 if (!empty($subjectPart)) {
735 $mail = loadEmailTemplate('member_' . $mode . '_' . strtolower($subjectPart) . '_' . $table, $content);
737 $mail = loadEmailTemplate('member_' . $mode . '_' . $table, $content);
741 sendEmail(postRequestParameter('userid_raw', $id), $subjectLine, $mail);
745 $subjectLine = getMessage('ADMIN_'.strtoupper($subject).'_'.strtoupper($table).'_SUBJECT');
747 // Send admin notification out
748 if (!empty($subjectPart)) {
749 sendAdminNotification($subjectLine, 'admin_' . $mode . '_' . strtolower($subjectPart) . '_' . $table, $content, postRequestParameter('userid_raw', $id));
751 sendAdminNotification($subjectLine, 'admin_' . $mode . '_' . $table, $content, postRequestParameter('userid_raw', $id));
755 // Build a special template list
756 function adminListBuilder ($listType, $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn) {
759 // "Walk"Â through all entries
760 foreach ($IDs as $id => $selected) {
762 $id = bigintval($id);
764 // Get result from a given column array and table name
765 $result = SQL_RESULT_FROM_ARRAY($table, $columns, $idColumn, $id, __FUNCTION__, __LINE__);
767 // Is there one entry?
768 if (SQL_NUMROWS($result) == 1) {
770 $content = SQL_FETCHARRAY($result);
773 foreach ($content as $key => $value) {
775 $idx = array_search($key, $columns, true);
777 //Â Do we have a userid?
778 if ($key == 'userid') {
779 // Add it again as raw id
780 $content['userid'] = bigintval($value);
783 // Handle the call in external function
784 $content[$key] = handleExtraValues($filterFunctions[$idx], $value, $extraValues[$idx]);
787 // Add color switching
788 $content['sw'] = $SW;
791 $OUT .= loadTemplate(sprintf("admin_%s_%s_row",
802 SQL_FREERESULT($result);
805 // Load master template
806 loadTemplate(sprintf("admin_%s_%s",
813 // Change status of "build" list
814 function adminBuilderStatusHandler ($mode, $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray) {
815 // All valid entries? (We hope so here!)
816 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues)) && (count($statusArray) > 0)) {
817 // "Walk" through all entries
818 foreach ($IDs as $id => $sel) {
819 // Construct SQL query
820 $sql = sprintf("UPDATE `{?_MYSQL_PREFIX?}_%s` SET", SQL_ESCAPE($table));
822 // Load data of entry
823 $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_%s` WHERE %s=%s LIMIT 1",
824 array($table, $idColumn, $id), __FUNCTION__, __LINE__);
827 $content = SQL_FETCHARRAY($result);
830 SQL_FREERESULT($result);
832 // Add all status entries (e.g. status column last_updated or so)
833 $newStatus = 'UNKNOWN';
834 $oldStatus = 'UNKNOWN';
835 $statusColumn = 'unknown';
836 foreach ($statusArray as $column => $statusInfo) {
837 // Does the entry exist?
838 if ((isset($content[$column])) && (isset($statusInfo[$content[$column]]))) {
839 // Add these entries for update
840 $sql .= sprintf(" %s='%s',", SQL_ESCAPE($column), SQL_ESCAPE($statusInfo[$content[$column]]));
843 if ($statusColumn == 'unknown') {
844 // Always (!!!) change status column first!
845 $oldStatus = $content[$column];
846 $newStatus = $statusInfo[$oldStatus];
847 $statusColumn = $column;
849 } elseif (isset($content[$column])) {
851 app_die(__FUNCTION__, __LINE__, ":UNFINISHED: id={$id}/{$column}[".gettype($statusInfo)."] = {$content[$column]}");
855 // Add other columns as well
856 foreach (postRequestArray() as $key => $entries) {
857 // Skip id, raw userid and 'do_$mode'
858 if (!in_array($key, array($idColumn, 'userid_raw', ('do_'.$mode)))) {
859 // Are there brackets () at the end?
860 if (substr($entries[$id], -2, 2) == "()") {
861 // Direct SQL command found
862 $sql .= sprintf(" %s=%s,", SQL_ESCAPE($key), SQL_ESCAPE($entries[$id]));
865 $sql .= sprintf(" %s='%s',", SQL_ESCAPE($key), SQL_ESCAPE($entries[$id]));
868 $content[$key] = $entries[$id];
873 // Finish SQL statement
874 $sql = substr($sql, 0, -1) . sprintf(" WHERE `%s`=%s AND `%s`='%s' LIMIT 1",
882 SQL_QUERY($sql, __FUNCTION__, __LINE__);
884 // Do we have an URL?
885 if (isset($content['url'])) {
886 // Then add a framekiller test as well
887 $content['frametester'] = generateFrametesterUrl($content['url']);
890 // Send "build mails" out
891 sendAdminBuildMails($mode, $table, $content, $id, $statusInfo[$content[$column]]);
896 // Delete rows by given id numbers
897 function adminDeleteEntriesConfirm ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $deleteNow=false, $idColumn='id', $userIdColumn='userid') {
898 // All valid entries? (We hope so here!)
899 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues))) {
900 // Shall we delete here or list for deletion?
901 if ($deleteNow === true) {
902 // The base SQL command:
903 $sql = "DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_%s` WHERE %s IN (%s)";
907 foreach ($IDs as $id => $sel) {
908 // Is there a userid?
909 if (isPostRequestParameterSet('userid_raw', $id)) {
910 // Load all data from that id
911 $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_%s` WHERE %s=%s LIMIT 1",
912 array($table, $idColumn, $id), __FUNCTION__, __LINE__);
915 $content = SQL_FETCHARRAY($result);
918 SQL_FREERESULT($result);
920 // Send "build mails" out
921 sendAdminBuildMails('del', $table, $content, $id);
925 $idList .= $id . ',';
929 SQL_QUERY($sql, array($table, $idColumn, substr($idList, 0, -1)), __FUNCTION__, __LINE__);
932 if (SQL_AFFECTEDROWS() == count($IDs)) {
934 loadTemplate('admin_settings_saved', false, getMessage('ADMIN_ALL_ENTRIES_REMOVED'));
936 // Some are still there :(
937 loadTemplate('admin_settings_saved', false, sprintf(getMessage('ADMIN_SOME_ENTRIES_NOT_DELETED'), SQL_AFFECTEDROWS(), count($IDs)));
940 // List for deletion confirmation
941 adminListBuilder('del', $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
946 // Edit rows by given id numbers
947 function adminEditEntriesConfirm ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $editNow=false, $idColumn='id', $userIdColumn='userid') {
948 // All valid entries? (We hope so here!)
949 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues))) {
950 // Shall we change here or list for editing?
951 if ($editNow === true) {
954 foreach ($IDs as $id => $sel) {
955 // Prepare content array (new values)
958 // Prepare SQL for this row
959 $sql = sprintf("UPDATE `{?_MYSQL_PREFIX?}_%s` SET",
962 foreach (postRequestArray() as $key => $entries) {
963 // Skip raw userid which is always invalid
964 if ($key == 'userid_raw') {
965 // Continue with next field
969 // Is entries an array?
970 if (($key != $idColumn) && (is_array($entries)) && (isset($entries[$id]))) {
971 // Add this entry to content
972 $content[$key] = $entries[$id];
974 // Send data through the filter function if found
975 if ((isset($filterFunctions[$key])) && (isset($extraValues[$key]))) {
976 // Filter function set!
977 $entries[$id] = handleExtraValues($filterFunctions[$key], $entries[$id], $extraValues[$key]);
980 // Then add this value
981 $sql .= sprintf(" `%s`='%s',",
983 SQL_ESCAPE($entries[$id])
985 } elseif (($key != $idColumn) && (!is_array($entries))) {
986 // Add normal entries as well!
987 $content[$key] = $entries;
990 // Do we have an URL?
992 // Then add a framekiller test as well
993 $content['frametester'] = generateFrametesterUrl($content[$key]);
997 // Finish SQL command
998 $sql = substr($sql, 0, -1) . " WHERE `" . $idColumn . "`=" . bigintval($id) . " LIMIT 1";
1001 SQL_QUERY($sql, __FUNCTION__, __LINE__);
1003 // Add affected rows
1004 $affected += SQL_AFFECTEDROWS();
1006 // Load all data from that id
1007 $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`=%s LIMIT 1",
1008 array($table, $idColumn, $id), __FUNCTION__, __LINE__);
1010 // Fetch the data and merge it into $content
1011 $content = merge_array($content, SQL_FETCHARRAY($result));
1014 SQL_FREERESULT($result);
1016 // Send "build mails" out
1017 sendAdminBuildMails('edit', $table, $content, $id);
1021 if ($affected == count($IDs)) {
1023 loadTemplate('admin_settings_saved', false, getMessage('ADMIN_ALL_ENTRIES_EDITED'));
1025 // Some are still there :(
1026 loadTemplate('admin_settings_saved', false, sprintf(getMessage('ADMIN_SOME_ENTRIES_NOT_EDITED'), $affected, count($IDs)));
1030 adminListBuilder('edit', $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1035 // Un-/lock rows by given id numbers
1036 function adminLockEntriesConfirm ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $statusArray=array(), $lockNow=false, $idColumn='id', $userIdColumn='userid') {
1037 // All valid entries? (We hope so here!)
1038 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues)) && (($lockNow === false) || (count($statusArray) == 1))) {
1039 // Shall we un-/lock here or list for locking?
1040 if ($lockNow === true) {
1042 adminBuilderStatusHandler('lock', $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray);
1045 adminListBuilder('lock', $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1050 // Undelete rows by given id numbers
1051 function adminUndeleteEntriesConfirm ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $statusArray=array(), $undeleteNow=false, $idColumn='id', $userIdColumn='userid') {
1052 // All valid entries? (We hope so here!)
1053 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues)) && (($undeleteNow === false) || (count($statusArray) == 1))) {
1054 // Shall we un-/lock here or list for locking?
1055 if ($undeleteNow === true) {
1057 adminBuilderStatusHandler('undelete', $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray);
1060 adminListBuilder('undelete', $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1065 // Checks proxy settins by fetching check-updates3.php from www.mxchange.org
1066 function adminTestProxySettings ($settingsArray) {
1067 // Set temporary the new settings
1068 mergeConfig($settingsArray);
1070 // Now get the test URL
1071 $content = sendGetRequest('check-updates3.php');
1073 // Is the first line with "200 OK"?
1074 $valid = (strpos($content[0], '200 OK') !== false);
1080 // Sends out a link to the given email adress so the admin can reset his/her password
1081 function sendAdminPasswordResetLink ($email) {
1085 //Â Look up administator login
1086 $result = SQL_QUERY_ESC("SELECT `id`, `login`, `password` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `email`='%s' LIMIT 1",
1087 array($email), __FUNCTION__, __LINE__);
1089 // Is there an account?
1090 if (SQL_NUMROWS($result) == '0') {
1091 // No account found!
1092 return getMessage('ADMIN_NO_LOGIN_WITH_EMAIL');
1096 $content = SQL_FETCHARRAY($result);
1099 SQL_FREERESULT($result);
1101 // Generate hash for reset link
1102 $content['hash'] = generateHash(getConfig('URL') . ':' . $content['id'] . ':' . $content['login'] . ':' . $content['password'], substr($content['password'], 10));
1105 unset($content['id']);
1106 unset($content['password']);
1109 $mailText = loadEmailTemplate('admin_reset_password', $content);
1112 sendEmail($email, getMessage('ADMIN_RESET_PASS_LINK_SUBJ'), $mailText);
1115 return getMessage('ADMIN_RESET_LINK_SENT');
1118 // Validate hash and login for password reset
1119 function adminResetValidateHashLogin ($hash, $login) {
1120 // By default nothing validates... ;)
1123 // Then try to find that user
1124 $result = SQL_QUERY_ESC("SELECT `id`, `password`, `email` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
1125 array($login), __FUNCTION__, __LINE__);
1127 // Is an account here?
1128 if (SQL_NUMROWS($result) == 1) {
1130 $content = SQL_FETCHARRAY($result);
1132 // Generate hash again
1133 $hashFromData = generateHash(getConfig('URL') . ':' . $content['id'] . ':' . $login . ':' . $content['password'], substr($content['password'], 10));
1136 $valid = ($hash == $hashFromData);
1140 SQL_FREERESULT($result);
1146 // Reset the password for the login. Do NOT call this function without calling above function first!
1147 function doResetAdminPassword ($login, $password) {
1148 // Generate hash (we already check for sql_patches in generateHash())
1149 $passHash = generateHash($password);
1152 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_admins` SET `password`='%s' WHERE `login`='%s' LIMIT 1",
1153 array($passHash, $login), __FUNCTION__, __LINE__);
1156 runFilterChain('post_admin_reset_pass', array('login' => $login, 'hash' => $passHash));
1159 return getMessage('ADMIN_PASSWORD_RESET_DONE');
1162 // Solves a task by given id number
1163 function adminSolveTask ($id) {
1164 // Update the task data
1165 adminUpdateTaskData($id, 'status', 'SOLVED');
1168 // Marks a given task as deleted
1169 function adminDeleteTask ($id) {
1170 // Update the task data
1171 adminUpdateTaskData($id, 'status', 'DELETED');
1174 // Function to update task data
1175 function adminUpdateTaskData ($id, $row, $data) {
1178 // Not an admin so redirect better
1179 redirectToUrl('modules.php?module=index');
1182 // Is the id not set, then we need a backtrace here... :(
1184 // Initiate backtrace
1185 debug_report_bug(sprintf("id is invalid: %s. row=%s, data=%s",
1193 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_task_system` SET `%s`='%s' WHERE `id`=%s LIMIT 1",
1198 ), __FUNCTION__, __LINE__);
1201 // Checks wether if the admin menu has entries
1202 function ifAdminMenuHasEntries ($action) {
1205 // Is the entry set?
1206 isset($GLOBALS['admin_menu_has_entries'][$action])
1208 // And do we have a menu for this action?
1209 $GLOBALS['admin_menu_has_entries'][$action] === true
1211 // Login has always a menu
1217 // Setter for 'admin_menu_has_entries'
1218 function setAdminMenuHasEntries ($action, $hasEntries) {
1219 $GLOBALS['admin_menu_has_entries'][$action] = (bool) $hasEntries;
1222 // Creates a link to the user's admin-profile
1223 function adminCreateUserLink ($userid) {
1224 // Is the userid set correctly?
1226 // Create a link to that profile
1227 return '{%url=modules.php?module=admin&what=list_user&userid=' . bigintval($userid) . '%}';
1230 // Return a link to the user list
1231 return '{%url=modules.php?module=admin&what=list_user%}';
1234 // Generate a "link" for the given admin id (admin_id)
1235 function generateAdminLink ($adminId) {
1236 // No assigned admin is default
1237 $adminLink = '<span class="admin_note">{--ADMIN_NO_ADMIN_ASSIGNED--}</span>';
1239 // Zero? = Not assigned
1240 if (bigintval($adminId) > 0) {
1241 // Load admin's login
1242 $login = getAdminLogin($adminId);
1244 // Is the login valid?
1245 if ($login != '***') {
1246 // Is the extension there?
1247 if (isExtensionActive('admins')) {
1249 $adminLink = '<a href="' . generateEmailLink(getAdminEmail($adminId), 'admins') . '" title="{--ADMIN_CONTACT_LINK_TITLE--}">' . $login . '</a>';
1251 // Extension not found
1252 $adminLink = getMaskedMessage('EXTENSION_PROBLEM_NOT_INSTALLED', 'admins');
1256 $adminLink = '<div class="admin_note">' . getMaskedMessage('ADMIN_ID_404', $adminId) . '</div>';
1264 // Verifies if the current admin has confirmed to alter expert settings
1267 // 'failed' = Something goes wrong (default)
1268 // 'agreed' = Has verified and and confirmed it to see them
1269 // 'forbidden' = Has not the proper right to alter them
1270 // 'update' = Need to update extension 'admins'
1271 // 'ask' = A form was send to the admin
1272 function doVerifyExpertSettings () {
1273 // Default return status is failed
1276 // Is the extension installed and recent?
1277 if (isExtensionInstalledAndNewer('admins', '0.7.3')) {
1278 // Okay, load the status
1279 $expertSettings = getAminsExpertSettings();
1282 if ($expertSettings == 'Y') {
1283 // Okay, does he want to see them?
1284 if (getAminsExpertWarning() == 'Y') {
1287 // Is the element set, then we need to change the admin
1288 if (isPostRequestParameterSet('expert_settings')) {
1289 // Get it and prepare final post data array
1290 $postData['login'][getCurrentAdminId()] = getAdminLogin(getCurrentAdminId());
1291 $postData['expert_warning'][getCurrentAdminId()] = 'N';
1293 // Change it in the admin
1294 adminsChangeAdminAccount($postData, 'expert_warning');
1297 unsetPostRequestParameter('ok');
1304 loadTemplate('admin_expert_settings_form');
1315 $return = 'forbidden';
1318 // Out-dated extension or not installed
1322 // Output message for other status than ask/agreed
1323 if (($return != 'ask') && ($return != 'agreed')) {
1325 loadTemplate('admin_settings_saved', false, getMessage('ADMIN_EXPERT_SETTINGS_STATUS_' . strtoupper($return)));