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=WEBMASTER) {
42 // Login does already exist
46 $result = SQL_QUERY_ESC("SELECT id FROM `{!_MYSQL_PREFIX!}_admins` WHERE login='%s' LIMIT 1",
47 array($user), __FILE__, __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), __FILE__, __LINE__);
58 SQL_FREERESULT($result);
63 // Only be executed on login procedure!
64 function CHECK_ADMIN_LOGIN ($admin_login, $password) {
65 global $cacheArray, $cacheInstance;
67 // By default no admin is found
71 $aid = GET_ADMIN_ID($admin_login);
73 // Init array with admin id by default
74 $data = array('aid' => $aid);
76 // Is the cache valid?
77 if (isset($cacheArray['admins']['password'][$aid])) {
78 // Get password from cache
79 $data['password'] = $cacheArray['admins']['password'][$aid];
81 incrementConfigEntry('cache_hits');
83 // Include more admins data?
84 if (GET_EXT_VERSION("admins") >= "0.7.0") {
86 $data['login_failures'] = $cacheArray['admins']['login_failures'][$aid];
87 $data['last_failure'] = $cacheArray['admins']['last_failure'][$aid];
89 } elseif (!EXT_IS_ACTIVE("cache")) {
90 // Add extra data via filter now
91 $ADD = RUN_FILTER('sql_admin_extra_data');
93 // Get password from DB
94 $result = SQL_QUERY_ESC("SELECT password".$ADD." FROM `{!_MYSQL_PREFIX!}_admins` WHERE id=%s LIMIT 1",
95 array($aid), __FILE__, __LINE__);
98 if (SQL_NUMROWS($result) == 1) {
99 // Login password found
103 $data = SQL_FETCHARRAY($result);
107 SQL_FREERESULT($result);
110 //* DEBUG: */ echo "*".$data['password']."/".md5($password)."/".$ret."<br />";
111 if ((isset($data['password'])) && (strlen($data['password']) == 32) && ($data['password'] == md5($password))) {
113 $data['password'] = generateHash($password);
115 // Is the sql_patches not installed, than we cannot have a valid hashed password here!
116 if (($ret == "pass") && ((EXT_VERSION_IS_OLDER("sql_patches", "0.3.6")) || (GET_EXT_VERSION("sql_patches") == ""))) $ret = "done";
117 } elseif ((EXT_VERSION_IS_OLDER("sql_patches", "0.3.6")) || (GET_EXT_VERSION("sql_patches") == "")) {
120 } elseif (!isset($data['password'])) {
121 // Password not found, so no valid login!
125 // Generate salt of password
126 define('__SALT', substr($data['password'], 0, -40));
129 // Check if password is same
130 //* DEBUG: */ echo "*".$ret.",".$data['password'].",".$password.",".$salt."*<br >\n";
131 if (($ret == "pass") && ($data['password'] == generateHash($password, $salt)) && ((!empty($salt))) || ($data['password'] == $password)) {
132 // Re-hash the plain passord with new random salt
133 $data['password'] = generateHash($password);
135 // Do we have 0.7.0 of admins or later?
136 // Remmeber login failures if available
137 if (GET_EXT_VERSION("admins") >= "0.7.2") {
138 // Store it in session
139 set_session('mxchange_admin_failures', $data['login_failures']);
140 set_session('mxchange_admin_last_fail', $data['last_failure']);
142 // Update password and reset login failures
143 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",
144 array($data['password'], $aid), __FILE__, __LINE__);
147 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_admins` SET password='%s' WHERE id=%s LIMIT 1",
148 array($data['password'], $aid), __FILE__, __LINE__);
152 REBUILD_CACHE("admins", "admin");
154 // Login has failed by default... ;-)
157 // Password matches so login here
158 if (LOGIN_ADMIN($admin_login, $data['password'])) {
162 } elseif ((empty($salt)) && ($ret == "pass")) {
163 // Something bad went wrong
165 } elseif ($ret == "done") {
166 // Try to login here if we have the old hashing way (sql_patches not installed?)
167 if (!LOGIN_ADMIN($admin_login, $data['password'])) {
168 // Something went wrong
173 // Count login failure if admins extension version is 0.7.0+
174 if (($ret == "pass") && (GET_EXT_VERSION("admins") >= "0.7.0")) {
176 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_admins` SET login_failures=login_failures+1,last_failure=NOW() WHERE id=%s LIMIT 1",
177 array($aid), __FILE__, __LINE__);
180 REBUILD_CACHE("admins", "admin");
184 //* DEBUG: */ die("RETURN=".$ret);
188 // Try to login the admin by setting some session/cookie variables
189 function LOGIN_ADMIN ($adminLogin, $passHash) {
190 global $cacheInstance;
192 // Reset failure counter on matching admins version
193 if ((GET_EXT_VERSION("admins") >= "0.7.0") && ((EXT_VERSION_IS_OLDER("sql_patches", "0.3.6")) || (GET_EXT_VERSION("sql_patches") == ""))) {
194 // Reset counter on out-dated sql_patches version
195 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_admins` SET login_failures=0,last_failure='0000-00-00 00:00:00' WHERE login='%s' LIMIT 1",
196 array($adminLogin), __FILE__, __LINE__);
199 REBUILD_CACHE("admins", "admin");
202 // Now set all session variables and return the result
205 set_session('admin_md5', generatePassString($passHash))
207 set_session('admin_login', $adminLogin)
209 set_session('admin_last', time())
211 set_session('admin_to', bigintval($_POST['timeout']))
216 // Only be executed on cookie checking
217 function CHECK_ADMIN_COOKIES ($admin_login, $password) {
219 $ret = "404"; $pass = "";
222 $pass = GET_ADMIN_HASH(GET_ADMIN_ID($admin_login));
223 if ($pass != "-1") $ret = "pass";
225 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):".generatePassString($pass)."(".strlen($pass).")/".$password."(".strlen($password).")<br />\n";
227 // Check if password matches
228 if (($ret == "pass") && ((generatePassString($pass) == $password) || ($pass == $password) || ((strlen($pass) == 32) && (md5($password) == $pass)))) {
229 // Passwords matches!
237 function admin_WriteData ($file, $comment, $prefix, $suffix, $DATA, $seek=0) {
238 // Initialize some variables
244 // Is the file there and read-/write-able?
245 if ((FILE_READABLE($file)) && (is_writeable($file))) {
246 $search = "CFG: ".$comment;
249 // Open the source file
250 $fp = @fopen($file, 'r') or OUTPUT_HTML("<strong>READ:</strong> ".$file."<br />");
252 // Is the resource valid?
253 if (is_resource($fp)) {
254 // Open temporary file
255 $fp_tmp = @fopen($tmp, 'w') or OUTPUT_HTML("<strong>WRITE:</strong> ".$tmp."<br />");
257 // Is the resource again valid?
258 if (is_resource($fp_tmp)) {
260 // Read from source file
261 $line = fgets ($fp, 1024);
263 if (strpos($line, $search) > -1) { $next = 0; $found = true; }
266 if ($next === $seek) {
268 $line = $prefix . $DATA . $suffix."\n";
274 // Write to temp file
275 fputs($fp_tmp, $line);
281 // Finished writing tmp file
288 if (($done) && ($found)) {
289 // Copy back tmp file and delete tmp :-)
292 define('_FATAL', false);
294 OUTPUT_HTML("<strong>CHANGE:</strong> 404!");
295 define('_FATAL', true);
297 OUTPUT_HTML("<strong>TMP:</strong> UNDONE!");
298 define('_FATAL', true);
302 // File not found, not readable or writeable
303 OUTPUT_HTML("<strong>404:</strong> ".$file."<br />");
308 function ADMIN_DO_ACTION($wht) {
309 global $menuDesription, $menuTitle, $cacheArray, $DATA;
311 //* DEBUG: */ echo __LINE__."*".$wht."/".$GLOBALS['module']."/".$GLOBALS['action']."/".$GLOBALS['what']."*<br />\n";
312 if (EXT_IS_ACTIVE("cache")) {
313 // Include cache instance
314 global $cacheInstance;
317 // Remove any spaces from variable
319 // Default admin action is the overview page
322 // Compile out some chars
323 $wht = COMPILE_CODE($wht, false, false, false);
327 $act = GET_ACTION($GLOBALS['module'], $wht);
329 // Define admin login name and ID number
330 define('__ADMIN_LOGIN', get_session('admin_login'));
331 define('__ADMIN_ID' , GET_CURRENT_ADMIN_ID());
334 if (EXT_IS_ACTIVE("admins")) {
335 define('__ADMIN_WELCOME', LOAD_TEMPLATE("admin_welcome_admins", true));
337 define('__ADMIN_WELCOME', LOAD_TEMPLATE("admin_welcome", true));
339 define('__ADMIN_FOOTER' , LOAD_TEMPLATE("admin_footer" , true));
340 define('__ADMIN_MENU' , ADD_ADMIN_MENU($act, $wht, true));
343 LOAD_TEMPLATE("admin_main_header");
345 // Check if action/what pair is valid
346 $result_action = SQL_QUERY_ESC("SELECT id FROM `{!_MYSQL_PREFIX!}_admin_menu`
347 WHERE action='%s' AND ((what='%s' AND what != 'overview') OR ((what='' OR `what` IS NULL) AND '%s'='overview'))
348 LIMIT 1", array($act, $wht, $wht), __FILE__, __LINE__);
349 if (SQL_NUMROWS($result_action) == 1) {
351 // Is valid but does the inlcude file exists?
352 $INC = sprintf("%sinc/modules/admin/action-%s.php", PATH, $act);
353 if ((FILE_READABLE($INC)) && (VALIDATE_MENU_ACTION("admin", $act, $wht)) && (__ACL_ALLOW == true)) {
354 // Ok, we finally load the admin action module
356 } elseif (__ACL_ALLOW == false) {
358 LOAD_TEMPLATE("admin_menu_failed", false, getMessage('ADMIN_ACCESS_DENIED'));
359 addFatalMessage(getMessage('ADMIN_ACCESS_DENIED'));
361 // Include file not found! :-(
362 LOAD_TEMPLATE("admin_menu_failed", false, getMessage('ADMIN_404_ACTION'));
363 addFatalMessage(ADMIN_404_ACTION_1.$act.ADMIN_404_ACTION_2);
366 // Invalid action/what pair found!
367 LOAD_TEMPLATE("admin_menu_failed", false, getMessage('ADMIN_INVALID_ACTION'));
368 addFatalMessage(ADMIN_INVALID_ACTION_1.$act."/".$wht.ADMIN_INVALID_ACTION_2);
372 SQL_FREERESULT($result_action);
375 LOAD_TEMPLATE("admin_main_footer");
378 function ADD_ADMIN_MENU($act, $wht, $return=false) {
379 global $menuDesription, $menuTitle, $cacheInstance;
386 $menuDesription = array();
387 $menuTitle = array();
389 // Is there a cache instance?
390 if ((is_object($cacheInstance)) && (getConfig('cache_admin_menu') == "Y")) {
392 $cacheName = "admin_".$act."_".$wht."_".GET_LANGUAGE()."_".strtolower(get_session('admin_login'));
394 // Is that cache there?
395 if ($cacheInstance->loadCacheFile($cacheName)) {
397 $data = $cacheInstance->getArrayFromCache();
400 $OUT = base64_decode($data['output'][0]);
401 $menuTitle = unserialize(base64_decode($data['title'][0]));
402 $menuDescription = unserialize(base64_decode($data['descr'][0]));
404 // Return or output content?
414 $result_main = SQL_QUERY("SELECT action, title, descr FROM `{!_MYSQL_PREFIX!}_admin_menu` WHERE (what='' OR `what` IS NULL) ORDER BY `sort`, id DESC", __FILE__, __LINE__);
415 if (SQL_NUMROWS($result_main) > 0)
417 $OUT = "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_menu_main\">
418 <tr><td colspan=\"2\" height=\"7\" class=\"seperator\"> </td></tr>\n";
419 while (list($menu, $title, $descr) = SQL_FETCHROW($result_main))
421 if ((EXT_IS_ACTIVE("admins")) && (GET_EXT_VERSION("admins") > "0.2"))
423 $ACL = ADMINS_CHECK_ACL($menu, "");
427 // ACL is "allow"... hmmm
434 // Insert compiled menu title and description
435 $menuTitle[$menu] = $title;
436 $menuDesription[$menu] = $descr;
439 <td class=\"admin_menu\" colspan=\"2\">
440 <NOBR> <strong>·</strong> ";
441 if (($menu == $act) && (empty($wht)))
447 $OUT .= "[<a href=\"{!URL!}/modules.php?module=admin&action=".$menu."\">";
450 if (($menu == $act) && (empty($wht)))
458 $OUT .= "</NOBR></td>
460 $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",
461 array($menu), __FILE__, __LINE__);
462 if ((SQL_NUMROWS($result_what) > 0) && ($act == $menu))
464 $menuDesription = array();
465 $menuTitle = array(); $SUB = true;
467 <td width=\"10\" class=\"seperator\"> </td>
468 <td class=\"admin_menu\">
469 <table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_menu_sub\">\n";
470 while (list($wht_sub, $title_what, $desc_what) = SQL_FETCHROW($result_what)) {
472 $INC = sprintf("%sinc/modules/admin/what-%s.php", PATH, $wht_sub);
473 if ((EXT_IS_ACTIVE("admins")) && (GET_EXT_VERSION("admins") > "0.2")) {
474 $ACL = ADMINS_CHECK_ACL("", $wht_sub);
476 // ACL is "allow"... hmmm
479 $readable = FILE_READABLE($INC);
481 // Insert compiled title and description
482 $menuTitle[$wht_sub] = $title_what;
483 $menuDesription[$wht_sub] = $desc_what;
485 <td class=\"admin_menu\" colspan=\"2\">
486 <NOBR> <strong>--></strong> ";
489 if ($wht == $wht_sub)
495 $OUT .= "[<a href=\"{!URL!}/modules.php?module=admin&what=".$wht_sub."\">";
500 $OUT .= "<i class=\"admin_note\">";
505 if ($wht == $wht_sub)
518 $OUT .= "</NOBR></td>
524 SQL_FREERESULT($result_what);
529 $OUT .= "<tr><td height=\"7\" colspan=\"2\"></td></tr>\n";
534 SQL_FREERESULT($result_main);
535 $OUT .= "</table>\n";
538 // Compile and run the code here. This inserts all constants into the
539 // HTML output. Costs me some time to figure this out... *sigh* Quix0r
540 $eval = "\$OUT = \"".COMPILE_CODE(addslashes($OUT))."\";";
543 // Is there a cache instance again?
544 if ((is_object($cacheInstance)) && (getConfig('cache_admin_menu') == "Y")) {
546 $cacheInstance->init($cacheName);
548 // Prepare cache data
550 'output' => base64_encode($OUT),
551 'title' => $menuTitle,
552 'descr' => $menuDesription
555 // Write the data away
556 $cacheInstance->addRow($data);
559 $cacheInstance->finalize();
562 // Return or output content?
570 function ADD_MEMBER_SELECTION_BOX ($def="0", $add_all=false, $return=false, $none=false, $field="userid")
572 // Output selection form with all confirmed user accounts listed
573 $result = SQL_QUERY("SELECT userid, surname, family FROM `{!_MYSQL_PREFIX!}_user_data` ORDER BY userid", __FILE__, __LINE__);
576 // USe this only for adding points (e.g. adding refs really makes no sence ;-) )
577 if ($add_all) $OUT = " <option value=\"all\">".ALL_MEMBERS."</option>\n";
578 elseif ($none) $OUT = " <option value=\"0\">".SELECT_NONE."</option>\n";
579 while (list($id, $sname, $fname) = SQL_FETCHROW($result))
581 $OUT .= " <option value=\"".bigintval($id)."\"";
582 if ($def == $id) $OUT .= " selected=\"selected\"";
583 $OUT .= ">".$sname." ".$fname." (".bigintval($id).")</option>\n";
587 SQL_FREERESULT($result);
590 // Remeber options in constant
591 define('_MEMBER_SELECTION', $OUT);
593 // Display selection box
594 define('__LANG_VALUE', GET_LANGUAGE());
597 LOAD_TEMPLATE("admin_member_selection_box", false, $GLOBALS['what']);
599 // Return content in selection frame
600 return "<select class=\"admin_select\" name=\"".$field."\" size=\"1\">\n".$OUT."</select>\n";
604 function ADMIN_MENU_SELECTION($MODE, $default="", $defid="") {
605 $wht = "`what` != ''";
606 if ($MODE == "action") $wht = "(what='' OR `what` IS NULL) AND action !='login'";
607 $result = SQL_QUERY_ESC("SELECT %s, title FROM `{!_MYSQL_PREFIX!}_admin_menu` WHERE ".$wht." ORDER BY `sort`",
608 array($MODE), __FILE__, __LINE__);
609 if (SQL_NUMROWS($result) > 0) {
610 // Load menu as selection
611 $OUT = "<select name=\"".$MODE."_menu";
612 if ((!empty($defid)) || ($defid == "0")) $OUT .= "[".$defid."]";
613 $OUT .= "\" size=\"1\" class=\"admin_select\">
614 <option value=\"\">".SELECT_NONE."</option>\n";
615 while (list($menu, $title) = SQL_FETCHROW($result)) {
616 $OUT .= " <option value=\"".$menu."\"";
617 if ((!empty($default)) && ($default == $menu)) $OUT .= " selected=\"selected\"";
618 $OUT .= ">".$title."</option>\n";
622 SQL_FREERESULT($result);
623 $OUT .= "</select>\n";
626 $OUT = ADMIN_PROBLEM_NO_MENU;
633 // Save settings to the database
634 function ADMIN_SAVE_SETTINGS (&$POST, $tableName="_config", $whereStatement="config=0", $translateComma=array(), $alwaysAdd=false) {
635 global $_CONFIG, $cacheArray, $cacheInstance;
637 // Prepare all arrays, variables
641 // Now, walk through all entries and prepare them for saving
642 foreach ($POST as $id => $val) {
643 // Process only formular field but not submit buttons ;)
645 // Do not save the ok value
646 CONVERT_SELECTIONS_TO_TIMESTAMP($POST, $DATA, $id, $skip);
648 // Shall we process this ID? It muss not be empty, of course
649 if ((!$skip) && (!empty($id))) {
651 $val = COMPILE_CODE($val);
653 // Translate the value? (comma to dot!)
654 if ((is_array($translateComma)) && (in_array($id, $translateComma))) {
655 // Then do it here... :)
656 $val = REVERT_COMMA($val);
659 // Shall we add numbers or strings?
661 if ("".$val."" == "".$test."") {
663 $DATA[] = sprintf("`%s`=%s", $id, $test);
666 $DATA[] = sprintf("`%s`='%s'", $id, trim($val));
669 // Update current configuration
670 $_CONFIG[$id] = $val;
675 // Check if entry does exist
678 if (!empty($whereStatement)) {
679 $result = SQL_QUERY("SELECT * FROM `{!_MYSQL_PREFIX!}".$tableName."` WHERE ".$whereStatement." LIMIT 1", __FILE__, __LINE__);
681 $result = SQL_QUERY("SELECT * FROM `{!_MYSQL_PREFIX!}".$tableName."` LIMIT 1", __FILE__, __LINE__);
685 if (SQL_NUMROWS($result) == 1) {
686 // "Implode" all data to single string
687 $DATA_UPDATE = implode(", ", $DATA);
689 // Generate SQL string
690 $SQL = sprintf("UPDATE `{!_MYSQL_PREFIX!}%s` SET %s WHERE %s LIMIT 1",
696 // Add Line (does only work with auto_increment!
697 $KEYs = array(); $VALUEs = array();
698 foreach ($DATA as $entry) {
700 $line = explode("=", $entry);
701 $KEYs[] = $line[0]; $VALUEs[] = $line[1];
704 // Add both in one line
705 $KEYs = implode(", ", $KEYs);
706 $VALUEs = implode(", ", $VALUEs);
708 // Generate SQL string
709 $SQL = sprintf("INSERT INTO {!_MYSQL_PREFIX!}%s (%s) VALUES (%s)",
717 SQL_FREERESULT($result);
719 // Simply run generated SQL string
720 SQL_QUERY($SQL, __FILE__, __LINE__);
723 REBUILD_CACHE("config", "config");
726 LOAD_TEMPLATE("admin_settings_saved", false, getMessage('SETTINGS_SAVED'));
729 // Generate a selection box
730 function ADMIN_MAKE_MENU_SELECTION ($menu, $type, $name, $default="") {
731 // Open the requested menu directory
732 $handle = opendir(sprintf("%sinc/modules/%s/", PATH, $menu)) or mxchange_die("Cannot load menu ".$menu."!");
734 // Init the selection box
735 $OUT = "<select name=\"".$name."\" class=\"admin_select\" size=\"1\">\n <option value=\"\">".IS_TOP_MENU."</option>\n";
737 // Walk through all files
738 while ($file = readdir($handle)) {
739 // Is this a PHP script?
740 if (($file != ".") && ($file != "..") && ($file != "lost+found") && (strpos($file, "".$type."-") > -1) && (strpos($file, ".php") > 0)) {
741 // Then test if the file is readable
742 $test = sprintf("%sinc/modules/%s/%s", PATH, $menu, $file);
744 // Is the file there?
745 if (FILE_READABLE($test)) {
746 // Extract the value for what=xxx
747 $part = substr($file, (strlen($type) + 1));
748 $part = substr($part, 0, -4);
750 // Is that part different from the overview?
751 if ($part != "overview") {
752 $OUT .= " <option value=\"".$part."\"";
753 if ($part == $default) $OUT .= " selected=\"selected\"";
754 $OUT .= ">".$part."</option>\n";
760 // Close dir and selection box
762 $OUT .= "</select>\n";
768 function ADMIN_USER_PROFILE_LINK ($uid, $title="", $wht="list_user") {
769 if (($title == "") && ($title != "0")) {
770 // Set userid as title
774 if (($title == "0") && ($wht == "list_refs")) {
775 // Return title again
779 //* DEBUG: */ echo "a:".$title."<br />";
781 return "<a href=\"{!URL!}/modules.php?module=admin&what=".$wht."&u_id=".$uid."\" title=\"".ADMIN_USER_PROFILE_TITLE."\">".$title."</a>";
784 // Check "logical-area-mode"
785 function ADMIN_CHECK_MENU_MODE () {
788 // Set the global mode as the mode for all admins
789 $MODE = getConfig('admin_menu');
793 $aid = GET_CURRENT_ADMIN_ID();
795 // Check individual settings of current admin
796 if (isset($cacheArray['admins']['la_mode'][$aid])) {
798 $ADMIN = $cacheArray['admins']['la_mode'][$aid];
799 incrementConfigEntry('cache_hits');
800 } elseif (GET_EXT_VERSION("admins") >= "0.6.7") {
801 // Load from database when version of "admins" is enough
802 $result = SQL_QUERY_ESC("SELECT la_mode FROM `{!_MYSQL_PREFIX!}_admins` WHERE id=%s LIMIT 1",
803 array($aid), __FILE__, __LINE__);
804 if (SQL_NUMROWS($result) == 1) {
806 list($ADMIN) = SQL_FETCHROW($result);
810 SQL_FREERESULT($result);
813 // Check what the admin wants and set it when it's not the global mode
814 if ($ADMIN != "global") $MODE = $ADMIN;
816 // Return admin-menu's mode
820 // Change activation status
821 function ADMIN_CHANGE_ACTIVATION_STATUS ($IDs, $table, $row, $idRow = "id") {
822 $cnt = 0; $newStatus = "Y";
823 if ((is_array($IDs)) && (count($IDs) > 0)) {
824 // "Walk" all through and count them
825 foreach ($IDs as $id => $selected) {
826 // Secure the ID number
827 $id = bigintval($id);
829 // Should always be set... ;-)
830 if (!empty($selected)) {
831 // Determine new status
832 $result = SQL_QUERY_ESC("SELECT %s FROM `{!_MYSQL_PREFIX!}_%s` WHERE %s=%s LIMIT 1",
833 array($row, $table, $idRow, $id), __FILE__, __LINE__);
836 if (SQL_NUMROWS($result) == 1) {
838 list($currStatus) = SQL_FETCHROW($result);
840 // And switch it N<->Y
841 if ($currStatus == "Y") $newStatus = "N"; else $newStatus = "Y";
843 // Change this status
844 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_%s` SET %s='%s' WHERE %s=%s LIMIT 1",
845 array($table, $row, $newStatus, $idRow, $id), __FILE__, __LINE__);
847 // Count up affected rows
848 $cnt += SQL_AFFECTEDROWS();
852 SQL_FREERESULT($result);
857 LOAD_TEMPLATE("admin_settings_saved", false, ADMIN_STATUS_CHANGED_1.$cnt.ADMIN_STATUS_CHANGED_2.count($IDs).ADMIN_STATUS_CHANGED_3);
860 LOAD_TEMPLATE("admin_settings_saved", false, getMessage('ADMIN_NOTHING_SELECTED_CHANGE'));
864 // Send mails for del/edit/lock build modes
865 function ADMIN_SEND_BUILD_MAILS ($mode, $table, $content, $id, $subjectPart="") {
866 // Default subject is the subject part
867 $subject = $subjectPart;
869 // Is the subject part not set?
870 if (empty($subjectPart)) {
871 // Then use it from the mode
872 $subject = strtoupper($mode);
875 // Is the raw userid set?
876 if ($_POST['uid_raw'][$id] > 0) {
878 $subjectLine = constant('MEMBER_'.strtoupper($subject).'_'.strtoupper($table).'_SUBJECT');
880 // Load email template
881 if (!empty($subjectPart)) {
882 $mail = LOAD_EMAIL_TEMPLATE("member_".$mode."_".strtolower($subjectPart)."_".$table, $content);
884 $mail = LOAD_EMAIL_TEMPLATE("member_".$mode."_".$table, $content);
888 SEND_EMAIL($_POST['uid_raw'][$id], $subjectLine, $mail);
892 $subjectLine = constant('ADMIN_'.strtoupper($subject).'_'.strtoupper($table).'_SUBJECT');
894 // Send admin notification out
895 if (!empty($subjectPart)) {
896 SEND_ADMIN_NOTIFICATION($subjectLine, "admin_".$mode."_".strtolower($subjectPart)."_".$table, $content, $_POST['uid_raw'][$id]);
898 SEND_ADMIN_NOTIFICATION($subjectLine, "admin_".$mode."_".$table, $content, $_POST['uid_raw'][$id]);
902 // Build a special template list
903 function ADMIN_BUILD_LIST ($listType, $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn) {
906 // "Walk" through all entries
907 foreach ($IDs as $id => $selected) {
909 $id = bigintval($id);
911 // Get result from a given column array and table name
912 $result = SQL_RESULT_FROM_ARRAY($table, $columns, $idColumn, $id, __FILE__, __LINE__);
914 // Is there one entry?
915 if (SQL_NUMROWS($result) == 1) {
917 $content = SQL_FETCHARRAY($result);
920 foreach ($content as $key => $value) {
922 $idx = array_search($key, $columns, true);
924 // Do we have a userid?
925 if ($key == "userid") {
926 // Add it again as raw id
927 $content['uid'] = bigintval($value);
930 // Handle the call in external function
931 $content[$key] = HANDLE_EXTRA_VALUES($filterFunctions[$idx], $value, $extraValues[$idx]);
934 // Add color switching
935 $content['sw'] = $SW;
938 $OUT .= LOAD_TEMPLATE(sprintf("admin_%s_%s_row",
949 SQL_FREERESULT($result);
952 // Load master template
953 LOAD_TEMPLATE(sprintf("admin_%s_%s",
960 // Change status of "build" list
961 function ADMIN_BUILD_STATUS_HANDLER ($mode, $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray) {
962 // All valid entries? (We hope so here!)
963 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues)) && (count($statusArray) > 0)) {
964 // "Walk" through all entries
965 foreach ($IDs as $id => $sel) {
966 // Construct SQL query
967 $SQL = sprintf("UPDATE `{!_MYSQL_PREFIX!}_%s` SET",
971 // Load data of entry
972 $result = SQL_QUERY_ESC("SELECT * FROM `{!_MYSQL_PREFIX!}_%s` WHERE %s=%s LIMIT 1",
973 array($table, $idColumn, $id), __FILE__, __LINE__);
976 $content = SQL_FETCHARRAY($result);
979 SQL_FREERESULT($result);
981 // Add all status entries (e.g. status column last_updated or so)
982 $newStatus = "UNKNOWN";
983 $oldStatus = "UNKNOWN";
984 $statusColumn = "unknown";
985 foreach ($statusArray as $column => $statusInfo) {
986 // Does the entry exist?
987 if ((isset($content[$column])) && (isset($statusInfo[$content[$column]]))) {
988 // Add these entries for update
989 $SQL .= sprintf(" %s='%s',", SQL_ESCAPE($column), SQL_ESCAPE($statusInfo[$content[$column]]));
992 if ($statusColumn == "unknown") {
993 // Always (!!!) change status column first!
994 $oldStatus = $content[$column];
995 $newStatus = $statusInfo[$oldStatus];
996 $statusColumn = $column;
998 } elseif (isset($content[$column])) {
1000 mxchange_die("{--".__FUNCTION__."--}:".__LINE__.":UNFINISHED: id={$id}/{$column}[".gettype($statusInfo)."] = {$content[$column]}");
1004 // Add other columns as well
1005 foreach ($_POST as $key => $entries) {
1006 // Skip id, raw userid and 'do_$mode'
1007 if (!in_array($key, array($idColumn, 'uid_raw', ('do_'.$mode)))) {
1008 // Are there brackets () at the end?
1009 if (substr($entries[$id], -2, 2) == "()") {
1010 // Direct SQL command found
1011 $SQL .= sprintf(" %s=%s,", SQL_ESCAPE($key), SQL_ESCAPE($entries[$id]));
1013 // Add regular entry
1014 $SQL .= sprintf(" %s='%s',", SQL_ESCAPE($key), SQL_ESCAPE($entries[$id]));
1017 $content[$key] = $entries[$id];
1022 // Finish SQL statement
1023 $SQL = substr($SQL, 0, -1) . sprintf(" WHERE %s=%s AND %s='%s' LIMIT 1",
1031 SQL_QUERY($SQL, __FILE__, __LINE__);
1033 // Do we have an URL?
1034 if (isset($content['url'])) {
1035 // Then add a framekiller test as well
1036 $content['frametester'] = FRAMETESTER($content['url']);
1039 // Send "build mails" out
1040 ADMIN_SEND_BUILD_MAILS($mode, $table, $content, $id, $statusInfo[$content[$column]]);
1045 // Delete rows by given ID numbers
1046 function ADMIN_DELETE_ENTRIES_CONFIRM ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $deleteNow=false, $idColumn="id", $userIdColumn="userid") {
1047 // All valid entries? (We hope so here!)
1048 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues))) {
1049 // Shall we delete here or list for deletion?
1051 // The base SQL command:
1052 $SQL = "DELETE LOW_PRIORITY FROM `{!_MYSQL_PREFIX!}_%s` WHERE %s IN (%s)";
1056 foreach ($IDs as $id => $sel) {
1057 // Is there a userid?
1058 if (isset($_POST['uid_raw'][$id])) {
1059 // Load all data from that id
1060 $result = SQL_QUERY_ESC("SELECT * FROM `{!_MYSQL_PREFIX!}_%s` WHERE %s=%s LIMIT 1",
1061 array($table, $idColumn, $id), __FILE__, __LINE__);
1064 $content = SQL_FETCHARRAY($result);
1067 SQL_FREERESULT($result);
1069 // Send "build mails" out
1070 ADMIN_SEND_BUILD_MAILS("del", $table, $content, $id);
1078 SQL_QUERY($SQL, array($table, $idColumn, substr($idList, 0, -1)), __FILE__, __LINE__);
1081 if (SQL_AFFECTEDROWS() == count($IDs)) {
1083 LOAD_TEMPLATE("admin_settings_saved", false, getMessage('ADMIN_ALL_ENTRIES_REMOVED'));
1085 // Some are still there :(
1086 LOAD_TEMPLATE("admin_settings_saved", false, sprintf(ADMIN_SOME_ENTRIES_NOT_DELETED, SQL_AFFECTEDROWS(), count($IDs)));
1089 // List for deletion confirmation
1090 ADMIN_BUILD_LIST("del", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1095 // Edit rows by given ID numbers
1096 function ADMIN_EDIT_ENTRIES_CONFIRM ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $editNow=false, $idColumn="id", $userIdColumn="userid") {
1097 // All valid entries? (We hope so here!)
1098 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues))) {
1099 // Shall we change here or list for editing?
1103 foreach ($IDs as $id => $sel) {
1104 // Prepare content array (new values)
1107 // Prepare SQL for this row
1108 $SQL = sprintf("UPDATE `{!_MYSQL_PREFIX!}_ SET",
1111 foreach ($_POST as $key => $entries) {
1112 // Skip raw userid which is always invalid
1113 if ($key == "uid_raw") {
1114 // Continue with next field
1118 // Is entries an array?
1119 if (($key != $idColumn) && (is_array($entries)) && (isset($entries[$id]))) {
1120 // Add this entry to content
1121 $content[$key] = $entries[$id];
1123 // Send data through the filter function if found
1124 if ((isset($filterFunctions[$key])) && (isset($extraValues[$key]))) {
1125 // Filter function set!
1126 $entries[$id] = HANDLE_EXTRA_VALUES($filterFunctions[$key], $entries[$id], $extraValues[$key]);
1129 // Then add this value
1130 $SQL .= sprintf(" %s='%s',",
1132 SQL_ESCAPE($entries[$id])
1134 } elseif (($key != $idColumn) && (!is_array($entries))) {
1135 // Add normal entries as well!
1136 $content[$key] = $entries;
1139 // Do we have an URL?
1140 if ($key == "url") {
1141 // Then add a framekiller test as well
1142 $content['frametester'] = FRAMETESTER($content[$key]);
1146 // Finish SQL command
1147 $SQL = substr($SQL, 0, -1) . " WHERE ".$idColumn."=".bigintval($id)." LIMIT 1";
1150 SQL_QUERY($SQL, __FILE__, __LINE__);
1152 // Add affected rows
1153 $affected += SQL_AFFECTEDROWS();
1155 // Load all data from that id
1156 $result = SQL_QUERY_ESC("SELECT * FROM `{!_MYSQL_PREFIX!}_%s` WHERE %s=%s LIMIT 1",
1157 array($table, $idColumn, $id), __FILE__, __LINE__);
1161 $DATA = SQL_FETCHARRAY($result);
1164 SQL_FREERESULT($result);
1166 // Send "build mails" out
1167 ADMIN_SEND_BUILD_MAILS("edit", $table, $content, $id);
1171 if ($affected == count($IDs)) {
1173 LOAD_TEMPLATE("admin_settings_saved", false, getMessage('ADMIN_ALL_ENTRIES_EDITED'));
1175 // Some are still there :(
1176 LOAD_TEMPLATE("admin_settings_saved", false, sprintf(ADMIN_SOME_ENTRIES_NOT_EDITED, $affected, count($IDs)));
1180 ADMIN_BUILD_LIST("edit", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1185 // Un-/lock rows by given ID numbers
1186 function ADMIN_LOCK_ENTRIES_CONFIRM ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $statusArray=array(), $lockNow=false, $idColumn="id", $userIdColumn="userid") {
1187 // All valid entries? (We hope so here!)
1188 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues)) && ((!$lockNow) || (count($statusArray) == 1))) {
1189 // Shall we un-/lock here or list for locking?
1192 ADMIN_BUILD_STATUS_HANDLER("lock", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray);
1195 ADMIN_BUILD_LIST("lock", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1200 // Undelete rows by given ID numbers
1201 function ADMIN_UNDELETE_ENTRIES_CONFIRM ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $statusArray=array(), $lockNow=false, $idColumn="id", $userIdColumn="userid") {
1202 // All valid entries? (We hope so here!)
1203 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues)) && ((!$lockNow) || (count($statusArray) == 1))) {
1204 // Shall we un-/lock here or list for locking?
1207 ADMIN_BUILD_STATUS_HANDLER("undelete", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray);
1210 ADMIN_BUILD_LIST("undelete", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1215 // Checks proxy settins by fetching check-updates3.php from www.mxchange.org
1216 function ADMIN_TEST_PROXY_SETTINGS ($settingsArray) {
1219 // Set temporary the new settings
1220 $_CONFIG = merge_array($_CONFIG, $settingsArray);
1222 // Now get the test URL
1223 $content = GET_URL("check-updates3.php");
1225 // Is the first line with "200 OK"?
1226 $valid = eregi("200 OK", $content[0]);
1232 // Sends out a link to the given email adress so the admin can reset his/her password
1233 function ADMIN_SEND_PASSWORD_RESET_LINK ($email) {
1237 // Compile out security characters (must be for looking up!)
1238 $email = COMPILE_CODE($email);
1240 // Look up administator login
1241 $result = SQL_QUERY_ESC("SELECT id, login, password FROM `{!_MYSQL_PREFIX!}_admins` WHERE email='%s' LIMIT 1",
1242 array($email), __FILE__, __LINE__);
1244 // Is there an account?
1245 if (SQL_NUMROWS($result) == 0) {
1246 // No account found!
1247 return getMessage('ADMIN_NO_LOGIN_WITH_EMAIL');
1251 $content = SQL_FETCHARRAY($result);
1254 SQL_FREERESULT($result);
1256 // Generate hash for reset link
1257 $content['hash'] = generateHash(URL.":".$content['id'].":".$content['login'].":".$content['password'], substr($content['password'], 10));
1260 unset($content['id']);
1261 unset($content['password']);
1264 $mailText = LOAD_EMAIL_TEMPLATE("admin_reset_password", $content);
1267 SEND_EMAIL($email, getMessage('ADMIN_RESET_PASS_LINK_SUBJ'), $mailText);
1270 return getMessage('ADMIN_RESET_LINK_SENT');
1273 // Validate hash and login for password reset
1274 function ADMIN_VALIDATE_RESET_LINK_HASH_LOGIN ($hash, $login) {
1275 // By default nothing validates... ;)
1278 // Compile the login for lookup
1279 $login = COMPILE_CODE($login);
1281 // Then try to find that user
1282 $result = SQL_QUERY_ESC("SELECT id, password, email FROM `{!_MYSQL_PREFIX!}_admins` WHERE login='%s' LIMIT 1",
1283 array($login), __FILE__, __LINE__);
1285 // Is an account here?
1286 if (SQL_NUMROWS($result) == 1) {
1288 $content = SQL_FETCHARRAY($result);
1290 // Generate hash again
1291 $hashFromData = generateHash(URL.":".$content['id'].":".$login.":".$content['password'], substr($content['password'], 10));
1294 $valid = ($hash == $hashFromData);
1298 SQL_FREERESULT($result);
1303 // Reset the password for the login. Do NOT call this function without calling above function first!
1304 function ADMIN_RESET_PASSWORD ($login, $password) {
1308 // Now check if we have sql_patches installed
1309 if (GET_EXT_VERSION("sql_patches") >= "0.3.6") {
1310 // Use new way of hashing
1311 $passHash = generateHash($password);
1314 $passHash = md5($password);
1318 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_admins` SET password='%s' WHERE login='%s' LIMIT 1",
1319 array($passHash, $login), __FILE__, __LINE__);
1322 RUN_FILTER('post_admin_reset_pass', array('login' => $login, 'hash' => $passHash));
1325 return ADMIN_PASSWORD_RESET_DONE;
1327 // Solves a task by given id number
1328 function ADMIN_SOLVE_TASK ($id) {
1329 // Update the task data
1330 ADMIN_UPDATE_TASK_DATA($id, "status", "SOLVED");
1332 // Marks a given task as deleted
1333 function ADMIN_DELETE_TASK ($id) {
1334 // Update the task data
1335 ADMIN_UPDATE_TASK_DATA($id, "status", "DELETED");
1337 // Function to update task data
1338 function ADMIN_UPDATE_TASK_DATA ($id, $row, $data) {
1340 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_task_system` SET %s='%s' WHERE id=%s LIMIT 1",
1341 array($row, $data, bigintval($id)), __FILE__, __LINE__);