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 (ereg(basename(__FILE__), $_SERVER['PHP_SELF']))
37 $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), "/inc") + 4) . "/security.php";
42 function REGISTER_ADMIN ($user, $md5, $email=WEBMASTER)
45 $result = SQL_QUERY_ESC("SELECT id FROM "._MYSQL_PREFIX."_admins WHERE login='%s' LIMIT 1",
46 array($user), __FILE__, __LINE__);
47 if (SQL_NUMROWS($result) == 0) {
48 // Ok, let's create the admin login
49 $result = SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_admins (login, password, email) VALUES('%s', '%s', '%s')",
50 array($user, $md5, $email), __FILE__, __LINE__);
54 SQL_FREERESULT($result);
56 // Login does already exist
61 // Only be executed on login procedure!
62 function CHECK_ADMIN_LOGIN ($admin_login, $password)
64 global $cacheArray, $_CONFIG, $cacheInstance;
70 // Is the cache valid?
71 if (!empty($cacheArray['admins']['aid'][$admin_login])) {
72 // Get password from cache
73 $data['password'] = $cacheArray['admins']['password'][$admin_login];
75 $_CONFIG['cache_hits']++;
77 // Include more admins data?
78 if (GET_EXT_VERSION("admins") >= "0.7.0") {
80 $data['login_failtures'] = $cacheArray['admins']['login_failtures'][$admin_login];
81 $data['last_failture'] = $cacheArray['admins']['last_failture'][$admin_login];
83 } elseif (GET_EXT_VERSION("cache") == "") {
85 if (GET_EXT_VERSION("admins") >= "0.7.0") {
87 $ADD = ", login_failtures, UNIX_TIMESTAMP(last_failture) AS last_failture";
90 // Get password from DB
91 $result = SQL_QUERY_ESC("SELECT password".$ADD." FROM "._MYSQL_PREFIX."_admins WHERE login='%s' LIMIT 1",
92 array($admin_login), __FILE__, __LINE__);
93 if (SQL_NUMROWS($result) == 1) {
94 // Login password found
98 $data = SQL_FETCHARRAY($result);
102 SQL_FREERESULT($result);
105 //* DEBUG: */ echo "*".$data['password']."/".md5($password)."/".$ret."<br />";
106 if ((isset($data['password'])) && (strlen($data['password']) == 32) && ($data['password'] == md5($password))) {
108 $data['password'] = generateHash($password);
110 // Is the sql_patches not installed, than we cannot have a valid hashed password here!
111 if (($ret == "pass") && ((GET_EXT_VERSION("sql_patches") < "0.3.6") || (GET_EXT_VERSION("sql_patches") == ""))) $ret = "done";
112 } elseif ((GET_EXT_VERSION("sql_patches") < "0.3.6") || (GET_EXT_VERSION("sql_patches") == "")) {
115 } elseif (!isset($data['password'])) {
116 // Password not found, so no valid login!
120 // Generate salt of password
121 define('__SALT', substr($data['password'], 0, -40));
124 // Check if password is same
125 //* DEBUG: */ echo "*".$ret.",".$data['password'].",".$password.",".$salt."*<br >\n";
126 if (($ret == "pass") && ($data['password'] == generateHash($password, $salt)) && (!empty($salt))) {
127 // Re-hash the plain passord with new random salt
128 $data['password'] = generateHash($password);
130 // Do we have 0.7.0 of admins or later?
131 // Remmeber login failtures if available
132 if (GET_EXT_VERSION("admins") >= "0.7.0") {
133 // Store it in session
134 set_session('mxchange_admin_failtures', $data['login_failtures']);
135 set_session('mxchange_admin_last_fail', $data['last_failture']);
139 $result = SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_admins SET password='%s',login_failtures=0,last_failture='0000-00-00 00:00:00' WHERE login='%s' LIMIT 1",
140 array($data['password'], $admin_login), __FILE__, __LINE__);
143 REBUILD_CACHE("admins", "admin");
145 // Login has failed by default... ;-)
148 // Password matches so login here
149 if (LOGIN_ADMIN($admin_login, $data['password'])) {
153 } elseif ((empty($salt)) && ($ret == "pass")) {
154 // Something bad went wrong
156 } elseif ($ret == "done") {
157 // Try to login here if we have the old hashing way (sql_patches not installed?)
158 if (!LOGIN_ADMIN($admin_login, $data['password'])) {
159 // Something went wrong
164 // Count login failture if admins extension version is 0.7.0+
165 if (($ret == "pass") && (GET_EXT_VERSION("admins") >= "0.7.0")) {
167 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_admins SET login_failtures=login_failtures+1,last_failture=NOW() WHERE login='%s' LIMIT 1",
168 array($admin_login), __FILE__, __LINE__);
171 REBUILD_CACHE("admins", "admin");
175 //* DEBUG: */ die("RETURN=".$ret);
179 // Try to login the admin by setting some session/cookie variables
180 function LOGIN_ADMIN ($adminLogin, $passHash) {
181 global $cacheInstance;
183 // Reset failture counter on matching admins version
184 if ((GET_EXT_VERSION("admins") >= "0.7.0") && ((GET_EXT_VERSION("sql_patches") < "0.3.6") || (GET_EXT_VERSION("sql_patches") == ""))) {
185 // Reset counter on out-dated sql_patches version
186 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_admins SET login_failtures=0,last_failture='0000-00-00 00:00:00' WHERE login='%s' LIMIT 1",
187 array($adminLogin), __FILE__, __LINE__);
190 REBUILD_CACHE("admins", "admin");
193 // Now set all session variables and return the result
196 set_session("admin_md5", generatePassString($passHash))
198 set_session("admin_login", $adminLogin)
200 set_session("admin_last", time())
202 set_session("admin_to", bigintval($_POST['timeout']))
207 // Only be executed on cookie checking
208 function CHECK_ADMIN_COOKIES ($admin_login, $password) {
209 global $cacheArray, $_CONFIG;
210 $ret = "404"; $pass = "";
211 if (!empty($cacheArray['admins']['aid'][$admin_login])) {
212 // Get password from cache
213 $pass = $cacheArray['admins']['password'][$admin_login];
215 $_CONFIG['cache_hits']++;
216 } elseif (GET_EXT_VERSION("cache") == "") {
217 // Get password from DB
218 $result = SQL_QUERY_ESC("SELECT password FROM "._MYSQL_PREFIX."_admins WHERE login='%s' LIMIT 1",
219 array($admin_login), __FILE__, __LINE__);
220 if (SQL_NUMROWS($result) == 1) {
225 list($pass) = SQL_FETCHROW($result);
229 SQL_FREERESULT($result);
232 //* DEBUG: */ echo __FUNCTION__.":".$pass."(".strlen($pass).")/".$password."(".strlen($password).")<br />\n";
234 // Check if password matches
235 if (($ret == "pass") && ((generatePassString($pass) == $password) || ($pass == $password) || ((strlen($pass) == 32) && (md5($password) == $pass)))) {
236 // Passwords matches!
244 function admin_WriteData ($file, $comment, $prefix, $suffix, $DATA, $seek=0) {
245 // Initialize some variables
250 // Is the file there and read-/write-able?
251 if ((FILE_READABLE($file)) && (is_writeable($file))) {
252 $search = "CFG: ".$comment;
255 // Open the source file
256 $fp = @fopen($file, 'r') or OUTPUT_HTML("<STRONG>READ:</STRONG> ".$file."<br />");
258 // Is the resource valid?
259 if (is_resource($fp)) {
260 // Open temporary file
261 $fp_tmp = @fopen($tmp, 'w') or OUTPUT_HTML("<STRONG>WRITE:</STRONG> ".$tmp."<br />");
263 // Is the resource again valid?
264 if (is_resource($fp_tmp)) {
266 // Read from source file
267 $line = fgets ($fp, 1024);
269 if (strpos($line, $search) > -1) { $next = 0; $found = true; }
272 if ($next == $seek) {
274 $line = $prefix . $DATA . $suffix."\n";
280 // Write to temp file
281 fputs($fp_tmp, $line);
287 // Finished writing tmp file
294 if (($done) && ($found)) {
295 // Copy back tmp file and delete tmp :-)
298 define('_FATAL', false);
300 OUTPUT_HTML("<STRONG>CHANGE:</STRONG> 404!");
301 define('_FATAL', true);
303 OUTPUT_HTML("<STRONG>TMP:</STRONG> UNDONE!");
304 define('_FATAL', true);
308 // File not found, not readable or writeable
309 OUTPUT_HTML("<STRONG>404:</STRONG> ".$file."<br />");
314 function ADMIN_DO_ACTION($wht)
316 global $menuDesription, $menuTitle, $_CONFIG, $cacheArray, $DATA, $DEPTH;
317 //* DEBUG: */ echo __LINE__."*".$wht."/".$GLOBALS['module']."/".$GLOBALS['action']."/".$GLOBALS['what']."*<br />\n";
318 if (EXT_IS_ACTIVE("cache"))
320 // Include cache instance
321 global $cacheInstance;
324 // Remove any spaces from variable
327 // Default admin action is the overview page
332 // Compile out some chars
333 $wht = COMPILE_CODE($wht, false, false, false);
337 $act = GET_ACTION($GLOBALS['module'], $wht);
339 // Define admin login name and ID number
340 define('__ADMIN_LOGIN', get_session('admin_login'));
341 define('__ADMIN_ID' , GET_ADMIN_ID(get_session('admin_login')));
344 if (EXT_IS_ACTIVE("admins")) {
345 define('__ADMIN_WELCOME', LOAD_TEMPLATE("admin_welcome_admins", true));
347 define('__ADMIN_WELCOME', LOAD_TEMPLATE("admin_welcome", true));
349 define('__ADMIN_FOOTER' , LOAD_TEMPLATE("admin_footer" , true));
350 define('__ADMIN_MENU' , ADD_ADMIN_MENU($act, $wht, true));
353 LOAD_TEMPLATE("admin_main_header");
355 // Check if action/what pair is valid
356 $result = SQL_QUERY_ESC("SELECT id FROM "._MYSQL_PREFIX."_admin_menu
357 WHERE action='%s' AND ((what='%s' AND what != 'overview') OR ((what='' OR what IS NULL) AND '%s'='overview'))
358 LIMIT 1", array($act, $wht, $wht), __FILE__, __LINE__);
359 if (SQL_NUMROWS($result) == 1)
362 SQL_FREERESULT($result);
364 // Is valid but does the inlcude file exists?
365 $INC = sprintf("%sinc/modules/admin/action-%s.php", PATH, $act);
366 if ((FILE_READABLE($INC)) && (VALIDATE_MENU_ACTION("admin", $act, $wht)) && (__ACL_ALLOW == true))
368 // Ok, we finally load the admin action module
371 elseif (__ACL_ALLOW == false)
374 LOAD_TEMPLATE("admin_menu_failed", false, ADMINS_ACCESS_DENIED);
375 ADD_FATAL(ADMINS_ACCESS_DENIED);
379 // Include file not found! :-(
380 LOAD_TEMPLATE("admin_menu_failed", false, ADMIN_404_ACTION);
381 ADD_FATAL(ADMIN_404_ACTION_1.$act.ADMIN_404_ACTION_2);
384 // Invalid action/what pair found!
385 LOAD_TEMPLATE("admin_menu_failed", false, ADMIN_INVALID_ACTION);
386 ADD_FATAL(ADMIN_INVALID_ACTION_1.$act."/".$wht.ADMIN_INVALID_ACTION_2);
390 LOAD_TEMPLATE("admin_main_footer");
393 function ADD_ADMIN_MENU($act, $wht,$return=false)
395 global $menuDesription, $menuTitle;
399 $menuDesription = array();
400 $menuTitle = array();
403 $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__);
405 if (SQL_NUMROWS($result_main) > 0)
407 $OUT = "<TABLE border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_menu_main\">
408 <TR><TD colspan=\"2\" height=\"7\" class=\"seperator\"> </TD></TR>\n";
409 while (list($menu, $title, $descr) = SQL_FETCHROW($result_main))
411 if ((EXT_IS_ACTIVE("admins")) && (GET_EXT_VERSION("admins") > "0.2"))
413 $ACL = ADMINS_CHECK_ACL($menu, "");
417 // ACL is "allow"... hmmm
424 // Insert compiled menu title and description
425 $menuTitle[$menu] = $title;
426 $menuDesription[$menu] = $descr;
429 <TD class=\"admin_menu\" colspan=\"2\">
430 <NOBR> <STRONG>·</STRONG> ";
431 if (($menu == $act) && (empty($wht)))
437 $OUT .= "[<A href=\"".URL."/modules.php?module=admin&action=".$menu."\">";
440 if (($menu == $act) && (empty($wht)))
448 $OUT .= "</NOBR></TD>
450 $result_what = SQL_QUERY_ESC("SELECT what, title, descr FROM "._MYSQL_PREFIX."_admin_menu WHERE action='%s' AND what != '' ORDER BY sort, id DESC",
451 array($menu), __FILE__, __LINE__);
452 if ((SQL_NUMROWS($result_what) > 0) && ($act == $menu))
454 $menuDesription = array();
455 $menuTitle = array(); $SUB = true;
457 <TD width=\"10\" class=\"seperator\"> </TD>
458 <TD class=\"admin_menu\">
459 <TABLE border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_menu_sub\">\n";
460 while (list($wht_sub, $title_what, $desc_what) = SQL_FETCHROW($result_what))
463 $INC = sprintf("%sinc/modules/admin/what-%s.php", PATH, $wht_sub);
464 if ((EXT_IS_ACTIVE("admins")) && (GET_EXT_VERSION("admins") > "0.2"))
466 $ACL = ADMINS_CHECK_ACL("", $wht_sub);
470 // ACL is "allow"... hmmm
473 $readable = FILE_READABLE($INC);
476 // Insert compiled title and description
477 $menuTitle[$wht_sub] = $title_what;
478 $menuDesription[$wht_sub] = $desc_what;
480 <TD class=\"admin_menu\" colspan=\"2\">
481 <NOBR> <STRONG>--></STRONG> ";
484 if ($wht == $wht_sub)
490 $OUT .= "[<A href=\"".URL."/modules.php?module=admin&what=".$wht_sub."\">";
495 $OUT .= "<I class=\"admin_note\">";
500 if ($wht == $wht_sub)
513 $OUT .= "</NOBR></TD>
519 SQL_FREERESULT($result_what);
524 $OUT .= "<TR><TD height=\"7\" colspan=\"2\"></TD></TR>\n";
529 SQL_FREERESULT($result_main);
530 $OUT .= "</TABLE>\n";
533 // Compile and run the code here. This inserts all constants into the
534 // HTML output. Costs me some time to figure this out... *sigh* Quix0r
535 $eval = "\$OUT = \"".COMPILE_CODE(addslashes($OUT))."\";";
538 // Return or output content?
546 function ADD_MEMBER_SELECTION_BOX ($def="0", $add_all=false, $return=false, $none=false)
548 // Output selection form with all confirmed user accounts listed
549 $result = SQL_QUERY("SELECT userid, surname, family FROM "._MYSQL_PREFIX."_user_data ORDER BY userid", __FILE__, __LINE__);
552 // USe this only for adding points (e.g. adding refs really makes no sence ;-) )
553 if ($add_all) $OUT = " <OPTION value=\"all\">".ALL_MEMBERS."</OPTION>\n";
554 elseif ($none) $OUT = " <OPTION value=\"0\">".SELECT_NONE."</OPTION>\n";
555 while (list($id, $sname, $fname) = SQL_FETCHROW($result))
557 $OUT .= " <OPTION value=\"".bigintval($id)."\"";
558 if ($def == $id) $OUT .= " selected=\"selected\"";
559 $OUT .= ">".$sname." ".$fname." (".bigintval($id).")</OPTION>\n";
563 SQL_FREERESULT($result);
566 // Remeber options in constant
567 define('_MEMBER_SELECTION', $OUT);
569 // Display selection box
570 define('__LANG_VALUE', GET_LANGUAGE());
573 LOAD_TEMPLATE("admin_member_selection_box", false, $GLOBALS['what']);
576 return "<select name=\"userid\" size=\"1\">\n".$OUT."</select>\n";
580 function ADMIN_MENU_SELECTION($MODE, $default="", $defid="") {
582 if ($MODE == "action") $wht = "(what='' OR what IS NULL) AND action !='login'";
583 $result = SQL_QUERY_ESC("SELECT %s, title FROM "._MYSQL_PREFIX."_admin_menu WHERE ".$wht." ORDER BY sort",
584 array($MODE), __FILE__, __LINE__);
585 if (SQL_NUMROWS($result) > 0) {
586 // Load menu as selection
587 $OUT = "<SELECT name=\"".$MODE."_menu";
588 if ((!empty($defid)) || ($defid == "0")) $OUT .= "[".$defid."]";
589 $OUT .= "\" size=\"1\" class=\"admin_select\">
590 <OPTION value=\"\">".SELECT_NONE."</OPTION>\n";
591 while (list($menu, $title) = SQL_FETCHROW($result)) {
592 $OUT .= " <OPTION value=\"".$menu."\"";
593 if ((!empty($default)) && ($default == $menu)) $OUT .= " selected=\"selected\"";
594 $OUT .= ">".$title."</OPTION>\n";
598 SQL_FREERESULT($result);
599 $OUT .= "</SELECT>\n";
602 $OUT = ADMIN_PROBLEM_NO_MENU;
608 // Save settings to the database
609 function ADMIN_SAVE_SETTINGS (&$POST, $tableName="_config", $whereStatement="config=0", $translateComma=array(), $alwaysAdd=false) {
610 global $_CONFIG, $cacheArray, $cacheInstance;
612 // Prepare all arrays, variables
616 // Now, walk through all entries and prepare them for saving
617 foreach ($POST as $id => $val) {
618 // Process only formular field but not submit buttons ;)
620 // Do not save the ok value
621 CONVERT_SELECTIONS_TO_TIMESTAMP($POST, $DATA, $id, $skip);
623 // Shall we process this ID? It muss not be empty, of course
624 if ((!$skip) && (!empty($id))) {
626 $val = COMPILE_CODE($val);
628 // Translate the value? (comma to dot!)
629 if ((is_array($translateComma)) && (in_array($id, $translateComma))) {
630 // Then do it here... :)
631 $val = str_replace(",", ".", $val);
634 // Shall we add numbers or strings?
636 if ("".$val."" == "".$test."") {
638 $DATA[] = $id."=".$val."";
641 $DATA[] = $id."='".trim($val)."'";
644 // Update current configuration
645 $_CONFIG[$id] = $val;
650 // Check if entry does exist
653 if (!empty($whereStatement)) {
654 $result = SQL_QUERY("SELECT * FROM "._MYSQL_PREFIX.$tableName." WHERE ".$whereStatement." LIMIT 1", __FILE__, __LINE__);
656 $result = SQL_QUERY("SELECT * FROM "._MYSQL_PREFIX.$tableName." LIMIT 1", __FILE__, __LINE__);
660 if (SQL_NUMROWS($result) == 1) {
661 // "Implode" all data to single string
662 $DATA_UPDATE = implode(", ", $DATA);
664 // Generate SQL string
665 $SQL = "UPDATE "._MYSQL_PREFIX.$tableName." SET ".$DATA_UPDATE." WHERE ".$whereStatement." LIMIT 1";
667 // Add Line (does only work with auto_increment!
668 $KEYs = array(); $VALUEs = array();
669 foreach ($DATA as $entry) {
671 $line = explode("=", $entry);
672 $KEYs[] = $line[0]; $VALUEs[] = $line[1];
675 // Add both in one line
676 $KEYs = implode(", ", $KEYs);
677 $VALUEs = implode(", ", $VALUEs);
679 // Generate SQL string
680 $SQL = "INSERT INTO "._MYSQL_PREFIX.$tableName." (".$KEYs.") VALUES(".$VALUEs.")";
684 SQL_FREERESULT($result);
686 // Simply run generated SQL string
687 $result = SQL_QUERY($SQL, __FILE__, __LINE__);
690 REBUILD_CACHE("config", "config");
693 LOAD_TEMPLATE("admin_settings_saved", false, "<STRONG class=\"admin_done\">".SETTINGS_SAVED."</STRONG>");
696 function ADMIN_MAKE_MENU_SELECTION($menu, $type, $name, $default="") {
697 // Open the requested menu directory
698 $handle = opendir(sprintf("%sinc/modules/%s/", PATH, $menu)) or mxchange_die("Cannot load menu ".$menu."!");
700 // Init the selection box
701 $OUT = "<SELECT name=\"".$name."\" class=\"admin_select\" size=\"1\">\n <OPTION value=\"\">".IS_TOP_MENU."</OPTION>\n";
703 // Walk through all files
704 while ($file = readdir($handle)) {
705 // Is this a PHP script?
706 if (($file != ".") && ($file != "..") && ($file != "lost+found") && (strpos($file, "".$type."-") > -1) && (strpos($file, ".php") > 0)) {
707 // Then test if the file is readable
708 $test = sprintf("%sinc/modules/%s/%s", PATH, $menu, $file);
709 if ((is_file($test)) && (is_readable($test))) {
710 // Extract the value for what=xxx
711 $part = substr($file, (strlen($type) + 1));
712 $part = substr($part, 0, -4);
714 // Is that part different from the overview?
715 if ($part != "overview") {
716 $OUT .= " <OPTION value=\"".$part."\"";
717 if ($part == $default) $OUT .= "selected";
718 $OUT .= ">".$part."</OPTION>\n";
724 // Close dir and selection box
726 $OUT .= "</SELECT>\n";
730 function ADMIN_USER_PROFILE_LINK($uid, $title="", $wht="list_user") {
731 if (($title == "") && ($title != "0")) {
732 // Set userid as title
736 if (($title == "0") && ($wht == "list_refs")) {
737 // Return title again
741 //* DEBUG: */ echo "A:".$title."<br />";
743 return "<A href=\"".URL."/modules.php?module=admin&what=".$wht."&u_id=".$uid."\" title=\"".ADMIN_USER_PROFILE_TITLE."\">".$title."</A>";
746 function ADMIN_CHECK_MENU_MODE() {
747 global $_CONFIG, $cacheArray;
749 // Set the global mode as the mode for all admins
750 $MODE = $_CONFIG['admin_menu']; $ADMIN = $MODE;
752 // Check individual settings of current admin
753 if (isset($cacheArray['admins']['la_mode'][get_session('admin_login')])) {
755 $ADMIN = $cacheArray['admins']['la_mode'][get_session('admin_login')];
756 $_CONFIG['cache_hits']++;
757 } elseif (GET_EXT_VERSION("admins") >= "0.6.7") {
758 // Load from database when version of "admins" is enough
759 $result = SQL_QUERY_ESC("SELECT la_mode FROM "._MYSQL_PREFIX."_admins WHERE login='%s' LIMIT 1",
760 array(get_session('admin_login')), __FILE__, __LINE__);
761 if (SQL_NUMROWS($result) == 1) {
763 list($ADMIN) = SQL_FETCHROW($result);
767 SQL_FREERESULT($result);
770 // Check what the admin wants and set it when it's not the global mode
771 if ($ADMIN != "global") $MODE = $ADMIN;
773 // Return admin-menu's mode
776 // Change activation status
777 function ADMIN_CHANGE_ACTIVATION_STATUS ($IDs, $table, $row, $idRow = "id") {
779 $cnt = 0; $newStatus = "Y";
780 if ((is_array($IDs)) && (count($IDs) > 0)) {
781 // "Walk" all through and count them
782 foreach ($IDs as $id => $selected) {
783 // Secure the ID number
784 $id = bigintval($id);
786 // Should always be 1 ;-)
787 if ($selected == 1) {
788 // Determine new status
789 $result = SQL_QUERY_ESC("SELECT %s FROM "._MYSQL_PREFIX."_%s WHERE %s=%s LIMIT 1",
790 array($row, $table, $idRow, $id), __FILE__, __LINE__);
793 if (SQL_NUMROWS($result) == 1) {
795 list($currStatus) = SQL_FETCHROW($result);
796 if ($currStatus == "Y") $newStatus='N'; else $newStatus = "Y";
798 // Change this status
799 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_%s SET %s='%s' WHERE %s=%s LIMIT 1",
800 array($table, $row, $newStatus, $idRow, $id), __FILE__, __LINE__);
802 // Count up affected rows
803 $cnt += SQL_AFFECTEDROWS();
807 SQL_FREERESULT($result);
812 LOAD_TEMPLATE("admin_settings_saved", false, ADMIN_STATUS_CHANGED_1.$cnt.ADMIN_STATUS_CHANGED_2.count($IDs).ADMIN_STATUS_CHANGED_3);
815 LOAD_TEMPLATE("admin_settings_saved", false, ADMIN_NOTHING_SELECTED_CHANGE);
818 // Send mails for del/edit/lock build modes
819 function ADMIN_SEND_BUILD_MAILS ($mode, $table, $content, $id, $subjectPart="") {
820 // Default subject is the subject part
821 $subject = $subjectPart;
823 // Is the subject part not set?
824 if (empty($subjectPart)) {
825 // Then use it from the mode
826 $subject = strtoupper($mode);
829 // Is the raw userid set?
830 if ($_POST['uid_raw'][$id] > 0) {
832 $eval = "\$subjectLine = MEMBER_".$subject."_".strtoupper($table)."_SUBJECT;";
835 // Load email template
836 if (!empty($subjectPart)) {
837 $mail = LOAD_EMAIL_TEMPLATE("member_".$mode."_".strtolower($subjectPart)."_".$table, $content);
839 $mail = LOAD_EMAIL_TEMPLATE("member_".$mode."_".$table, $content);
843 SEND_EMAIL($_POST['uid_raw'][$id], $subjectLine, $mail);
847 $eval = "\$subjectLine = ADMIN_".$subject."_".strtoupper($table)."_SUBJECT;";
850 // Send admin notification out
851 if (!empty($subjectPart)) {
852 SEND_ADMIN_NOTIFICATION($subjectLine, "admin_".$mode."_".strtolower($subjectPart)."_".$table, $content, $_POST['uid_raw'][$id]);
854 SEND_ADMIN_NOTIFICATION($subjectLine, "admin_".$mode."_".$table, $content, $_POST['uid_raw'][$id]);
857 // Build a special template list
858 function ADMIN_BUILD_LIST ($listType, $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn) {
862 // "Walk" through all entries
863 foreach ($IDs as $id => $selected) {
865 $id = bigintval($id);
867 // Get result from a given column array and table name
868 $result = SQL_RESULT_FROM_ARRAY($table, $columns, $idColumn, $id);
870 // Is there one entry?
871 if (SQL_NUMROWS($result) == 1) {
873 $content = SQL_FETCHARRAY($result);
876 foreach ($content as $key => $value) {
878 $idx = array_search($key, $columns, true);
880 // Do we have a userid?
881 if ($key == "userid") {
882 // Add it again as raw id
883 $content['uid'] = bigintval($value);
886 // Handle the call in external function
887 $content[$key] = HANDLE_EXTRA_VALUES($filterFunctions[$idx], $value, $extraValues[$idx]);
890 // Add color switching
891 $content['sw'] = $SW;
894 $OUT .= LOAD_TEMPLATE("admin_".$listType."_".$table."_row", true, $content);
901 SQL_FREERESULT($result);
904 // Load master template
905 LOAD_TEMPLATE("admin_".$listType."_".$table."", false, $OUT);
907 // Delete rows by given ID numbers
908 function ADMIN_DELETE_ENTRIES_CONFIRM ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $deleteNow=false, $idColumn="id", $userIdColumn="userid") {
909 // All valid entries? (We hope so here!)
910 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues))) {
911 // Shall we delete here or list for deletion?
914 $SQL = "DELETE LOW_PRIORITY FROM "._MYSQL_PREFIX."_%s WHERE %s IN (%s)";
916 foreach ($IDs as $id => $sel) {
917 // Is there a userid?
918 if (isset($_POST['uid_raw'][$id])) {
919 // Load all data from that id
920 $result = SQL_QUERY_ESC("SELECT * FROM "._MYSQL_PREFIX."_%s WHERE %s=%s LIMIT 1",
921 array($table, $idColumn, $id), __FILE__, __LINE__);
924 $content = SQL_FETCHARRAY($result);
927 SQL_FREERESULT($result);
929 // Send "build mails" out
930 ADMIN_SEND_BUILD_MAILS("del", $table, $content, $id);
938 SQL_QUERY($SQL, array($table, $idColumn, substr($idList, 0, -1)), __FILE__, __LINE__);
941 if (SQL_AFFECTEDROWS() == count($IDs)) {
943 LOAD_TEMPLATE("admin_settings_saved", false, ADMIN_ALL_ENTRIES_REMOVED);
945 // Some are still there :(
946 LOAD_TEMPLATE("admin_settings_saved", false, sprintf(ADMIN_SOME_ENTRIES_NOT_DELETED, SQL_AFFECTEDROWS(), count($IDs)));
949 // List for deletion confirmation
950 ADMIN_BUILD_LIST("del", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
954 // Edit rows by given ID numbers
955 function ADMIN_EDIT_ENTRIES_CONFIRM ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $editNow=false, $idColumn="id", $userIdColumn="userid") {
956 // All valid entries? (We hope so here!)
957 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues))) {
958 // Shall we change here or list for editing?
962 foreach ($IDs as $id => $sel) {
963 // Prepare content array (new values)
966 // Prepare SQL for this row
967 $SQL = "UPDATE "._MYSQL_PREFIX."_".$table." SET";
968 foreach ($_POST as $key => $entries) {
969 // Skip raw userid which is always invalid
970 if ($key == "uid_raw") {
971 // Continue with next field
975 // Is entries an array?
976 if (($key != $idColumn) && (is_array($entries)) && (isset($entries[$id]))) {
977 // Add this entry to content
978 $content[$key] = $entries[$id];
980 // Send data through the filter function if found
981 if ((isset($filterFunctions[$key])) && (isset($extraValues[$key]))) {
982 // Filter function set!
983 $entries[$id] = HANDLE_EXTRA_VALUES($filterFunctions[$key], $entries[$id], $extraValues[$key]);
986 // Then add this value
987 $SQL .= sprintf(" %s='%s',",
989 SQL_ESCAPE($entries[$id])
991 } elseif (($key != $idColumn) && (!is_array($entries))) {
992 // Add normal entries as well!
993 $content[$key] = $entries;
996 // Do we have an URL?
998 // Then add a framekiller test as well
999 $content['frametester'] = FRAMETESTER($content[$key]);
1002 $SQL = substr($SQL, 0, -1) . " WHERE ".$idColumn."=".bigintval($id)." LIMIT 1";
1005 SQL_QUERY($SQL, __FILE__, __LINE__);
1007 // Add affected rows
1008 $affected += SQL_AFFECTEDROWS();
1010 // Load all data from that id
1011 $result = SQL_QUERY_ESC("SELECT * FROM "._MYSQL_PREFIX."_%s WHERE %s=%s LIMIT 1",
1012 array($table, $idColumn, $id), __FILE__, __LINE__);
1016 $DATA = SQL_FETCHARRAY($result);
1019 SQL_FREERESULT($result);
1021 // Send "build mails" out
1022 ADMIN_SEND_BUILD_MAILS("edit", $table, $content, $id);
1026 if ($affected == count($IDs)) {
1028 LOAD_TEMPLATE("admin_settings_saved", false, ADMIN_ALL_ENTRIES_EDITED);
1030 // Some are still there :(
1031 LOAD_TEMPLATE("admin_settings_saved", false, sprintf(ADMIN_SOME_ENTRIES_NOT_EDITED, $affected, count($IDs)));
1035 ADMIN_BUILD_LIST("edit", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1039 // Un-/lock rows by given ID numbers
1040 function ADMIN_LOCK_ENTRIES_CONFIRM ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $statusArray=array(), $lockNow=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)) && ((!$lockNow) || (count($statusArray) == 1))) {
1043 // Shall we un-/lock here or list for locking?
1046 foreach ($IDs as $id => $sel) {
1047 // Construct SQL query
1048 $SQL = "UPDATE "._MYSQL_PREFIX."_".$table." SET";
1050 // Load data of entry
1051 $result = SQL_QUERY_ESC("SELECT * FROM "._MYSQL_PREFIX."_%s WHERE %s=%s LIMIT 1",
1052 array($table, $idColumn, $id), __FILE__, __LINE__);
1055 $content = SQL_FETCHARRAY($result);
1058 SQL_FREERESULT($result);
1060 // Add all status entries (e.g. status column last_updated or so)
1061 $newStatus = "UNKNOWN";
1062 $oldStatus = "UNKNOWN";
1063 $statusColumn = "unknown";
1064 foreach ($statusArray as $column => $statusInfo) {
1065 // Does the entry exist?
1066 if ((isset($content[$column])) && (isset($statusInfo[$content[$column]]))) {
1067 // Add these entries for update
1068 $SQL .= sprintf(" %s='%s',", SQL_ESCAPE($column), SQL_ESCAPE($statusInfo[$content[$column]]));
1071 if ($statusColumn == "unknown") {
1072 // Always (!!!) change status column first!
1073 $oldStatus = $content[$column];
1074 $newStatus = $statusInfo[$oldStatus];
1075 $statusColumn = $column;
1077 } elseif (isset($content[$column])) {
1079 die("UNFINISHED: {$column}[".gettype($statusInfo)."] = {$content[$column]}");
1083 // Add other columns as well
1084 foreach ($_POST as $key => $entries) {
1085 // Skip id, raw userid and 'do_lock'
1086 if (!in_array($key, array($idColumn, 'uid_raw', 'do_lock'))) {
1087 // Are there brackets () at the end?
1088 if (substr($entries[$id], -2, 2) == "()") {
1089 // Direct SQL command found
1090 $SQL .= sprintf(" %s=%s,", SQL_ESCAPE($key), SQL_ESCAPE($entries[$id]));
1092 // Add regular entry
1093 $SQL .= sprintf(" %s='%s',", SQL_ESCAPE($key), SQL_ESCAPE($entries[$id]));
1098 // Finish SQL statement
1099 $SQL = substr($SQL, 0, -1) . " WHERE ".$idColumn."=".bigintval($id)." AND ".$statusColumn."='".$oldStatus."' LIMIT 1";
1102 SQL_QUERY($SQL, __FILE__, __LINE__);
1104 // Do we have an URL?
1105 if (isset($content['url'])) {
1106 // Then add a framekiller test as well
1107 $content['frametester'] = FRAMETESTER($content['url']);
1110 // Send "build mails" out
1111 ADMIN_SEND_BUILD_MAILS("lock", $table, $content, $id, $statusInfo[$content[$column]]);
1115 ADMIN_BUILD_LIST("lock", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1119 // Checks proxy settins by fetching check-updates3.php from www.mxchange.org
1120 function ADMIN_TEST_PROXY_SETTINGS ($settingsArray) {
1123 // Set temporary the new settings
1124 $_CONFIG = array_merge($_CONFIG, $settingsArray);
1126 // Now get the test URL
1127 $content = GET_URL("check-updates3.php");
1129 // Is the first line with "200 OK"?
1130 $valid = eregi("200 OK", $content[0]);
1135 // Sends out a link to the given email adress so the admin can reset his/her password
1136 function ADMIN_SEND_PASSWORD_RESET_LINK ($email) {
1141 // Compile out security characters (must be for looking up!)
1142 $email = COMPILE_CODE($email);
1144 // Look up administator login
1145 $result = SQL_QUERY_ESC("SELECT id, login, password FROM "._MYSQL_PREFIX."_admins WHERE email='%s' LIMIT 1",
1146 array($email), __FILE__, __LINE__);
1148 // Is there an account?
1149 if (SQL_NUMROWS($result) == 0) {
1150 // No account found!
1151 return ADMIN_NO_LOGIN_WITH_EMAIL;
1155 $content = SQL_FETCHARRAY($result);
1158 SQL_FREERESULT($result);
1160 // Generate hash for reset link
1161 $content['hash'] = generateHash(URL.":".$content['id'].":".$content['login'].":".$content['password'], substr($content['password'], 10));
1164 unset($content['id']);
1165 unset($content['password']);
1168 $mailText = LOAD_EMAIL_TEMPLATE("admin_reset_password", $content);
1171 SEND_EMAIL($email, ADMIN_RESET_PASS_LINK_SUBJ, $mailText);
1174 return ADMIN_RESET_LINK_SENT;
1176 // Validate hash and login for password reset
1177 function ADMIN_VALIDATE_RESET_LINK_HASH_LOGIN ($hash, $login) {
1178 // By default nothing validates... ;)
1181 // Compile the login for lookup
1182 $login = COMPILE_CODE($login);
1184 // Then try to find that user
1185 $result = SQL_QUERY_ESC("SELECT id, password, email FROM "._MYSQL_PREFIX."_admins WHERE login='%s' LIMIT 1",
1186 array($login), __FILE__, __LINE__);
1188 // Is an account here?
1189 if (SQL_NUMROWS($result) == 1) {
1191 $content = SQL_FETCHARRAY($result);
1193 // Generate hash again
1194 $hashFromData = generateHash(URL.":".$content['id'].":".$login.":".$content['password'], substr($content['password'], 10));
1197 $valid = ($hash == $hashFromData);
1201 SQL_FREERESULT($result);
1206 // Reset the password for the login. Do NOT call this function without calling above function first!
1207 function ADMIN_RESET_PASSWORD ($login, $password) {
1211 // Now check if we have sql_patches installed
1212 if (GET_EXT_VERSION("sql_patches") >= "0.3.6") {
1213 // Use new way of hashing
1214 $passHash = generateHash($password);
1217 $passHash = md5($password);
1221 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_admins SET password='%s' WHERE login='%s' LIMIT 1",
1222 array($passHash, $login), __FILE__, __LINE__);
1225 return ADMIN_PASSWORD_RESET_DONE;
1227 // Solves a task by given id number
1228 function ADMIN_SOLVE_TASK ($id) {
1229 // Update the task data
1230 ADMIN_UPDATE_TASK_DATA($id, "status", "SOLVED");
1232 // Marks a given task as deleted
1233 function ADMIN_DELETE_TASK ($id) {
1234 // Update the task data
1235 ADMIN_UPDATE_TASK_DATA($id, "status", "DELETED");
1237 // Function to update task data
1238 function ADMIN_UPDATE_TASK_DATA ($id, $row, $data) {
1240 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_task_system SET %s='%s' WHERE id=%s LIMIT 1",
1241 array($row, $data, bigintval($id)), __FILE__, __LINE__);