2 /************************************************************************
3 * MXChange v0.2.1 Start: 08/31/2003 *
4 * =============== Last change: 11/23/2004 *
6 * -------------------------------------------------------------------- *
7 * File : admin-inc.php *
8 * -------------------------------------------------------------------- *
9 * Short description : Administrative related functions *
10 * -------------------------------------------------------------------- *
11 * Kurzbeschreibung : Fuer die Administration benoetigte Funktionen *
12 * -------------------------------------------------------------------- *
14 * -------------------------------------------------------------------- *
15 * Copyright (c) 2003 - 2008 by Roland Haeder *
16 * For more information visit: http://www.mxchange.org *
18 * This program is free software; you can redistribute it and/or modify *
19 * it under the terms of the GNU General Public License as published by *
20 * the Free Software Foundation; either version 2 of the License, or *
21 * (at your option) any later version. *
23 * This program is distributed in the hope that it will be useful, *
24 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
25 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
26 * GNU General Public License for more details. *
28 * You should have received a copy of the GNU General Public License *
29 * along with this program; if not, write to the Free Software *
30 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
32 ************************************************************************/
34 // Some security stuff...
35 if (!defined('__SECURITY')) {
36 $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), "/inc") + 4) . "/security.php";
40 // Register an administrator account
41 function REGISTER_ADMIN ($user, $md5, $email=WEBMASTER) {
42 // Login does already exist
46 $result = SQL_QUERY_ESC("SELECT id FROM `{!_MYSQL_PREFIX!}_admins` WHERE login='%s' LIMIT 1",
47 array($user), __FILE__, __LINE__);
49 // Is the entry there?
50 if (SQL_NUMROWS($result) == 0) {
51 // Ok, let's create the admin login
52 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_admins` (login, password, email) VALUES ('%s', '%s', '%s')",
53 array($user, $md5, $email), __FILE__, __LINE__);
58 SQL_FREERESULT($result);
63 // Only be executed on login procedure!
64 function CHECK_ADMIN_LOGIN ($admin_login, $password) {
65 global $cacheArray, $cacheInstance;
67 // By default no admin is found
71 $aid = GET_ADMIN_ID($admin_login);
73 // Init array with admin id by default
74 $data = array('aid' => $aid);
76 // Is the cache valid?
77 if (isset($cacheArray['admins']['password'][$aid])) {
78 // Get password from cache
79 $data['password'] = $cacheArray['admins']['password'][$aid];
81 incrementConfigEntry('cache_hits');
83 // Include more admins data?
84 if (GET_EXT_VERSION("admins") >= "0.7.0") {
86 $data['login_failures'] = $cacheArray['admins']['login_failures'][$aid];
87 $data['last_failure'] = $cacheArray['admins']['last_failure'][$aid];
89 } elseif (!EXT_IS_ACTIVE("cache")) {
90 // Add extra data via filter now
91 $ADD = RUN_FILTER('sql_admin_extra_data');
93 // Get password from DB
94 $result = SQL_QUERY_ESC("SELECT password".$ADD." FROM `{!_MYSQL_PREFIX!}_admins` WHERE id=%s LIMIT 1",
95 array($aid), __FILE__, __LINE__);
98 if (SQL_NUMROWS($result) == 1) {
99 // Login password found
103 $data = SQL_FETCHARRAY($result);
107 SQL_FREERESULT($result);
110 //* DEBUG: */ echo "*".$data['password']."/".md5($password)."/".$ret."<br />";
111 if ((isset($data['password'])) && (strlen($data['password']) == 32) && ($data['password'] == md5($password))) {
113 $data['password'] = generateHash($password);
115 // Is the sql_patches not installed, than we cannot have a valid hashed password here!
116 if (($ret == "pass") && ((EXT_VERSION_IS_OLDER("sql_patches", "0.3.6")) || (GET_EXT_VERSION("sql_patches") == ""))) $ret = "done";
117 } elseif ((EXT_VERSION_IS_OLDER("sql_patches", "0.3.6")) || (GET_EXT_VERSION("sql_patches") == "")) {
120 } elseif (!isset($data['password'])) {
121 // Password not found, so no valid login!
125 // Generate salt of password
126 define('__SALT', substr($data['password'], 0, -40));
129 // Check if password is same
130 //* DEBUG: */ echo "*".$ret.",".$data['password'].",".$password.",".$salt."*<br >\n";
131 if (($ret == "pass") && ($data['password'] == generateHash($password, $salt)) && ((!empty($salt))) || ($data['password'] == $password)) {
132 // Re-hash the plain passord with new random salt
133 $data['password'] = generateHash($password);
135 // Do we have 0.7.0 of admins or later?
136 // Remmeber login failures if available
137 if (GET_EXT_VERSION("admins") >= "0.7.2") {
138 // Store it in session
139 set_session('mxchange_admin_failures', $data['login_failures']);
140 set_session('mxchange_admin_last_fail', $data['last_failure']);
142 // Update password and reset login failures
143 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_admins` SET password='%s',login_failures=0,last_failure='0000-00-00 00:00:00' WHERE id=%s LIMIT 1",
144 array($data['password'], $aid), __FILE__, __LINE__);
147 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_admins` SET password='%s' WHERE id=%s LIMIT 1",
148 array($data['password'], $aid), __FILE__, __LINE__);
152 REBUILD_CACHE("admins", "admin");
154 // Login has failed by default... ;-)
157 // Password matches so login here
158 if (LOGIN_ADMIN($admin_login, $data['password'])) {
162 } elseif ((empty($salt)) && ($ret == "pass")) {
163 // Something bad went wrong
165 } elseif ($ret == "done") {
166 // Try to login here if we have the old hashing way (sql_patches not installed?)
167 if (!LOGIN_ADMIN($admin_login, $data['password'])) {
168 // Something went wrong
173 // Count login failure if admins extension version is 0.7.0+
174 if (($ret == "pass") && (GET_EXT_VERSION("admins") >= "0.7.0")) {
176 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_admins` SET login_failures=login_failures+1,last_failure=NOW() WHERE id=%s LIMIT 1",
177 array($aid), __FILE__, __LINE__);
180 REBUILD_CACHE("admins", "admin");
184 //* DEBUG: */ die("RETURN=".$ret);
188 // Try to login the admin by setting some session/cookie variables
189 function LOGIN_ADMIN ($adminLogin, $passHash) {
190 global $cacheInstance;
192 // Reset failure counter on matching admins version
193 if ((GET_EXT_VERSION("admins") >= "0.7.0") && ((EXT_VERSION_IS_OLDER("sql_patches", "0.3.6")) || (GET_EXT_VERSION("sql_patches") == ""))) {
194 // Reset counter on out-dated sql_patches version
195 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_admins` SET login_failures=0,last_failure='0000-00-00 00:00:00' WHERE login='%s' LIMIT 1",
196 array($adminLogin), __FILE__, __LINE__);
199 REBUILD_CACHE("admins", "admin");
202 // Now set all session variables and return the result
205 set_session('admin_md5', generatePassString($passHash))
207 set_session('admin_login', $adminLogin)
209 set_session('admin_last', time())
211 set_session('admin_to', bigintval($_POST['timeout']))
216 // Only be executed on cookie checking
217 function CHECK_ADMIN_COOKIES ($admin_login, $password) {
219 $ret = "404"; $pass = "";
222 $pass = GET_ADMIN_HASH(GET_ADMIN_ID($admin_login));
223 if ($pass != "-1") $ret = "pass";
225 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):".generatePassString($pass)."(".strlen($pass).")/".$password."(".strlen($password).")<br />\n";
227 // Check if password matches
228 if (($ret == "pass") && ((generatePassString($pass) == $password) || ($pass == $password) || ((strlen($pass) == 32) && (md5($password) == $pass)))) {
229 // Passwords matches!
238 function ADMIN_DO_ACTION($wht) {
239 global $menuDesription, $menuTitle, $cacheArray, $DATA;
241 //* DEBUG: */ echo __LINE__."*".$wht."/".$GLOBALS['module']."/".$GLOBALS['action']."/".$GLOBALS['what']."*<br />\n";
242 if (EXT_IS_ACTIVE("cache")) {
243 // Include cache instance
244 global $cacheInstance;
247 // Remove any spaces from variable
249 // Default admin action is the overview page
252 // Compile out some chars
253 $wht = COMPILE_CODE($wht, false, false, false);
257 $act = GET_ACTION($GLOBALS['module'], $wht);
259 // Define admin login name and ID number
260 define('__ADMIN_LOGIN', get_session('admin_login'));
261 define('__ADMIN_ID' , GET_CURRENT_ADMIN_ID());
264 if (EXT_IS_ACTIVE("admins")) {
265 define('__ADMIN_WELCOME', LOAD_TEMPLATE("admin_welcome_admins", true));
267 define('__ADMIN_WELCOME', LOAD_TEMPLATE("admin_welcome", true));
269 define('__ADMIN_FOOTER' , LOAD_TEMPLATE("admin_footer" , true));
270 define('__ADMIN_MENU' , ADD_ADMIN_MENU($act, $wht, true));
273 LOAD_TEMPLATE("admin_main_header");
275 // Check if action/what pair is valid
276 $result_action = SQL_QUERY_ESC("SELECT id FROM `{!_MYSQL_PREFIX!}_admin_menu`
277 WHERE `action`='%s' AND ((what='%s' AND what != 'overview') OR ((what='' OR `what` IS NULL) AND '%s'='overview'))
278 LIMIT 1", array($act, $wht, $wht), __FILE__, __LINE__);
279 if (SQL_NUMROWS($result_action) == 1) {
281 // Is valid but does the inlcude file exists?
282 $INC = sprintf("inc/modules/admin/action-%s.php", $act);
283 if ((INCLUDE_READABLE($INC)) && (VALIDATE_MENU_ACTION("admin", $act, $wht)) && (__ACL_ALLOW == true)) {
284 // Ok, we finally load the admin action module
286 } elseif (__ACL_ALLOW == false) {
288 LOAD_TEMPLATE("admin_menu_failed", false, getMessage('ADMIN_ACCESS_DENIED'));
289 addFatalMessage(getMessage('ADMIN_ACCESS_DENIED'));
291 // Include file not found! :-(
292 LOAD_TEMPLATE("admin_menu_failed", false, sprintf(getMessage('ADMIN_ACTION_404'), $act));
293 addFatalMessage(getMessage('ADMIN_ACTION_404'), $act);
296 // Invalid action/what pair found!
297 LOAD_TEMPLATE("admin_menu_failed", false, sprintf(getMessage('ADMIN_ACTION_INVALID'), $act."/".$wht));
298 addFatalMessage(getMessage('ADMIN_ACTION_INVALID'), $act."/".$wht);
302 SQL_FREERESULT($result_action);
305 LOAD_TEMPLATE("admin_main_footer");
308 function ADD_ADMIN_MENU($act, $wht, $return=false) {
309 global $menuDesription, $menuTitle, $cacheInstance;
316 $menuDesription = array();
317 $menuTitle = array();
319 // Is there a cache instance?
320 if ((is_object($cacheInstance)) && (getConfig('cache_admin_menu') == "Y")) {
322 $cacheName = "admin_".$act."_".$wht."_".GET_LANGUAGE()."_".strtolower(get_session('admin_login'));
324 // Is that cache there?
325 if ($cacheInstance->loadCacheFile($cacheName)) {
327 $data = $cacheInstance->getArrayFromCache();
330 $OUT = base64_decode($data['output'][0]);
331 $menuTitle = unserialize(base64_decode($data['title'][0]));
332 $menuDescription = unserialize(base64_decode($data['descr'][0]));
334 // Return or output content?
344 $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__);
345 if (SQL_NUMROWS($result_main) > 0) {
346 $OUT = "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_menu_main\">
347 <tr><td colspan=\"2\" height=\"7\" class=\"seperator\"> </td></tr>\n";
348 while (list($menu, $title, $descr) = SQL_FETCHROW($result_main)) {
349 if ((EXT_IS_ACTIVE("admins")) && (GET_EXT_VERSION("admins") > "0.2")) {
350 $ACL = ADMINS_CHECK_ACL($menu, "");
352 // ACL is "allow"... hmmm
358 // Insert compiled menu title and description
359 $menuTitle[$menu] = $title;
360 $menuDesription[$menu] = $descr;
363 <td class=\"admin_menu\" colspan=\"2\">
364 <NOBR> <strong>·</strong> ";
365 if (($menu == $act) && (empty($wht)))
371 $OUT .= "[<a href=\"{!URL!}/modules.php?module=admin&action=".$menu."\">";
374 if (($menu == $act) && (empty($wht)))
382 $OUT .= "</NOBR></td>
384 $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",
385 array($menu), __FILE__, __LINE__);
386 if ((SQL_NUMROWS($result_what) > 0) && ($act == $menu))
388 $menuDesription = array();
389 $menuTitle = array(); $SUB = true;
391 <td width=\"10\" class=\"seperator\"> </td>
392 <td class=\"admin_menu\">
393 <table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_menu_sub\">\n";
394 while (list($wht_sub, $title_what, $desc_what) = SQL_FETCHROW($result_what)) {
396 $INC = sprintf("%sinc/modules/admin/what-%s.php", constant('PATH'), $wht_sub);
397 if ((EXT_IS_ACTIVE("admins")) && (GET_EXT_VERSION("admins") > "0.2")) {
398 $ACL = ADMINS_CHECK_ACL("", $wht_sub);
400 // ACL is "allow"... hmmm
403 $readable = INCLUDE_READABLE($INC);
405 // Insert compiled title and description
406 $menuTitle[$wht_sub] = $title_what;
407 $menuDesription[$wht_sub] = $desc_what;
409 <td class=\"admin_menu\" colspan=\"2\">
410 <NOBR> <strong>--></strong> ";
411 if ($readable === true)
413 if ($wht == $wht_sub)
419 $OUT .= "[<a href=\"{!URL!}/modules.php?module=admin&what=".$wht_sub."\">";
424 $OUT .= "<i class=\"admin_note\">";
427 if ($readable === true)
429 if ($wht == $wht_sub)
442 $OUT .= "</NOBR></td>
448 SQL_FREERESULT($result_what);
453 $OUT .= "<tr><td height=\"7\" colspan=\"2\"></td></tr>\n";
458 SQL_FREERESULT($result_main);
459 $OUT .= "</table>\n";
462 // Compile and run the code here. This inserts all constants into the
463 // HTML output. Costs me some time to figure this out... *sigh* Quix0r
464 $eval = "\$OUT = \"".COMPILE_CODE(SQL_ESCAPE($OUT))."\";";
467 // Is there a cache instance again?
468 if ((is_object($cacheInstance)) && (getConfig('cache_admin_menu') == "Y")) {
470 $cacheInstance->init($cacheName);
472 // Prepare cache data
474 'output' => base64_encode($OUT),
475 'title' => $menuTitle,
476 'descr' => $menuDesription
479 // Write the data away
480 $cacheInstance->addRow($data);
483 $cacheInstance->finalize();
486 // Return or output content?
494 function ADD_MEMBER_SELECTION_BOX ($def="0", $add_all=false, $return=false, $none=false, $field="userid")
496 // Output selection form with all confirmed user accounts listed
497 $result = SQL_QUERY("SELECT userid, surname, family FROM `{!_MYSQL_PREFIX!}_user_data` ORDER BY userid", __FILE__, __LINE__);
500 // USe this only for adding points (e.g. adding refs really makes no sence ;-) )
501 if ($add_all) $OUT = " <option value=\"all\">".ALL_MEMBERS."</option>\n";
502 elseif ($none) $OUT = " <option value=\"0\">".SELECT_NONE."</option>\n";
503 while (list($id, $sname, $fname) = SQL_FETCHROW($result))
505 $OUT .= " <option value=\"".bigintval($id)."\"";
506 if ($def == $id) $OUT .= " selected=\"selected\"";
507 $OUT .= ">".$sname." ".$fname." (".bigintval($id).")</option>\n";
511 SQL_FREERESULT($result);
514 // Remeber options in constant
515 define('_MEMBER_SELECTION', $OUT);
517 // Display selection box
518 define('__LANG_VALUE', GET_LANGUAGE());
521 LOAD_TEMPLATE("admin_member_selection_box", false, $GLOBALS['what']);
523 // Return content in selection frame
524 return "<select class=\"admin_select\" name=\"".$field."\" size=\"1\">\n".$OUT."</select>\n";
528 function ADMIN_MENU_SELECTION($MODE, $default="", $defid="") {
529 $wht = "`what` != ''";
530 if ($MODE == "action") $wht = "(what='' OR `what` IS NULL) AND action !='login'";
531 $result = SQL_QUERY_ESC("SELECT %s, title FROM `{!_MYSQL_PREFIX!}_admin_menu` WHERE ".$wht." ORDER BY `sort`",
532 array($MODE), __FILE__, __LINE__);
533 if (SQL_NUMROWS($result) > 0) {
534 // Load menu as selection
535 $OUT = "<select name=\"".$MODE."_menu";
536 if ((!empty($defid)) || ($defid == "0")) $OUT .= "[".$defid."]";
537 $OUT .= "\" size=\"1\" class=\"admin_select\">
538 <option value=\"\">".SELECT_NONE."</option>\n";
539 while (list($menu, $title) = SQL_FETCHROW($result)) {
540 $OUT .= " <option value=\"".$menu."\"";
541 if ((!empty($default)) && ($default == $menu)) $OUT .= " selected=\"selected\"";
542 $OUT .= ">".$title."</option>\n";
546 SQL_FREERESULT($result);
547 $OUT .= "</select>\n";
550 $OUT = ADMIN_PROBLEM_NO_MENU;
557 // Save settings to the database
558 function ADMIN_SAVE_SETTINGS (&$POST, $tableName="_config", $whereStatement="config=0", $translateComma=array(), $alwaysAdd=false) {
559 global $cacheArray, $cacheInstance;
561 // Prepare all arrays, variables
565 // Now, walk through all entries and prepare them for saving
566 foreach ($POST as $id => $val) {
567 // Process only formular field but not submit buttons ;)
569 // Do not save the ok value
570 CONVERT_SELECTIONS_TO_TIMESTAMP($POST, $DATA, $id, $skip);
572 // Shall we process this ID? It muss not be empty, of course
573 if ((!$skip) && (!empty($id))) {
575 $val = COMPILE_CODE($val);
577 // Translate the value? (comma to dot!)
578 if ((is_array($translateComma)) && (in_array($id, $translateComma))) {
579 // Then do it here... :)
580 $val = REVERT_COMMA($val);
583 // Shall we add numbers or strings?
585 if ("".$val."" == "".$test."") {
587 $DATA[] = sprintf("`%s`=%s", $id, $test);
590 $DATA[] = sprintf("`%s`='%s'", $id, trim($val));
593 // Update current configuration
594 setConfigEntry($id, $val);
599 // Check if entry does exist
602 if (!empty($whereStatement)) {
603 $result = SQL_QUERY("SELECT * FROM `{!_MYSQL_PREFIX!}".$tableName."` WHERE ".$whereStatement." LIMIT 1", __FILE__, __LINE__);
605 $result = SQL_QUERY("SELECT * FROM `{!_MYSQL_PREFIX!}".$tableName."` LIMIT 1", __FILE__, __LINE__);
609 if (SQL_NUMROWS($result) == 1) {
610 // "Implode" all data to single string
611 $DATA_UPDATE = implode(", ", $DATA);
613 // Generate SQL string
614 $SQL = sprintf("UPDATE `{!_MYSQL_PREFIX!}%s` SET %s WHERE %s LIMIT 1",
620 // Add Line (does only work with auto_increment!
621 $KEYs = array(); $VALUEs = array();
622 foreach ($DATA as $entry) {
624 $line = explode("=", $entry);
625 $KEYs[] = $line[0]; $VALUEs[] = $line[1];
628 // Add both in one line
629 $KEYs = implode(", ", $KEYs);
630 $VALUEs = implode(", ", $VALUEs);
632 // Generate SQL string
633 $SQL = sprintf("INSERT INTO {!_MYSQL_PREFIX!}%s (%s) VALUES (%s)",
641 SQL_FREERESULT($result);
643 // Simply run generated SQL string
644 SQL_QUERY($SQL, __FILE__, __LINE__);
647 REBUILD_CACHE("config", "config");
650 LOAD_TEMPLATE("admin_settings_saved", false, getMessage('SETTINGS_SAVED'));
653 // Generate a selection box
654 function ADMIN_MAKE_MENU_SELECTION ($menu, $type, $name, $default="") {
655 // Open the requested menu directory
656 $handle = opendir(sprintf("%sinc/modules/%s/", constant('PATH'), $menu)) or mxchange_die("Cannot load menu ".$menu."!");
658 // Init the selection box
659 $OUT = "<select name=\"".$name."\" class=\"admin_select\" size=\"1\">\n <option value=\"\">".IS_TOP_MENU."</option>\n";
661 // Walk through all files
662 while ($file = readdir($handle)) {
663 // Is this a PHP script?
664 if (($file != ".") && ($file != "..") && ($file != "lost+found") && (strpos($file, "".$type."-") > -1) && (strpos($file, ".php") > 0)) {
665 // Then test if the file is readable
666 $test = sprintf("%sinc/modules/%s/%s", constant('PATH'), $menu, $file);
668 // Is the file there?
669 if (FILE_READABLE($test)) {
670 // Extract the value for what=xxx
671 $part = substr($file, (strlen($type) + 1));
672 $part = substr($part, 0, -4);
674 // Is that part different from the overview?
675 if ($part != "overview") {
676 $OUT .= " <option value=\"".$part."\"";
677 if ($part == $default) $OUT .= " selected=\"selected\"";
678 $OUT .= ">".$part."</option>\n";
684 // Close dir and selection box
686 $OUT .= "</select>\n";
692 function ADMIN_USER_PROFILE_LINK ($uid, $title="", $wht="list_user") {
693 if (($title == "") && ($title != "0")) {
694 // Set userid as title
698 if (($title == "0") && ($wht == "list_refs")) {
699 // Return title again
703 //* DEBUG: */ echo "a:".$title."<br />";
705 return "<a href=\"{!URL!}/modules.php?module=admin&what=".$wht."&u_id=".$uid."\" title=\"{--ADMIN_USER_PROFILE_TITLE--}\">".$title."</a>";
708 // Check "logical-area-mode"
709 function ADMIN_CHECK_MENU_MODE () {
712 // Set the global mode as the mode for all admins
713 $MODE = getConfig('admin_menu');
717 $aid = GET_CURRENT_ADMIN_ID();
719 // Check individual settings of current admin
720 if (isset($cacheArray['admins']['la_mode'][$aid])) {
722 $ADMIN = $cacheArray['admins']['la_mode'][$aid];
723 incrementConfigEntry('cache_hits');
724 } elseif (GET_EXT_VERSION("admins") >= "0.6.7") {
725 // Load from database when version of "admins" is enough
726 $result = SQL_QUERY_ESC("SELECT la_mode FROM `{!_MYSQL_PREFIX!}_admins` WHERE id=%s LIMIT 1",
727 array($aid), __FILE__, __LINE__);
728 if (SQL_NUMROWS($result) == 1) {
730 list($ADMIN) = SQL_FETCHROW($result);
734 SQL_FREERESULT($result);
737 // Check what the admin wants and set it when it's not the global mode
738 if ($ADMIN != "global") $MODE = $ADMIN;
740 // Return admin-menu's mode
744 // Change activation status
745 function ADMIN_CHANGE_ACTIVATION_STATUS ($IDs, $table, $row, $idRow = "id") {
746 $cnt = 0; $newStatus = "Y";
747 if ((is_array($IDs)) && (count($IDs) > 0)) {
748 // "Walk" all through and count them
749 foreach ($IDs as $id => $selected) {
750 // Secure the ID number
751 $id = bigintval($id);
753 // Should always be set... ;-)
754 if (!empty($selected)) {
755 // Determine new status
756 $result = SQL_QUERY_ESC("SELECT %s FROM `{!_MYSQL_PREFIX!}_%s` WHERE %s=%s LIMIT 1",
757 array($row, $table, $idRow, $id), __FILE__, __LINE__);
760 if (SQL_NUMROWS($result) == 1) {
762 list($currStatus) = SQL_FETCHROW($result);
764 // And switch it N<->Y
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, getMessage('ADMIN_NOTHING_SELECTED_CHANGE'));
788 // Send mails for del/edit/lock build modes
789 function ADMIN_SEND_BUILD_MAILS ($mode, $table, $content, $id, $subjectPart="") {
790 // Default subject is the subject part
791 $subject = $subjectPart;
793 // Is the subject part not set?
794 if (empty($subjectPart)) {
795 // Then use it from the mode
796 $subject = strtoupper($mode);
799 // Is the raw userid set?
800 if ($_POST['uid_raw'][$id] > 0) {
802 $subjectLine = constant('MEMBER_'.strtoupper($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 $subjectLine = constant('ADMIN_'.strtoupper($subject).'_'.strtoupper($table).'_SUBJECT');
818 // Send admin notification out
819 if (!empty($subjectPart)) {
820 SEND_ADMIN_NOTIFICATION($subjectLine, "admin_".$mode."_".strtolower($subjectPart)."_".$table, $content, $_POST['uid_raw'][$id]);
822 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) {
830 // "Walk" through all entries
831 foreach ($IDs as $id => $selected) {
833 $id = bigintval($id);
835 // Get result from a given column array and table name
836 $result = SQL_RESULT_FROM_ARRAY($table, $columns, $idColumn, $id, __FILE__, __LINE__);
838 // Is there one entry?
839 if (SQL_NUMROWS($result) == 1) {
841 $content = SQL_FETCHARRAY($result);
844 foreach ($content as $key => $value) {
846 $idx = array_search($key, $columns, true);
848 // Do we have a userid?
849 if ($key == "userid") {
850 // Add it again as raw id
851 $content['uid'] = bigintval($value);
854 // Handle the call in external function
855 $content[$key] = HANDLE_EXTRA_VALUES($filterFunctions[$idx], $value, $extraValues[$idx]);
858 // Add color switching
859 $content['sw'] = $SW;
862 $OUT .= LOAD_TEMPLATE(sprintf("admin_%s_%s_row",
873 SQL_FREERESULT($result);
876 // Load master template
877 LOAD_TEMPLATE(sprintf("admin_%s_%s",
884 // Change status of "build" list
885 function ADMIN_BUILD_STATUS_HANDLER ($mode, $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray) {
886 // All valid entries? (We hope so here!)
887 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues)) && (count($statusArray) > 0)) {
888 // "Walk" through all entries
889 foreach ($IDs as $id => $sel) {
890 // Construct SQL query
891 $SQL = sprintf("UPDATE `{!_MYSQL_PREFIX!}_%s` SET",
895 // Load data of entry
896 $result = SQL_QUERY_ESC("SELECT * FROM `{!_MYSQL_PREFIX!}_%s` WHERE %s=%s LIMIT 1",
897 array($table, $idColumn, $id), __FILE__, __LINE__);
900 $content = SQL_FETCHARRAY($result);
903 SQL_FREERESULT($result);
905 // Add all status entries (e.g. status column last_updated or so)
906 $newStatus = "UNKNOWN";
907 $oldStatus = "UNKNOWN";
908 $statusColumn = "unknown";
909 foreach ($statusArray as $column => $statusInfo) {
910 // Does the entry exist?
911 if ((isset($content[$column])) && (isset($statusInfo[$content[$column]]))) {
912 // Add these entries for update
913 $SQL .= sprintf(" %s='%s',", SQL_ESCAPE($column), SQL_ESCAPE($statusInfo[$content[$column]]));
916 if ($statusColumn == "unknown") {
917 // Always (!!!) change status column first!
918 $oldStatus = $content[$column];
919 $newStatus = $statusInfo[$oldStatus];
920 $statusColumn = $column;
922 } elseif (isset($content[$column])) {
924 mxchange_die("{--".__FUNCTION__."--}:".__LINE__.":UNFINISHED: id={$id}/{$column}[".gettype($statusInfo)."] = {$content[$column]}");
928 // Add other columns as well
929 foreach ($_POST as $key => $entries) {
930 // Skip id, raw userid and 'do_$mode'
931 if (!in_array($key, array($idColumn, 'uid_raw', ('do_'.$mode)))) {
932 // Are there brackets () at the end?
933 if (substr($entries[$id], -2, 2) == "()") {
934 // Direct SQL command found
935 $SQL .= sprintf(" %s=%s,", SQL_ESCAPE($key), SQL_ESCAPE($entries[$id]));
938 $SQL .= sprintf(" %s='%s',", SQL_ESCAPE($key), SQL_ESCAPE($entries[$id]));
941 $content[$key] = $entries[$id];
946 // Finish SQL statement
947 $SQL = substr($SQL, 0, -1) . sprintf(" WHERE %s=%s AND %s='%s' LIMIT 1",
955 SQL_QUERY($SQL, __FILE__, __LINE__);
957 // Do we have an URL?
958 if (isset($content['url'])) {
959 // Then add a framekiller test as well
960 $content['frametester'] = FRAMETESTER($content['url']);
963 // Send "build mails" out
964 ADMIN_SEND_BUILD_MAILS($mode, $table, $content, $id, $statusInfo[$content[$column]]);
969 // Delete rows by given ID numbers
970 function ADMIN_DELETE_ENTRIES_CONFIRM ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $deleteNow=false, $idColumn="id", $userIdColumn="userid") {
971 // All valid entries? (We hope so here!)
972 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues))) {
973 // Shall we delete here or list for deletion?
975 // The base SQL command:
976 $SQL = "DELETE LOW_PRIORITY FROM `{!_MYSQL_PREFIX!}_%s` WHERE %s IN (%s)";
980 foreach ($IDs as $id => $sel) {
981 // Is there a userid?
982 if (isset($_POST['uid_raw'][$id])) {
983 // Load all data from that id
984 $result = SQL_QUERY_ESC("SELECT * FROM `{!_MYSQL_PREFIX!}_%s` WHERE %s=%s LIMIT 1",
985 array($table, $idColumn, $id), __FILE__, __LINE__);
988 $content = SQL_FETCHARRAY($result);
991 SQL_FREERESULT($result);
993 // Send "build mails" out
994 ADMIN_SEND_BUILD_MAILS("del", $table, $content, $id);
1002 SQL_QUERY($SQL, array($table, $idColumn, substr($idList, 0, -1)), __FILE__, __LINE__);
1005 if (SQL_AFFECTEDROWS() == count($IDs)) {
1007 LOAD_TEMPLATE("admin_settings_saved", false, getMessage('ADMIN_ALL_ENTRIES_REMOVED'));
1009 // Some are still there :(
1010 LOAD_TEMPLATE("admin_settings_saved", false, sprintf(ADMIN_SOME_ENTRIES_NOT_DELETED, SQL_AFFECTEDROWS(), count($IDs)));
1013 // List for deletion confirmation
1014 ADMIN_BUILD_LIST("del", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1019 // Edit rows by given ID numbers
1020 function ADMIN_EDIT_ENTRIES_CONFIRM ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $editNow=false, $idColumn="id", $userIdColumn="userid") {
1021 // All valid entries? (We hope so here!)
1022 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues))) {
1023 // Shall we change here or list for editing?
1027 foreach ($IDs as $id => $sel) {
1028 // Prepare content array (new values)
1031 // Prepare SQL for this row
1032 $SQL = sprintf("UPDATE `{!_MYSQL_PREFIX!}_ SET",
1035 foreach ($_POST as $key => $entries) {
1036 // Skip raw userid which is always invalid
1037 if ($key == "uid_raw") {
1038 // Continue with next field
1042 // Is entries an array?
1043 if (($key != $idColumn) && (is_array($entries)) && (isset($entries[$id]))) {
1044 // Add this entry to content
1045 $content[$key] = $entries[$id];
1047 // Send data through the filter function if found
1048 if ((isset($filterFunctions[$key])) && (isset($extraValues[$key]))) {
1049 // Filter function set!
1050 $entries[$id] = HANDLE_EXTRA_VALUES($filterFunctions[$key], $entries[$id], $extraValues[$key]);
1053 // Then add this value
1054 $SQL .= sprintf(" %s='%s',",
1056 SQL_ESCAPE($entries[$id])
1058 } elseif (($key != $idColumn) && (!is_array($entries))) {
1059 // Add normal entries as well!
1060 $content[$key] = $entries;
1063 // Do we have an URL?
1064 if ($key == "url") {
1065 // Then add a framekiller test as well
1066 $content['frametester'] = FRAMETESTER($content[$key]);
1070 // Finish SQL command
1071 $SQL = substr($SQL, 0, -1) . " WHERE ".$idColumn."=".bigintval($id)." LIMIT 1";
1074 SQL_QUERY($SQL, __FILE__, __LINE__);
1076 // Add affected rows
1077 $affected += SQL_AFFECTEDROWS();
1079 // Load all data from that id
1080 $result = SQL_QUERY_ESC("SELECT * FROM `{!_MYSQL_PREFIX!}_%s` WHERE %s=%s LIMIT 1",
1081 array($table, $idColumn, $id), __FILE__, __LINE__);
1085 $DATA = SQL_FETCHARRAY($result);
1088 SQL_FREERESULT($result);
1090 // Send "build mails" out
1091 ADMIN_SEND_BUILD_MAILS("edit", $table, $content, $id);
1095 if ($affected == count($IDs)) {
1097 LOAD_TEMPLATE("admin_settings_saved", false, getMessage('ADMIN_ALL_ENTRIES_EDITED'));
1099 // Some are still there :(
1100 LOAD_TEMPLATE("admin_settings_saved", false, sprintf(ADMIN_SOME_ENTRIES_NOT_EDITED, $affected, count($IDs)));
1104 ADMIN_BUILD_LIST("edit", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1109 // Un-/lock rows by given ID numbers
1110 function ADMIN_LOCK_ENTRIES_CONFIRM ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $statusArray=array(), $lockNow=false, $idColumn="id", $userIdColumn="userid") {
1111 // All valid entries? (We hope so here!)
1112 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues)) && ((!$lockNow) || (count($statusArray) == 1))) {
1113 // Shall we un-/lock here or list for locking?
1116 ADMIN_BUILD_STATUS_HANDLER("lock", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray);
1119 ADMIN_BUILD_LIST("lock", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1124 // Undelete rows by given ID numbers
1125 function ADMIN_UNDELETE_ENTRIES_CONFIRM ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $statusArray=array(), $lockNow=false, $idColumn="id", $userIdColumn="userid") {
1126 // All valid entries? (We hope so here!)
1127 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues)) && ((!$lockNow) || (count($statusArray) == 1))) {
1128 // Shall we un-/lock here or list for locking?
1131 ADMIN_BUILD_STATUS_HANDLER("undelete", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray);
1134 ADMIN_BUILD_LIST("undelete", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1139 // Checks proxy settins by fetching check-updates3.php from www.mxchange.org
1140 function ADMIN_TEST_PROXY_SETTINGS ($settingsArray) {
1141 // Set temporary the new settings
1142 mergeConfig($settingsArray);
1144 // Now get the test URL
1145 $content = GET_URL("check-updates3.php");
1147 // Is the first line with "200 OK"?
1148 $valid = eregi("200 OK", $content[0]);
1154 // Sends out a link to the given email adress so the admin can reset his/her password
1155 function ADMIN_SEND_PASSWORD_RESET_LINK ($email) {
1159 // Compile out security characters (must be for looking up!)
1160 $email = COMPILE_CODE($email);
1162 // Look up administator login
1163 $result = SQL_QUERY_ESC("SELECT id, login, password FROM `{!_MYSQL_PREFIX!}_admins` WHERE email='%s' LIMIT 1",
1164 array($email), __FILE__, __LINE__);
1166 // Is there an account?
1167 if (SQL_NUMROWS($result) == 0) {
1168 // No account found!
1169 return getMessage('ADMIN_NO_LOGIN_WITH_EMAIL');
1173 $content = SQL_FETCHARRAY($result);
1176 SQL_FREERESULT($result);
1178 // Generate hash for reset link
1179 $content['hash'] = generateHash(URL.":".$content['id'].":".$content['login'].":".$content['password'], substr($content['password'], 10));
1182 unset($content['id']);
1183 unset($content['password']);
1186 $mailText = LOAD_EMAIL_TEMPLATE("admin_reset_password", $content);
1189 SEND_EMAIL($email, getMessage('ADMIN_RESET_PASS_LINK_SUBJ'), $mailText);
1192 return getMessage('ADMIN_RESET_LINK_SENT');
1195 // Validate hash and login for password reset
1196 function ADMIN_VALIDATE_RESET_LINK_HASH_LOGIN ($hash, $login) {
1197 // By default nothing validates... ;)
1200 // Compile the login for lookup
1201 $login = COMPILE_CODE($login);
1203 // Then try to find that user
1204 $result = SQL_QUERY_ESC("SELECT id, password, email FROM `{!_MYSQL_PREFIX!}_admins` WHERE login='%s' LIMIT 1",
1205 array($login), __FILE__, __LINE__);
1207 // Is an account here?
1208 if (SQL_NUMROWS($result) == 1) {
1210 $content = SQL_FETCHARRAY($result);
1212 // Generate hash again
1213 $hashFromData = generateHash(URL.":".$content['id'].":".$login.":".$content['password'], substr($content['password'], 10));
1216 $valid = ($hash == $hashFromData);
1220 SQL_FREERESULT($result);
1225 // Reset the password for the login. Do NOT call this function without calling above function first!
1226 function ADMIN_RESET_PASSWORD ($login, $password) {
1230 // Now check if we have sql_patches installed
1231 if (GET_EXT_VERSION("sql_patches") >= "0.3.6") {
1232 // Use new way of hashing
1233 $passHash = generateHash($password);
1236 $passHash = md5($password);
1240 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_admins` SET password='%s' WHERE login='%s' LIMIT 1",
1241 array($passHash, $login), __FILE__, __LINE__);
1244 RUN_FILTER('post_admin_reset_pass', array('login' => $login, 'hash' => $passHash));
1247 return ADMIN_PASSWORD_RESET_DONE;
1249 // Solves a task by given id number
1250 function ADMIN_SOLVE_TASK ($id) {
1251 // Update the task data
1252 ADMIN_UPDATE_TASK_DATA($id, "status", "SOLVED");
1254 // Marks a given task as deleted
1255 function ADMIN_DELETE_TASK ($id) {
1256 // Update the task data
1257 ADMIN_UPDATE_TASK_DATA($id, "status", "DELETED");
1259 // Function to update task data
1260 function ADMIN_UPDATE_TASK_DATA ($id, $row, $data) {
1262 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_task_system` SET %s='%s' WHERE id=%s LIMIT 1",
1263 array($row, $data, bigintval($id)), __FILE__, __LINE__);