2 /************************************************************************
3 * MXChange v0.2.1 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 * -------------------------------------------------------------------- *
14 * -------------------------------------------------------------------- *
15 * Copyright (c) 2003 - 2008 by Roland Haeder *
16 * For more information visit: http://www.mxchange.org *
18 * This program is free software; you can redistribute it and/or modify *
19 * it under the terms of the GNU General Public License as published by *
20 * the Free Software Foundation; either version 2 of the License, or *
21 * (at your option) any later version. *
23 * This program is distributed in the hope that it will be useful, *
24 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
25 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
26 * GNU General Public License for more details. *
28 * You should have received a copy of the GNU General Public License *
29 * along with this program; if not, write to the Free Software *
30 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
32 ************************************************************************/
34 // Some security stuff...
35 if (!defined('__SECURITY')) {
36 $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), "/inc") + 4) . "/security.php";
40 // Register an administrator account
41 function REGISTER_ADMIN ($user, $md5, $email) {
42 // Login does already exist
46 $result = SQL_QUERY_ESC("SELECT id FROM `{!_MYSQL_PREFIX!}_admins` WHERE login='%s' LIMIT 1",
47 array($user), __FUNCTION__, __LINE__);
49 // Is the entry there?
50 if (SQL_NUMROWS($result) == 0) {
51 // Ok, let's create the admin login
52 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_admins` (login, password, email) VALUES ('%s', '%s', '%s')",
53 array($user, $md5, $email), __FUNCTION__, __LINE__);
58 SQL_FREERESULT($result);
64 // Only be executed on login procedure!
65 function CHECK_ADMIN_LOGIN ($admin_login, $password) {
66 // By default no admin is found
70 $aid = GET_ADMIN_ID($admin_login);
72 // Init array with admin id by default
73 $data = array('aid' => $aid);
75 // Is the cache valid?
76 if (isset($GLOBALS['cache_array']['admins']['password'][$aid])) {
77 // Get password from cache
78 $data['password'] = $GLOBALS['cache_array']['admins']['password'][$aid];
80 incrementConfigEntry('cache_hits');
82 // Include more admins data?
83 if (GET_EXT_VERSION("admins") >= "0.7.0") {
85 $data['login_failures'] = $GLOBALS['cache_array']['admins']['login_failures'][$aid];
86 $data['last_failure'] = $GLOBALS['cache_array']['admins']['last_failure'][$aid];
88 } elseif (!EXT_IS_ACTIVE("cache")) {
89 // Add extra data via filter now
90 $ADD = runFilterChain('sql_admin_extra_data');
92 // Get password from DB
93 $result = SQL_QUERY_ESC("SELECT password".$ADD." FROM `{!_MYSQL_PREFIX!}_admins` WHERE id=%s LIMIT 1",
94 array($aid), __FUNCTION__, __LINE__);
97 if (SQL_NUMROWS($result) == 1) {
98 // Login password found
102 $data = SQL_FETCHARRAY($result);
106 SQL_FREERESULT($result);
109 //* DEBUG: */ echo "*".$data['password']."/".md5($password)."/".$ret."<br />";
110 if ((isset($data['password'])) && (strlen($data['password']) == 32) && ($data['password'] == md5($password))) {
112 $data['password'] = generateHash($password);
114 // Is the sql_patches not installed, than we cannot have a valid hashed password here!
115 if (($ret == "pass") && ((EXT_VERSION_IS_OLDER("sql_patches", "0.3.6")) || (GET_EXT_VERSION("sql_patches") == ""))) $ret = "done";
116 } elseif ((EXT_VERSION_IS_OLDER("sql_patches", "0.3.6")) || (GET_EXT_VERSION("sql_patches") == "")) {
119 } elseif (!isset($data['password'])) {
120 // Password not found, so no valid login!
124 // Generate salt of password
125 define('__SALT', substr($data['password'], 0, -40));
128 // Check if password is same
129 //* DEBUG: */ echo "*".$ret.",".$data['password'].",".$password.",".$salt."*<br >\n";
130 if (($ret == "pass") && ($data['password'] == generateHash($password, $salt)) && ((!empty($salt))) || ($data['password'] == $password)) {
131 // Re-hash the plain passord with new random salt
132 $data['password'] = generateHash($password);
134 // Do we have 0.7.0 of admins or later?
135 // Remmeber login failures if available
136 if (GET_EXT_VERSION("admins") >= "0.7.2") {
137 // Store it in session
138 set_session('mxchange_admin_failures', $data['login_failures']);
139 set_session('mxchange_admin_last_fail', $data['last_failure']);
141 // Update password and reset login failures
142 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_admins` SET password='%s',login_failures=0,last_failure='0000-00-00 00:00:00' WHERE id=%s LIMIT 1",
143 array($data['password'], $aid), __FUNCTION__, __LINE__);
146 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_admins` SET password='%s' WHERE id=%s LIMIT 1",
147 array($data['password'], $aid), __FUNCTION__, __LINE__);
151 rebuildCacheFiles("admins", "admin");
153 // Login has failed by default... ;-)
156 // Password matches so login here
157 if (LOGIN_ADMIN($admin_login, $data['password'])) {
161 } elseif ((empty($salt)) && ($ret == "pass")) {
162 // Something bad went wrong
164 } elseif ($ret == "done") {
165 // Try to login here if we have the old hashing way (sql_patches not installed?)
166 if (!LOGIN_ADMIN($admin_login, $data['password'])) {
167 // Something went wrong
172 // Count login failure if admins extension version is 0.7.0+
173 if (($ret == "pass") && (GET_EXT_VERSION("admins") >= "0.7.0")) {
175 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_admins` SET login_failures=login_failures+1,last_failure=NOW() WHERE id=%s LIMIT 1",
176 array($aid), __FUNCTION__, __LINE__);
179 rebuildCacheFiles("admins", "admin");
183 //* DEBUG: */ die("RETURN=".$ret);
187 // Try to login the admin by setting some session/cookie variables
188 function LOGIN_ADMIN ($adminLogin, $passHash) {
189 // Reset failure counter on matching admins version
190 if ((GET_EXT_VERSION("admins") >= "0.7.0") && ((EXT_VERSION_IS_OLDER("sql_patches", "0.3.6")) || (GET_EXT_VERSION("sql_patches") == ""))) {
191 // Reset counter on out-dated sql_patches version
192 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_admins` SET login_failures=0,last_failure='0000-00-00 00:00:00' WHERE login='%s' LIMIT 1",
193 array($adminLogin), __FUNCTION__, __LINE__);
196 rebuildCacheFiles("admins", "admin");
199 // Now set all session variables and return the result
202 set_session('admin_md5', generatePassString($passHash))
204 set_session('admin_login', $adminLogin)
206 set_session('admin_last', time())
208 set_session('admin_to', bigintval(REQUEST_POST('timeout')))
213 // Only be executed on cookie checking
214 function CHECK_ADMIN_COOKIES ($admin_login, $password) {
215 // By default no admin cookies are found
216 $ret = "404"; $pass = "";
219 $pass = GET_ADMIN_HASH(GET_ADMIN_ID($admin_login));
220 if ($pass != "-1") $ret = "pass";
222 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):".generatePassString($pass)."(".strlen($pass).")/".$password."(".strlen($password).")<br />\n";
224 // Check if password matches
225 if (($ret == "pass") && ((generatePassString($pass) == $password) || ($pass == $password) || ((strlen($pass) == 32) && (md5($password) == $pass)))) {
226 // Passwords matches!
235 function ADMIN_DO_ACTION ($wht) {
237 //* DEBUG: */ echo __LINE__."*".$wht."/".$GLOBALS['module']."/".$GLOBALS['action']."/".$GLOBALS['what']."*<br />\n";
239 // Remove any spaces from variable
241 // Default admin action is the overview page
244 // Compile out some chars
245 $wht = COMPILE_CODE($wht, false, false, false);
249 $act = GET_ACTION($GLOBALS['module'], $wht);
251 // Define admin login name and ID number
252 define('__ADMIN_LOGIN', get_session('admin_login'));
253 define('__ADMIN_ID' , GET_CURRENT_ADMIN_ID());
256 if (EXT_IS_ACTIVE("admins")) {
257 define('__ADMIN_WELCOME', LOAD_TEMPLATE("admin_welcome_admins", true));
259 define('__ADMIN_WELCOME', LOAD_TEMPLATE("admin_welcome", true));
261 define('__ADMIN_FOOTER' , LOAD_TEMPLATE("admin_footer" , true));
262 define('__ADMIN_MENU' , ADD_ADMIN_MENU($act, $wht, true));
265 LOAD_TEMPLATE("admin_main_header");
267 // Check if action/what pair is valid
268 $result_action = SQL_QUERY_ESC("SELECT id FROM `{!_MYSQL_PREFIX!}_admin_menu`
269 WHERE `action`='%s' AND ((what='%s' AND what != 'overview') OR ((what='' OR `what` IS NULL) AND '%s'='overview'))
270 LIMIT 1", array($act, $wht, $wht), __FUNCTION__, __LINE__);
271 if (SQL_NUMROWS($result_action) == 1) {
272 // Is valid but does the inlcude file exists?
273 $INC = sprintf("inc/modules/admin/action-%s.php", $act);
274 if ((INCLUDE_READABLE($INC)) && (VALIDATE_MENU_ACTION("admin", $act, $wht)) && ($GLOBALS['acl_allow'] === true)) {
275 // Ok, we finally load the admin action module
277 } elseif ($GLOBALS['acl_allow'] === false) {
279 LOAD_TEMPLATE("admin_menu_failed", false, getMessage('ADMIN_ACCESS_DENIED'));
280 addFatalMessage(__FUNCTION__, __LINE__, getMessage('ADMIN_ACCESS_DENIED'));
282 // Include file not found! :-(
283 LOAD_TEMPLATE("admin_menu_failed", false, sprintf(getMessage('ADMIN_ACTION_404'), $act));
284 addFatalMessage(__FUNCTION__, __LINE__, getMessage('ADMIN_ACTION_404'), $act);
287 // Invalid action/what pair found!
288 LOAD_TEMPLATE("admin_menu_failed", false, sprintf(getMessage('ADMIN_ACTION_INVALID'), $act."/".$wht));
289 addFatalMessage(__FUNCTION__, __LINE__, getMessage('ADMIN_ACTION_INVALID'), $act."/".$wht);
293 SQL_FREERESULT($result_action);
296 LOAD_TEMPLATE("admin_main_footer");
300 function ADD_ADMIN_MENU ($act, $wht, $return=false) {
306 $GLOBALS['menu']['description'] = array();
307 $GLOBALS['menu']['title'] = array();
309 // Is there a cache instance?
310 if ((isCacheInstanceValid()) && (getConfig('cache_admin_menu') == "Y")) {
312 $cacheName = "admin_".$act."_".$wht."_".GET_LANGUAGE()."_".strtolower(get_session('admin_login'));
314 // Is that cache there?
315 if ($GLOBALS['cache_instance']->loadCacheFile($cacheName)) {
317 $data = $GLOBALS['cache_instance']->getArrayFromCache();
320 $OUT = base64_decode($data['output'][0]);
321 $GLOBALS['menu']['title'] = unserialize(base64_decode($data['title'][0]));
322 $GLOBALS['menu']['description'] = unserialize(base64_decode($data['descr'][0]));
324 // Return or output content?
325 if ($return === true) {
334 $result_main = SQL_QUERY("SELECT action, title, descr FROM `{!_MYSQL_PREFIX!}_admin_menu` WHERE (what='' OR `what` IS NULL) ORDER BY `sort`, id DESC", __FUNCTION__, __LINE__);
335 if (SQL_NUMROWS($result_main) > 0) {
336 $OUT = "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_menu_main\">
337 <tr><td colspan=\"2\" height=\"7\" class=\"seperator\"> </td></tr>\n";
338 // @TODO Rewrite this to $content = SQL_FETCHARRAY()
339 while (list($menu, $title, $descr) = SQL_FETCHROW($result_main)) {
340 if ((EXT_IS_ACTIVE("admins")) && (GET_EXT_VERSION("admins") > "0.2")) {
341 $ACL = ADMINS_CHECK_ACL($menu, "");
343 // ACL is "allow"... hmmm
349 // Insert compiled menu title and description
350 $GLOBALS['menu']['title'][$menu] = $title;
351 $GLOBALS['menu']['description'][$menu] = $descr;
354 <td class=\"admin_menu\" colspan=\"2\">
355 <nobr> <strong>·</strong> ";
356 if (($menu == $act) && (empty($wht))) {
359 $OUT .= "[<a href=\"{!URL!}/modules.php?module=admin&action=".$menu."\">";
364 if (($menu == $act) && (empty($wht))) {
369 $OUT .= "</nobr></td>
371 $result_what = SQL_QUERY_ESC("SELECT what, title, descr FROM `{!_MYSQL_PREFIX!}_admin_menu` WHERE `action`='%s' AND `what` != '' AND `what` IS NOT NULL ORDER BY `sort`, id DESC",
372 array($menu), __FUNCTION__, __LINE__);
373 if ((SQL_NUMROWS($result_what) > 0) && ($act == $menu))
375 $GLOBALS['menu']['description'] = array();
376 $GLOBALS['menu']['title'] = array(); $SUB = true;
378 <td width=\"10\" class=\"seperator\"> </td>
379 <td class=\"admin_menu\">
380 <table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_menu_sub\">\n";
381 // @TODO Rewrite this to $content = SQL_FETCHARRAY()
382 while (list($wht_sub, $title_what, $desc_what) = SQL_FETCHROW($result_what)) {
384 $INC = sprintf("inc/modules/admin/what-%s.php", $wht_sub);
385 if ((EXT_IS_ACTIVE("admins")) && (GET_EXT_VERSION("admins") > "0.2")) {
386 $ACL = ADMINS_CHECK_ACL("", $wht_sub);
388 // ACL is "allow"... hmmm
392 // Is the file readable?
393 $readable = INCLUDE_READABLE($INC);
397 // Insert compiled title and description
398 $GLOBALS['menu']['title'][$wht_sub] = $title_what;
399 $GLOBALS['menu']['description'][$wht_sub] = $desc_what;
401 <td class=\"admin_menu\" colspan=\"2\">
402 <nobr> <strong>--></strong> ";
403 if ($readable === true) {
404 if ($wht == $wht_sub) {
407 $OUT .= "[<a href=\"{!URL!}/modules.php?module=admin&what=".$wht_sub."\">";
410 $OUT .= "<i class=\"admin_note\">";
415 if ($readable === true) {
416 if ($wht == $wht_sub) {
424 $OUT .= "</nobr></td>
430 SQL_FREERESULT($result_what);
435 $OUT .= "<tr><td height=\"7\" colspan=\"2\"></td></tr>\n";
440 SQL_FREERESULT($result_main);
441 $OUT .= "</table>\n";
444 // Is there a cache instance again?
445 if ((isCacheInstanceValid()) && (getConfig('cache_admin_menu') == "Y")) {
447 $GLOBALS['cache_instance']->init($cacheName);
449 // Prepare cache data
451 'output' => base64_encode($OUT),
452 'title' => $GLOBALS['menu']['title'],
453 'descr' => $GLOBALS['menu']['description']
456 // Write the data away
457 $GLOBALS['cache_instance']->addRow($data);
460 $GLOBALS['cache_instance']->finalize();
463 // Return or output content?
464 if ($return === true) {
471 // Create member selection box
472 function ADD_MEMBER_SELECTION_BOX ($def="0", $add_all=false, $return=false, $none=false, $field="userid") {
473 // Output selection form with all confirmed user accounts listed
474 $result = SQL_QUERY("SELECT userid, surname, family FROM `{!_MYSQL_PREFIX!}_user_data` ORDER BY userid", __FUNCTION__, __LINE__);
479 // USe this only for adding points (e.g. adding refs really makes no sence ;-) )
480 if ($add_all === true) $OUT = " <option value=\"all\">{--ALL_MEMBERS--}</option>\n";
481 elseif ($none === true) $OUT = " <option value=\"0\">{--SELECT_NONE--}</option>\n";
483 while ($content = SQL_FETCHARRAY($result)) {
484 $OUT .= " <option value=\"".bigintval($content['userid'])."\"";
485 if ($def == $content['userid']) $OUT .= " selected=\"selected\"";
486 $OUT .= ">".$content['surname']." ".$content['family']." (".bigintval($content['userid']).")</option>\n";
490 SQL_FREERESULT($result);
493 // Remeber options in constant
494 // @TODO Rewrite these both constants
495 define('_MEMBER_SELECTION', $OUT);
497 // Display selection box
498 define('__LANG_VALUE', GET_LANGUAGE());
501 LOAD_TEMPLATE("admin_member_selection_box", false, $GLOBALS['what']);
503 // Return content in selection frame
504 return "<select class=\"admin_select\" name=\"".$field."\" size=\"1\">\n".$OUT."</select>\n";
508 // Create a menu selection box for given menu system
509 function ADMIN_MENU_SELECTION ($MODE, $default="", $defid="") {
510 $wht = "`what` != ''";
511 if ($MODE == "action") $wht = "(what='' OR `what` IS NULL) AND action !='login'";
512 $result = SQL_QUERY_ESC("SELECT %s, title FROM `{!_MYSQL_PREFIX!}_admin_menu` WHERE ".$wht." ORDER BY `sort`",
513 array($MODE), __FUNCTION__, __LINE__);
514 if (SQL_NUMROWS($result) > 0) {
515 // Load menu as selection
516 $OUT = "<select name=\"".$MODE."_menu";
517 if ((!empty($defid)) || ($defid == "0")) $OUT .= "[".$defid."]";
518 $OUT .= "\" size=\"1\" class=\"admin_select\">
519 <option value=\"\">{--SELECT_NONE--}</option>\n";
520 // @TODO Try to rewrite this to $content = SQL_FETCHARRAY(). Please look some lines above for the dynamic query
521 while (list($menu, $title) = SQL_FETCHROW($result)) {
522 $OUT .= " <option value=\"".$menu."\"";
523 if ((!empty($default)) && ($default == $menu)) $OUT .= " selected=\"selected\"";
524 $OUT .= ">".$title."</option>\n";
528 SQL_FREERESULT($result);
529 $OUT .= "</select>\n";
532 $OUT = getMessage('ADMIN_PROBLEM_NO_MENU');
539 // Wrapper for $_POST and ADMIN_SAVE_SETTINGS
540 function ADMIN_SAVE_SETTINGS_POST () {
542 $POST = REQUEST_POST_ARRAY();
544 // Call the lower function
545 ADMIN_SAVE_SETTINGS($POST);
548 // Save settings to the database
549 function ADMIN_SAVE_SETTINGS (&$POST, $tableName = "_config", $whereStatement = "config=0", $translateComma = array(), $alwaysAdd = false) {
550 // Prepare all arrays, variables
554 // Now, walk through all entries and prepare them for saving
555 foreach ($POST as $id => $val) {
556 // Process only formular field but not submit buttons ;)
558 // Do not save the ok value
559 CONVERT_SELECTIONS_TO_TIMESTAMP($POST, $DATA, $id, $skip);
561 // Shall we process this ID? It muss not be empty, of course
562 if ((!$skip) && (!empty($id))) {
564 $val = COMPILE_CODE($val);
566 // Translate the value? (comma to dot!)
567 if ((is_array($translateComma)) && (in_array($id, $translateComma))) {
568 // Then do it here... :)
569 $val = REVERT_COMMA($val);
572 // Shall we add numbers or strings?
574 if ("".$val."" == "".$test."") {
576 $DATA[] = sprintf("`%s`=%s", $id, $test);
579 $DATA[] = sprintf("`%s`='%s'", $id, trim($val));
582 // Update current configuration
583 setConfigEntry($id, $val);
588 // Check if entry does exist
591 if (!empty($whereStatement)) {
592 $result = SQL_QUERY("SELECT * FROM `{!_MYSQL_PREFIX!}".$tableName."` WHERE ".$whereStatement." LIMIT 1", __FUNCTION__, __LINE__);
594 $result = SQL_QUERY("SELECT * FROM `{!_MYSQL_PREFIX!}".$tableName."` LIMIT 1", __FUNCTION__, __LINE__);
598 if (SQL_NUMROWS($result) == 1) {
599 // "Implode" all data to single string
600 $DATA_UPDATE = implode(", ", $DATA);
602 // Generate SQL string
603 $sql = sprintf("UPDATE `{!_MYSQL_PREFIX!}%s` SET %s WHERE %s LIMIT 1",
609 // Add Line (does only work with auto_increment!
610 $KEYs = array(); $VALUEs = array();
611 foreach ($DATA as $entry) {
613 $line = explode("=", $entry);
614 $KEYs[] = $line[0]; $VALUEs[] = $line[1];
617 // Add both in one line
618 $KEYs = implode(", ", $KEYs);
619 $VALUEs = implode(", ", $VALUEs);
621 // Generate SQL string
622 $sql = sprintf("INSERT INTO {!_MYSQL_PREFIX!}%s (%s) VALUES (%s)",
630 SQL_FREERESULT($result);
632 // Simply run generated SQL string
633 SQL_QUERY($sql, __FUNCTION__, __LINE__);
636 rebuildCacheFiles("config", "config");
639 LOAD_TEMPLATE("admin_settings_saved", false, getMessage('SETTINGS_SAVED'));
642 // Generate a selection box
643 function ADMIN_MAKE_MENU_SELECTION ($menu, $type, $name, $default="") {
644 // Open the requested menu directory
645 $handle = opendir(sprintf("%sinc/modules/%s/", constant('PATH'), $menu)) or mxchange_die("Cannot load menu ".$menu."!");
647 // Init the selection box
648 $OUT = "<select name=\"".$name."\" class=\"admin_select\" size=\"1\">
649 <option value=\"\">{--IS_TOP_MENU--}</option>\n";
651 // Walk through all files
652 while ($file = readdir($handle)) {
653 // Is this a PHP script?
654 if (($file != ".") && ($file != "..") && ($file != "lost+found") && (strpos($file, "".$type."-") > -1) && (strpos($file, ".php") > 0)) {
655 // Then test if the file is readable
656 $test = sprintf("%sinc/modules/%s/%s", constant('PATH'), $menu, $file);
658 // Is the file there?
659 if (FILE_READABLE($test)) {
660 // Extract the value for what=xxx
661 $part = substr($file, (strlen($type) + 1));
662 $part = substr($part, 0, -4);
664 // Is that part different from the overview?
665 if ($part != "overview") {
666 $OUT .= " <option value=\"".$part."\"";
667 if ($part == $default) $OUT .= " selected=\"selected\"";
668 $OUT .= ">".$part."</option>\n";
674 // Close dir and selection box
676 $OUT .= "</select>\n";
682 function ADMIN_USER_PROFILE_LINK ($uid, $title="", $wht="list_user") {
683 if (($title == "") && ($title != "0")) {
684 // Set userid as title
688 if (($title == "0") && ($wht == "list_refs")) {
689 // Return title again
693 //* DEBUG: */ echo "a:".$title."<br />";
695 return "<a href=\"{!URL!}/modules.php?module=admin&what=".$wht."&uid=".$uid."\" title=\"{--ADMIN_USER_PROFILE_TITLE--}\">".$title."</a>";
698 // Check "logical-area-mode"
699 function ADMIN_CHECK_MENU_MODE () {
700 // Set the global mode as the mode for all admins
701 $MODE = getConfig('admin_menu');
705 $aid = GET_CURRENT_ADMIN_ID();
707 // Check individual settings of current admin
708 if (isset($GLOBALS['cache_array']['admins']['la_mode'][$aid])) {
710 $ADMIN = $GLOBALS['cache_array']['admins']['la_mode'][$aid];
711 incrementConfigEntry('cache_hits');
712 } elseif (GET_EXT_VERSION("admins") >= "0.6.7") {
713 // Load from database when version of "admins" is enough
714 $result = SQL_QUERY_ESC("SELECT la_mode FROM `{!_MYSQL_PREFIX!}_admins` WHERE id=%s LIMIT 1",
715 array($aid), __FUNCTION__, __LINE__);
716 if (SQL_NUMROWS($result) == 1) {
718 list($ADMIN) = SQL_FETCHROW($result);
722 SQL_FREERESULT($result);
725 // Check what the admin wants and set it when it's not the global mode
726 if ($ADMIN != "global") $MODE = $ADMIN;
728 // Return admin-menu's mode
732 // Change activation status
733 function ADMIN_CHANGE_ACTIVATION_STATUS ($IDs, $table, $row, $idRow = "id") {
734 $cnt = 0; $newStatus = "Y";
735 if ((is_array($IDs)) && (count($IDs) > 0)) {
736 // "Walk" all through and count them
737 foreach ($IDs as $id => $selected) {
738 // Secure the ID number
739 $id = bigintval($id);
741 // Should always be set... ;-)
742 if (!empty($selected)) {
743 // Determine new status
744 $result = SQL_QUERY_ESC("SELECT %s FROM `{!_MYSQL_PREFIX!}_%s` WHERE %s=%s LIMIT 1",
745 array($row, $table, $idRow, $id), __FUNCTION__, __LINE__);
748 if (SQL_NUMROWS($result) == 1) {
750 list($currStatus) = SQL_FETCHROW($result);
752 // And switch it N<->Y
753 if ($currStatus == "Y") $newStatus = "N"; else $newStatus = "Y";
755 // Change this status
756 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_%s` SET %s='%s' WHERE %s=%s LIMIT 1",
757 array($table, $row, $newStatus, $idRow, $id), __FUNCTION__, __LINE__);
759 // Count up affected rows
760 $cnt += SQL_AFFECTEDROWS();
764 SQL_FREERESULT($result);
769 LOAD_TEMPLATE("admin_settings_saved", false, sprintf(getMessage('ADMIN_STATUS_CHANGED'), $cnt, count($IDs)));
772 LOAD_TEMPLATE("admin_settings_saved", false, getMessage('ADMIN_NOTHING_SELECTED_CHANGE'));
776 // Send mails for del/edit/lock build modes
777 function ADMIN_SEND_BUILD_MAILS ($mode, $table, $content, $id, $subjectPart="") {
778 // Default subject is the subject part
779 $subject = $subjectPart;
781 // Is the subject part not set?
782 if (empty($subjectPart)) {
783 // Then use it from the mode
784 $subject = strtoupper($mode);
787 // Is the raw userid set?
788 if (REQUEST_POST('uid_raw', $id) > 0) {
790 $subjectLine = getMessage('MEMBER_'.strtoupper($subject).'_'.strtoupper($table).'_SUBJECT');
792 // Load email template
793 if (!empty($subjectPart)) {
794 $mail = LOAD_EMAIL_TEMPLATE("member_".$mode."_".strtolower($subjectPart)."_".$table, $content);
796 $mail = LOAD_EMAIL_TEMPLATE("member_".$mode."_".$table, $content);
800 SEND_EMAIL(REQUEST_POST('uid_raw', $id), $subjectLine, $mail);
804 $subjectLine = getMessage('ADMIN_'.strtoupper($subject).'_'.strtoupper($table).'_SUBJECT');
806 // Send admin notification out
807 if (!empty($subjectPart)) {
808 SEND_ADMIN_NOTIFICATION($subjectLine, "admin_".$mode."_".strtolower($subjectPart)."_".$table, $content, REQUEST_POST('uid_raw', $id));
810 SEND_ADMIN_NOTIFICATION($subjectLine, "admin_".$mode."_".$table, $content, REQUEST_POST('uid_raw', $id));
814 // Build a special template list
815 function ADMIN_BUILD_LIST ($listType, $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn) {
818 // "Walk" through all entries
819 foreach ($IDs as $id => $selected) {
821 $id = bigintval($id);
823 // Get result from a given column array and table name
824 $result = SQL_RESULT_FROM_ARRAY($table, $columns, $idColumn, $id, __FUNCTION__, __LINE__);
826 // Is there one entry?
827 if (SQL_NUMROWS($result) == 1) {
829 $content = SQL_FETCHARRAY($result);
832 foreach ($content as $key => $value) {
834 $idx = array_search($key, $columns, true);
836 // Do we have a userid?
837 if ($key == "userid") {
838 // Add it again as raw id
839 $content['uid'] = bigintval($value);
842 // Handle the call in external function
843 $content[$key] = HANDLE_EXTRA_VALUES($filterFunctions[$idx], $value, $extraValues[$idx]);
846 // Add color switching
847 $content['sw'] = $SW;
850 $OUT .= LOAD_TEMPLATE(sprintf("admin_%s_%s_row",
861 SQL_FREERESULT($result);
864 // Load master template
865 LOAD_TEMPLATE(sprintf("admin_%s_%s",
872 // Change status of "build" list
873 function ADMIN_BUILD_STATUS_HANDLER ($mode, $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray) {
874 // All valid entries? (We hope so here!)
875 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues)) && (count($statusArray) > 0)) {
876 // "Walk" through all entries
877 foreach ($IDs as $id => $sel) {
878 // Construct SQL query
879 $sql = sprintf("UPDATE `{!_MYSQL_PREFIX!}_%s` SET",
883 // Load data of entry
884 $result = SQL_QUERY_ESC("SELECT * FROM `{!_MYSQL_PREFIX!}_%s` WHERE %s=%s LIMIT 1",
885 array($table, $idColumn, $id), __FUNCTION__, __LINE__);
888 $content = SQL_FETCHARRAY($result);
891 SQL_FREERESULT($result);
893 // Add all status entries (e.g. status column last_updated or so)
894 $newStatus = "UNKNOWN";
895 $oldStatus = "UNKNOWN";
896 $statusColumn = "unknown";
897 foreach ($statusArray as $column => $statusInfo) {
898 // Does the entry exist?
899 if ((isset($content[$column])) && (isset($statusInfo[$content[$column]]))) {
900 // Add these entries for update
901 $sql .= sprintf(" %s='%s',", SQL_ESCAPE($column), SQL_ESCAPE($statusInfo[$content[$column]]));
904 if ($statusColumn == "unknown") {
905 // Always (!!!) change status column first!
906 $oldStatus = $content[$column];
907 $newStatus = $statusInfo[$oldStatus];
908 $statusColumn = $column;
910 } elseif (isset($content[$column])) {
912 mxchange_die("{--".__FUNCTION__."--}:".__LINE__.":UNFINISHED: id={$id}/{$column}[".gettype($statusInfo)."] = {$content[$column]}");
916 // Add other columns as well
917 foreach (REQUEST_POST_ARRAY() as $key => $entries) {
918 // Skip id, raw userid and 'do_$mode'
919 if (!in_array($key, array($idColumn, 'uid_raw', ('do_'.$mode)))) {
920 // Are there brackets () at the end?
921 if (substr($entries[$id], -2, 2) == "()") {
922 // Direct SQL command found
923 $sql .= sprintf(" %s=%s,", SQL_ESCAPE($key), SQL_ESCAPE($entries[$id]));
926 $sql .= sprintf(" %s='%s',", SQL_ESCAPE($key), SQL_ESCAPE($entries[$id]));
929 $content[$key] = $entries[$id];
934 // Finish SQL statement
935 $sql = substr($sql, 0, -1) . sprintf(" WHERE %s=%s AND %s='%s' LIMIT 1",
943 SQL_QUERY($sql, __FUNCTION__, __LINE__);
945 // Do we have an URL?
946 if (isset($content['url'])) {
947 // Then add a framekiller test as well
948 $content['frametester'] = FRAMETESTER($content['url']);
951 // Send "build mails" out
952 ADMIN_SEND_BUILD_MAILS($mode, $table, $content, $id, $statusInfo[$content[$column]]);
957 // Delete rows by given ID numbers
958 function ADMIN_DELETE_ENTRIES_CONFIRM ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $deleteNow=false, $idColumn="id", $userIdColumn="userid") {
959 // All valid entries? (We hope so here!)
960 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues))) {
961 // Shall we delete here or list for deletion?
963 // The base SQL command:
964 $sql = "DELETE LOW_PRIORITY FROM `{!_MYSQL_PREFIX!}_%s` WHERE %s IN (%s)";
968 foreach ($IDs as $id => $sel) {
969 // Is there a userid?
970 if (REQUEST_ISSET_POST('uid_raw', $id)) {
971 // Load all data from that id
972 $result = SQL_QUERY_ESC("SELECT * FROM `{!_MYSQL_PREFIX!}_%s` WHERE %s=%s LIMIT 1",
973 array($table, $idColumn, $id), __FUNCTION__, __LINE__);
976 $content = SQL_FETCHARRAY($result);
979 SQL_FREERESULT($result);
981 // Send "build mails" out
982 ADMIN_SEND_BUILD_MAILS("del", $table, $content, $id);
990 SQL_QUERY($sql, array($table, $idColumn, substr($idList, 0, -1)), __FUNCTION__, __LINE__);
993 if (SQL_AFFECTEDROWS() == count($IDs)) {
995 LOAD_TEMPLATE("admin_settings_saved", false, getMessage('ADMIN_ALL_ENTRIES_REMOVED'));
997 // Some are still there :(
998 LOAD_TEMPLATE("admin_settings_saved", false, sprintf(getMessage('ADMIN_SOME_ENTRIES_NOT_DELETED'), SQL_AFFECTEDROWS(), count($IDs)));
1001 // List for deletion confirmation
1002 ADMIN_BUILD_LIST("del", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1007 // Edit rows by given ID numbers
1008 function ADMIN_EDIT_ENTRIES_CONFIRM ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $editNow=false, $idColumn="id", $userIdColumn="userid") {
1009 // All valid entries? (We hope so here!)
1010 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues))) {
1011 // Shall we change here or list for editing?
1015 foreach ($IDs as $id => $sel) {
1016 // Prepare content array (new values)
1019 // Prepare SQL for this row
1020 $sql = sprintf("UPDATE `{!_MYSQL_PREFIX!}_ SET",
1023 foreach (REQUEST_POST_ARRAY() as $key => $entries) {
1024 // Skip raw userid which is always invalid
1025 if ($key == "uid_raw") {
1026 // Continue with next field
1030 // Is entries an array?
1031 if (($key != $idColumn) && (is_array($entries)) && (isset($entries[$id]))) {
1032 // Add this entry to content
1033 $content[$key] = $entries[$id];
1035 // Send data through the filter function if found
1036 if ((isset($filterFunctions[$key])) && (isset($extraValues[$key]))) {
1037 // Filter function set!
1038 $entries[$id] = HANDLE_EXTRA_VALUES($filterFunctions[$key], $entries[$id], $extraValues[$key]);
1041 // Then add this value
1042 $sql .= sprintf(" %s='%s',",
1044 SQL_ESCAPE($entries[$id])
1046 } elseif (($key != $idColumn) && (!is_array($entries))) {
1047 // Add normal entries as well!
1048 $content[$key] = $entries;
1051 // Do we have an URL?
1052 if ($key == "url") {
1053 // Then add a framekiller test as well
1054 $content['frametester'] = FRAMETESTER($content[$key]);
1058 // Finish SQL command
1059 $sql = substr($sql, 0, -1) . " WHERE ".$idColumn."=".bigintval($id)." LIMIT 1";
1062 SQL_QUERY($sql, __FUNCTION__, __LINE__);
1064 // Add affected rows
1065 $affected += SQL_AFFECTEDROWS();
1067 // Load all data from that id
1068 $result = SQL_QUERY_ESC("SELECT * FROM `{!_MYSQL_PREFIX!}_%s` WHERE %s=%s LIMIT 1",
1069 array($table, $idColumn, $id), __FUNCTION__, __LINE__);
1073 $DATA = SQL_FETCHARRAY($result);
1076 SQL_FREERESULT($result);
1078 // Send "build mails" out
1079 ADMIN_SEND_BUILD_MAILS("edit", $table, $content, $id);
1083 if ($affected == count($IDs)) {
1085 LOAD_TEMPLATE("admin_settings_saved", false, getMessage('ADMIN_ALL_ENTRIES_EDITED'));
1087 // Some are still there :(
1088 LOAD_TEMPLATE("admin_settings_saved", false, sprintf(getMessage('ADMIN_SOME_ENTRIES_NOT_EDITED'), $affected, count($IDs)));
1092 ADMIN_BUILD_LIST("edit", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1097 // Un-/lock rows by given ID numbers
1098 function ADMIN_LOCK_ENTRIES_CONFIRM ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $statusArray=array(), $lockNow=false, $idColumn="id", $userIdColumn="userid") {
1099 // All valid entries? (We hope so here!)
1100 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues)) && ((!$lockNow) || (count($statusArray) == 1))) {
1101 // Shall we un-/lock here or list for locking?
1104 ADMIN_BUILD_STATUS_HANDLER("lock", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray);
1107 ADMIN_BUILD_LIST("lock", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1112 // Undelete rows by given ID numbers
1113 function ADMIN_UNDELETE_ENTRIES_CONFIRM ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $statusArray=array(), $lockNow=false, $idColumn="id", $userIdColumn="userid") {
1114 // All valid entries? (We hope so here!)
1115 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues)) && ((!$lockNow) || (count($statusArray) == 1))) {
1116 // Shall we un-/lock here or list for locking?
1119 ADMIN_BUILD_STATUS_HANDLER("undelete", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray);
1122 ADMIN_BUILD_LIST("undelete", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1127 // Checks proxy settins by fetching check-updates3.php from www.mxchange.org
1128 function ADMIN_TEST_PROXY_SETTINGS ($settingsArray) {
1129 // Set temporary the new settings
1130 mergeConfig($settingsArray);
1132 // Now get the test URL
1133 $content = GET_URL("check-updates3.php");
1135 // Is the first line with "200 OK"?
1136 $valid = eregi("200 OK", $content[0]);
1142 // Sends out a link to the given email adress so the admin can reset his/her password
1143 function ADMIN_SEND_PASSWORD_RESET_LINK ($email) {
1147 // Compile out security characters (must be for looking up!)
1148 $email = COMPILE_CODE($email);
1150 // Look up administator login
1151 $result = SQL_QUERY_ESC("SELECT id, login, password FROM `{!_MYSQL_PREFIX!}_admins` WHERE email='%s' LIMIT 1",
1152 array($email), __FUNCTION__, __LINE__);
1154 // Is there an account?
1155 if (SQL_NUMROWS($result) == 0) {
1156 // No account found!
1157 return getMessage('ADMIN_NO_LOGIN_WITH_EMAIL');
1161 $content = SQL_FETCHARRAY($result);
1164 SQL_FREERESULT($result);
1166 // Generate hash for reset link
1167 $content['hash'] = generateHash(URL.":".$content['id'].":".$content['login'].":".$content['password'], substr($content['password'], 10));
1170 unset($content['id']);
1171 unset($content['password']);
1174 $mailText = LOAD_EMAIL_TEMPLATE("admin_reset_password", $content);
1177 SEND_EMAIL($email, getMessage('ADMIN_RESET_PASS_LINK_SUBJ'), $mailText);
1180 return getMessage('ADMIN_RESET_LINK_SENT');
1183 // Validate hash and login for password reset
1184 function ADMIN_VALIDATE_RESET_LINK_HASH_LOGIN ($hash, $login) {
1185 // By default nothing validates... ;)
1188 // Compile the login for lookup
1189 $login = COMPILE_CODE($login);
1191 // Then try to find that user
1192 $result = SQL_QUERY_ESC("SELECT id, password, email FROM `{!_MYSQL_PREFIX!}_admins` WHERE login='%s' LIMIT 1",
1193 array($login), __FUNCTION__, __LINE__);
1195 // Is an account here?
1196 if (SQL_NUMROWS($result) == 1) {
1198 $content = SQL_FETCHARRAY($result);
1200 // Generate hash again
1201 $hashFromData = generateHash(URL.":".$content['id'].":".$login.":".$content['password'], substr($content['password'], 10));
1204 $valid = ($hash == $hashFromData);
1208 SQL_FREERESULT($result);
1213 // Reset the password for the login. Do NOT call this function without calling above function first!
1214 function ADMIN_RESET_PASSWORD ($login, $password) {
1218 // Now check if we have sql_patches installed
1219 if (GET_EXT_VERSION("sql_patches") >= "0.3.6") {
1220 // Use new way of hashing
1221 $passHash = generateHash($password);
1224 $passHash = md5($password);
1228 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_admins` SET password='%s' WHERE login='%s' LIMIT 1",
1229 array($passHash, $login), __FUNCTION__, __LINE__);
1232 runFilterChain('post_admin_reset_pass', array('login' => $login, 'hash' => $passHash));
1235 return ADMIN_PASSWORD_RESET_DONE;
1237 // Solves a task by given id number
1238 function ADMIN_SOLVE_TASK ($id) {
1239 // Update the task data
1240 ADMIN_UPDATE_TASK_DATA($id, "status", "SOLVED");
1242 // Marks a given task as deleted
1243 function ADMIN_DELETE_TASK ($id) {
1244 // Update the task data
1245 ADMIN_UPDATE_TASK_DATA($id, "status", "DELETED");
1247 // Function to update task data
1248 function ADMIN_UPDATE_TASK_DATA ($id, $row, $data) {
1250 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_task_system` SET %s='%s' WHERE id=%s LIMIT 1",
1251 array($row, $data, bigintval($id)), __FUNCTION__, __LINE__);