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";
41 function REGISTER_ADMIN ($user, $md5, $email=WEBMASTER)
44 $result = SQL_QUERY_ESC("SELECT id FROM "._MYSQL_PREFIX."_admins WHERE login='%s' LIMIT 1",
45 array($user), __FILE__, __LINE__);
46 if (SQL_NUMROWS($result) == 0) {
47 // Ok, let's create the admin login
48 $result = SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_admins (login, password, email) VALUES ('%s', '%s', '%s')",
49 array($user, $md5, $email), __FILE__, __LINE__);
53 SQL_FREERESULT($result);
55 // Login does already exist
60 // Only be executed on login procedure!
61 function CHECK_ADMIN_LOGIN ($admin_login, $password) {
62 global $cacheArray, $_CONFIG, $cacheInstance;
69 $aid = GET_ADMIN_ID($admin_login);
71 // Is the cache valid?
72 if (!empty($cacheArray['admins']['password'][$aid])) {
73 // Get password from cache
74 $data['password'] = $cacheArray['admins']['password'][$aid];
76 if (getConfig('cache_hits') > 0) { $_CONFIG['cache_hits']++; } else { $_CONFIG['cache_hits'] = 1; }
78 // Include more admins data?
79 if (GET_EXT_VERSION("admins") >= "0.7.0") {
81 $data['login_failtures'] = $cacheArray['admins']['login_failtures'][$aid];
82 $data['last_failture'] = $cacheArray['admins']['last_failture'][$aid];
84 } elseif (!EXT_IS_ACTIVE("cache")) {
86 if (GET_EXT_VERSION("admins") >= "0.7.0") {
88 $ADD = ", login_failtures, UNIX_TIMESTAMP(last_failture) AS last_failture";
91 // Get password from DB
92 $result = SQL_QUERY_ESC("SELECT password".$ADD." FROM "._MYSQL_PREFIX."_admins WHERE id=%s LIMIT 1",
93 array($aid), __FILE__, __LINE__);
94 if (SQL_NUMROWS($result) == 1) {
95 // Login password found
99 $data = SQL_FETCHARRAY($result);
103 SQL_FREERESULT($result);
106 //* DEBUG: */ echo "*".$data['password']."/".md5($password)."/".$ret."<br />";
107 if ((isset($data['password'])) && (strlen($data['password']) == 32) && ($data['password'] == md5($password))) {
109 $data['password'] = generateHash($password);
111 // Is the sql_patches not installed, than we cannot have a valid hashed password here!
112 if (($ret == "pass") && ((EXT_VERSION_IS_OLDER("sql_patches", "0.3.6")) || (GET_EXT_VERSION("sql_patches") == ""))) $ret = "done";
113 } elseif ((EXT_VERSION_IS_OLDER("sql_patches", "0.3.6")) || (GET_EXT_VERSION("sql_patches") == "")) {
116 } elseif (!isset($data['password'])) {
117 // Password not found, so no valid login!
121 // Generate salt of password
122 define('__SALT', substr($data['password'], 0, -40));
125 // Check if password is same
126 //* DEBUG: */ echo "*".$ret.",".$data['password'].",".$password.",".$salt."*<br >\n";
127 if (($ret == "pass") && ($data['password'] == generateHash($password, $salt)) && ((!empty($salt))) || ($data['password'] == $password)) {
128 // Re-hash the plain passord with new random salt
129 $data['password'] = generateHash($password);
131 // Do we have 0.7.0 of admins or later?
132 // Remmeber login failtures if available
133 if (GET_EXT_VERSION("admins") >= "0.7.0") {
134 // Store it in session
135 set_session('mxchange_admin_failtures', $data['login_failtures']);
136 set_session('mxchange_admin_last_fail', $data['last_failture']);
138 // Update password and reset login failtures
139 $result = SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_admins SET password='%s',login_failtures=0,last_failture='0000-00-00 00:00:00' WHERE id=%s LIMIT 1",
140 array($data['password'], $aid), __FILE__, __LINE__);
143 $result = SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_admins SET password='%s' WHERE id=%s LIMIT 1",
144 array($data['password'], $aid), __FILE__, __LINE__);
148 REBUILD_CACHE("admins", "admin");
150 // Login has failed by default... ;-)
153 // Password matches so login here
154 if (LOGIN_ADMIN($admin_login, $data['password'])) {
158 } elseif ((empty($salt)) && ($ret == "pass")) {
159 // Something bad went wrong
161 } elseif ($ret == "done") {
162 // Try to login here if we have the old hashing way (sql_patches not installed?)
163 if (!LOGIN_ADMIN($admin_login, $data['password'])) {
164 // Something went wrong
169 // Count login failture if admins extension version is 0.7.0+
170 if (($ret == "pass") && (GET_EXT_VERSION("admins") >= "0.7.0")) {
172 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_admins SET login_failtures=login_failtures+1,last_failture=NOW() WHERE id=%s LIMIT 1",
173 array($aid), __FILE__, __LINE__);
176 REBUILD_CACHE("admins", "admin");
180 //* DEBUG: */ die("RETURN=".$ret);
184 // Try to login the admin by setting some session/cookie variables
185 function LOGIN_ADMIN ($adminLogin, $passHash) {
186 global $cacheInstance;
188 // Reset failture counter on matching admins version
189 if ((GET_EXT_VERSION("admins") >= "0.7.0") && ((EXT_VERSION_IS_OLDER("sql_patches", "0.3.6")) || (GET_EXT_VERSION("sql_patches") == ""))) {
190 // Reset counter on out-dated sql_patches version
191 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_admins SET login_failtures=0,last_failture='0000-00-00 00:00:00' WHERE login='%s' LIMIT 1",
192 array($adminLogin), __FILE__, __LINE__);
195 REBUILD_CACHE("admins", "admin");
198 // Now set all session variables and return the result
201 set_session("admin_md5", generatePassString($passHash))
203 set_session("admin_login", $adminLogin)
205 set_session("admin_last", time())
207 set_session("admin_to", bigintval($_POST['timeout']))
212 // Only be executed on cookie checking
213 function CHECK_ADMIN_COOKIES ($admin_login, $password) {
214 global $cacheArray, $_CONFIG;
215 $ret = "404"; $pass = "";
218 $pass = GET_ADMIN_HASH(GET_ADMIN_ID($admin_login));
219 if ($pass != "-1") $ret = "pass";
221 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):".generatePassString($pass)."(".strlen($pass).")/".$password."(".strlen($password).")<br />\n";
223 // Check if password matches
224 if (($ret == "pass") && ((generatePassString($pass) == $password) || ($pass == $password) || ((strlen($pass) == 32) && (md5($password) == $pass)))) {
225 // Passwords matches!
233 function admin_WriteData ($file, $comment, $prefix, $suffix, $DATA, $seek=0) {
234 // Initialize some variables
240 // Is the file there and read-/write-able?
241 if ((FILE_READABLE($file)) && (is_writeable($file))) {
242 $search = "CFG: ".$comment;
245 // Open the source file
246 $fp = @fopen($file, 'r') or OUTPUT_HTML("<STRONG>READ:</STRONG> ".$file."<br />");
248 // Is the resource valid?
249 if (is_resource($fp)) {
250 // Open temporary file
251 $fp_tmp = @fopen($tmp, 'w') or OUTPUT_HTML("<STRONG>WRITE:</STRONG> ".$tmp."<br />");
253 // Is the resource again valid?
254 if (is_resource($fp_tmp)) {
256 // Read from source file
257 $line = fgets ($fp, 1024);
259 if (strpos($line, $search) > -1) { $next = 0; $found = true; }
262 if ($next === $seek) {
264 $line = $prefix . $DATA . $suffix."\n";
270 // Write to temp file
271 fputs($fp_tmp, $line);
277 // Finished writing tmp file
284 if (($done) && ($found)) {
285 // Copy back tmp file and delete tmp :-)
288 define('_FATAL', false);
290 OUTPUT_HTML("<STRONG>CHANGE:</STRONG> 404!");
291 define('_FATAL', true);
293 OUTPUT_HTML("<STRONG>TMP:</STRONG> UNDONE!");
294 define('_FATAL', true);
298 // File not found, not readable or writeable
299 OUTPUT_HTML("<STRONG>404:</STRONG> ".$file."<br />");
304 function ADMIN_DO_ACTION($wht) {
305 global $menuDesription, $menuTitle, $_CONFIG, $cacheArray, $DATA, $DEPTH;
307 //* DEBUG: */ echo __LINE__."*".$wht."/".$GLOBALS['module']."/".$GLOBALS['action']."/".$GLOBALS['what']."*<br />\n";
308 if (EXT_IS_ACTIVE("cache")) {
309 // Include cache instance
310 global $cacheInstance;
313 // Remove any spaces from variable
315 // Default admin action is the overview page
318 // Compile out some chars
319 $wht = COMPILE_CODE($wht, false, false, false);
323 $act = GET_ACTION($GLOBALS['module'], $wht);
325 // Define admin login name and ID number
326 define('__ADMIN_LOGIN', get_session('admin_login'));
327 define('__ADMIN_ID' , GET_CURRENT_ADMIN_ID());
330 if (EXT_IS_ACTIVE("admins")) {
331 define('__ADMIN_WELCOME', LOAD_TEMPLATE("admin_welcome_admins", true));
333 define('__ADMIN_WELCOME', LOAD_TEMPLATE("admin_welcome", true));
335 define('__ADMIN_FOOTER' , LOAD_TEMPLATE("admin_footer" , true));
336 define('__ADMIN_MENU' , ADD_ADMIN_MENU($act, $wht, true));
339 LOAD_TEMPLATE("admin_main_header");
341 // Check if action/what pair is valid
342 $result_action = SQL_QUERY_ESC("SELECT id FROM "._MYSQL_PREFIX."_admin_menu
343 WHERE action='%s' AND ((what='%s' AND what != 'overview') OR ((what='' OR what IS NULL) AND '%s'='overview'))
344 LIMIT 1", array($act, $wht, $wht), __FILE__, __LINE__);
345 if (SQL_NUMROWS($result_action) == 1) {
347 // Is valid but does the inlcude file exists?
348 $INC = sprintf("%sinc/modules/admin/action-%s.php", PATH, $act);
349 if ((FILE_READABLE($INC)) && (VALIDATE_MENU_ACTION("admin", $act, $wht)) && (__ACL_ALLOW == true)) {
350 // Ok, we finally load the admin action module
352 } elseif (__ACL_ALLOW == false) {
354 LOAD_TEMPLATE("admin_menu_failed", false, ADMINS_ACCESS_DENIED);
355 ADD_FATAL(ADMINS_ACCESS_DENIED);
357 // Include file not found! :-(
358 LOAD_TEMPLATE("admin_menu_failed", false, ADMIN_404_ACTION);
359 ADD_FATAL(ADMIN_404_ACTION_1.$act.ADMIN_404_ACTION_2);
362 // Invalid action/what pair found!
363 LOAD_TEMPLATE("admin_menu_failed", false, ADMIN_INVALID_ACTION);
364 ADD_FATAL(ADMIN_INVALID_ACTION_1.$act."/".$wht.ADMIN_INVALID_ACTION_2);
368 SQL_FREERESULT($result_action);
371 LOAD_TEMPLATE("admin_main_footer");
374 function ADD_ADMIN_MENU($act, $wht, $return=false) {
375 global $menuDesription, $menuTitle, $cacheInstance, $_CONFIG;
382 $menuDesription = array();
383 $menuTitle = array();
385 // Is there a cache instance?
386 if ((is_object($cacheInstance)) && (getConfig('cache_admin_menu') == "Y")) {
388 $cacheName = "admin_".$act."_".$wht."_".GET_LANGUAGE()."_".strtolower(get_session('admin_login'));
390 // Is that cache there?
391 if ($cacheInstance->loadCacheFile($cacheName)) {
393 $data = $cacheInstance->getArrayFromCache();
396 $OUT = base64_decode($data['output'][0]);
397 $menuTitle = unserialize(base64_decode($data['title'][0]));
398 $menuDescription = unserialize(base64_decode($data['descr'][0]));
400 // Return or output content?
410 $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__);
411 if (SQL_NUMROWS($result_main) > 0)
413 $OUT = "<TABLE border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_menu_main\">
414 <TR><TD colspan=\"2\" height=\"7\" class=\"seperator\"> </TD></TR>\n";
415 while (list($menu, $title, $descr) = SQL_FETCHROW($result_main))
417 if ((EXT_IS_ACTIVE("admins")) && (GET_EXT_VERSION("admins") > "0.2"))
419 $ACL = ADMINS_CHECK_ACL($menu, "");
423 // ACL is "allow"... hmmm
430 // Insert compiled menu title and description
431 $menuTitle[$menu] = $title;
432 $menuDesription[$menu] = $descr;
435 <TD class=\"admin_menu\" colspan=\"2\">
436 <NOBR> <STRONG>·</STRONG> ";
437 if (($menu == $act) && (empty($wht)))
443 $OUT .= "[<A href=\"".URL."/modules.php?module=admin&action=".$menu."\">";
446 if (($menu == $act) && (empty($wht)))
454 $OUT .= "</NOBR></TD>
456 $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",
457 array($menu), __FILE__, __LINE__);
458 if ((SQL_NUMROWS($result_what) > 0) && ($act == $menu))
460 $menuDesription = array();
461 $menuTitle = array(); $SUB = true;
463 <TD width=\"10\" class=\"seperator\"> </TD>
464 <TD class=\"admin_menu\">
465 <TABLE border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_menu_sub\">\n";
466 while (list($wht_sub, $title_what, $desc_what) = SQL_FETCHROW($result_what)) {
468 $INC = sprintf("%sinc/modules/admin/what-%s.php", PATH, $wht_sub);
469 if ((EXT_IS_ACTIVE("admins")) && (GET_EXT_VERSION("admins") > "0.2")) {
470 $ACL = ADMINS_CHECK_ACL("", $wht_sub);
472 // ACL is "allow"... hmmm
475 $readable = FILE_READABLE($INC);
477 // Insert compiled title and description
478 $menuTitle[$wht_sub] = $title_what;
479 $menuDesription[$wht_sub] = $desc_what;
481 <TD class=\"admin_menu\" colspan=\"2\">
482 <NOBR> <STRONG>--></STRONG> ";
485 if ($wht == $wht_sub)
491 $OUT .= "[<A href=\"".URL."/modules.php?module=admin&what=".$wht_sub."\">";
496 $OUT .= "<I class=\"admin_note\">";
501 if ($wht == $wht_sub)
514 $OUT .= "</NOBR></TD>
520 SQL_FREERESULT($result_what);
525 $OUT .= "<TR><TD height=\"7\" colspan=\"2\"></TD></TR>\n";
530 SQL_FREERESULT($result_main);
531 $OUT .= "</TABLE>\n";
534 // Compile and run the code here. This inserts all constants into the
535 // HTML output. Costs me some time to figure this out... *sigh* Quix0r
536 $eval = "\$OUT = \"".COMPILE_CODE(addslashes($OUT))."\";";
539 // Is there a cache instance again?
540 if ((is_object($cacheInstance)) && (getConfig('cache_admin_menu') == "Y")) {
542 $cacheInstance->init($cacheName);
544 // Prepare cache data
546 'output' => base64_encode($OUT),
547 'title' => $menuTitle,
548 'descr' => $menuDesription
551 // Write the data away
552 $cacheInstance->addRow($data);
555 $cacheInstance->finalize();
558 // Return or output content?
566 function ADD_MEMBER_SELECTION_BOX ($def="0", $add_all=false, $return=false, $none=false, $field="userid")
568 // Output selection form with all confirmed user accounts listed
569 $result = SQL_QUERY("SELECT userid, surname, family FROM `"._MYSQL_PREFIX."_user_data` ORDER BY userid", __FILE__, __LINE__);
572 // USe this only for adding points (e.g. adding refs really makes no sence ;-) )
573 if ($add_all) $OUT = " <OPTION value=\"all\">".ALL_MEMBERS."</OPTION>\n";
574 elseif ($none) $OUT = " <OPTION value=\"0\">".SELECT_NONE."</OPTION>\n";
575 while (list($id, $sname, $fname) = SQL_FETCHROW($result))
577 $OUT .= " <OPTION value=\"".bigintval($id)."\"";
578 if ($def == $id) $OUT .= " selected=\"selected\"";
579 $OUT .= ">".$sname." ".$fname." (".bigintval($id).")</OPTION>\n";
583 SQL_FREERESULT($result);
586 // Remeber options in constant
587 define('_MEMBER_SELECTION', $OUT);
589 // Display selection box
590 define('__LANG_VALUE', GET_LANGUAGE());
593 LOAD_TEMPLATE("admin_member_selection_box", false, $GLOBALS['what']);
595 // Return content in selection frame
596 return "<select class=\"admin_select\" name=\"".$field."\" size=\"1\">\n".$OUT."</select>\n";
600 function ADMIN_MENU_SELECTION($MODE, $default="", $defid="") {
602 if ($MODE == "action") $wht = "(what='' OR what IS NULL) AND action !='login'";
603 $result = SQL_QUERY_ESC("SELECT %s, title FROM `"._MYSQL_PREFIX."_admin_menu` WHERE ".$wht." ORDER BY sort",
604 array($MODE), __FILE__, __LINE__);
605 if (SQL_NUMROWS($result) > 0) {
606 // Load menu as selection
607 $OUT = "<SELECT name=\"".$MODE."_menu";
608 if ((!empty($defid)) || ($defid == "0")) $OUT .= "[".$defid."]";
609 $OUT .= "\" size=\"1\" class=\"admin_select\">
610 <OPTION value=\"\">".SELECT_NONE."</OPTION>\n";
611 while (list($menu, $title) = SQL_FETCHROW($result)) {
612 $OUT .= " <OPTION value=\"".$menu."\"";
613 if ((!empty($default)) && ($default == $menu)) $OUT .= " selected=\"selected\"";
614 $OUT .= ">".$title."</OPTION>\n";
618 SQL_FREERESULT($result);
619 $OUT .= "</SELECT>\n";
622 $OUT = ADMIN_PROBLEM_NO_MENU;
628 // Save settings to the database
629 function ADMIN_SAVE_SETTINGS (&$POST, $tableName="_config", $whereStatement="config=0", $translateComma=array(), $alwaysAdd=false) {
630 global $_CONFIG, $cacheArray, $cacheInstance;
632 // Prepare all arrays, variables
636 // Now, walk through all entries and prepare them for saving
637 foreach ($POST as $id => $val) {
638 // Process only formular field but not submit buttons ;)
640 // Do not save the ok value
641 CONVERT_SELECTIONS_TO_TIMESTAMP($POST, $DATA, $id, $skip);
643 // Shall we process this ID? It muss not be empty, of course
644 if ((!$skip) && (!empty($id))) {
646 $val = COMPILE_CODE($val);
648 // Translate the value? (comma to dot!)
649 if ((is_array($translateComma)) && (in_array($id, $translateComma))) {
650 // Then do it here... :)
651 $val = REVERT_COMMA($val);
654 // Shall we add numbers or strings?
656 if ("".$val."" == "".$test."") {
658 $DATA[] = sprintf("`%s`=%s", $id, $test);
661 $DATA[] = sprintf("`%s`='%s'", $id, trim($val));
664 // Update current configuration
665 $_CONFIG[$id] = $val;
670 // Check if entry does exist
673 if (!empty($whereStatement)) {
674 $result = SQL_QUERY("SELECT * FROM `"._MYSQL_PREFIX.$tableName."` WHERE ".$whereStatement." LIMIT 1", __FILE__, __LINE__);
676 $result = SQL_QUERY("SELECT * FROM `"._MYSQL_PREFIX.$tableName."` LIMIT 1", __FILE__, __LINE__);
680 if (SQL_NUMROWS($result) == 1) {
681 // "Implode" all data to single string
682 $DATA_UPDATE = implode(", ", $DATA);
684 // Generate SQL string
685 $SQL = sprintf("UPDATE `"._MYSQL_PREFIX."%s` SET %s WHERE %s LIMIT 1",
691 // Add Line (does only work with auto_increment!
692 $KEYs = array(); $VALUEs = array();
693 foreach ($DATA as $entry) {
695 $line = explode("=", $entry);
696 $KEYs[] = $line[0]; $VALUEs[] = $line[1];
699 // Add both in one line
700 $KEYs = implode(", ", $KEYs);
701 $VALUEs = implode(", ", $VALUEs);
703 // Generate SQL string
704 $SQL = sprintf("INSERT INTO "._MYSQL_PREFIX."%s (%s) VALUES (%s)",
712 SQL_FREERESULT($result);
714 // Simply run generated SQL string
715 $result = SQL_QUERY($SQL, __FILE__, __LINE__);
718 REBUILD_CACHE("config", "config");
721 LOAD_TEMPLATE("admin_settings_saved", false, "<STRONG class=\"admin_done\">".SETTINGS_SAVED."</STRONG>");
724 function ADMIN_MAKE_MENU_SELECTION($menu, $type, $name, $default="") {
725 // Open the requested menu directory
726 $handle = opendir(sprintf("%sinc/modules/%s/", 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", PATH, $menu, $file);
737 if ((is_file($test)) && (is_readable($test))) {
738 // Extract the value for what=xxx
739 $part = substr($file, (strlen($type) + 1));
740 $part = substr($part, 0, -4);
742 // Is that part different from the overview?
743 if ($part != "overview") {
744 $OUT .= " <OPTION value=\"".$part."\"";
745 if ($part == $default) $OUT .= "selected";
746 $OUT .= ">".$part."</OPTION>\n";
752 // Close dir and selection box
754 $OUT .= "</SELECT>\n";
758 function ADMIN_USER_PROFILE_LINK ($uid, $title="", $wht="list_user") {
759 if (($title == "") && ($title != "0")) {
760 // Set userid as title
764 if (($title == "0") && ($wht == "list_refs")) {
765 // Return title again
769 //* DEBUG: */ echo "A:".$title."<br />";
771 return "<A href=\"".URL."/modules.php?module=admin&what=".$wht."&u_id=".$uid."\" title=\"".ADMIN_USER_PROFILE_TITLE."\">".$title."</A>";
774 function ADMIN_CHECK_MENU_MODE() {
775 global $_CONFIG, $cacheArray;
777 // Set the global mode as the mode for all admins
778 $MODE = getConfig('admin_menu');
782 $aid = GET_CURRENT_ADMIN_ID();
784 // Check individual settings of current admin
785 if (isset($cacheArray['admins']['la_mode'][$aid])) {
787 $ADMIN = $cacheArray['admins']['la_mode'][$aid];
788 if (getConfig('cache_hits') > 0) { $_CONFIG['cache_hits']++; } else { $_CONFIG['cache_hits'] = 1; }
789 } elseif (GET_EXT_VERSION("admins") >= "0.6.7") {
790 // Load from database when version of "admins" is enough
791 $result = SQL_QUERY_ESC("SELECT la_mode FROM "._MYSQL_PREFIX."_admins WHERE id=%s LIMIT 1",
792 array($aid), __FILE__, __LINE__);
793 if (SQL_NUMROWS($result) == 1) {
795 list($ADMIN) = SQL_FETCHROW($result);
799 SQL_FREERESULT($result);
802 // Check what the admin wants and set it when it's not the global mode
803 if ($ADMIN != "global") $MODE = $ADMIN;
805 // Return admin-menu's mode
808 // Change activation status
809 function ADMIN_CHANGE_ACTIVATION_STATUS ($IDs, $table, $row, $idRow = "id") {
811 $cnt = 0; $newStatus = "Y";
812 if ((is_array($IDs)) && (count($IDs) > 0)) {
813 // "Walk" all through and count them
814 foreach ($IDs as $id => $selected) {
815 // Secure the ID number
816 $id = bigintval($id);
818 // Should always be 1 ;-)
819 if ($selected == 1) {
820 // Determine new status
821 $result = SQL_QUERY_ESC("SELECT %s FROM "._MYSQL_PREFIX."_%s WHERE %s=%s LIMIT 1",
822 array($row, $table, $idRow, $id), __FILE__, __LINE__);
825 if (SQL_NUMROWS($result) == 1) {
827 list($currStatus) = SQL_FETCHROW($result);
828 if ($currStatus == "Y") $newStatus='N'; else $newStatus = "Y";
830 // Change this status
831 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_%s SET %s='%s' WHERE %s=%s LIMIT 1",
832 array($table, $row, $newStatus, $idRow, $id), __FILE__, __LINE__);
834 // Count up affected rows
835 $cnt += SQL_AFFECTEDROWS();
839 SQL_FREERESULT($result);
844 LOAD_TEMPLATE("admin_settings_saved", false, ADMIN_STATUS_CHANGED_1.$cnt.ADMIN_STATUS_CHANGED_2.count($IDs).ADMIN_STATUS_CHANGED_3);
847 LOAD_TEMPLATE("admin_settings_saved", false, ADMIN_NOTHING_SELECTED_CHANGE);
850 // Send mails for del/edit/lock build modes
851 function ADMIN_SEND_BUILD_MAILS ($mode, $table, $content, $id, $subjectPart="") {
852 // Default subject is the subject part
853 $subject = $subjectPart;
855 // Is the subject part not set?
856 if (empty($subjectPart)) {
857 // Then use it from the mode
858 $subject = strtoupper($mode);
861 // Is the raw userid set?
862 if ($_POST['uid_raw'][$id] > 0) {
864 $subjectLine = constant('MEMBER_'.strtoupper($subject).'_'.strtoupper($table).'_SUBJECT');
866 // Load email template
867 if (!empty($subjectPart)) {
868 $mail = LOAD_EMAIL_TEMPLATE("member_".$mode."_".strtolower($subjectPart)."_".$table, $content);
870 $mail = LOAD_EMAIL_TEMPLATE("member_".$mode."_".$table, $content);
874 SEND_EMAIL($_POST['uid_raw'][$id], $subjectLine, $mail);
878 $subjectLine = constant('ADMIN_'.strtoupper($subject).'_'.strtoupper($table).'_SUBJECT');
880 // Send admin notification out
881 if (!empty($subjectPart)) {
882 SEND_ADMIN_NOTIFICATION($subjectLine, "admin_".$mode."_".strtolower($subjectPart)."_".$table, $content, $_POST['uid_raw'][$id]);
884 SEND_ADMIN_NOTIFICATION($subjectLine, "admin_".$mode."_".$table, $content, $_POST['uid_raw'][$id]);
887 // Build a special template list
888 function ADMIN_BUILD_LIST ($listType, $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn) {
892 // "Walk" through all entries
893 foreach ($IDs as $id => $selected) {
895 $id = bigintval($id);
897 // Get result from a given column array and table name
898 $result = SQL_RESULT_FROM_ARRAY($table, $columns, $idColumn, $id, __FILE__, __LINE__);
900 // Is there one entry?
901 if (SQL_NUMROWS($result) == 1) {
903 $content = SQL_FETCHARRAY($result);
906 foreach ($content as $key => $value) {
908 $idx = array_search($key, $columns, true);
910 // Do we have a userid?
911 if ($key == "userid") {
912 // Add it again as raw id
913 $content['uid'] = bigintval($value);
916 // Handle the call in external function
917 $content[$key] = HANDLE_EXTRA_VALUES($filterFunctions[$idx], $value, $extraValues[$idx]);
920 // Add color switching
921 $content['sw'] = $SW;
924 $OUT .= LOAD_TEMPLATE(sprintf("admin_%s_%s_row",
935 SQL_FREERESULT($result);
938 // Load master template
939 LOAD_TEMPLATE(sprintf("admin_%s_%s",
945 // Change status of "build" list
946 function ADMIN_BUILD_STATUS_HANDLER ($mode, $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray) {
947 // All valid entries? (We hope so here!)
948 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues)) && (count($statusArray) > 0)) {
949 // "Walk" through all entries
950 foreach ($IDs as $id => $sel) {
951 // Construct SQL query
952 $SQL = "UPDATE "._MYSQL_PREFIX."_".$table." SET";
954 // Load data of entry
955 $result = SQL_QUERY_ESC("SELECT * FROM "._MYSQL_PREFIX."_%s WHERE %s=%s LIMIT 1",
956 array($table, $idColumn, $id), __FILE__, __LINE__);
959 $content = SQL_FETCHARRAY($result);
962 SQL_FREERESULT($result);
964 // Add all status entries (e.g. status column last_updated or so)
965 $newStatus = "UNKNOWN";
966 $oldStatus = "UNKNOWN";
967 $statusColumn = "unknown";
968 foreach ($statusArray as $column => $statusInfo) {
969 // Does the entry exist?
970 if ((isset($content[$column])) && (isset($statusInfo[$content[$column]]))) {
971 // Add these entries for update
972 $SQL .= sprintf(" %s='%s',", SQL_ESCAPE($column), SQL_ESCAPE($statusInfo[$content[$column]]));
975 if ($statusColumn == "unknown") {
976 // Always (!!!) change status column first!
977 $oldStatus = $content[$column];
978 $newStatus = $statusInfo[$oldStatus];
979 $statusColumn = $column;
981 } elseif (isset($content[$column])) {
983 mxchange_die("{--".__FUNCTION__."--}:".__LINE__.":UNFINISHED: id={$id}/{$column}[".gettype($statusInfo)."] = {$content[$column]}");
987 // Add other columns as well
988 foreach ($_POST as $key => $entries) {
989 // Skip id, raw userid and 'do_$mode'
990 if (!in_array($key, array($idColumn, 'uid_raw', ('do_'.$mode)))) {
991 // Are there brackets () at the end?
992 if (substr($entries[$id], -2, 2) == "()") {
993 // Direct SQL command found
994 $SQL .= sprintf(" %s=%s,", SQL_ESCAPE($key), SQL_ESCAPE($entries[$id]));
997 $SQL .= sprintf(" %s='%s',", SQL_ESCAPE($key), SQL_ESCAPE($entries[$id]));
1000 $content[$key] = $entries[$id];
1005 // Finish SQL statement
1006 $SQL = substr($SQL, 0, -1) . sprintf(" WHERE %s=%s AND %s='%s' LIMIT 1",
1014 SQL_QUERY($SQL, __FILE__, __LINE__);
1016 // Do we have an URL?
1017 if (isset($content['url'])) {
1018 // Then add a framekiller test as well
1019 $content['frametester'] = FRAMETESTER($content['url']);
1022 // Send "build mails" out
1023 ADMIN_SEND_BUILD_MAILS($mode, $table, $content, $id, $statusInfo[$content[$column]]);
1027 // Delete rows by given ID numbers
1028 function ADMIN_DELETE_ENTRIES_CONFIRM ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $deleteNow=false, $idColumn="id", $userIdColumn="userid") {
1029 // All valid entries? (We hope so here!)
1030 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues))) {
1031 // Shall we delete here or list for deletion?
1033 // The base SQL command:
1034 $SQL = "DELETE LOW_PRIORITY FROM "._MYSQL_PREFIX."_%s WHERE %s IN (%s)";
1038 foreach ($IDs as $id => $sel) {
1039 // Is there a userid?
1040 if (isset($_POST['uid_raw'][$id])) {
1041 // Load all data from that id
1042 $result = SQL_QUERY_ESC("SELECT * FROM "._MYSQL_PREFIX."_%s WHERE %s=%s LIMIT 1",
1043 array($table, $idColumn, $id), __FILE__, __LINE__);
1046 $content = SQL_FETCHARRAY($result);
1049 SQL_FREERESULT($result);
1051 // Send "build mails" out
1052 ADMIN_SEND_BUILD_MAILS("del", $table, $content, $id);
1060 SQL_QUERY($SQL, array($table, $idColumn, substr($idList, 0, -1)), __FILE__, __LINE__);
1063 if (SQL_AFFECTEDROWS() == count($IDs)) {
1065 LOAD_TEMPLATE("admin_settings_saved", false, ADMIN_ALL_ENTRIES_REMOVED);
1067 // Some are still there :(
1068 LOAD_TEMPLATE("admin_settings_saved", false, sprintf(ADMIN_SOME_ENTRIES_NOT_DELETED, SQL_AFFECTEDROWS(), count($IDs)));
1071 // List for deletion confirmation
1072 ADMIN_BUILD_LIST("del", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1076 // Edit rows by given ID numbers
1077 function ADMIN_EDIT_ENTRIES_CONFIRM ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $editNow=false, $idColumn="id", $userIdColumn="userid") {
1078 // All valid entries? (We hope so here!)
1079 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues))) {
1080 // Shall we change here or list for editing?
1084 foreach ($IDs as $id => $sel) {
1085 // Prepare content array (new values)
1088 // Prepare SQL for this row
1089 $SQL = "UPDATE "._MYSQL_PREFIX."_".$table." SET";
1090 foreach ($_POST as $key => $entries) {
1091 // Skip raw userid which is always invalid
1092 if ($key == "uid_raw") {
1093 // Continue with next field
1097 // Is entries an array?
1098 if (($key != $idColumn) && (is_array($entries)) && (isset($entries[$id]))) {
1099 // Add this entry to content
1100 $content[$key] = $entries[$id];
1102 // Send data through the filter function if found
1103 if ((isset($filterFunctions[$key])) && (isset($extraValues[$key]))) {
1104 // Filter function set!
1105 $entries[$id] = HANDLE_EXTRA_VALUES($filterFunctions[$key], $entries[$id], $extraValues[$key]);
1108 // Then add this value
1109 $SQL .= sprintf(" %s='%s',",
1111 SQL_ESCAPE($entries[$id])
1113 } elseif (($key != $idColumn) && (!is_array($entries))) {
1114 // Add normal entries as well!
1115 $content[$key] = $entries;
1118 // Do we have an URL?
1119 if ($key == "url") {
1120 // Then add a framekiller test as well
1121 $content['frametester'] = FRAMETESTER($content[$key]);
1125 // Finish SQL command
1126 $SQL = substr($SQL, 0, -1) . " WHERE ".$idColumn."=".bigintval($id)." LIMIT 1";
1129 SQL_QUERY($SQL, __FILE__, __LINE__);
1131 // Add affected rows
1132 $affected += SQL_AFFECTEDROWS();
1134 // Load all data from that id
1135 $result = SQL_QUERY_ESC("SELECT * FROM "._MYSQL_PREFIX."_%s WHERE %s=%s LIMIT 1",
1136 array($table, $idColumn, $id), __FILE__, __LINE__);
1140 $DATA = SQL_FETCHARRAY($result);
1143 SQL_FREERESULT($result);
1145 // Send "build mails" out
1146 ADMIN_SEND_BUILD_MAILS("edit", $table, $content, $id);
1150 if ($affected == count($IDs)) {
1152 LOAD_TEMPLATE("admin_settings_saved", false, ADMIN_ALL_ENTRIES_EDITED);
1154 // Some are still there :(
1155 LOAD_TEMPLATE("admin_settings_saved", false, sprintf(ADMIN_SOME_ENTRIES_NOT_EDITED, $affected, count($IDs)));
1159 ADMIN_BUILD_LIST("edit", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1163 // Un-/lock rows by given ID numbers
1164 function ADMIN_LOCK_ENTRIES_CONFIRM ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $statusArray=array(), $lockNow=false, $idColumn="id", $userIdColumn="userid") {
1165 // All valid entries? (We hope so here!)
1166 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues)) && ((!$lockNow) || (count($statusArray) == 1))) {
1167 // Shall we un-/lock here or list for locking?
1170 ADMIN_BUILD_STATUS_HANDLER("lock", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray);
1173 ADMIN_BUILD_LIST("lock", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1177 // Undelete rows by given ID numbers
1178 function ADMIN_UNDELETE_ENTRIES_CONFIRM ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $statusArray=array(), $lockNow=false, $idColumn="id", $userIdColumn="userid") {
1179 // All valid entries? (We hope so here!)
1180 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues)) && ((!$lockNow) || (count($statusArray) == 1))) {
1181 // Shall we un-/lock here or list for locking?
1184 ADMIN_BUILD_STATUS_HANDLER("undelete", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray);
1187 ADMIN_BUILD_LIST("undelete", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1191 // Checks proxy settins by fetching check-updates3.php from www.mxchange.org
1192 function ADMIN_TEST_PROXY_SETTINGS ($settingsArray) {
1195 // Set temporary the new settings
1196 $_CONFIG = merge_array($_CONFIG, $settingsArray);
1198 // Now get the test URL
1199 $content = GET_URL("check-updates3.php");
1201 // Is the first line with "200 OK"?
1202 $valid = eregi("200 OK", $content[0]);
1207 // Sends out a link to the given email adress so the admin can reset his/her password
1208 function ADMIN_SEND_PASSWORD_RESET_LINK ($email) {
1213 // Compile out security characters (must be for looking up!)
1214 $email = COMPILE_CODE($email);
1216 // Look up administator login
1217 $result = SQL_QUERY_ESC("SELECT id, login, password FROM "._MYSQL_PREFIX."_admins WHERE email='%s' LIMIT 1",
1218 array($email), __FILE__, __LINE__);
1220 // Is there an account?
1221 if (SQL_NUMROWS($result) == 0) {
1222 // No account found!
1223 return ADMIN_NO_LOGIN_WITH_EMAIL;
1227 $content = SQL_FETCHARRAY($result);
1230 SQL_FREERESULT($result);
1232 // Generate hash for reset link
1233 $content['hash'] = generateHash(URL.":".$content['id'].":".$content['login'].":".$content['password'], substr($content['password'], 10));
1236 unset($content['id']);
1237 unset($content['password']);
1240 $mailText = LOAD_EMAIL_TEMPLATE("admin_reset_password", $content);
1243 SEND_EMAIL($email, ADMIN_RESET_PASS_LINK_SUBJ, $mailText);
1246 return ADMIN_RESET_LINK_SENT;
1248 // Validate hash and login for password reset
1249 function ADMIN_VALIDATE_RESET_LINK_HASH_LOGIN ($hash, $login) {
1250 // By default nothing validates... ;)
1253 // Compile the login for lookup
1254 $login = COMPILE_CODE($login);
1256 // Then try to find that user
1257 $result = SQL_QUERY_ESC("SELECT id, password, email FROM "._MYSQL_PREFIX."_admins WHERE login='%s' LIMIT 1",
1258 array($login), __FILE__, __LINE__);
1260 // Is an account here?
1261 if (SQL_NUMROWS($result) == 1) {
1263 $content = SQL_FETCHARRAY($result);
1265 // Generate hash again
1266 $hashFromData = generateHash(URL.":".$content['id'].":".$login.":".$content['password'], substr($content['password'], 10));
1269 $valid = ($hash == $hashFromData);
1273 SQL_FREERESULT($result);
1278 // Reset the password for the login. Do NOT call this function without calling above function first!
1279 function ADMIN_RESET_PASSWORD ($login, $password) {
1283 // Now check if we have sql_patches installed
1284 if (GET_EXT_VERSION("sql_patches") >= "0.3.6") {
1285 // Use new way of hashing
1286 $passHash = generateHash($password);
1289 $passHash = md5($password);
1293 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_admins SET password='%s' WHERE login='%s' LIMIT 1",
1294 array($passHash, $login), __FILE__, __LINE__);
1297 RUN_FILTER('post_admin_reset_pass', array('login' => $login, 'hash' => $passHash));
1300 return ADMIN_PASSWORD_RESET_DONE;
1302 // Solves a task by given id number
1303 function ADMIN_SOLVE_TASK ($id) {
1304 // Update the task data
1305 ADMIN_UPDATE_TASK_DATA($id, "status", "SOLVED");
1307 // Marks a given task as deleted
1308 function ADMIN_DELETE_TASK ($id) {
1309 // Update the task data
1310 ADMIN_UPDATE_TASK_DATA($id, "status", "DELETED");
1312 // Function to update task data
1313 function ADMIN_UPDATE_TASK_DATA ($id, $row, $data) {
1315 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_task_system SET %s='%s' WHERE id=%s LIMIT 1",
1316 array($row, $data, bigintval($id)), __FILE__, __LINE__);