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;
65 $ret = "404"; $pass = "";
66 if (!empty($cacheArray['admins']['aid'][$admin_login])) {
67 // Get password from cache
68 $pass = $cacheArray['admins']['password'][$admin_login];
70 $_CONFIG['cache_hits']++;
73 if (GET_EXT_VERSION("admins") >= "0.7.0") {
75 $ADD = ", login_failtures, UNIX_TIMESTAMP(last_failture) AS last_failture";
78 // Get password from DB
79 $result = SQL_QUERY_ESC("SELECT password".$ADD." FROM "._MYSQL_PREFIX."_admins WHERE login='%s' LIMIT 1",
80 array($admin_login), __FILE__, __LINE__);
81 if (SQL_NUMROWS($result) == 1) {
82 // Login password found
86 $data = SQL_FETCHARRAY($result);
90 SQL_FREERESULT($result);
93 //* DEBUG: */ echo "*".$data['password']."/".md5($password)."/".$ret."<br />";
94 if ((strlen($data['password']) == 32) && ($data['password'] == md5($password))) {
96 $data['password'] = generateHash($password);
98 // Is the sql_patches not installed, than we cannot have a valid hashed password here!
99 if (($ret == "pass") && ((GET_EXT_VERSION("sql_patches") < "0.3.6") || (GET_EXT_VERSION("sql_patches") == ""))) $ret = "done";
100 } elseif ((GET_EXT_VERSION("sql_patches") < "0.3.6") || (GET_EXT_VERSION("sql_patches") == "")) {
105 // Generate salt of password
106 define('__SALT', substr($data['password'], 0, -40));
109 // Check if password is same
110 //* DEBUG: */ echo "*".$ret.",".$data['password'].",".$password.",".$salt."*<br >\n";
111 if (($ret == "pass") && ($data['password'] == generateHash($password, $salt)) && (!empty($salt))) {
112 // Change the passord hash here
113 $data['password'] = generateHash($password);
115 // Do we have 0.7.0 of admins or later?
116 // Remmeber login failtures if available
117 if (GET_EXT_VERSION("admins") >= "0.7.0") {
118 // Store it in session
119 set_session("mxchange_admin_failtures", $data['login_failtures']);
120 ses_session("mxchange_admin_last_fail", $data['last_failture']);
124 $result = SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_admins SET password='%s' WHERE login='%s' LIMIT 1",
125 array($data['password'], $admin_login), __FILE__, __LINE__);
127 // Shall I remove the cache file?
128 if ((EXT_IS_ACTIVE("cache")) && ($cacheInstance != false)) {
129 if ($cacheInstance->cache_file("admins", true)) $cacheInstance->cache_destroy();
132 // Login has failed by default... ;-)
135 // Password matches so login here
136 if (LOGIN_ADMIN($admin_login, $data['password'])) {
140 } elseif ((empty($salt)) && ($ret == "pass")) {
141 // Something bad went wrong
143 } elseif ($ret == "done") {
144 // Try to login here if we have the old hashing way (sql_patches not installed?)
145 if (!LOGIN_ADMIN($admin_login, $data['password'])) {
146 // Something went wrong
152 //* DEBUG: */ die("RETURN=".$ret);
156 // Try to login the admin by setting some session/cookie variables
157 function LOGIN_ADMIN ($adminLogin, $passHash) {
158 // Now set all session variables and return the result
161 set_session("admin_md5", generatePassString($passHash))
163 set_session("admin_login", $adminLogin)
165 set_session("admin_last", time())
167 set_session("admin_to", $_POST['timeout'])
172 // Only be executed on cookie checking
173 function CHECK_ADMIN_COOKIES ($admin_login, $password) {
174 global $cacheArray, $_CONFIG;
175 $ret = "404"; $pass = "";
176 if (!empty($cacheArray['admins']['aid'][$admin_login])) {
177 // Get password from cache
178 $pass = $cacheArray['admins']['password'][$admin_login];
180 $_CONFIG['cache_hits']++;
182 // Get password from DB
183 $result = SQL_QUERY_ESC("SELECT password FROM "._MYSQL_PREFIX."_admins WHERE login='%s' LIMIT 1",
184 array($admin_login), __FILE__, __LINE__);
185 if (SQL_NUMROWS($result) == 1) {
190 list($pass) = SQL_FETCHROW($result);
194 SQL_FREERESULT($result);
197 //* DEBUG: */ echo __FUNCTION__.":".$pass."(".strlen($pass).")/".$password."(".strlen($password).")<br />\n";
199 // Check if password matches
200 if (($ret == "pass") && ((generatePassString($pass) == $password) || ($pass == $password) || ((strlen($pass) == 32) && (md5($password) == $pass)))) {
201 // Passwords matches!
209 function admin_WriteData ($file, $comment, $prefix, $suffix, $DATA, $seek=0) {
210 // Initialize some variables
215 // Is the file there and read-/write-able?
216 if ((FILE_READABLE($file)) && (is_writeable($file))) {
217 $search = "CFG: ".$comment;
220 // Open the source file
221 $fp = @fopen($file, 'r') or OUTPUT_HTML("<STRONG>READ:</STRONG> ".$file."<br />");
223 // Is the resource valid?
224 if (is_resource($fp)) {
225 // Open temporary file
226 $fp_tmp = @fopen($tmp, 'w') or OUTPUT_HTML("<STRONG>WRITE:</STRONG> ".$tmp."<br />");
228 // Is the resource again valid?
229 if (is_resource($fp_tmp)) {
231 // Read from source file
232 $line = fgets ($fp, 1024);
234 if (strpos($line, $search) > -1) { $next = 0; $found = true; }
237 if ($next == $seek) {
239 $line = $prefix . $DATA . $suffix."\n";
245 // Write to temp file
246 fputs($fp_tmp, $line);
252 // Finished writing tmp file
259 if (($done) && ($found)) {
260 // Copy back tmp file and delete tmp :-)
263 define('_FATAL', false);
265 OUTPUT_HTML("<STRONG>CHANGE:</STRONG> 404!");
266 define('_FATAL', true);
268 OUTPUT_HTML("<STRONG>TMP:</STRONG> UNDONE!");
269 define('_FATAL', true);
273 // File not found, not readable or writeable
274 OUTPUT_HTML("<STRONG>404:</STRONG> ".$file."<br />");
279 function ADMIN_DO_ACTION($wht)
281 global $menuDesription, $menuTitle, $_CONFIG, $cacheArray, $DATA, $DEPTH;
282 //* DEBUG: */ echo __LINE__."*".$wht."/".$GLOBALS['module']."/".$GLOBALS['action']."/".$GLOBALS['what']."*<br />\n";
283 if (EXT_IS_ACTIVE("cache"))
285 // Include cache instance
286 global $cacheInstance;
289 // Remove any spaces from variable
292 // Default admin action is the overview page
297 // Compile out some chars
298 $wht = COMPILE_CODE($wht, false, false, false);
302 $act = GET_ACTION($GLOBALS['module'], $wht);
304 // Define admin login name and ID number
305 define('__ADMIN_LOGIN', get_session('admin_login'));
306 define('__ADMIN_ID' , GET_ADMIN_ID(get_session('admin_login')));
309 if (EXT_IS_ACTIVE("admins")) {
310 define('__ADMIN_WELCOME', LOAD_TEMPLATE("admin_welcome_admins", true));
312 define('__ADMIN_WELCOME', LOAD_TEMPLATE("admin_welcome", true));
314 define('__ADMIN_FOOTER' , LOAD_TEMPLATE("admin_footer" , true));
315 define('__ADMIN_MENU' , ADD_ADMIN_MENU($act, $wht, true));
318 LOAD_TEMPLATE("admin_main_header");
320 // Check if action/what pair is valid
321 $result = SQL_QUERY_ESC("SELECT id FROM "._MYSQL_PREFIX."_admin_menu
322 WHERE action='%s' AND ((what='%s' AND what != 'overview') OR ((what='' OR what IS NULL) AND '%s'='overview'))
323 LIMIT 1", array($act, $wht, $wht), __FILE__, __LINE__);
324 if (SQL_NUMROWS($result) == 1)
327 SQL_FREERESULT($result);
329 // Is valid but does the inlcude file exists?
330 $INC = sprintf("%sinc/modules/admin/action-%s.php", PATH, $act);
331 if ((FILE_READABLE($INC)) && (VALIDATE_MENU_ACTION("admin", $act, $wht)) && (__ACL_ALLOW == true))
333 // Ok, we finally load the admin action module
336 elseif (__ACL_ALLOW == false)
339 LOAD_TEMPLATE("admin_menu_failed", false, ADMINS_ACCESS_DENIED);
340 ADD_FATAL(ADMINS_ACCESS_DENIED);
344 // Include file not found! :-(
345 LOAD_TEMPLATE("admin_menu_failed", false, ADMIN_404_ACTION);
346 ADD_FATAL(ADMIN_404_ACTION_1.$act.ADMIN_404_ACTION_2);
349 // Invalid action/what pair found!
350 LOAD_TEMPLATE("admin_menu_failed", false, ADMIN_INVALID_ACTION);
351 ADD_FATAL(ADMIN_INVALID_ACTION_1.$act."/".$wht.ADMIN_INVALID_ACTION_2);
355 LOAD_TEMPLATE("admin_main_footer");
358 function ADD_ADMIN_MENU($act, $wht,$return=false)
360 global $menuDesription, $menuTitle;
364 $menuDesription = array();
365 $menuTitle = array();
368 $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__);
370 if (SQL_NUMROWS($result_main) > 0)
372 $OUT = "<TABLE border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_menu_main\">
373 <TR><TD colspan=\"2\" height=\"7\" class=\"seperator\"> </TD></TR>\n";
374 while (list($menu, $title, $descr) = SQL_FETCHROW($result_main))
376 if ((EXT_IS_ACTIVE("admins")) && (GET_EXT_VERSION("admins") > "0.2"))
378 $ACL = ADMINS_CHECK_ACL($menu, "");
382 // ACL is "allow"... hmmm
389 // Insert compiled menu title and description
390 $menuTitle[$menu] = $title;
391 $menuDesription[$menu] = $descr;
394 <TD class=\"admin_menu\" colspan=\"2\">
395 <NOBR> <STRONG>·</STRONG> ";
396 if (($menu == $act) && (empty($wht)))
402 $OUT .= "[<A href=\"".URL."/modules.php?module=admin&action=".$menu."\">";
405 if (($menu == $act) && (empty($wht)))
413 $OUT .= "</NOBR></TD>
415 $result_what = SQL_QUERY_ESC("SELECT what, title, descr FROM "._MYSQL_PREFIX."_admin_menu WHERE action='%s' AND what != '' ORDER BY sort, id DESC",
416 array($menu), __FILE__, __LINE__);
417 if ((SQL_NUMROWS($result_what) > 0) && ($act == $menu))
419 $menuDesription = array();
420 $menuTitle = array(); $SUB = true;
422 <TD width=\"10\" class=\"seperator\"> </TD>
423 <TD class=\"admin_menu\">
424 <TABLE border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_menu_sub\">\n";
425 while (list($wht_sub, $title_what, $desc_what) = SQL_FETCHROW($result_what))
428 $INC = sprintf("%sinc/modules/admin/what-%s.php", PATH, $wht_sub);
429 if ((EXT_IS_ACTIVE("admins")) && (GET_EXT_VERSION("admins") > "0.2"))
431 $ACL = ADMINS_CHECK_ACL("", $wht_sub);
435 // ACL is "allow"... hmmm
438 $readable = FILE_READABLE($INC);
441 // Insert compiled title and description
442 $menuTitle[$wht_sub] = $title_what;
443 $menuDesription[$wht_sub] = $desc_what;
445 <TD class=\"admin_menu\" colspan=\"2\">
446 <NOBR> <STRONG>--></STRONG> ";
449 if ($wht == $wht_sub)
455 $OUT .= "[<A href=\"".URL."/modules.php?module=admin&what=".$wht_sub."\">";
460 $OUT .= "<I class=\"admin_note\">";
465 if ($wht == $wht_sub)
478 $OUT .= "</NOBR></TD>
484 SQL_FREERESULT($result_what);
489 $OUT .= "<TR><TD height=\"7\" colspan=\"2\"></TD></TR>\n";
494 SQL_FREERESULT($result_main);
495 $OUT .= "</TABLE>\n";
498 // Compile and run the code here. This inserts all constants into the
499 // HTML output. Costs me some time to figure this out... *sigh* Quix0r
500 $eval = "\$OUT = \"".COMPILE_CODE(addslashes($OUT))."\";";
503 // Return or output content?
511 function ADD_MEMBER_SELECTION_BOX ($def="0", $add_all=false, $return=false, $none=false)
513 // Output selection form with all confirmed user accounts listed
514 $result = SQL_QUERY("SELECT userid, surname, family FROM "._MYSQL_PREFIX."_user_data ORDER BY userid", __FILE__, __LINE__);
517 // USe this only for adding points (e.g. adding refs really makes no sence ;-) )
518 if ($add_all) $OUT = " <OPTION value=\"all\">".ALL_MEMBERS."</OPTION>\n";
519 elseif ($none) $OUT = " <OPTION value=\"0\">".SELECT_NONE."</OPTION>\n";
520 while (list($id, $sname, $fname) = SQL_FETCHROW($result))
522 $OUT .= " <OPTION value=\"".bigintval($id)."\"";
523 if ($def == $id) $OUT .= " selected=\"selected\"";
524 $OUT .= ">".$sname." ".$fname." (".bigintval($id).")</OPTION>\n";
528 SQL_FREERESULT($result);
531 // Remeber options in constant
532 define('_MEMBER_SELECTION', $OUT);
534 // Display selection box
535 define('__LANG_VALUE', GET_LANGUAGE());
538 LOAD_TEMPLATE("admin_member_selection_box", false, $GLOBALS['what']);
541 return "<select name=\"userid\" size=\"1\">\n".$OUT."</select>\n";
545 function ADMIN_MENU_SELECTION($MODE, $default="", $defid="") {
547 if ($MODE == "action") $wht = "(what='' OR what IS NULL) AND action !='login'";
548 $result = SQL_QUERY_ESC("SELECT %s, title FROM "._MYSQL_PREFIX."_admin_menu WHERE ".$wht." ORDER BY sort",
549 array($MODE), __FILE__, __LINE__);
550 if (SQL_NUMROWS($result) > 0) {
551 // Load menu as selection
552 $OUT = "<SELECT name=\"".$MODE."_menu";
553 if ((!empty($defid)) || ($defid == "0")) $OUT .= "[".$defid."]";
554 $OUT .= "\" size=\"1\" class=\"admin_select\">
555 <OPTION value=\"\">".SELECT_NONE."</OPTION>\n";
556 while (list($menu, $title) = SQL_FETCHROW($result)) {
557 $OUT .= " <OPTION value=\"".$menu."\"";
558 if ((!empty($default)) && ($default == $menu)) $OUT .= " selected=\"selected\"";
559 $OUT .= ">".$title."</OPTION>\n";
563 SQL_FREERESULT($result);
564 $OUT .= "</SELECT>\n";
567 $OUT = ADMIN_PROBLEM_NO_MENU;
573 // Save settings to the database
574 function ADMIN_SAVE_SETTINGS (&$POST, $tableName="_config", $whereStatement="config=0", $translateComma=array(), $alwaysAdd=false) {
575 global $_CONFIG, $cacheArray, $cacheInstance;
577 // Prepare all arrays, variables
581 // Now, walk through all entries and prepare them for saving
582 foreach ($POST as $id => $val) {
583 // Process only formular field but not submit buttons ;)
585 // Do not save the ok value
586 CONVERT_SELECTIONS_TO_TIMESTAMP($POST, $DATA, $id, $skip);
588 // Shall we process this ID? It muss not be empty, of course
589 if ((!$skip) && (!empty($id))) {
591 $val = COMPILE_CODE($val);
593 // Translate the value? (comma to dot!)
594 if ((is_array($translateComma)) && (in_array($id, $translateComma))) {
595 // Then do it here... :)
596 $val = str_replace(",", ".", $val);
599 // Shall we add numbers or strings?
601 if ("".$val."" == "".$test."") {
603 $DATA[] = $id."=".$val."";
606 $DATA[] = $id."='".trim($val)."'";
609 // Update current configuration
610 $_CONFIG[$id] = $val;
615 // Check if entry does exist
618 if (!empty($whereStatement)) {
619 $result = SQL_QUERY("SELECT * FROM "._MYSQL_PREFIX.$tableName." WHERE ".$whereStatement." LIMIT 1", __FILE__, __LINE__);
621 $result = SQL_QUERY("SELECT * FROM "._MYSQL_PREFIX.$tableName." LIMIT 1", __FILE__, __LINE__);
625 if (SQL_NUMROWS($result) == 1) {
626 // "Implode" all data to single string
627 $DATA_UPDATE = implode(", ", $DATA);
629 // Generate SQL string
630 $SQL = "UPDATE "._MYSQL_PREFIX.$tableName." SET ".$DATA_UPDATE." WHERE ".$whereStatement." LIMIT 1";
632 // Add Line (does only work with auto_increment!
633 $KEYs = array(); $VALUEs = array();
634 foreach ($DATA as $entry) {
636 $line = explode("=", $entry);
637 $KEYs[] = $line[0]; $VALUEs[] = $line[1];
640 // Add both in one line
641 $KEYs = implode(", ", $KEYs);
642 $VALUEs = implode(", ", $VALUEs);
644 // Generate SQL string
645 $SQL = "INSERT INTO "._MYSQL_PREFIX.$tableName." (".$KEYs.") VALUES(".$VALUEs.")";
649 SQL_FREERESULT($result);
651 // Simply run generated SQL string
652 $result = SQL_QUERY($SQL, __FILE__, __LINE__);
654 // Is the config table updated and the cache extension installed?
655 if ((GET_EXT_VERSION("cache") >= "0.1.2") && ($tableName == "_config")) {
657 if ($cacheInstance->cache_file("config", true)) $cacheInstance->cache_destroy();
662 LOAD_TEMPLATE("admin_settings_saved", false, "<STRONG class=\"admin_done\">".SETTINGS_SAVED."</STRONG>");
665 function ADMIN_MAKE_MENU_SELECTION($menu, $type, $name, $default="") {
666 // Open the requested menu directory
667 $handle = opendir(sprintf("%sinc/modules/%s/", PATH, $menu)) or mxchange_die("Cannot load menu ".$menu."!");
669 // Init the selection box
670 $OUT = "<SELECT name=\"".$name."\" class=\"admin_select\" size=\"1\">\n <OPTION value=\"\">".IS_TOP_MENU."</OPTION>\n";
672 // Walk through all files
673 while ($file = readdir($handle)) {
674 // Is this a PHP script?
675 if (($file != ".") && ($file != "..") && ($file != "lost+found") && (strpos($file, "".$type."-") > -1) && (strpos($file, ".php") > 0)) {
676 // Then test if the file is readable
677 $test = sprintf("%sinc/modules/%s/%s", PATH, $menu, $file);
678 if ((is_file($test)) && (is_readable($test))) {
679 // Extract the value for what=xxx
680 $part = substr($file, (strlen($type) + 1));
681 $part = substr($part, 0, -4);
683 // Is that part different from the overview?
684 if ($part != "overview") {
685 $OUT .= " <OPTION value=\"".$part."\"";
686 if ($part == $default) $OUT .= "selected";
687 $OUT .= ">".$part."</OPTION>\n";
693 // Close dir and selection box
695 $OUT .= "</SELECT>\n";
699 function ADMIN_USER_PROFILE_LINK($uid, $title="", $wht="list_user") {
700 if (($title == "") && ($title != "0")) {
701 // Set userid as title
705 if (($title == "0") && ($wht == "list_refs")) {
706 // Return title again
710 //* DEBUG: */ echo "A:".$title."<br />";
712 return "<A href=\"".URL."/modules.php?module=admin&what=".$wht."&u_id=".$uid."\" title=\"".ADMIN_USER_PROFILE_TITLE."\">".$title."</A>";
715 function ADMIN_CHECK_MENU_MODE() {
716 global $_CONFIG, $cacheArray;
718 // Set the global mode as the mode for all admins
719 $MODE = $_CONFIG['admin_menu']; $ADMIN = $MODE;
721 // Check individual settings of current admin
722 if (isset($cacheArray['admins']['la_mode'][get_session('admin_login')])) {
724 $ADMIN = $cacheArray['admins']['la_mode'][get_session('admin_login')];
725 $_CONFIG['cache_hits']++;
726 } elseif (GET_EXT_VERSION("admins") >= "0.6.7") {
727 // Load from database when version of "admins" is enough
728 $result = SQL_QUERY_ESC("SELECT la_mode FROM "._MYSQL_PREFIX."_admins WHERE login='%s' LIMIT 1",
729 array(get_session('admin_login')), __FILE__, __LINE__);
730 if (SQL_NUMROWS($result) == 1) {
732 list($ADMIN) = SQL_FETCHROW($result);
736 SQL_FREERESULT($result);
739 // Check what the admin wants and set it when it's not the global mode
740 if ($ADMIN != "global") $MODE = $ADMIN;
742 // Return admin-menu's mode
745 // Change activation status
746 function ADMIN_CHANGE_ACTIVATION_STATUS ($IDs, $table, $row, $idRow = "id") {
748 $cnt = 0; $newStatus = "Y";
749 if ((is_array($IDs)) && (count($IDs) > 0)) {
750 // "Walk" all through and count them
751 foreach ($IDs as $id => $selected) {
752 // Secure the ID number
753 $id = bigintval($id);
755 // Should always be 1 ;-)
756 if ($selected == 1) {
757 // Determine new status
758 $result = SQL_QUERY_ESC("SELECT %s FROM "._MYSQL_PREFIX."_%s WHERE %s=%s LIMIT 1",
759 array($row, $table, $idRow, $id), __FILE__, __LINE__);
762 if (SQL_NUMROWS($result) == 1) {
764 list($currStatus) = SQL_FETCHROW($result);
765 if ($currStatus == "Y") $newStatus='N'; else $newStatus = "Y";
767 // Change this status
768 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_%s SET %s='%s' WHERE %s=%s LIMIT 1",
769 array($table, $row, $newStatus, $idRow, $id), __FILE__, __LINE__);
771 // Count up affected rows
772 $cnt += SQL_AFFECTEDROWS();
776 SQL_FREERESULT($result);
781 LOAD_TEMPLATE("admin_settings_saved", false, ADMIN_STATUS_CHANGED_1.$cnt.ADMIN_STATUS_CHANGED_2.count($IDs).ADMIN_STATUS_CHANGED_3);
784 LOAD_TEMPLATE("admin_settings_saved", false, ADMIN_NOTHING_SELECTED_CHANGE);
787 // Send mails for del/edit/lock build modes
788 function ADMIN_SEND_BUILD_MAILS ($mode, $table, $content, $id, $subjectPart="") {
789 // Default subject is the subject part
790 $subject = $subjectPart;
792 // Is the subject part not set?
793 if (empty($subjectPart)) {
794 // Then use it from the mode
795 $subject = strtoupper($mode);
798 // Is the raw userid set?
799 if ($_POST['uid_raw'][$id] > 0) {
801 $eval = "\$subjectLine = MEMBER_".$subject."_".strtoupper($table)."_SUBJECT;";
804 // Load email template
805 if (!empty($subjectPart)) {
806 $mail = LOAD_EMAIL_TEMPLATE("member_".$mode."_".strtolower($subjectPart)."_".$table, $content);
808 $mail = LOAD_EMAIL_TEMPLATE("member_".$mode."_".$table, $content);
812 SEND_EMAIL($_POST['uid_raw'][$id], $subjectLine, $mail);
816 $eval = "\$subjectLine = ADMIN_".$subject."_".strtoupper($table)."_SUBJECT;";
819 // Send admin notification out
820 if (!empty($subjectPart)) {
821 SEND_ADMIN_NOTIFICATION($subjectLine, "admin_".$mode."_".strtolower($subjectPart)."_".$table, $content, $_POST['uid_raw'][$id]);
823 SEND_ADMIN_NOTIFICATION($subjectLine, "admin_".$mode."_".$table, $content, $_POST['uid_raw'][$id]);
826 // Build a special template list
827 function ADMIN_BUILD_LIST ($listType, $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn) {
831 // "Walk" through all entries
832 foreach ($IDs as $id => $selected) {
834 $id = bigintval($id);
836 // Get result from a given column array and table name
837 $result = SQL_RESULT_FROM_ARRAY($table, $columns, $idColumn, $id);
839 // Is there one entry?
840 if (SQL_NUMROWS($result) == 1) {
842 $content = SQL_FETCHARRAY($result);
845 foreach ($content as $key => $value) {
847 $idx = array_search($key, $columns, true);
849 // Do we have a userid?
850 if ($key == "userid") {
851 // Add it again as raw id
852 $content['uid'] = bigintval($value);
855 // Handle the call in external function
856 $content[$key] = HANDLE_EXTRA_VALUES($filterFunctions[$idx], $value, $extraValues[$idx]);
859 // Add color switching
860 $content['sw'] = $SW;
863 $OUT .= LOAD_TEMPLATE("admin_".$listType."_".$table."_row", true, $content);
870 SQL_FREERESULT($result);
873 // Load master template
874 LOAD_TEMPLATE("admin_".$listType."_".$table."", false, $OUT);
876 // Delete rows by given ID numbers
877 function ADMIN_DELETE_ENTRIES_CONFIRM ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $deleteNow=false, $idColumn="id", $userIdColumn="userid") {
878 // All valid entries? (We hope so here!)
879 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues))) {
880 // Shall we delete here or list for deletion?
883 $SQL = "DELETE LOW_PRIORITY FROM "._MYSQL_PREFIX."_%s WHERE %s IN (%s)";
885 foreach ($IDs as $id => $sel) {
886 // Is there a userid?
887 if (isset($_POST['uid_raw'][$id])) {
888 // Load all data from that id
889 $result = SQL_QUERY_ESC("SELECT * FROM "._MYSQL_PREFIX."_%s WHERE %s=%s LIMIT 1",
890 array($table, $idColumn, $id), __FILE__, __LINE__);
893 $content = SQL_FETCHARRAY($result);
896 SQL_FREERESULT($result);
898 // Send "build mails" out
899 ADMIN_SEND_BUILD_MAILS("del", $table, $content, $id);
907 SQL_QUERY($SQL, array($table, $idColumn, substr($idList, 0, -1)), __FILE__, __LINE__);
910 if (SQL_AFFECTEDROWS() == count($IDs)) {
912 LOAD_TEMPLATE("admin_settings_saved", false, ADMIN_ALL_ENTRIES_REMOVED);
914 // Some are still there :(
915 LOAD_TEMPLATE("admin_settings_saved", false, sprintf(ADMIN_SOME_ENTRIES_NOT_DELETED, SQL_AFFECTEDROWS(), count($IDs)));
918 // List for deletion confirmation
919 ADMIN_BUILD_LIST("del", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
923 // Edit rows by given ID numbers
924 function ADMIN_EDIT_ENTRIES_CONFIRM ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $editNow=false, $idColumn="id", $userIdColumn="userid") {
925 // All valid entries? (We hope so here!)
926 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues))) {
927 // Shall we change here or list for editing?
931 foreach ($IDs as $id => $sel) {
932 // Prepare content array (new values)
935 // Prepare SQL for this row
936 $SQL = "UPDATE "._MYSQL_PREFIX."_".$table." SET";
937 foreach ($_POST as $key => $entries) {
938 // Skip raw userid which is always invalid
939 if ($key == "uid_raw") {
940 // Continue with next field
944 // Is entries an array?
945 if (($key != $idColumn) && (is_array($entries)) && (isset($entries[$id]))) {
946 // Add this entry to content
947 $content[$key] = $entries[$id];
949 // Send data through the filter function if found
950 if ((isset($filterFunctions[$key])) && (isset($extraValues[$key]))) {
951 // Filter function set!
952 $entries[$id] = HANDLE_EXTRA_VALUES($filterFunctions[$key], $entries[$id], $extraValues[$key]);
955 // Then add this value
956 $SQL .= sprintf(" %s='%s',",
958 SQL_ESCAPE($entries[$id])
960 } elseif (($key != $idColumn) && (!is_array($entries))) {
961 // Add normal entries as well!
962 $content[$key] = $entries;
965 // Do we have an URL?
967 // Then add a framekiller test as well
968 $content['frametester'] = FRAMETESTER($content[$key]);
971 $SQL = substr($SQL, 0, -1) . " WHERE ".$idColumn."=".bigintval($id)." LIMIT 1";
974 SQL_QUERY($SQL, __FILE__, __LINE__);
977 $affected += SQL_AFFECTEDROWS();
979 // Load all data from that id
980 $result = SQL_QUERY_ESC("SELECT * FROM "._MYSQL_PREFIX."_%s WHERE %s=%s LIMIT 1",
981 array($table, $idColumn, $id), __FILE__, __LINE__);
985 $DATA = SQL_FETCHARRAY($result);
988 SQL_FREERESULT($result);
990 // Send "build mails" out
991 ADMIN_SEND_BUILD_MAILS("edit", $table, $content, $id);
995 if ($affected == count($IDs)) {
997 LOAD_TEMPLATE("admin_settings_saved", false, ADMIN_ALL_ENTRIES_EDITED);
999 // Some are still there :(
1000 LOAD_TEMPLATE("admin_settings_saved", false, sprintf(ADMIN_SOME_ENTRIES_NOT_EDITED, $affected, count($IDs)));
1004 ADMIN_BUILD_LIST("edit", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1008 // Un-/lock rows by given ID numbers
1009 function ADMIN_LOCK_ENTRIES_CONFIRM ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $statusArray=array(), $lockNow=false, $idColumn="id", $userIdColumn="userid") {
1010 // All valid entries? (We hope so here!)
1011 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues)) && ((!$lockNow) || (count($statusArray) == 1))) {
1012 // Shall we un-/lock here or list for locking?
1015 foreach ($IDs as $id => $sel) {
1016 // Construct SQL query
1017 $SQL = "UPDATE "._MYSQL_PREFIX."_".$table." SET";
1019 // Load data of entry
1020 $result = SQL_QUERY_ESC("SELECT * FROM "._MYSQL_PREFIX."_%s WHERE %s=%s LIMIT 1",
1021 array($table, $idColumn, $id), __FILE__, __LINE__);
1024 $content = SQL_FETCHARRAY($result);
1027 SQL_FREERESULT($result);
1029 // Add all status entries (e.g. status column last_updated or so)
1030 $newStatus = "UNKNOWN";
1031 $oldStatus = "UNKNOWN";
1032 $statusColumn = "unknown";
1033 foreach ($statusArray as $column => $statusInfo) {
1034 // Does the entry exist?
1035 if ((isset($content[$column])) && (isset($statusInfo[$content[$column]]))) {
1036 // Add these entries for update
1037 $SQL .= sprintf(" %s='%s',", SQL_ESCAPE($column), SQL_ESCAPE($statusInfo[$content[$column]]));
1040 if ($statusColumn == "unknown") {
1041 // Always (!!!) change status column first!
1042 $oldStatus = $content[$column];
1043 $newStatus = $statusInfo[$oldStatus];
1044 $statusColumn = $column;
1046 } elseif (isset($content[$column])) {
1048 die("UNFINISHED: {$column}[".gettype($statusInfo)."] = {$content[$column]}");
1052 // Add other columns as well
1053 foreach ($_POST as $key => $entries) {
1054 // Skip id, raw userid and 'do_lock'
1055 if (!in_array($key, array($idColumn, 'uid_raw', 'do_lock'))) {
1056 // Are there brackets () at the end?
1057 if (substr($entries[$id], -2, 2) == "()") {
1058 // Direct SQL command found
1059 $SQL .= sprintf(" %s=%s,", SQL_ESCAPE($key), SQL_ESCAPE($entries[$id]));
1061 // Add regular entry
1062 $SQL .= sprintf(" %s='%s',", SQL_ESCAPE($key), SQL_ESCAPE($entries[$id]));
1067 // Finish SQL statement
1068 $SQL = substr($SQL, 0, -1) . " WHERE ".$idColumn."=".bigintval($id)." AND ".$statusColumn."='".$oldStatus."' LIMIT 1";
1071 SQL_QUERY($SQL, __FILE__, __LINE__);
1073 // Do we have an URL?
1074 if (isset($content['url'])) {
1075 // Then add a framekiller test as well
1076 $content['frametester'] = FRAMETESTER($content['url']);
1079 // Send "build mails" out
1080 ADMIN_SEND_BUILD_MAILS("lock", $table, $content, $id, $statusInfo[$content[$column]]);
1084 ADMIN_BUILD_LIST("lock", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1088 // Checks proxy settins by fetching check-updates3.php from www.mxchange.org
1089 function ADMIN_TEST_PROXY_SETTINGS ($settingsArray) {
1092 // Set temporary the new settings
1093 $_CONFIG = array_merge($_CONFIG, $settingsArray);
1095 // Now get the test URL
1096 $content = GET_URL("check-updates3.php");
1098 // Is the first line with "200 OK"?
1099 $valid = eregi("200 OK", $content[0]);
1104 // Sends out a link to the given email adress so the admin can reset his/her password
1105 function ADMIN_SEND_PASSWORD_RESET_LINK ($email) {
1110 // Compile out security characters (must be for looking up!)
1111 $email = COMPILE_CODE($email);
1113 // Look up administator login
1114 $result = SQL_QUERY_ESC("SELECT id, login, password FROM "._MYSQL_PREFIX."_admins WHERE email='%s' LIMIT 1",
1115 array($email), __FILE__, __LINE__);
1117 // Is there an account?
1118 if (SQL_NUMROWS($result) == 0) {
1119 // No account found!
1120 return ADMIN_NO_LOGIN_WITH_EMAIL;
1124 $content = SQL_FETCHARRAY($result);
1127 SQL_FREERESULT($result);
1129 // Generate hash for reset link
1130 $content['hash'] = generateHash(URL.":".$content['id'].":".$content['login'].":".$content['password'], substr($content['password'], 10));
1133 unset($content['id']);
1134 unset($content['password']);
1137 $mailText = LOAD_EMAIL_TEMPLATE("admin_reset_password", $content);
1140 SEND_EMAIL($email, ADMIN_RESET_PASS_LINK_SUBJ, $mailText);
1143 return ADMIN_RESET_LINK_SENT;
1145 // Validate hash and login for password reset
1146 function ADMIN_VALIDATE_RESET_LINK_HASH_LOGIN ($hash, $login) {
1147 // By default nothing validates... ;)
1150 // Compile the login for lookup
1151 $login = COMPILE_CODE($login);
1153 // Then try to find that user
1154 $result = SQL_QUERY_ESC("SELECT id, password, email FROM "._MYSQL_PREFIX."_admins WHERE login='%s' LIMIT 1",
1155 array($login), __FILE__, __LINE__);
1157 // Is an account here?
1158 if (SQL_NUMROWS($result) == 1) {
1160 $content = SQL_FETCHARRAY($result);
1162 // Generate hash again
1163 $hashFromData = generateHash(URL.":".$content['id'].":".$login.":".$content['password'], substr($content['password'], 10));
1166 $valid = ($hash == $hashFromData);
1170 SQL_FREERESULT($result);
1175 // Reset the password for the login. Do NOT call this function without calling above function first!
1176 function ADMIN_RESET_PASSWORD ($login, $password) {
1180 // Now check if we have sql_patches installed
1181 if (GET_EXT_VERSION("sql_patches") >= "0.3.6") {
1182 // Use new way of hashing
1183 $passHash = generateHash($password);
1186 $passHash = md5($password);
1190 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_admins SET password='%s' WHERE login='%s' LIMIT 1",
1191 array($passHash, $login), __FILE__, __LINE__);
1194 return ADMIN_PASSWORD_RESET_DONE;
1196 // Solves a task by given id number
1197 function ADMIN_SOLVE_TASK ($id) {
1198 // Update the task data
1199 ADMIN_UPDATE_TASK_DATA($id, "status", "SOLVED");
1201 // Marks a given task as deleted
1202 function ADMIN_DELETE_TASK ($id) {
1203 // Update the task data
1204 ADMIN_UPDATE_TASK_DATA($id, "status", "DELETED");
1206 // Function to update task data
1207 function ADMIN_UPDATE_TASK_DATA ($id, $row, $data) {
1209 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_task_system SET %s='%s' WHERE id=%s LIMIT 1",
1210 array($row, $data, bigintval($id)), __FILE__, __LINE__);