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("inc/modules/admin/action-%s.php", $act);
353 if ((INCLUDE_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, sprintf(getMessage('ADMIN_ACTION_404'), $act));
363 addFatalMessage(getMessage('ADMIN_ACTION_404'), $act);
366 // Invalid action/what pair found!
367 LOAD_TEMPLATE("admin_menu_failed", false, sprintf(getMessage('ADMIN_ACTION_INVALID'), $act."/".$wht));
368 addFatalMessage(getMessage('ADMIN_ACTION_INVALID'), $act."/".$wht);
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) {
416 $OUT = "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_menu_main\">
417 <tr><td colspan=\"2\" height=\"7\" class=\"seperator\"> </td></tr>\n";
418 while (list($menu, $title, $descr) = SQL_FETCHROW($result_main)) {
419 if ((EXT_IS_ACTIVE("admins")) && (GET_EXT_VERSION("admins") > "0.2")) {
420 $ACL = ADMINS_CHECK_ACL($menu, "");
422 // ACL is "allow"... hmmm
428 // Insert compiled menu title and description
429 $menuTitle[$menu] = $title;
430 $menuDesription[$menu] = $descr;
433 <td class=\"admin_menu\" colspan=\"2\">
434 <NOBR> <strong>·</strong> ";
435 if (($menu == $act) && (empty($wht)))
441 $OUT .= "[<a href=\"{!URL!}/modules.php?module=admin&action=".$menu."\">";
444 if (($menu == $act) && (empty($wht)))
452 $OUT .= "</NOBR></td>
454 $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",
455 array($menu), __FILE__, __LINE__);
456 if ((SQL_NUMROWS($result_what) > 0) && ($act == $menu))
458 $menuDesription = array();
459 $menuTitle = array(); $SUB = true;
461 <td width=\"10\" class=\"seperator\"> </td>
462 <td class=\"admin_menu\">
463 <table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_menu_sub\">\n";
464 while (list($wht_sub, $title_what, $desc_what) = SQL_FETCHROW($result_what)) {
466 $INC = sprintf("%sinc/modules/admin/what-%s.php", constant('PATH'), $wht_sub);
467 if ((EXT_IS_ACTIVE("admins")) && (GET_EXT_VERSION("admins") > "0.2")) {
468 $ACL = ADMINS_CHECK_ACL("", $wht_sub);
470 // ACL is "allow"... hmmm
473 $readable = INCLUDE_READABLE($INC);
475 // Insert compiled title and description
476 $menuTitle[$wht_sub] = $title_what;
477 $menuDesription[$wht_sub] = $desc_what;
479 <td class=\"admin_menu\" colspan=\"2\">
480 <NOBR> <strong>--></strong> ";
481 if ($readable === true)
483 if ($wht == $wht_sub)
489 $OUT .= "[<a href=\"{!URL!}/modules.php?module=admin&what=".$wht_sub."\">";
494 $OUT .= "<i class=\"admin_note\">";
497 if ($readable === true)
499 if ($wht == $wht_sub)
512 $OUT .= "</NOBR></td>
518 SQL_FREERESULT($result_what);
523 $OUT .= "<tr><td height=\"7\" colspan=\"2\"></td></tr>\n";
528 SQL_FREERESULT($result_main);
529 $OUT .= "</table>\n";
532 // Compile and run the code here. This inserts all constants into the
533 // HTML output. Costs me some time to figure this out... *sigh* Quix0r
534 $eval = "\$OUT = \"".COMPILE_CODE(SQL_ESCAPE($OUT))."\";";
537 // Is there a cache instance again?
538 if ((is_object($cacheInstance)) && (getConfig('cache_admin_menu') == "Y")) {
540 $cacheInstance->init($cacheName);
542 // Prepare cache data
544 'output' => base64_encode($OUT),
545 'title' => $menuTitle,
546 'descr' => $menuDesription
549 // Write the data away
550 $cacheInstance->addRow($data);
553 $cacheInstance->finalize();
556 // Return or output content?
564 function ADD_MEMBER_SELECTION_BOX ($def="0", $add_all=false, $return=false, $none=false, $field="userid")
566 // Output selection form with all confirmed user accounts listed
567 $result = SQL_QUERY("SELECT userid, surname, family FROM `{!_MYSQL_PREFIX!}_user_data` ORDER BY userid", __FILE__, __LINE__);
570 // USe this only for adding points (e.g. adding refs really makes no sence ;-) )
571 if ($add_all) $OUT = " <option value=\"all\">".ALL_MEMBERS."</option>\n";
572 elseif ($none) $OUT = " <option value=\"0\">".SELECT_NONE."</option>\n";
573 while (list($id, $sname, $fname) = SQL_FETCHROW($result))
575 $OUT .= " <option value=\"".bigintval($id)."\"";
576 if ($def == $id) $OUT .= " selected=\"selected\"";
577 $OUT .= ">".$sname." ".$fname." (".bigintval($id).")</option>\n";
581 SQL_FREERESULT($result);
584 // Remeber options in constant
585 define('_MEMBER_SELECTION', $OUT);
587 // Display selection box
588 define('__LANG_VALUE', GET_LANGUAGE());
591 LOAD_TEMPLATE("admin_member_selection_box", false, $GLOBALS['what']);
593 // Return content in selection frame
594 return "<select class=\"admin_select\" name=\"".$field."\" size=\"1\">\n".$OUT."</select>\n";
598 function ADMIN_MENU_SELECTION($MODE, $default="", $defid="") {
599 $wht = "`what` != ''";
600 if ($MODE == "action") $wht = "(what='' OR `what` IS NULL) AND action !='login'";
601 $result = SQL_QUERY_ESC("SELECT %s, title FROM `{!_MYSQL_PREFIX!}_admin_menu` WHERE ".$wht." ORDER BY `sort`",
602 array($MODE), __FILE__, __LINE__);
603 if (SQL_NUMROWS($result) > 0) {
604 // Load menu as selection
605 $OUT = "<select name=\"".$MODE."_menu";
606 if ((!empty($defid)) || ($defid == "0")) $OUT .= "[".$defid."]";
607 $OUT .= "\" size=\"1\" class=\"admin_select\">
608 <option value=\"\">".SELECT_NONE."</option>\n";
609 while (list($menu, $title) = SQL_FETCHROW($result)) {
610 $OUT .= " <option value=\"".$menu."\"";
611 if ((!empty($default)) && ($default == $menu)) $OUT .= " selected=\"selected\"";
612 $OUT .= ">".$title."</option>\n";
616 SQL_FREERESULT($result);
617 $OUT .= "</select>\n";
620 $OUT = ADMIN_PROBLEM_NO_MENU;
627 // Save settings to the database
628 function ADMIN_SAVE_SETTINGS (&$POST, $tableName="_config", $whereStatement="config=0", $translateComma=array(), $alwaysAdd=false) {
629 global $cacheArray, $cacheInstance;
631 // Prepare all arrays, variables
635 // Now, walk through all entries and prepare them for saving
636 foreach ($POST as $id => $val) {
637 // Process only formular field but not submit buttons ;)
639 // Do not save the ok value
640 CONVERT_SELECTIONS_TO_TIMESTAMP($POST, $DATA, $id, $skip);
642 // Shall we process this ID? It muss not be empty, of course
643 if ((!$skip) && (!empty($id))) {
645 $val = COMPILE_CODE($val);
647 // Translate the value? (comma to dot!)
648 if ((is_array($translateComma)) && (in_array($id, $translateComma))) {
649 // Then do it here... :)
650 $val = REVERT_COMMA($val);
653 // Shall we add numbers or strings?
655 if ("".$val."" == "".$test."") {
657 $DATA[] = sprintf("`%s`=%s", $id, $test);
660 $DATA[] = sprintf("`%s`='%s'", $id, trim($val));
663 // Update current configuration
664 setConfigEntry($id, $val);
669 // Check if entry does exist
672 if (!empty($whereStatement)) {
673 $result = SQL_QUERY("SELECT * FROM `{!_MYSQL_PREFIX!}".$tableName."` WHERE ".$whereStatement." LIMIT 1", __FILE__, __LINE__);
675 $result = SQL_QUERY("SELECT * FROM `{!_MYSQL_PREFIX!}".$tableName."` LIMIT 1", __FILE__, __LINE__);
679 if (SQL_NUMROWS($result) == 1) {
680 // "Implode" all data to single string
681 $DATA_UPDATE = implode(", ", $DATA);
683 // Generate SQL string
684 $SQL = sprintf("UPDATE `{!_MYSQL_PREFIX!}%s` SET %s WHERE %s LIMIT 1",
690 // Add Line (does only work with auto_increment!
691 $KEYs = array(); $VALUEs = array();
692 foreach ($DATA as $entry) {
694 $line = explode("=", $entry);
695 $KEYs[] = $line[0]; $VALUEs[] = $line[1];
698 // Add both in one line
699 $KEYs = implode(", ", $KEYs);
700 $VALUEs = implode(", ", $VALUEs);
702 // Generate SQL string
703 $SQL = sprintf("INSERT INTO {!_MYSQL_PREFIX!}%s (%s) VALUES (%s)",
711 SQL_FREERESULT($result);
713 // Simply run generated SQL string
714 SQL_QUERY($SQL, __FILE__, __LINE__);
717 REBUILD_CACHE("config", "config");
720 LOAD_TEMPLATE("admin_settings_saved", false, getMessage('SETTINGS_SAVED'));
723 // Generate a selection box
724 function ADMIN_MAKE_MENU_SELECTION ($menu, $type, $name, $default="") {
725 // Open the requested menu directory
726 $handle = opendir(sprintf("%sinc/modules/%s/", constant('PATH'), $menu)) or mxchange_die("Cannot load menu ".$menu."!");
728 // Init the selection box
729 $OUT = "<select name=\"".$name."\" class=\"admin_select\" size=\"1\">\n <option value=\"\">".IS_TOP_MENU."</option>\n";
731 // Walk through all files
732 while ($file = readdir($handle)) {
733 // Is this a PHP script?
734 if (($file != ".") && ($file != "..") && ($file != "lost+found") && (strpos($file, "".$type."-") > -1) && (strpos($file, ".php") > 0)) {
735 // Then test if the file is readable
736 $test = sprintf("%sinc/modules/%s/%s", constant('PATH'), $menu, $file);
738 // Is the file there?
739 if (FILE_READABLE($test)) {
740 // Extract the value for what=xxx
741 $part = substr($file, (strlen($type) + 1));
742 $part = substr($part, 0, -4);
744 // Is that part different from the overview?
745 if ($part != "overview") {
746 $OUT .= " <option value=\"".$part."\"";
747 if ($part == $default) $OUT .= " selected=\"selected\"";
748 $OUT .= ">".$part."</option>\n";
754 // Close dir and selection box
756 $OUT .= "</select>\n";
762 function ADMIN_USER_PROFILE_LINK ($uid, $title="", $wht="list_user") {
763 if (($title == "") && ($title != "0")) {
764 // Set userid as title
768 if (($title == "0") && ($wht == "list_refs")) {
769 // Return title again
773 //* DEBUG: */ echo "a:".$title."<br />";
775 return "<a href=\"{!URL!}/modules.php?module=admin&what=".$wht."&u_id=".$uid."\" title=\"{--ADMIN_USER_PROFILE_TITLE--}\">".$title."</a>";
778 // Check "logical-area-mode"
779 function ADMIN_CHECK_MENU_MODE () {
782 // Set the global mode as the mode for all admins
783 $MODE = getConfig('admin_menu');
787 $aid = GET_CURRENT_ADMIN_ID();
789 // Check individual settings of current admin
790 if (isset($cacheArray['admins']['la_mode'][$aid])) {
792 $ADMIN = $cacheArray['admins']['la_mode'][$aid];
793 incrementConfigEntry('cache_hits');
794 } elseif (GET_EXT_VERSION("admins") >= "0.6.7") {
795 // Load from database when version of "admins" is enough
796 $result = SQL_QUERY_ESC("SELECT la_mode FROM `{!_MYSQL_PREFIX!}_admins` WHERE id=%s LIMIT 1",
797 array($aid), __FILE__, __LINE__);
798 if (SQL_NUMROWS($result) == 1) {
800 list($ADMIN) = SQL_FETCHROW($result);
804 SQL_FREERESULT($result);
807 // Check what the admin wants and set it when it's not the global mode
808 if ($ADMIN != "global") $MODE = $ADMIN;
810 // Return admin-menu's mode
814 // Change activation status
815 function ADMIN_CHANGE_ACTIVATION_STATUS ($IDs, $table, $row, $idRow = "id") {
816 $cnt = 0; $newStatus = "Y";
817 if ((is_array($IDs)) && (count($IDs) > 0)) {
818 // "Walk" all through and count them
819 foreach ($IDs as $id => $selected) {
820 // Secure the ID number
821 $id = bigintval($id);
823 // Should always be set... ;-)
824 if (!empty($selected)) {
825 // Determine new status
826 $result = SQL_QUERY_ESC("SELECT %s FROM `{!_MYSQL_PREFIX!}_%s` WHERE %s=%s LIMIT 1",
827 array($row, $table, $idRow, $id), __FILE__, __LINE__);
830 if (SQL_NUMROWS($result) == 1) {
832 list($currStatus) = SQL_FETCHROW($result);
834 // And switch it N<->Y
835 if ($currStatus == "Y") $newStatus = "N"; else $newStatus = "Y";
837 // Change this status
838 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_%s` SET %s='%s' WHERE %s=%s LIMIT 1",
839 array($table, $row, $newStatus, $idRow, $id), __FILE__, __LINE__);
841 // Count up affected rows
842 $cnt += SQL_AFFECTEDROWS();
846 SQL_FREERESULT($result);
851 LOAD_TEMPLATE("admin_settings_saved", false, ADMIN_STATUS_CHANGED_1.$cnt.ADMIN_STATUS_CHANGED_2.count($IDs).ADMIN_STATUS_CHANGED_3);
854 LOAD_TEMPLATE("admin_settings_saved", false, getMessage('ADMIN_NOTHING_SELECTED_CHANGE'));
858 // Send mails for del/edit/lock build modes
859 function ADMIN_SEND_BUILD_MAILS ($mode, $table, $content, $id, $subjectPart="") {
860 // Default subject is the subject part
861 $subject = $subjectPart;
863 // Is the subject part not set?
864 if (empty($subjectPart)) {
865 // Then use it from the mode
866 $subject = strtoupper($mode);
869 // Is the raw userid set?
870 if ($_POST['uid_raw'][$id] > 0) {
872 $subjectLine = constant('MEMBER_'.strtoupper($subject).'_'.strtoupper($table).'_SUBJECT');
874 // Load email template
875 if (!empty($subjectPart)) {
876 $mail = LOAD_EMAIL_TEMPLATE("member_".$mode."_".strtolower($subjectPart)."_".$table, $content);
878 $mail = LOAD_EMAIL_TEMPLATE("member_".$mode."_".$table, $content);
882 SEND_EMAIL($_POST['uid_raw'][$id], $subjectLine, $mail);
886 $subjectLine = constant('ADMIN_'.strtoupper($subject).'_'.strtoupper($table).'_SUBJECT');
888 // Send admin notification out
889 if (!empty($subjectPart)) {
890 SEND_ADMIN_NOTIFICATION($subjectLine, "admin_".$mode."_".strtolower($subjectPart)."_".$table, $content, $_POST['uid_raw'][$id]);
892 SEND_ADMIN_NOTIFICATION($subjectLine, "admin_".$mode."_".$table, $content, $_POST['uid_raw'][$id]);
896 // Build a special template list
897 function ADMIN_BUILD_LIST ($listType, $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn) {
900 // "Walk" through all entries
901 foreach ($IDs as $id => $selected) {
903 $id = bigintval($id);
905 // Get result from a given column array and table name
906 $result = SQL_RESULT_FROM_ARRAY($table, $columns, $idColumn, $id, __FILE__, __LINE__);
908 // Is there one entry?
909 if (SQL_NUMROWS($result) == 1) {
911 $content = SQL_FETCHARRAY($result);
914 foreach ($content as $key => $value) {
916 $idx = array_search($key, $columns, true);
918 // Do we have a userid?
919 if ($key == "userid") {
920 // Add it again as raw id
921 $content['uid'] = bigintval($value);
924 // Handle the call in external function
925 $content[$key] = HANDLE_EXTRA_VALUES($filterFunctions[$idx], $value, $extraValues[$idx]);
928 // Add color switching
929 $content['sw'] = $SW;
932 $OUT .= LOAD_TEMPLATE(sprintf("admin_%s_%s_row",
943 SQL_FREERESULT($result);
946 // Load master template
947 LOAD_TEMPLATE(sprintf("admin_%s_%s",
954 // Change status of "build" list
955 function ADMIN_BUILD_STATUS_HANDLER ($mode, $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray) {
956 // All valid entries? (We hope so here!)
957 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues)) && (count($statusArray) > 0)) {
958 // "Walk" through all entries
959 foreach ($IDs as $id => $sel) {
960 // Construct SQL query
961 $SQL = sprintf("UPDATE `{!_MYSQL_PREFIX!}_%s` SET",
965 // Load data of entry
966 $result = SQL_QUERY_ESC("SELECT * FROM `{!_MYSQL_PREFIX!}_%s` WHERE %s=%s LIMIT 1",
967 array($table, $idColumn, $id), __FILE__, __LINE__);
970 $content = SQL_FETCHARRAY($result);
973 SQL_FREERESULT($result);
975 // Add all status entries (e.g. status column last_updated or so)
976 $newStatus = "UNKNOWN";
977 $oldStatus = "UNKNOWN";
978 $statusColumn = "unknown";
979 foreach ($statusArray as $column => $statusInfo) {
980 // Does the entry exist?
981 if ((isset($content[$column])) && (isset($statusInfo[$content[$column]]))) {
982 // Add these entries for update
983 $SQL .= sprintf(" %s='%s',", SQL_ESCAPE($column), SQL_ESCAPE($statusInfo[$content[$column]]));
986 if ($statusColumn == "unknown") {
987 // Always (!!!) change status column first!
988 $oldStatus = $content[$column];
989 $newStatus = $statusInfo[$oldStatus];
990 $statusColumn = $column;
992 } elseif (isset($content[$column])) {
994 mxchange_die("{--".__FUNCTION__."--}:".__LINE__.":UNFINISHED: id={$id}/{$column}[".gettype($statusInfo)."] = {$content[$column]}");
998 // Add other columns as well
999 foreach ($_POST as $key => $entries) {
1000 // Skip id, raw userid and 'do_$mode'
1001 if (!in_array($key, array($idColumn, 'uid_raw', ('do_'.$mode)))) {
1002 // Are there brackets () at the end?
1003 if (substr($entries[$id], -2, 2) == "()") {
1004 // Direct SQL command found
1005 $SQL .= sprintf(" %s=%s,", SQL_ESCAPE($key), SQL_ESCAPE($entries[$id]));
1007 // Add regular entry
1008 $SQL .= sprintf(" %s='%s',", SQL_ESCAPE($key), SQL_ESCAPE($entries[$id]));
1011 $content[$key] = $entries[$id];
1016 // Finish SQL statement
1017 $SQL = substr($SQL, 0, -1) . sprintf(" WHERE %s=%s AND %s='%s' LIMIT 1",
1025 SQL_QUERY($SQL, __FILE__, __LINE__);
1027 // Do we have an URL?
1028 if (isset($content['url'])) {
1029 // Then add a framekiller test as well
1030 $content['frametester'] = FRAMETESTER($content['url']);
1033 // Send "build mails" out
1034 ADMIN_SEND_BUILD_MAILS($mode, $table, $content, $id, $statusInfo[$content[$column]]);
1039 // Delete rows by given ID numbers
1040 function ADMIN_DELETE_ENTRIES_CONFIRM ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $deleteNow=false, $idColumn="id", $userIdColumn="userid") {
1041 // All valid entries? (We hope so here!)
1042 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues))) {
1043 // Shall we delete here or list for deletion?
1045 // The base SQL command:
1046 $SQL = "DELETE LOW_PRIORITY FROM `{!_MYSQL_PREFIX!}_%s` WHERE %s IN (%s)";
1050 foreach ($IDs as $id => $sel) {
1051 // Is there a userid?
1052 if (isset($_POST['uid_raw'][$id])) {
1053 // Load all data from that id
1054 $result = SQL_QUERY_ESC("SELECT * FROM `{!_MYSQL_PREFIX!}_%s` WHERE %s=%s LIMIT 1",
1055 array($table, $idColumn, $id), __FILE__, __LINE__);
1058 $content = SQL_FETCHARRAY($result);
1061 SQL_FREERESULT($result);
1063 // Send "build mails" out
1064 ADMIN_SEND_BUILD_MAILS("del", $table, $content, $id);
1072 SQL_QUERY($SQL, array($table, $idColumn, substr($idList, 0, -1)), __FILE__, __LINE__);
1075 if (SQL_AFFECTEDROWS() == count($IDs)) {
1077 LOAD_TEMPLATE("admin_settings_saved", false, getMessage('ADMIN_ALL_ENTRIES_REMOVED'));
1079 // Some are still there :(
1080 LOAD_TEMPLATE("admin_settings_saved", false, sprintf(ADMIN_SOME_ENTRIES_NOT_DELETED, SQL_AFFECTEDROWS(), count($IDs)));
1083 // List for deletion confirmation
1084 ADMIN_BUILD_LIST("del", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1089 // Edit rows by given ID numbers
1090 function ADMIN_EDIT_ENTRIES_CONFIRM ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $editNow=false, $idColumn="id", $userIdColumn="userid") {
1091 // All valid entries? (We hope so here!)
1092 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues))) {
1093 // Shall we change here or list for editing?
1097 foreach ($IDs as $id => $sel) {
1098 // Prepare content array (new values)
1101 // Prepare SQL for this row
1102 $SQL = sprintf("UPDATE `{!_MYSQL_PREFIX!}_ SET",
1105 foreach ($_POST as $key => $entries) {
1106 // Skip raw userid which is always invalid
1107 if ($key == "uid_raw") {
1108 // Continue with next field
1112 // Is entries an array?
1113 if (($key != $idColumn) && (is_array($entries)) && (isset($entries[$id]))) {
1114 // Add this entry to content
1115 $content[$key] = $entries[$id];
1117 // Send data through the filter function if found
1118 if ((isset($filterFunctions[$key])) && (isset($extraValues[$key]))) {
1119 // Filter function set!
1120 $entries[$id] = HANDLE_EXTRA_VALUES($filterFunctions[$key], $entries[$id], $extraValues[$key]);
1123 // Then add this value
1124 $SQL .= sprintf(" %s='%s',",
1126 SQL_ESCAPE($entries[$id])
1128 } elseif (($key != $idColumn) && (!is_array($entries))) {
1129 // Add normal entries as well!
1130 $content[$key] = $entries;
1133 // Do we have an URL?
1134 if ($key == "url") {
1135 // Then add a framekiller test as well
1136 $content['frametester'] = FRAMETESTER($content[$key]);
1140 // Finish SQL command
1141 $SQL = substr($SQL, 0, -1) . " WHERE ".$idColumn."=".bigintval($id)." LIMIT 1";
1144 SQL_QUERY($SQL, __FILE__, __LINE__);
1146 // Add affected rows
1147 $affected += SQL_AFFECTEDROWS();
1149 // Load all data from that id
1150 $result = SQL_QUERY_ESC("SELECT * FROM `{!_MYSQL_PREFIX!}_%s` WHERE %s=%s LIMIT 1",
1151 array($table, $idColumn, $id), __FILE__, __LINE__);
1155 $DATA = SQL_FETCHARRAY($result);
1158 SQL_FREERESULT($result);
1160 // Send "build mails" out
1161 ADMIN_SEND_BUILD_MAILS("edit", $table, $content, $id);
1165 if ($affected == count($IDs)) {
1167 LOAD_TEMPLATE("admin_settings_saved", false, getMessage('ADMIN_ALL_ENTRIES_EDITED'));
1169 // Some are still there :(
1170 LOAD_TEMPLATE("admin_settings_saved", false, sprintf(ADMIN_SOME_ENTRIES_NOT_EDITED, $affected, count($IDs)));
1174 ADMIN_BUILD_LIST("edit", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1179 // Un-/lock rows by given ID numbers
1180 function ADMIN_LOCK_ENTRIES_CONFIRM ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $statusArray=array(), $lockNow=false, $idColumn="id", $userIdColumn="userid") {
1181 // All valid entries? (We hope so here!)
1182 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues)) && ((!$lockNow) || (count($statusArray) == 1))) {
1183 // Shall we un-/lock here or list for locking?
1186 ADMIN_BUILD_STATUS_HANDLER("lock", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray);
1189 ADMIN_BUILD_LIST("lock", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1194 // Undelete rows by given ID numbers
1195 function ADMIN_UNDELETE_ENTRIES_CONFIRM ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $statusArray=array(), $lockNow=false, $idColumn="id", $userIdColumn="userid") {
1196 // All valid entries? (We hope so here!)
1197 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues)) && ((!$lockNow) || (count($statusArray) == 1))) {
1198 // Shall we un-/lock here or list for locking?
1201 ADMIN_BUILD_STATUS_HANDLER("undelete", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray);
1204 ADMIN_BUILD_LIST("undelete", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1209 // Checks proxy settins by fetching check-updates3.php from www.mxchange.org
1210 function ADMIN_TEST_PROXY_SETTINGS ($settingsArray) {
1211 // Set temporary the new settings
1212 mergeConfig($settingsArray);
1214 // Now get the test URL
1215 $content = GET_URL("check-updates3.php");
1217 // Is the first line with "200 OK"?
1218 $valid = eregi("200 OK", $content[0]);
1224 // Sends out a link to the given email adress so the admin can reset his/her password
1225 function ADMIN_SEND_PASSWORD_RESET_LINK ($email) {
1229 // Compile out security characters (must be for looking up!)
1230 $email = COMPILE_CODE($email);
1232 // Look up administator login
1233 $result = SQL_QUERY_ESC("SELECT id, login, password FROM `{!_MYSQL_PREFIX!}_admins` WHERE email='%s' LIMIT 1",
1234 array($email), __FILE__, __LINE__);
1236 // Is there an account?
1237 if (SQL_NUMROWS($result) == 0) {
1238 // No account found!
1239 return getMessage('ADMIN_NO_LOGIN_WITH_EMAIL');
1243 $content = SQL_FETCHARRAY($result);
1246 SQL_FREERESULT($result);
1248 // Generate hash for reset link
1249 $content['hash'] = generateHash(URL.":".$content['id'].":".$content['login'].":".$content['password'], substr($content['password'], 10));
1252 unset($content['id']);
1253 unset($content['password']);
1256 $mailText = LOAD_EMAIL_TEMPLATE("admin_reset_password", $content);
1259 SEND_EMAIL($email, getMessage('ADMIN_RESET_PASS_LINK_SUBJ'), $mailText);
1262 return getMessage('ADMIN_RESET_LINK_SENT');
1265 // Validate hash and login for password reset
1266 function ADMIN_VALIDATE_RESET_LINK_HASH_LOGIN ($hash, $login) {
1267 // By default nothing validates... ;)
1270 // Compile the login for lookup
1271 $login = COMPILE_CODE($login);
1273 // Then try to find that user
1274 $result = SQL_QUERY_ESC("SELECT id, password, email FROM `{!_MYSQL_PREFIX!}_admins` WHERE login='%s' LIMIT 1",
1275 array($login), __FILE__, __LINE__);
1277 // Is an account here?
1278 if (SQL_NUMROWS($result) == 1) {
1280 $content = SQL_FETCHARRAY($result);
1282 // Generate hash again
1283 $hashFromData = generateHash(URL.":".$content['id'].":".$login.":".$content['password'], substr($content['password'], 10));
1286 $valid = ($hash == $hashFromData);
1290 SQL_FREERESULT($result);
1295 // Reset the password for the login. Do NOT call this function without calling above function first!
1296 function ADMIN_RESET_PASSWORD ($login, $password) {
1300 // Now check if we have sql_patches installed
1301 if (GET_EXT_VERSION("sql_patches") >= "0.3.6") {
1302 // Use new way of hashing
1303 $passHash = generateHash($password);
1306 $passHash = md5($password);
1310 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_admins` SET password='%s' WHERE login='%s' LIMIT 1",
1311 array($passHash, $login), __FILE__, __LINE__);
1314 RUN_FILTER('post_admin_reset_pass', array('login' => $login, 'hash' => $passHash));
1317 return ADMIN_PASSWORD_RESET_DONE;
1319 // Solves a task by given id number
1320 function ADMIN_SOLVE_TASK ($id) {
1321 // Update the task data
1322 ADMIN_UPDATE_TASK_DATA($id, "status", "SOLVED");
1324 // Marks a given task as deleted
1325 function ADMIN_DELETE_TASK ($id) {
1326 // Update the task data
1327 ADMIN_UPDATE_TASK_DATA($id, "status", "DELETED");
1329 // Function to update task data
1330 function ADMIN_UPDATE_TASK_DATA ($id, $row, $data) {
1332 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_task_system` SET %s='%s' WHERE id=%s LIMIT 1",
1333 array($row, $data, bigintval($id)), __FILE__, __LINE__);