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 * -------------------------------------------------------------------- *
15 * $Tag:: 0.2.1-FINAL $ *
17 * Needs to be in all Files and every File needs "svn propset *
18 * svn:keywords Date Revision" (autoprobset!) at least!!!!!! *
19 * -------------------------------------------------------------------- *
20 * Copyright (c) 2003 - 2008 by Roland Haeder *
21 * For more information visit: http://www.mxchange.org *
23 * This program is free software; you can redistribute it and/or modify *
24 * it under the terms of the GNU General Public License as published by *
25 * the Free Software Foundation; either version 2 of the License, or *
26 * (at your option) any later version. *
28 * This program is distributed in the hope that it will be useful, *
29 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
30 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
31 * GNU General Public License for more details. *
33 * You should have received a copy of the GNU General Public License *
34 * along with this program; if not, write to the Free Software *
35 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
37 ************************************************************************/
39 // Some security stuff...
40 if (!defined('__SECURITY')) {
41 $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), '/inc') + 4) . '/security.php';
45 // Register an administrator account
46 function REGISTER_ADMIN ($user, $md5, $email) {
47 // Login does already exist
51 $result = SQL_QUERY_ESC("SELECT id FROM `{!_MYSQL_PREFIX!}_admins` WHERE login='%s' LIMIT 1",
52 array($user), __FUNCTION__, __LINE__);
54 // Is the entry there?
55 if (SQL_NUMROWS($result) == 0) {
56 // Ok, let's create the admin login
57 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_admins` (login, password, email) VALUES ('%s', '%s', '%s')",
58 array($user, $md5, $email), __FUNCTION__, __LINE__);
63 SQL_FREERESULT($result);
69 // Only be executed on login procedure!
70 function CHECK_ADMIN_LOGIN ($admin_login, $password) {
71 // By default no admin is found
75 $aid = GET_ADMIN_ID($admin_login);
77 // Init array with admin id by default
78 $data = array('aid' => $aid);
80 // Is the cache valid?
81 if (isset($GLOBALS['cache_array']['admins']['password'][$aid])) {
82 // Get password from cache
83 $data['password'] = $GLOBALS['cache_array']['admins']['password'][$aid];
85 incrementConfigEntry('cache_hits');
87 // Include more admins data?
88 if (GET_EXT_VERSION('admins') >= '0.7.2') {
90 $data['login_failures'] = $GLOBALS['cache_array']['admins']['login_failures'][$aid];
91 $data['last_failure'] = $GLOBALS['cache_array']['admins']['last_failure'][$aid];
93 } elseif (!EXT_IS_ACTIVE('cache')) {
94 // Add extra data via filter now
95 $add = runFilterChain('sql_admin_extra_data');
97 // Get password from DB
98 $result = SQL_QUERY_ESC("SELECT password".$add." FROM `{!_MYSQL_PREFIX!}_admins` WHERE id=%s LIMIT 1",
99 array($aid), __FUNCTION__, __LINE__);
102 if (SQL_NUMROWS($result) == 1) {
103 // Login password found
107 $data = SQL_FETCHARRAY($result);
111 SQL_FREERESULT($result);
114 //* DEBUG: */ echo "*".$data['password']."/".md5($password)."/".$ret."<br />";
115 if ((isset($data['password'])) && (strlen($data['password']) == 32) && ($data['password'] == md5($password))) {
117 $data['password'] = generateHash($password);
119 // Is the sql_patches not installed, than we cannot have a valid hashed password here!
120 if (($ret == 'pass') && ((EXT_VERSION_IS_OLDER('sql_patches', '0.3.6')) || (GET_EXT_VERSION('sql_patches') == ""))) $ret = "done";
121 } elseif ((EXT_VERSION_IS_OLDER('sql_patches', '0.3.6')) || (GET_EXT_VERSION('sql_patches') == "")) {
124 } elseif (!isset($data['password'])) {
125 // Password not found, so no valid login!
129 // Generate salt of password
130 define('__SALT', substr($data['password'], 0, -40));
133 // Check if password is same
134 //* DEBUG: */ echo "*".$ret.",".$data['password'].",".$password.",".$salt."*<br >\n";
135 if (($ret == 'pass') && ($data['password'] == generateHash($password, $salt)) && ((!empty($salt))) || ($data['password'] == $password)) {
136 // Re-hash the plain passord with new random salt
137 $data['password'] = generateHash($password);
139 // Do we have 0.7.0 of admins or later?
140 // Remmeber login failures if available
141 if (GET_EXT_VERSION('admins') >= '0.7.2') {
142 // Store it in session
143 set_session('mxchange_admin_failures', $data['login_failures']);
144 set_session('mxchange_admin_last_fail', $data['last_failure']);
146 // Update password and reset login failures
147 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",
148 array($data['password'], $aid), __FUNCTION__, __LINE__);
151 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_admins` SET password='%s' WHERE id=%s LIMIT 1",
152 array($data['password'], $aid), __FUNCTION__, __LINE__);
156 rebuildCacheFiles('admins', 'admin');
158 // Login has failed by default... ;-)
161 // Password matches so login here
162 if (LOGIN_ADMIN($admin_login, $data['password'])) {
166 } elseif ((empty($salt)) && ($ret == 'pass')) {
167 // Something bad went wrong
169 } elseif ($ret == "done") {
170 // Try to login here if we have the old hashing way (sql_patches not installed?)
171 if (!LOGIN_ADMIN($admin_login, $data['password'])) {
172 // Something went wrong
177 // Count login failure if admins extension version is 0.7.0+
178 if (($ret == 'pass') && (GET_EXT_VERSION('admins') >= '0.7.0')) {
180 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_admins` SET login_failures=login_failures+1,last_failure=NOW() WHERE id=%s LIMIT 1",
181 array($aid), __FUNCTION__, __LINE__);
184 rebuildCacheFiles('admins', 'admin');
188 //* DEBUG: */ die("RETURN=".$ret);
192 // Try to login the admin by setting some session/cookie variables
193 function LOGIN_ADMIN ($adminLogin, $passHash) {
194 // Reset failure counter on matching admins version
195 if ((GET_EXT_VERSION('admins') >= '0.7.0') && ((EXT_VERSION_IS_OLDER('sql_patches', '0.3.6')) || (GET_EXT_VERSION('sql_patches') == ""))) {
196 // Reset counter on out-dated sql_patches version
197 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_admins` SET login_failures=0,last_failure='0000-00-00 00:00:00' WHERE login='%s' LIMIT 1",
198 array($adminLogin), __FUNCTION__, __LINE__);
201 rebuildCacheFiles('admins', 'admin');
204 // Now set all session variables and return the result
207 set_session('admin_md5', generatePassString($passHash))
209 set_session('admin_login', $adminLogin)
211 set_session('admin_last', time())
213 set_session('admin_to', bigintval(REQUEST_POST('timeout')))
218 // Only be executed on cookie checking
219 function CHECK_ADMIN_COOKIES ($admin_login, $password) {
220 // By default no admin cookies are found
221 $ret = "404"; $pass = '';
224 $pass = GET_ADMIN_HASH(GET_ADMIN_ID($admin_login));
225 if ($pass != "-1") $ret = 'pass';
227 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):".generatePassString($pass)."(".strlen($pass).")/".$password."(".strlen($password).")<br />\n";
229 // Check if password matches
230 if (($ret == 'pass') && ((generatePassString($pass) == $password) || ($pass == $password) || ((strlen($pass) == 32) && (md5($password) == $pass)))) {
231 // Passwords matches!
240 function ADMIN_DO_ACTION ($wht) {
242 //* DEBUG: */ echo __LINE__."*".$wht."/".$GLOBALS['module']."/".$GLOBALS['action']."/".$GLOBALS['what']."*<br />\n";
244 // Remove any spaces from variable
246 // Default admin action is the overview page
249 // Compile out some chars
250 $wht = COMPILE_CODE($wht, false, false, false);
254 $act = GET_ACTION($GLOBALS['module'], $wht);
256 // Define admin login name and ID number
257 define('__ADMIN_LOGIN', get_session('admin_login'));
258 define('__ADMIN_ID' , GET_CURRENT_ADMIN_ID());
261 if (EXT_IS_ACTIVE('admins')) {
262 define('__ADMIN_WELCOME', LOAD_TEMPLATE("admin_welcome_admins", true));
264 define('__ADMIN_WELCOME', LOAD_TEMPLATE("admin_welcome", true));
266 define('__ADMIN_FOOTER' , LOAD_TEMPLATE("admin_footer" , true));
267 define('__ADMIN_MENU' , ADD_ADMIN_MENU($act, $wht, true));
270 LOAD_TEMPLATE("admin_main_header");
272 // Check if action/what pair is valid
273 $result_action = SQL_QUERY_ESC("SELECT id FROM `{!_MYSQL_PREFIX!}_admin_menu`
274 WHERE `action`='%s' AND ((`what`='%s' AND what != 'overview') OR ((`what`='' OR `what` IS NULL) AND '%s'='overview'))
275 LIMIT 1", array($act, $wht, $wht), __FUNCTION__, __LINE__);
276 if (SQL_NUMROWS($result_action) == 1) {
277 // Is valid but does the inlcude file exists?
278 $INC = sprintf("inc/modules/admin/action-%s.php", $act);
279 if ((INCLUDE_READABLE($INC)) && (VALIDATE_MENU_ACTION('admin', $act, $wht)) && ($GLOBALS['acl_allow'] === true)) {
280 // Ok, we finally load the admin action module
282 } elseif ($GLOBALS['acl_allow'] === false) {
284 LOAD_TEMPLATE("admin_menu_failed", false, getMessage('ADMIN_ACCESS_DENIED'));
285 addFatalMessage(__FUNCTION__, __LINE__, getMessage('ADMIN_ACCESS_DENIED'));
287 // Include file not found! :-(
288 LOAD_TEMPLATE("admin_menu_failed", false, sprintf(getMessage('ADMIN_ACTION_404'), $act));
289 addFatalMessage(__FUNCTION__, __LINE__, getMessage('ADMIN_ACTION_404'), $act);
292 // Invalid action/what pair found!
293 LOAD_TEMPLATE("admin_menu_failed", false, sprintf(getMessage('ADMIN_ACTION_INVALID'), $act."/".$wht));
294 addFatalMessage(__FUNCTION__, __LINE__, getMessage('ADMIN_ACTION_INVALID'), $act."/".$wht);
298 SQL_FREERESULT($result_action);
301 LOAD_TEMPLATE("admin_main_footer");
305 function ADD_ADMIN_MENU ($act, $wht, $return=false) {
311 $GLOBALS['menu']['description'] = array();
312 $GLOBALS['menu']['title'] = array();
314 // Is there a cache instance?
315 if ((isCacheInstanceValid()) && (getConfig('cache_admin_menu') == 'Y')) {
317 $cacheName = "admin_".$act."_".$wht."_".GET_LANGUAGE()."_".strtolower(get_session('admin_login'));
319 // Is that cache there?
320 if ($GLOBALS['cache_instance']->loadCacheFile($cacheName)) {
322 $data = $GLOBALS['cache_instance']->getArrayFromCache();
325 $OUT = base64_decode($data['output'][0]);
326 $GLOBALS['menu']['title'] = unserialize(base64_decode($data['title'][0]));
327 $GLOBALS['menu']['description'] = unserialize(base64_decode($data['descr'][0]));
329 // Return or output content?
330 if ($return === true) {
339 $result_main = SQL_QUERY("SELECT action, title, descr FROM `{!_MYSQL_PREFIX!}_admin_menu` WHERE (`what`='' OR `what` IS NULL) ORDER BY `sort`, id DESC", __FUNCTION__, __LINE__);
340 if (SQL_NUMROWS($result_main) > 0) {
341 $OUT = "<div style=\"height:7px\" class=\"seperator\"> </div>\n";
342 $OUT .= "<ul class=\"admin_menu_main\">\n";
343 // @TODO Rewrite this to $content = SQL_FETCHARRAY()
344 while (list($menu, $title, $descr) = SQL_FETCHROW($result_main)) {
345 if ((EXT_IS_ACTIVE('admins')) && (GET_EXT_VERSION('admins') > '0.2.0')) {
346 $ACL = ADMINS_CHECK_ACL($menu, '');
348 // ACL is "allow"... hmmm
354 // Insert compiled menu title and description
355 $GLOBALS['menu']['title'][$menu] = $title;
356 $GLOBALS['menu']['description'][$menu] = $descr;
358 $OUT .= "<li class=\"admin_menu\">
359 <div class=\"nobr\"><strong>·</strong> ";
361 if (($menu == $act) && (empty($wht))) {
364 $OUT .= "[<a href=\"{!URL!}/modules.php?module=admin&action=".$menu."\">";
369 if (($menu == $act) && (empty($wht))) {
378 // Check for menu entries
379 $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",
380 array($menu), __FUNCTION__, __LINE__);
382 // Remember the count for later checks
383 setAdminMenuHasEntries($menu, ((SQL_NUMROWS($result_what) > 0) && ($act == $menu)));
385 // Do we have entries?
386 if ((ifAdminMenuHasEntries($menu)) && (SQL_NUMROWS($result_what) > 0)) {
387 $GLOBALS['menu']['description'] = array();
388 $GLOBALS['menu']['title'] = array(); $SUB = true;
389 $OUT .= "<ul class=\"admin_menu_sub\">\n";
390 // @TODO Rewrite this to $content = SQL_FETCHARRAY()
391 while (list($wht_sub, $title_what, $desc_what) = SQL_FETCHROW($result_what)) {
393 $INC = sprintf("inc/modules/admin/what-%s.php", $wht_sub);
394 if ((EXT_IS_ACTIVE('admins')) && (GET_EXT_VERSION('admins') > '0.2.0')) {
395 $ACL = ADMINS_CHECK_ACL("", $wht_sub);
397 // ACL is "allow"... hmmm
401 // Is the file readable?
402 $readable = INCLUDE_READABLE($INC);
406 // Insert compiled title and description
407 $GLOBALS['menu']['title'][$wht_sub] = $title_what;
408 $GLOBALS['menu']['description'][$wht_sub] = $desc_what;
409 $OUT .= "<li class=\"admin_menu\">
410 <div class=\"nobr\"><strong>--></strong> ";
411 if ($readable === true) {
412 if ($wht == $wht_sub) {
415 $OUT .= "[<a href=\"{!URL!}/modules.php?module=admin&what=".$wht_sub."\">";
418 $OUT .= "<em class=\"admin_note\">";
423 if ($readable === true) {
424 if ($wht == $wht_sub) {
438 SQL_FREERESULT($result_what);
443 $OUT .= "<li style=\"height:7px\" class=\"seperator\"> </li>\n";
448 SQL_FREERESULT($result_main);
452 // Is there a cache instance again?
453 if ((isCacheInstanceValid()) && (getConfig('cache_admin_menu') == 'Y')) {
455 $GLOBALS['cache_instance']->init($cacheName);
457 // Prepare cache data
459 'output' => base64_encode($OUT),
460 'title' => $GLOBALS['menu']['title'],
461 'descr' => $GLOBALS['menu']['description']
464 // Write the data away
465 $GLOBALS['cache_instance']->addRow($data);
468 $GLOBALS['cache_instance']->finalize();
471 // Return or output content?
472 if ($return === true) {
479 // Create member selection box
480 function ADD_MEMBER_SELECTION_BOX ($def="0", $add_all=false, $return=false, $none=false, $field='userid') {
481 // Output selection form with all confirmed user accounts listed
482 $result = SQL_QUERY("SELECT userid, surname, family FROM `{!_MYSQL_PREFIX!}_user_data` ORDER BY userid", __FUNCTION__, __LINE__);
487 // USe this only for adding points (e.g. adding refs really makes no sence ;-) )
488 if ($add_all === true) $OUT = " <option value=\"all\">{--ALL_MEMBERS--}</option>\n";
489 elseif ($none === true) $OUT = " <option value=\"0\">{--SELECT_NONE--}</option>\n";
491 while ($content = SQL_FETCHARRAY($result)) {
492 $OUT .= " <option value=\"".bigintval($content['userid'])."\"";
493 if ($def == $content['userid']) $OUT .= ' selected="selected"';
494 $OUT .= ">".$content['surname']." ".$content['family']." (".bigintval($content['userid']).")</option>\n";
498 SQL_FREERESULT($result);
501 // Remeber options in constant
502 // @TODO Rewrite these both constants
503 define('_MEMBER_SELECTION', $OUT);
505 // Display selection box
506 define('__LANG_VALUE', GET_LANGUAGE());
509 LOAD_TEMPLATE("admin_member_selection_box", false, $GLOBALS['what']);
511 // Return content in selection frame
512 return "<select class=\"admin_select\" name=\"".$field."\" size=\"1\">\n".$OUT."</select>\n";
516 // Create a menu selection box for given menu system
517 function ADMIN_MENU_SELECTION ($mode, $default="", $defid="") {
518 $wht = "`what` != ''";
519 if ($mode == "action") $wht = "(`what`='' OR `what` IS NULL) AND action !='login'";
520 $result = SQL_QUERY_ESC("SELECT %s, title FROM `{!_MYSQL_PREFIX!}_admin_menu` WHERE ".$wht." ORDER BY `sort`",
521 array($mode), __FUNCTION__, __LINE__);
522 if (SQL_NUMROWS($result) > 0) {
523 // Load menu as selection
524 $OUT = "<select name=\"".$mode."_menu";
525 if ((!empty($defid)) || ($defid == "0")) $OUT .= "[".$defid."]";
526 $OUT .= "\" size=\"1\" class=\"admin_select\">
527 <option value=\"\">{--SELECT_NONE--}</option>\n";
528 // @TODO Try to rewrite this to $content = SQL_FETCHARRAY(). Please look some lines above for the dynamic query
529 while (list($menu, $title) = SQL_FETCHROW($result)) {
530 $OUT .= " <option value=\"".$menu."\"";
531 if ((!empty($default)) && ($default == $menu)) $OUT .= ' selected="selected"';
532 $OUT .= ">".$title."</option>\n";
536 SQL_FREERESULT($result);
537 $OUT .= "</select>\n";
540 $OUT = getMessage('ADMIN_PROBLEM_NO_MENU');
547 // Wrapper for $_POST and ADMIN_SAVE_SETTINGS
548 function ADMIN_SAVE_SETTINGS_POST () {
550 $POST = REQUEST_POST_ARRAY();
552 // Call the lower function
553 ADMIN_SAVE_SETTINGS($POST);
556 // Save settings to the database
557 function ADMIN_SAVE_SETTINGS (&$POST, $tableName = "_config", $whereStatement = "config=0", $translateComma = array(), $alwaysAdd = false) {
558 // Prepare all arrays, variables
562 // Now, walk through all entries and prepare them for saving
563 foreach ($POST as $id => $val) {
564 // Process only formular field but not submit buttons ;)
566 // Do not save the ok value
567 CONVERT_SELECTIONS_TO_TIMESTAMP($POST, $DATA, $id, $skip);
569 // Shall we process this ID? It muss not be empty, of course
570 if ((!$skip) && (!empty($id))) {
572 $val = COMPILE_CODE($val);
574 // Translate the value? (comma to dot!)
575 if ((is_array($translateComma)) && (in_array($id, $translateComma))) {
576 // Then do it here... :)
577 $val = REVERT_COMMA($val);
580 // Shall we add numbers or strings?
582 if ("".$val."" == "".$test."") {
584 $DATA[] = sprintf("`%s`=%s", $id, $test);
587 $DATA[] = sprintf("`%s`='%s'", $id, trim($val));
590 // Update current configuration
591 setConfigEntry($id, $val);
596 // Check if entry does exist
599 if (!empty($whereStatement)) {
600 $result = SQL_QUERY("SELECT * FROM `{!_MYSQL_PREFIX!}".$tableName."` WHERE ".$whereStatement." LIMIT 1", __FUNCTION__, __LINE__);
602 $result = SQL_QUERY("SELECT * FROM `{!_MYSQL_PREFIX!}".$tableName."` LIMIT 1", __FUNCTION__, __LINE__);
606 if (SQL_NUMROWS($result) == 1) {
607 // "Implode" all data to single string
608 $DATA_UPDATE = implode(", ", $DATA);
610 // Generate SQL string
611 $sql = sprintf("UPDATE `{!_MYSQL_PREFIX!}%s` SET %s WHERE %s LIMIT 1",
617 // Add Line (does only work with auto_increment!
618 $KEYs = array(); $VALUEs = array();
619 foreach ($DATA as $entry) {
621 $line = explode("=", $entry);
622 $KEYs[] = $line[0]; $VALUEs[] = $line[1];
625 // Add both in one line
626 $KEYs = implode(", ", $KEYs);
627 $VALUEs = implode(", ", $VALUEs);
629 // Generate SQL string
630 $sql = sprintf("INSERT INTO {!_MYSQL_PREFIX!}%s (%s) VALUES (%s)",
638 SQL_FREERESULT($result);
640 // Simply run generated SQL string
641 SQL_QUERY($sql, __FUNCTION__, __LINE__);
644 rebuildCacheFiles("config", "config");
647 LOAD_TEMPLATE('admin_settings_saved', false, getMessage('SETTINGS_SAVED'));
650 // Generate a selection box
651 function ADMIN_MAKE_MENU_SELECTION ($menu, $type, $name, $default="") {
652 // Open the requested menu directory
653 $menuArray = GET_DIR_AS_ARRAY(sprintf("inc/modules/%s/", $menu), '', false, false);
655 // Init the selection box
656 $OUT = "<select name=\"".$name."\" class=\"admin_select\" size=\"1\">
657 <option value=\"\">{--IS_TOP_MENU--}</option>\n";
659 // Walk through all files
660 foreach ($menuArray as $file) {
661 // Is this a PHP script?
662 if (($file != ".") && ($file != "..") && ($file != "lost+found") && (strpos($file, "".$type."-") > -1) && (strpos($file, ".php") > 0)) {
663 // Then test if the file is readable
664 $test = sprintf("%sinc/modules/%s/%s", constant('PATH'), $menu, $file);
666 // Is the file there?
667 if (FILE_READABLE($test)) {
668 // Extract the value for what=xxx
669 $part = substr($file, (strlen($type) + 1));
670 $part = substr($part, 0, -4);
672 // Is that part different from the overview?
673 if ($part != "overview") {
674 $OUT .= " <option value=\"".$part."\"";
675 if ($part == $default) $OUT .= ' selected="selected"';
676 $OUT .= ">".$part."</option>\n";
682 // Close selection box
683 $OUT .= "</select>\n";
689 // Creates a user-profile link for the admin. This function can also be used for many other purposes
690 function ADMIN_USER_PROFILE_LINK ($uid, $title="", $wht="list_user") {
691 if (($title == "") && ($title != "0")) {
692 // Set userid as title
696 if (($title == "0") && ($wht == "list_refs")) {
697 // Return title again
701 //* DEBUG: */ echo "a:".$title."<br />";
703 return "<a href=\"{!URL!}/modules.php?module=admin&what=".$wht."&uid=".$uid."\" title=\"{--ADMIN_USER_PROFILE_TITLE--}\">".$title."</a>";
706 // Check "logical-area-mode"
707 function ADMIN_CHECK_MENU_MODE () {
708 // Set the global mode as the mode for all admins
709 $mode = getConfig('admin_menu');
713 $aid = GET_CURRENT_ADMIN_ID();
715 // Check individual settings of current admin
716 if (isset($GLOBALS['cache_array']['admins']['la_mode'][$aid])) {
718 $ADMIN = $GLOBALS['cache_array']['admins']['la_mode'][$aid];
719 incrementConfigEntry('cache_hits');
720 } elseif (GET_EXT_VERSION('admins') >= '0.6.7') {
721 // Load from database when version of 'admins' is enough
722 $result = SQL_QUERY_ESC("SELECT la_mode FROM `{!_MYSQL_PREFIX!}_admins` WHERE id=%s LIMIT 1",
723 array($aid), __FUNCTION__, __LINE__);
724 if (SQL_NUMROWS($result) == 1) {
726 list($ADMIN) = SQL_FETCHROW($result);
730 SQL_FREERESULT($result);
733 // Check what the admin wants and set it when it's not the global mode
734 if ($ADMIN != "global") $mode = $ADMIN;
736 // Return admin-menu's mode
740 // Change activation status
741 function ADMIN_CHANGE_ACTIVATION_STATUS ($IDs, $table, $row, $idRow = "id") {
742 $cnt = 0; $newStatus = "Y";
743 if ((is_array($IDs)) && (count($IDs) > 0)) {
744 // "Walk" all through and count them
745 foreach ($IDs as $id => $selected) {
746 // Secure the ID number
747 $id = bigintval($id);
749 // Should always be set... ;-)
750 if (!empty($selected)) {
751 // Determine new status
752 $result = SQL_QUERY_ESC("SELECT %s FROM `{!_MYSQL_PREFIX!}_%s` WHERE %s=%s LIMIT 1",
753 array($row, $table, $idRow, $id), __FUNCTION__, __LINE__);
756 if (SQL_NUMROWS($result) == 1) {
758 list($currStatus) = SQL_FETCHROW($result);
760 // And switch it N<->Y
761 if ($currStatus == 'Y') $newStatus = "N"; else $newStatus = "Y";
763 // Change this status
764 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_%s` SET %s='%s' WHERE %s=%s LIMIT 1",
765 array($table, $row, $newStatus, $idRow, $id), __FUNCTION__, __LINE__);
767 // Count up affected rows
768 $cnt += SQL_AFFECTEDROWS();
772 SQL_FREERESULT($result);
777 LOAD_TEMPLATE('admin_settings_saved', false, sprintf(getMessage('ADMIN_STATUS_CHANGED'), $cnt, count($IDs)));
780 LOAD_TEMPLATE('admin_settings_saved', false, getMessage('ADMIN_NOTHING_SELECTED_CHANGE'));
784 // Send mails for del/edit/lock build modes
785 function ADMIN_SEND_BUILD_MAILS ($mode, $table, $content, $id, $subjectPart="") {
786 // Default subject is the subject part
787 $subject = $subjectPart;
789 // Is the subject part not set?
790 if (empty($subjectPart)) {
791 // Then use it from the mode
792 $subject = strtoupper($mode);
795 // Is the raw userid set?
796 if (REQUEST_POST('uid_raw', $id) > 0) {
798 $subjectLine = getMessage('MEMBER_'.strtoupper($subject).'_'.strtoupper($table).'_SUBJECT');
800 // Load email template
801 if (!empty($subjectPart)) {
802 $mail = LOAD_EMAIL_TEMPLATE("member_".$mode."_".strtolower($subjectPart)."_".$table, $content);
804 $mail = LOAD_EMAIL_TEMPLATE("member_".$mode."_".$table, $content);
808 SEND_EMAIL(REQUEST_POST('uid_raw', $id), $subjectLine, $mail);
812 $subjectLine = getMessage('ADMIN_'.strtoupper($subject).'_'.strtoupper($table).'_SUBJECT');
814 // Send admin notification out
815 if (!empty($subjectPart)) {
816 SEND_ADMIN_NOTIFICATION($subjectLine, "admin_".$mode."_".strtolower($subjectPart)."_".$table, $content, REQUEST_POST('uid_raw', $id));
818 SEND_ADMIN_NOTIFICATION($subjectLine, "admin_".$mode."_".$table, $content, REQUEST_POST('uid_raw', $id));
822 // Build a special template list
823 function ADMIN_BUILD_LIST ($listType, $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn) {
826 // "Walk" through all entries
827 foreach ($IDs as $id => $selected) {
829 $id = bigintval($id);
831 // Get result from a given column array and table name
832 $result = SQL_RESULT_FROM_ARRAY($table, $columns, $idColumn, $id, __FUNCTION__, __LINE__);
834 // Is there one entry?
835 if (SQL_NUMROWS($result) == 1) {
837 $content = SQL_FETCHARRAY($result);
840 foreach ($content as $key => $value) {
842 $idx = array_search($key, $columns, true);
844 // Do we have a userid?
845 if ($key == 'userid') {
846 // Add it again as raw id
847 $content['uid'] = bigintval($value);
850 // Handle the call in external function
851 $content[$key] = HANDLE_EXTRA_VALUES($filterFunctions[$idx], $value, $extraValues[$idx]);
854 // Add color switching
855 $content['sw'] = $SW;
858 $OUT .= LOAD_TEMPLATE(sprintf("admin_%s_%s_row",
869 SQL_FREERESULT($result);
872 // Load master template
873 LOAD_TEMPLATE(sprintf("admin_%s_%s",
880 // Change status of "build" list
881 function ADMIN_BUILD_STATUS_HANDLER ($mode, $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray) {
882 // All valid entries? (We hope so here!)
883 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues)) && (count($statusArray) > 0)) {
884 // "Walk" through all entries
885 foreach ($IDs as $id => $sel) {
886 // Construct SQL query
887 $sql = sprintf("UPDATE `{!_MYSQL_PREFIX!}_%s` SET",
891 // Load data of entry
892 $result = SQL_QUERY_ESC("SELECT * FROM `{!_MYSQL_PREFIX!}_%s` WHERE %s=%s LIMIT 1",
893 array($table, $idColumn, $id), __FUNCTION__, __LINE__);
896 $content = SQL_FETCHARRAY($result);
899 SQL_FREERESULT($result);
901 // Add all status entries (e.g. status column last_updated or so)
902 $newStatus = "UNKNOWN";
903 $oldStatus = "UNKNOWN";
904 $statusColumn = "unknown";
905 foreach ($statusArray as $column => $statusInfo) {
906 // Does the entry exist?
907 if ((isset($content[$column])) && (isset($statusInfo[$content[$column]]))) {
908 // Add these entries for update
909 $sql .= sprintf(" %s='%s',", SQL_ESCAPE($column), SQL_ESCAPE($statusInfo[$content[$column]]));
912 if ($statusColumn == "unknown") {
913 // Always (!!!) change status column first!
914 $oldStatus = $content[$column];
915 $newStatus = $statusInfo[$oldStatus];
916 $statusColumn = $column;
918 } elseif (isset($content[$column])) {
920 app_die(__FUNCTION__, __LINE__, ":UNFINISHED: id={$id}/{$column}[".gettype($statusInfo)."] = {$content[$column]}");
924 // Add other columns as well
925 foreach (REQUEST_POST_ARRAY() as $key => $entries) {
926 // Skip id, raw userid and 'do_$mode'
927 if (!in_array($key, array($idColumn, 'uid_raw', ('do_'.$mode)))) {
928 // Are there brackets () at the end?
929 if (substr($entries[$id], -2, 2) == "()") {
930 // Direct SQL command found
931 $sql .= sprintf(" %s=%s,", SQL_ESCAPE($key), SQL_ESCAPE($entries[$id]));
934 $sql .= sprintf(" %s='%s',", SQL_ESCAPE($key), SQL_ESCAPE($entries[$id]));
937 $content[$key] = $entries[$id];
942 // Finish SQL statement
943 $sql = substr($sql, 0, -1) . sprintf(" WHERE `%s`=%s AND `%s`='%s' LIMIT 1",
951 SQL_QUERY($sql, __FUNCTION__, __LINE__);
953 // Do we have an URL?
954 if (isset($content['url'])) {
955 // Then add a framekiller test as well
956 $content['frametester'] = FRAMETESTER($content['url']);
959 // Send "build mails" out
960 ADMIN_SEND_BUILD_MAILS($mode, $table, $content, $id, $statusInfo[$content[$column]]);
965 // Delete rows by given ID numbers
966 function ADMIN_DELETE_ENTRIES_CONFIRM ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $deleteNow=false, $idColumn="id", $userIdColumn='userid') {
967 // All valid entries? (We hope so here!)
968 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues))) {
969 // Shall we delete here or list for deletion?
971 // The base SQL command:
972 $sql = "DELETE LOW_PRIORITY FROM `{!_MYSQL_PREFIX!}_%s` WHERE %s IN (%s)";
976 foreach ($IDs as $id => $sel) {
977 // Is there a userid?
978 if (REQUEST_ISSET_POST('uid_raw', $id)) {
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), __FUNCTION__, __LINE__);
984 $content = SQL_FETCHARRAY($result);
987 SQL_FREERESULT($result);
989 // Send "build mails" out
990 ADMIN_SEND_BUILD_MAILS("del", $table, $content, $id);
998 SQL_QUERY($sql, array($table, $idColumn, substr($idList, 0, -1)), __FUNCTION__, __LINE__);
1001 if (SQL_AFFECTEDROWS() == count($IDs)) {
1003 LOAD_TEMPLATE('admin_settings_saved', false, getMessage('ADMIN_ALL_ENTRIES_REMOVED'));
1005 // Some are still there :(
1006 LOAD_TEMPLATE('admin_settings_saved', false, sprintf(getMessage('ADMIN_SOME_ENTRIES_NOT_DELETED'), SQL_AFFECTEDROWS(), count($IDs)));
1009 // List for deletion confirmation
1010 ADMIN_BUILD_LIST("del", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1015 // Edit rows by given ID numbers
1016 function ADMIN_EDIT_ENTRIES_CONFIRM ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $editNow=false, $idColumn="id", $userIdColumn='userid') {
1017 // All valid entries? (We hope so here!)
1018 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues))) {
1019 // Shall we change here or list for editing?
1023 foreach ($IDs as $id => $sel) {
1024 // Prepare content array (new values)
1027 // Prepare SQL for this row
1028 $sql = sprintf("UPDATE `{!_MYSQL_PREFIX!}_ SET",
1031 foreach (REQUEST_POST_ARRAY() as $key => $entries) {
1032 // Skip raw userid which is always invalid
1033 if ($key == "uid_raw") {
1034 // Continue with next field
1038 // Is entries an array?
1039 if (($key != $idColumn) && (is_array($entries)) && (isset($entries[$id]))) {
1040 // Add this entry to content
1041 $content[$key] = $entries[$id];
1043 // Send data through the filter function if found
1044 if ((isset($filterFunctions[$key])) && (isset($extraValues[$key]))) {
1045 // Filter function set!
1046 $entries[$id] = HANDLE_EXTRA_VALUES($filterFunctions[$key], $entries[$id], $extraValues[$key]);
1049 // Then add this value
1050 $sql .= sprintf(" %s='%s',",
1052 SQL_ESCAPE($entries[$id])
1054 } elseif (($key != $idColumn) && (!is_array($entries))) {
1055 // Add normal entries as well!
1056 $content[$key] = $entries;
1059 // Do we have an URL?
1060 if ($key == "url") {
1061 // Then add a framekiller test as well
1062 $content['frametester'] = FRAMETESTER($content[$key]);
1066 // Finish SQL command
1067 $sql = substr($sql, 0, -1) . " WHERE ".$idColumn."=".bigintval($id)." LIMIT 1";
1070 SQL_QUERY($sql, __FUNCTION__, __LINE__);
1072 // Add affected rows
1073 $affected += SQL_AFFECTEDROWS();
1075 // Load all data from that id
1076 $result = SQL_QUERY_ESC("SELECT * FROM `{!_MYSQL_PREFIX!}_%s` WHERE %s=%s LIMIT 1",
1077 array($table, $idColumn, $id), __FUNCTION__, __LINE__);
1081 $DATA = SQL_FETCHARRAY($result);
1084 SQL_FREERESULT($result);
1086 // Send "build mails" out
1087 ADMIN_SEND_BUILD_MAILS("edit", $table, $content, $id);
1091 if ($affected == count($IDs)) {
1093 LOAD_TEMPLATE('admin_settings_saved', false, getMessage('ADMIN_ALL_ENTRIES_EDITED'));
1095 // Some are still there :(
1096 LOAD_TEMPLATE('admin_settings_saved', false, sprintf(getMessage('ADMIN_SOME_ENTRIES_NOT_EDITED'), $affected, count($IDs)));
1100 ADMIN_BUILD_LIST("edit", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1105 // Un-/lock rows by given ID numbers
1106 function ADMIN_LOCK_ENTRIES_CONFIRM ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $statusArray=array(), $lockNow=false, $idColumn="id", $userIdColumn='userid') {
1107 // All valid entries? (We hope so here!)
1108 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues)) && ((!$lockNow) || (count($statusArray) == 1))) {
1109 // Shall we un-/lock here or list for locking?
1112 ADMIN_BUILD_STATUS_HANDLER("lock", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray);
1115 ADMIN_BUILD_LIST("lock", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1120 // Undelete rows by given ID numbers
1121 function ADMIN_UNDELETE_ENTRIES_CONFIRM ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $statusArray=array(), $lockNow=false, $idColumn="id", $userIdColumn='userid') {
1122 // All valid entries? (We hope so here!)
1123 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues)) && ((!$lockNow) || (count($statusArray) == 1))) {
1124 // Shall we un-/lock here or list for locking?
1127 ADMIN_BUILD_STATUS_HANDLER("undelete", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray);
1130 ADMIN_BUILD_LIST("undelete", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1135 // Checks proxy settins by fetching check-updates3.php from www.mxchange.org
1136 function ADMIN_TEST_PROXY_SETTINGS ($settingsArray) {
1137 // Set temporary the new settings
1138 mergeConfig($settingsArray);
1140 // Now get the test URL
1141 $content = GET_URL("check-updates3.php");
1143 // Is the first line with "200 OK"?
1144 $valid = eregi("200 OK", $content[0]);
1150 // Sends out a link to the given email adress so the admin can reset his/her password
1151 function ADMIN_SEND_PASSWORD_RESET_LINK ($email) {
1155 // Compile out security characters (must be for looking up!)
1156 $email = COMPILE_CODE($email);
1158 // Look up administator login
1159 $result = SQL_QUERY_ESC("SELECT id, login, password FROM `{!_MYSQL_PREFIX!}_admins` WHERE email='%s' LIMIT 1",
1160 array($email), __FUNCTION__, __LINE__);
1162 // Is there an account?
1163 if (SQL_NUMROWS($result) == 0) {
1164 // No account found!
1165 return getMessage('ADMIN_NO_LOGIN_WITH_EMAIL');
1169 $content = SQL_FETCHARRAY($result);
1172 SQL_FREERESULT($result);
1174 // Generate hash for reset link
1175 $content['hash'] = generateHash(URL.":".$content['id'].":".$content['login'].":".$content['password'], substr($content['password'], 10));
1178 unset($content['id']);
1179 unset($content['password']);
1182 $mailText = LOAD_EMAIL_TEMPLATE("admin_reset_password", $content);
1185 SEND_EMAIL($email, getMessage('ADMIN_RESET_PASS_LINK_SUBJ'), $mailText);
1188 return getMessage('ADMIN_RESET_LINK_SENT');
1191 // Validate hash and login for password reset
1192 function ADMIN_VALIDATE_RESET_LINK_HASH_LOGIN ($hash, $login) {
1193 // By default nothing validates... ;)
1196 // Compile the login for lookup
1197 $login = COMPILE_CODE($login);
1199 // Then try to find that user
1200 $result = SQL_QUERY_ESC("SELECT id, password, email FROM `{!_MYSQL_PREFIX!}_admins` WHERE login='%s' LIMIT 1",
1201 array($login), __FUNCTION__, __LINE__);
1203 // Is an account here?
1204 if (SQL_NUMROWS($result) == 1) {
1206 $content = SQL_FETCHARRAY($result);
1208 // Generate hash again
1209 $hashFromData = generateHash(URL.":".$content['id'].":".$login.":".$content['password'], substr($content['password'], 10));
1212 $valid = ($hash == $hashFromData);
1216 SQL_FREERESULT($result);
1222 // Reset the password for the login. Do NOT call this function without calling above function first!
1223 function ADMIN_RESET_PASSWORD ($login, $password) {
1227 // Now check if we have sql_patches installed
1228 if (GET_EXT_VERSION('sql_patches') >= '0.3.6') {
1229 // Use new way of hashing
1230 $passHash = generateHash($password);
1233 $passHash = md5($password);
1237 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_admins` SET password='%s' WHERE login='%s' LIMIT 1",
1238 array($passHash, $login), __FUNCTION__, __LINE__);
1241 runFilterChain('post_admin_reset_pass', array('login' => $login, 'hash' => $passHash));
1244 return ADMIN_PASSWORD_RESET_DONE;
1247 // Solves a task by given id number
1248 function ADMIN_SOLVE_TASK ($id) {
1249 // Update the task data
1250 ADMIN_UPDATE_TASK_DATA($id, "status", "SOLVED");
1253 // Marks a given task as deleted
1254 function ADMIN_DELETE_TASK ($id) {
1255 // Update the task data
1256 ADMIN_UPDATE_TASK_DATA($id, "status", "DELETED");
1259 // Function to update task data
1260 function ADMIN_UPDATE_TASK_DATA ($id, $row, $data) {
1261 // Is the id not set, then we need a backtrace here... :(
1263 // Initiate backtrace
1264 debug_report_bug(sprintf("id is invalid: %s. row=%s, data=%s",
1272 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_task_system` SET %s='%s' WHERE id=%s LIMIT 1",
1273 array($row, $data, bigintval($id)), __FUNCTION__, __LINE__);
1276 // Checks wether if the admin menu has entries
1277 function ifAdminMenuHasEntries ($action) {
1280 isset($GLOBALS['admin_menu_has_entries'][$action])
1282 $GLOBALS['admin_menu_has_entries'][$action] === true
1289 // Setter for 'admin_menu_has_entries'
1290 function setAdminMenuHasEntries ($action, $hasEntries) {
1291 $GLOBALS['admin_menu_has_entries'][$action] = (bool) $hasEntries;
1294 // Creates a link to the user's admin-profile
1295 function ADMIN_CREATE_USERID_LINK ($uid) {
1296 // Is the userid set correctly?
1298 // Create a link to that profile
1299 return "{!URL!}/modules.php?module=admin&what=list_user&uid=".bigintval($uid);
1302 // Return a link to the user list
1303 return "{!URL!}/modules.php?module=admin&what=list_user";