2 /************************************************************************
3 * Mailer v0.2.1-FINAL 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 - 2009 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')) {
44 // Register an administrator account
45 function addAdminAccount ($user, $md5, $email) {
46 // Login does already exist
50 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
51 array($user), __FUNCTION__, __LINE__);
53 // Is the entry there?
54 if (SQL_NUMROWS($result) == '0') {
55 // Ok, let's create the admin login
56 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_admins` (`login`, `password`, `email`) VALUES ('%s', '%s', '%s')",
61 ), __FUNCTION__, __LINE__);
68 SQL_FREERESULT($result);
74 // Only be executed on login procedure!
75 function ifAdminLoginDataIsValid ($admin, $password) {
76 // By default no admin is found
80 $adminId = getAdminId($admin);
82 // Init array with admin id by default
83 $data = array('admin_id' => $adminId);
85 // Is the cache valid?
86 if (isAdminHashSet($admin)) {
87 // Get password from cache
88 $data['password'] = getAdminHash($admin);
90 incrementStatsEntry('cache_hits');
92 // Include more admins data?
93 if ((isExtensionInstalledAndNewer('admins', '0.7.2')) && (isset($GLOBALS['cache_array']['admin']['login_failures'][$adminId]))) {
95 $data['login_failures'] = $GLOBALS['cache_array']['admin']['login_failures'][$adminId];
96 $data['last_failure'] = $GLOBALS['cache_array']['admin']['last_failure'][$adminId];
98 } elseif (!isExtensionActive('cache')) {
99 // Add extra data via filter now
100 $add = runFilterChain('sql_admin_extra_data');
102 // Get password from DB
103 $result = SQL_QUERY_ESC("SELECT `password`" . $add . " FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
104 array($adminId), __FUNCTION__, __LINE__);
107 if (SQL_NUMROWS($result) == 1) {
108 // Login password found
112 $data = SQL_FETCHARRAY($result);
116 SQL_FREERESULT($result);
119 //* DEBUG: */ outputHtml('*' . $data['password'] . '/' . md5($password) .'/' . $ret . '*<br />');
120 if ((isset($data['password'])) && (strlen($data['password']) == 32) && ($data['password'] == md5($password))) {
122 $data['password'] = generateHash($password);
124 // Is the sql_patches not installed, than we cannot have a valid hashed password here!
125 //* DEBUG: */ outputHtml($ret . ',' . intval(isExtensionInstalledAndOlder('sql_patches', '0.3.6')) . '/' . intval(!isExtensionInstalled('sql_patches')).'<br />');
126 if (($ret == 'pass') && ((isExtensionInstalledAndOlder('sql_patches', '0.3.6')) || (!isExtensionInstalled('sql_patches')))) $ret = 'done';
127 } elseif ((isExtensionInstalledAndOlder('sql_patches', '0.3.6')) || (!isExtensionInstalled('sql_patches'))) {
130 } elseif (!isset($data['password'])) {
131 // Password not found, so no valid login!
135 // Generate salt of password
136 $salt = substr($data['password'], 0, -40);
138 // Check if password is same
139 //* DEBUG: */ outputHtml('*' . $ret . ',' . $data['password'] . ',' . $password . ',' . $salt . '*<br />');
140 if (($ret == 'pass') && ($data['password'] == generateHash($password, $salt)) && ((!empty($salt))) || ($data['password'] == md5($password))) {
141 // Re-hash the plain passord with new random salt
142 $data['password'] = generateHash($password);
144 // Do we have 0.7.0 of admins or later?
145 // Remmeber login failures if available
146 if ((isExtensionInstalledAndNewer('admins', '0.7.2')) && (isset($data['login_failures']))) {
147 // Store it in session
148 setSession('mxchange_admin_failures', $data['login_failures']);
149 setSession('mxchange_admin_last_fail', $data['last_failure']);
151 // Update password and reset login failures
152 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",
153 array($data['password'], $adminId), __FUNCTION__, __LINE__);
156 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_admins` SET `password`='%s' WHERE `id`=%s LIMIT 1",
157 array($data['password'], $adminId), __FUNCTION__, __LINE__);
161 rebuildCacheFile('admin', 'admin');
163 // Login has failed by default... ;-)
166 // Password matches so login here
167 if (doAdminLogin($admin, $data['password'])) {
171 } elseif ((empty($salt)) && ($ret == 'pass')) {
172 // Something bad went wrong
173 $ret = 'failed_salt';
174 } elseif ($ret == 'done') {
175 // Try to login here if we have the old hashing way (sql_patches not installed?)
176 if (!doAdminLogin($admin, $data['password'])) {
177 // Something went wrong
182 // Count login failure if admins extension version is 0.7.0+
183 if (($ret == 'pass') && (getExtensionVersion('admins') >= '0.7.0')) {
185 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_admins` SET login_failures`=`login_failures`+1,`last_failure`=NOW() WHERE `id`=%s LIMIT 1",
186 array($adminId), __FUNCTION__, __LINE__);
189 rebuildCacheFile('admin', 'admin');
193 //* DEBUG: */ die('RETURN=' . $ret);
197 // Try to login the admin by setting some session/cookie variables
198 function doAdminLogin ($adminLogin, $passHash) {
199 // Reset failure counter on matching admins version
200 if ((isExtensionInstalledAndNewer('admins', '0.7.0')) && ((isExtensionOlder('sql_patches', '0.3.6')) || (!isExtensionInstalled('sql_patches')))) {
201 // Reset counter on out-dated sql_patches version
202 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_admins` SET `login_failures`=0, `last_failure`='0000-00-00 00:00:00' WHERE `login`='%s' LIMIT 1",
203 array($adminLogin), __FUNCTION__, __LINE__);
206 rebuildCacheFile('admin', 'admin');
209 // Now set all session variables and return the result
211 setSession('admin_md5', generatePassString($passHash))
213 setSession('admin_login', $adminLogin)
215 setSession('admin_last', time())
219 // Only be executed on cookie checking
220 function ifAdminCookiesAreValid ($admin, $password) {
221 // By default no admin cookies are found
226 $pass = getAdminHash($admin);
227 if ($pass != '-1') $ret = 'pass';
229 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):".generatePassString($pass).'('.strlen($pass).")/".$password.'('.strlen($password).")<br />");
231 // Check if password matches
232 if (($ret == 'pass') && ((generatePassString($pass) == $password) || ($pass == $password) || ((strlen($pass) == 32) && (md5($password) == $pass))) && (isAdmin())) {
233 // Passwords matches!
241 // Do an admin action
242 function doAdminAction () {
246 //* DEBUG: */ outputHtml(__LINE__."*".$what.'/'.getModule().'/'.getAction().'/'.getWhat()."*<br />");
248 // Remove any spaces from variable
250 // Default admin action is the overview page
254 $what = secureString($what);
258 $action = getModeAction(getModule(), $what);
260 // Define admin login name and id number
261 $content['login'] = getSession('admin_login');
262 $content['id'] = getCurrentAdminId();
265 if (isExtensionActive('admins')) {
266 $content['welcome'] = loadTemplate('admin_welcome_admins', true, $content);
268 $content['welcome'] = loadTemplate('admin_welcome', true, $content);
270 $content['footer'] = loadTemplate('admin_footer' , true, $content);
271 $content['menu'] = addAdminMenu($action, $what, true);
274 loadTemplate('admin_main_header', false, $content);
276 // Check if action/what pair is valid
277 $result_action = SQL_QUERY_ESC("SELECT
280 `{?_MYSQL_PREFIX?}_admin_menu`
285 `what`='%s' AND `what` != 'overview'
288 `what`='' OR `what` IS NULL
299 ), __FUNCTION__, __LINE__);
301 // Do we have an entry?
302 if (SQL_NUMROWS($result_action) == 1) {
303 // Is valid but does the inlcude file exists?
304 $inc = sprintf("inc/modules/admin/action-%s.php", $action);
305 if ((isIncludeReadable($inc)) && (isMenuActionValid('admin', $action, $what)) && ($GLOBALS['acl_allow'] === true)) {
306 // Ok, we finally load the admin action module
308 } elseif ($GLOBALS['acl_allow'] === false) {
310 loadTemplate('admin_menu_failed', false, getMaskedMessage('ADMIN_ACCESS_DENIED', $what));
312 // Include file not found! :-(
313 loadTemplate('admin_menu_failed', false, getMaskedMessage('ADMIN_ACTION_404', $action));
316 // Invalid action/what pair found!
317 loadTemplate('admin_menu_failed', false, getMaskedMessage('ADMIN_ACTION_INVALID', $action . '/' . $what));
321 SQL_FREERESULT($result_action);
324 loadTemplate('admin_main_footer', false, $content);
327 // Adds an admin menu
328 function addAdminMenu ($action, $what, $return=false) {
334 $GLOBALS['menu']['description'] = array();
335 $GLOBALS['menu']['title'] = array();
338 $result_main = SQL_QUERY("SELECT
339 `action`, `title`, `descr`
341 `{?_MYSQL_PREFIX?}_admin_menu`
343 (`what`='' OR `what` IS NULL)
346 `id` DESC", __FUNCTION__, __LINE__);
348 // Do we have entries?
349 if (SQL_NUMROWS($result_main) > 0) {
350 $OUT = '<div style="height:7px" class="seperator"> </div>';
351 $OUT .= '<ul class="admin_menu_main">';
352 // @TODO Rewrite this to $content = SQL_FETCHARRAY()
353 while (list($menu, $title, $descr) = SQL_FETCHROW($result_main)) {
354 if ((isExtensionActive('admins')) && (getExtensionVersion('admins') > '0.2.0')) {
355 $ACL = adminsCheckAdminAcl($menu, '');
357 // @TODO ACL is 'allow'... hmmm
362 $inc = sprintf("inc/modules/admin/action-%s.php", $menu);
364 // Is the file readable?
365 $readable = isIncludeReadable($inc);
368 if ($SUB === false) {
369 // Insert compiled menu title and description
370 $GLOBALS['menu']['title'][$menu] = $title;
371 $GLOBALS['menu']['description'][$menu] = $descr;
373 $OUT .= '<li class="admin_menu">
374 <div class="nobr"><strong>·</strong> ';
376 if ($readable === true) {
377 if (($menu == $action) && (empty($what))) {
380 $OUT .= '[<a href="{%url=modules.php?module=admin&action=' . $menu . '%}">';
383 $OUT .= '<em style="cursor:help" class="admin_note" title="{--MENU_ACTION_404--}">';
388 if ($readable === true) {
389 if (($menu == $action) && (empty($what))) {
401 // Check for menu entries
402 $result_what = SQL_QUERY_ESC("SELECT
403 `what`, `title`, `descr`
405 `{?_MYSQL_PREFIX?}_admin_menu`
413 array($menu), __FUNCTION__, __LINE__);
415 // Remember the count for later checks
416 setAdminMenuHasEntries($menu, ((SQL_NUMROWS($result_what) > 0) && ($action == $menu)));
418 // Do we have entries?
419 if ((ifAdminMenuHasEntries($menu)) && (SQL_NUMROWS($result_what) > 0)) {
420 $GLOBALS['menu']['description'] = array();
421 $GLOBALS['menu']['title'] = array(); $SUB = true;
422 $OUT .= '<li class="admin_menu_sub"><ul class="admin_menu_sub">';
423 // @TODO Rewrite this to $content = SQL_FETCHARRAY()
424 while (list($what_sub, $title_what, $desc_what) = SQL_FETCHROW($result_what)) {
425 // Check for access level
426 if ((isExtensionActive('admins')) && (getExtensionVersion('admins') > '0.2.0')) {
427 $ACL = adminsCheckAdminAcl('', $what_sub);
429 // @TODO ACL is 'allow'... hmmm
434 $inc = sprintf("inc/modules/admin/what-%s.php", $what_sub);
436 // Is the file readable?
437 $readable = isIncludeReadable($inc);
441 // Insert compiled title and description
442 $GLOBALS['menu']['title'][$what_sub] = $title_what;
443 $GLOBALS['menu']['description'][$what_sub] = $desc_what;
444 $OUT .= '<li class="admin_menu">
445 <div class="nobr"><strong>--></strong> ';
446 if ($readable === true) {
447 if ($what == $what_sub) {
450 $OUT .= '[<a href="{%url=modules.php?module=admin&what=' . $what_sub . '%}">';
453 $OUT .= '<em style="cursor:help" class="admin_note" title="{--MENU_WHAT_404--}">';
458 if ($readable === true) {
459 if ($what == $what_sub) {
473 SQL_FREERESULT($result_what);
478 $OUT .= '<li style="height:7px" class="seperator"> </li>';
483 SQL_FREERESULT($result_main);
487 // Is there a cache instance again?
488 // Return or output content?
489 if ($return === true) {
496 // Create member selection box
497 function addMemberSelectionBox ($def=0, $add_all=false, $return=false, $none=false, $field='userid') {
498 // Output selection form with all confirmed user accounts listed
499 $result = SQL_QUERY("SELECT `userid`, `surname`, `family` FROM `{?_MYSQL_PREFIX?}_user_data` ORDER BY `userid` ASC", __FUNCTION__, __LINE__);
504 // USe this only for adding points (e.g. adding refs really makes no sence ;-) )
505 if ($add_all === true) $OUT = ' <option value="all">{--ALL_MEMBERS--}</option>';
506 elseif ($none === true) $OUT = ' <option value="0">{--SELECT_NONE--}</option>';
508 while ($content = SQL_FETCHARRAY($result)) {
509 $OUT .= ' <option value="' . bigintval($content['userid']) . '"';
510 if ($def == $content['userid']) $OUT .= ' selected="selected"';
511 $OUT .= '>' . $content['surname'] . ' ' . $content['family'] . ' (' . bigintval($content['userid']) . ')</option>';
515 SQL_FREERESULT($result);
517 if ($return === false) {
518 // Remeber options in constant
519 $content['member_selection'] = $OUT;
520 $content['what'] = getWhat();
523 loadTemplate('admin_member_selection_box', false, $content);
525 // Return content in selection frame
526 return '<select class="admin_select" name="' . $field . '" size="1">' . $OUT . '</select>';
530 // Create a menu selection box for given menu system
531 // @TODO Try to rewrite this to adminAddMenuSelectionBox()
533 function adminMenuSelectionBox_DEPRECATED ($mode, $default = '', $defid = '') {
534 $what = "`what` != ''";
535 if ($mode == 'action') $what = "(`what`='' OR `what` IS NULL) AND `action` !='login'";
537 $result = SQL_QUERY_ESC("SELECT %s, `title` FROM `{?_MYSQL_PREFIX?}_admin_menu` WHERE ".$what." ORDER BY `sort` ASC",
538 array($mode), __FUNCTION__, __LINE__);
539 if (SQL_NUMROWS($result) > 0) {
540 // Load menu as selection
541 $OUT = "<select name=\"".$mode."_menu";
542 if ((!empty($defid)) || ($defid == '0')) $OUT .= "[".$defid."]";
543 $OUT .= "\" size=\"1\" class=\"admin_select\">
544 <option value=\"\">{--SELECT_NONE--}</option>\n";
545 // @TODO Try to rewrite this to $content = SQL_FETCHARRAY(). Please look some lines above for the dynamic query
546 while (list($menu, $title) = SQL_FETCHROW($result)) {
547 $OUT .= " <option value=\"".$menu."\"";
548 if ((!empty($default)) && ($default == $menu)) $OUT .= ' selected="selected"';
549 $OUT .= ">".$title."</option>\n";
553 SQL_FREERESULT($result);
554 $OUT .= "</select>\n";
557 $OUT = getMessage('ADMIN_PROBLEM_NO_MENU');
564 // Wrapper for $_POST and adminSaveSettings
565 function adminSaveSettingsFromPostData ($tableName = '_config', $whereStatement = '`config`=0', $translateComma = array(), $alwaysAdd = false, $displayMessage = true) {
567 $postData = postRequestArray();
569 // Call the lower function
570 adminSaveSettings($postData, $tableName, $whereStatement, $translateComma, $alwaysAdd, $displayMessage);
573 // Save settings to the database
574 function adminSaveSettings (&$postData, $tableName = '_config', $whereStatement = '`config`=0', $translateComma = array(), $alwaysAdd = false, $displayMessage = true) {
575 // Prepare all arrays, variables
579 // Now, walk through all entries and prepare them for saving
580 foreach ($postData as $id => $val) {
581 // Process only formular field but not submit buttons ;)
583 // Do not save the ok value
584 convertSelectionsToTimestamp($postData, $DATA, $id, $skip);
586 // Shall we process this id? It muss not be empty, of course
587 if (($skip === false) && (!empty($id)) && (!isset($GLOBALS['skip_config'][$id]))) {
588 // Translate the value? (comma to dot!)
589 if ((is_array($translateComma)) && (in_array($id, $translateComma))) {
590 // Then do it here... :)
591 $val = convertCommaToDot($val);
594 // Shall we add numbers or strings?
596 if ('' . $val . '' == '' . $test . '') {
598 $DATA[] = sprintf("`%s`=%s", $id, $test);
601 $DATA[] = sprintf("`%s`='%s'", $id, trim($val));
604 // Do not add a config entry twice
605 $GLOBALS['skip_config'][$id] = true;
607 // Update current configuration
608 setConfigEntry($id, $val);
613 // Check if entry does exist
615 if ($alwaysAdd === false) {
616 if (!empty($whereStatement)) {
617 $result = SQL_QUERY("SELECT * FROM `{?_MYSQL_PREFIX?}" . $tableName . "` WHERE " . $whereStatement . " LIMIT 1", __FUNCTION__, __LINE__);
619 $result = SQL_QUERY("SELECT * FROM `{?_MYSQL_PREFIX?}" . $tableName . "` LIMIT 1", __FUNCTION__, __LINE__);
623 if (SQL_NUMROWS($result) == 1) {
624 // "Implode" all data to single string
625 $DATA_UPDATE = implode(', ', $DATA);
627 // Generate SQL string
628 $sql = sprintf("UPDATE `{?_MYSQL_PREFIX?}%s` SET %s WHERE %s LIMIT 1",
634 // Add Line (does only work with auto_increment!
635 $KEYs = array(); $values = array();
636 foreach ($DATA as $entry) {
638 $line = explode('=', $entry);
639 $KEYs[] = $line[0]; $values[] = $line[1];
642 // Add both in one line
643 $KEYs = implode('`, `', $KEYs);
644 $values = implode(', ', $values);
646 // Generate SQL string
647 $sql = sprintf("INSERT INTO `{?_MYSQL_PREFIX?}%s` (%s) VALUES (%s)",
655 SQL_FREERESULT($result);
657 // Simply run generated SQL string
658 SQL_QUERY($sql, __FUNCTION__, __LINE__);
660 // Remember affected rows
661 $affected = SQL_AFFECTEDROWS();
664 rebuildCacheFile('config', 'config');
666 // Settings saved, so display message?
667 if ($displayMessage === true) loadTemplate('admin_settings_saved', false, getMessage('SETTINGS_SAVED'));
669 // Return affected rows
673 // Generate a selection box
674 function adminAddMenuSelectionBox ($menu, $type, $name, $default = '') {
675 // Open the requested menu directory
676 $menuArray = getArrayFromDirectory(sprintf("inc/modules/%s/", $menu), '', false, false);
678 // Init the selection box
679 $OUT = "<select name=\"".$name."\" class=\"admin_select\" size=\"1\">
680 <option value=\"\">{--IS_TOP_MENU--}</option>\n";
682 // Walk through all files
683 foreach ($menuArray as $file) {
684 // Is this a PHP script?
685 if ((!isDirectory($file)) && (strpos($file, "".$type.'-') > -1) && (strpos($file, '.php') > 0)) {
686 // Then test if the file is readable
687 $test = sprintf("inc/modules/%s/%s", $menu, $file);
689 // Is the file there?
690 if (isIncludeReadable($test)) {
691 // Extract the value for what=xxx
692 $part = substr($file, (strlen($type) + 1));
693 $part = substr($part, 0, -4);
695 // Is that part different from the overview?
696 if ($part != 'overview') {
697 $OUT .= " <option value=\"".$part."\"";
698 if ($part == $default) $OUT .= ' selected="selected"';
699 $OUT .= ">".$part."</option>\n";
705 // Close selection box
706 $OUT .= "</select>\n";
712 // Creates a user-profile link for the admin. This function can also be used for many other purposes
713 function generateUserProfileLink ($userid, $title = '', $what = 'list_user') {
714 if (($title == '') && ($userid > 0)) {
715 // Set userid as title
717 } elseif ($userid == 0) {
718 // User id zero is invalid
719 return '<strong>' . $userid . '</strong>';
722 if (($title == '0') && ($what == 'list_refs')) {
723 // Return title again
725 } elseif (isExtensionActive('nickname')) {
727 $nick = getNickname($userid);
729 // Is it not empty, use it as title else the userid
730 if (!empty($nick)) $title = $nick . '(' . $userid . ')'; else $title = $userid;
734 return '[<a href="{%url=modules.php?module=admin&what=' . $what . '&userid=' . $userid . '%}" title="{--ADMIN_USER_PROFILE_TITLE--}">' . $title . '</a>]';
737 // Check "logical-area-mode"
738 function adminGetMenuMode () {
739 // Set the global mode as the mode for all admins
740 $mode = getConfig('admin_menu');
744 $adminId = getCurrentAdminId();
746 // Check individual settings of current admin
747 if (isset($GLOBALS['cache_array']['admin']['la_mode'][$adminId])) {
749 $adminMode = $GLOBALS['cache_array']['admin']['la_mode'][$adminId];
750 incrementStatsEntry('cache_hits');
751 } elseif (isExtensionInstalledAndNewer('admins', '0.6.7')) {
752 // Load from database when version of 'admins' is enough
753 $result = SQL_QUERY_ESC("SELECT la_mode FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
754 array($adminId), __FUNCTION__, __LINE__);
756 // Do we have an entry?
757 if (SQL_NUMROWS($result) == 1) {
759 list($adminMode) = SQL_FETCHROW($result);
763 SQL_FREERESULT($result);
766 // Check what the admin wants and set it when it's not the global mode
767 if ($adminMode != 'global') $mode = $adminMode;
769 // Return admin-menu's mode
773 // Change activation status
774 function adminChangeActivationStatus ($IDs, $table, $row, $idRow = 'id') {
775 $cnt = '0'; $newStatus = 'Y';
776 if ((is_array($IDs)) && (count($IDs) > 0)) {
777 // "Walk" all through and count them
778 foreach ($IDs as $id => $selected) {
779 // Secure the id number
780 $id = bigintval($id);
782 // Should always be set... ;-)
783 if (!empty($selected)) {
784 // Determine new status
785 $result = SQL_QUERY_ESC("SELECT %s FROM `{?_MYSQL_PREFIX?}_%s` WHERE %s=%s LIMIT 1",
786 array($row, $table, $idRow, $id), __FUNCTION__, __LINE__);
789 if (SQL_NUMROWS($result) == 1) {
791 list($currStatus) = SQL_FETCHROW($result);
793 // And switch it N<->Y
794 if ($currStatus == 'Y') $newStatus = 'N'; else $newStatus = 'Y';
796 // Change this status
797 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s` SET %s='%s' WHERE %s=%s LIMIT 1",
798 array($table, $row, $newStatus, $idRow, $id), __FUNCTION__, __LINE__);
800 // Count up affected rows
801 $cnt += SQL_AFFECTEDROWS();
805 SQL_FREERESULT($result);
810 loadTemplate('admin_settings_saved', false, sprintf(getMessage('ADMIN_STATUS_CHANGED'), $cnt, count($IDs)));
813 loadTemplate('admin_settings_saved', false, getMessage('ADMIN_NOTHING_SELECTED_CHANGE'));
817 // Send mails for del/edit/lock build modes
818 function sendAdminBuildMails ($mode, $table, $content, $id, $subjectPart = '') {
819 // Default subject is the subject part
820 $subject = $subjectPart;
822 // Is the subject part not set?
823 if (empty($subjectPart)) {
824 // Then use it from the mode
825 $subject = strtoupper($mode);
828 // Is the raw userid set?
829 if (postRequestElement('userid_raw', $id) > 0) {
831 $subjectLine = getMessage('MEMBER_'.strtoupper($subject).'_'.strtoupper($table).'_SUBJECT');
833 // Load email template
834 if (!empty($subjectPart)) {
835 $mail = loadEmailTemplate('member_' . $mode . '_' . strtolower($subjectPart) . '_' . $table, $content);
837 $mail = loadEmailTemplate('member_' . $mode . '_' . $table, $content);
841 sendEmail(postRequestElement('userid_raw', $id), $subjectLine, $mail);
845 $subjectLine = getMessage('ADMIN_'.strtoupper($subject).'_'.strtoupper($table).'_SUBJECT');
847 // Send admin notification out
848 if (!empty($subjectPart)) {
849 sendAdminNotification($subjectLine, 'admin_' . $mode . '_' . strtolower($subjectPart) . '_' . $table, $content, postRequestElement('userid_raw', $id));
851 sendAdminNotification($subjectLine, 'admin_' . $mode . '_' . $table, $content, postRequestElement('userid_raw', $id));
855 // Build a special template list
856 function adminListBuilder ($listType, $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn) {
859 // "Walk"Â through all entries
860 foreach ($IDs as $id => $selected) {
862 $id = bigintval($id);
864 // Get result from a given column array and table name
865 $result = SQL_RESULT_FROM_ARRAY($table, $columns, $idColumn, $id, __FUNCTION__, __LINE__);
867 // Is there one entry?
868 if (SQL_NUMROWS($result) == 1) {
870 $content = SQL_FETCHARRAY($result);
873 foreach ($content as $key => $value) {
875 $idx = array_search($key, $columns, true);
877 //Â Do we have a userid?
878 if ($key == 'userid') {
879 // Add it again as raw id
880 $content['userid'] = bigintval($value);
883 // Handle the call in external function
884 $content[$key] = handleExtraValues($filterFunctions[$idx], $value, $extraValues[$idx]);
887 // Add color switching
888 $content['sw'] = $SW;
891 $OUT .= loadTemplate(sprintf("admin_%s_%s_row",
902 SQL_FREERESULT($result);
905 // Load master template
906 loadTemplate(sprintf("admin_%s_%s",
913 // Change status of "build" list
914 function adminBuilderStatusHandler ($mode, $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray) {
915 // All valid entries? (We hope so here!)
916 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues)) && (count($statusArray) > 0)) {
917 // "Walk" through all entries
918 foreach ($IDs as $id => $sel) {
919 // Construct SQL query
920 $sql = sprintf("UPDATE `{?_MYSQL_PREFIX?}_%s` SET", SQL_ESCAPE($table));
922 // Load data of entry
923 $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_%s` WHERE %s=%s LIMIT 1",
924 array($table, $idColumn, $id), __FUNCTION__, __LINE__);
927 $content = SQL_FETCHARRAY($result);
930 SQL_FREERESULT($result);
932 // Add all status entries (e.g. status column last_updated or so)
933 $newStatus = 'UNKNOWN';
934 $oldStatus = 'UNKNOWN';
935 $statusColumn = 'unknown';
936 foreach ($statusArray as $column => $statusInfo) {
937 // Does the entry exist?
938 if ((isset($content[$column])) && (isset($statusInfo[$content[$column]]))) {
939 // Add these entries for update
940 $sql .= sprintf(" %s='%s',", SQL_ESCAPE($column), SQL_ESCAPE($statusInfo[$content[$column]]));
943 if ($statusColumn == 'unknown') {
944 // Always (!!!) change status column first!
945 $oldStatus = $content[$column];
946 $newStatus = $statusInfo[$oldStatus];
947 $statusColumn = $column;
949 } elseif (isset($content[$column])) {
951 app_die(__FUNCTION__, __LINE__, ":UNFINISHED: id={$id}/{$column}[".gettype($statusInfo)."] = {$content[$column]}");
955 // Add other columns as well
956 foreach (postRequestArray() as $key => $entries) {
957 // Skip id, raw userid and 'do_$mode'
958 if (!in_array($key, array($idColumn, 'userid_raw', ('do_'.$mode)))) {
959 // Are there brackets () at the end?
960 if (substr($entries[$id], -2, 2) == "()") {
961 // Direct SQL command found
962 $sql .= sprintf(" %s=%s,", SQL_ESCAPE($key), SQL_ESCAPE($entries[$id]));
965 $sql .= sprintf(" %s='%s',", SQL_ESCAPE($key), SQL_ESCAPE($entries[$id]));
968 $content[$key] = $entries[$id];
973 // Finish SQL statement
974 $sql = substr($sql, 0, -1) . sprintf(" WHERE `%s`=%s AND `%s`='%s' LIMIT 1",
982 SQL_QUERY($sql, __FUNCTION__, __LINE__);
984 // Do we have an URL?
985 if (isset($content['url'])) {
986 // Then add a framekiller test as well
987 $content['frametester'] = generateFrametesterUrl($content['url']);
990 // Send "build mails" out
991 sendAdminBuildMails($mode, $table, $content, $id, $statusInfo[$content[$column]]);
996 // Delete rows by given id numbers
997 function adminDeleteEntriesConfirm ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $deleteNow=false, $idColumn='id', $userIdColumn='userid') {
998 // All valid entries? (We hope so here!)
999 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues))) {
1000 // Shall we delete here or list for deletion?
1001 if ($deleteNow === true) {
1002 // The base SQL command:
1003 $sql = "DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_%s` WHERE %s IN (%s)";
1007 foreach ($IDs as $id => $sel) {
1008 // Is there a userid?
1009 if (isPostRequestElementSet('userid_raw', $id)) {
1010 // Load all data from that id
1011 $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_%s` WHERE %s=%s LIMIT 1",
1012 array($table, $idColumn, $id), __FUNCTION__, __LINE__);
1015 $content = SQL_FETCHARRAY($result);
1018 SQL_FREERESULT($result);
1020 // Send "build mails" out
1021 sendAdminBuildMails('del', $table, $content, $id);
1025 $idList .= $id . ',';
1029 SQL_QUERY($sql, array($table, $idColumn, substr($idList, 0, -1)), __FUNCTION__, __LINE__);
1032 if (SQL_AFFECTEDROWS() == count($IDs)) {
1034 loadTemplate('admin_settings_saved', false, getMessage('ADMIN_ALL_ENTRIES_REMOVED'));
1036 // Some are still there :(
1037 loadTemplate('admin_settings_saved', false, sprintf(getMessage('ADMIN_SOME_ENTRIES_NOT_DELETED'), SQL_AFFECTEDROWS(), count($IDs)));
1040 // List for deletion confirmation
1041 adminListBuilder('del', $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1046 // Edit rows by given id numbers
1047 function adminEditEntriesConfirm ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $editNow=false, $idColumn='id', $userIdColumn='userid') {
1048 // All valid entries? (We hope so here!)
1049 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues))) {
1050 // Shall we change here or list for editing?
1051 if ($editNow === true) {
1054 foreach ($IDs as $id => $sel) {
1055 // Prepare content array (new values)
1058 // Prepare SQL for this row
1059 $sql = sprintf("UPDATE `{?_MYSQL_PREFIX?}_%s` SET",
1062 foreach (postRequestArray() as $key => $entries) {
1063 // Skip raw userid which is always invalid
1064 if ($key == 'userid_raw') {
1065 // Continue with next field
1069 // Is entries an array?
1070 if (($key != $idColumn) && (is_array($entries)) && (isset($entries[$id]))) {
1071 // Add this entry to content
1072 $content[$key] = $entries[$id];
1074 // Send data through the filter function if found
1075 if ((isset($filterFunctions[$key])) && (isset($extraValues[$key]))) {
1076 // Filter function set!
1077 $entries[$id] = handleExtraValues($filterFunctions[$key], $entries[$id], $extraValues[$key]);
1080 // Then add this value
1081 $sql .= sprintf(" `%s`='%s',",
1083 SQL_ESCAPE($entries[$id])
1085 } elseif (($key != $idColumn) && (!is_array($entries))) {
1086 // Add normal entries as well!
1087 $content[$key] = $entries;
1090 // Do we have an URL?
1091 if ($key == 'url') {
1092 // Then add a framekiller test as well
1093 $content['frametester'] = generateFrametesterUrl($content[$key]);
1097 // Finish SQL command
1098 $sql = substr($sql, 0, -1) . " WHERE `" . $idColumn . "`=" . bigintval($id) . " LIMIT 1";
1101 SQL_QUERY($sql, __FUNCTION__, __LINE__);
1103 // Add affected rows
1104 $affected += SQL_AFFECTEDROWS();
1106 // Load all data from that id
1107 $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`=%s LIMIT 1",
1108 array($table, $idColumn, $id), __FUNCTION__, __LINE__);
1110 // Fetch the data and merge it into $content
1111 $content = merge_array($content, SQL_FETCHARRAY($result));
1114 SQL_FREERESULT($result);
1116 // Send "build mails" out
1117 sendAdminBuildMails('edit', $table, $content, $id);
1121 if ($affected == count($IDs)) {
1123 loadTemplate('admin_settings_saved', false, getMessage('ADMIN_ALL_ENTRIES_EDITED'));
1125 // Some are still there :(
1126 loadTemplate('admin_settings_saved', false, sprintf(getMessage('ADMIN_SOME_ENTRIES_NOT_EDITED'), $affected, count($IDs)));
1130 adminListBuilder('edit', $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1135 // Un-/lock rows by given id numbers
1136 function adminLockEntriesConfirm ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $statusArray=array(), $lockNow=false, $idColumn='id', $userIdColumn='userid') {
1137 // All valid entries? (We hope so here!)
1138 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues)) && (($lockNow === false) || (count($statusArray) == 1))) {
1139 // Shall we un-/lock here or list for locking?
1140 if ($lockNow === true) {
1142 adminBuilderStatusHandler('lock', $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray);
1145 adminListBuilder('lock', $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1150 // Undelete rows by given id numbers
1151 function adminUndeleteEntriesConfirm ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $statusArray=array(), $undeleteNow=false, $idColumn='id', $userIdColumn='userid') {
1152 // All valid entries? (We hope so here!)
1153 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues)) && (($undeleteNow === false) || (count($statusArray) == 1))) {
1154 // Shall we un-/lock here or list for locking?
1155 if ($undeleteNow === true) {
1157 adminBuilderStatusHandler('undelete', $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray);
1160 adminListBuilder('undelete', $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1165 // Checks proxy settins by fetching check-updates3.php from www.mxchange.org
1166 function adminTestProxySettings ($settingsArray) {
1167 // Set temporary the new settings
1168 mergeConfig($settingsArray);
1170 // Now get the test URL
1171 $content = sendGetRequest('check-updates3.php');
1173 // Is the first line with "200 OK"?
1174 $valid = (strpos($content[0], '200 OK') !== false);
1180 // Sends out a link to the given email adress so the admin can reset his/her password
1181 function sendAdminPasswordResetLink ($email) {
1185 //Â Look up administator login
1186 $result = SQL_QUERY_ESC("SELECT `id`, `login`, `password` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `email`='%s' LIMIT 1",
1187 array($email), __FUNCTION__, __LINE__);
1189 // Is there an account?
1190 if (SQL_NUMROWS($result) == '0') {
1191 // No account found!
1192 return getMessage('ADMIN_NO_LOGIN_WITH_EMAIL');
1196 $content = SQL_FETCHARRAY($result);
1199 SQL_FREERESULT($result);
1201 // Generate hash for reset link
1202 $content['hash'] = generateHash(getConfig('URL') . ':' . $content['id'] . ':' . $content['login'] . ':' . $content['password'], substr($content['password'], 10));
1205 unset($content['id']);
1206 unset($content['password']);
1209 $mailText = loadEmailTemplate('admin_reset_password', $content);
1212 sendEmail($email, getMessage('ADMIN_RESET_PASS_LINK_SUBJ'), $mailText);
1215 return getMessage('ADMIN_RESET_LINK_SENT');
1218 // Validate hash and login for password reset
1219 function adminResetValidateHashLogin ($hash, $login) {
1220 // By default nothing validates... ;)
1223 // Then try to find that user
1224 $result = SQL_QUERY_ESC("SELECT `id`, `password`, `email` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
1225 array($login), __FUNCTION__, __LINE__);
1227 // Is an account here?
1228 if (SQL_NUMROWS($result) == 1) {
1230 $content = SQL_FETCHARRAY($result);
1232 // Generate hash again
1233 $hashFromData = generateHash(getConfig('URL') . ':' . $content['id'] . ':' . $login . ':' . $content['password'], substr($content['password'], 10));
1236 $valid = ($hash == $hashFromData);
1240 SQL_FREERESULT($result);
1246 // Reset the password for the login. Do NOT call this function without calling above function first!
1247 function doResetAdminPassword ($login, $password) {
1251 // Now check if we have sql_patches installed
1252 if (isExtensionInstalledAndNewer('sql_patches', '0.3.6')) {
1253 // Use new way of hashing
1254 $passHash = generateHash($password);
1257 $passHash = md5($password);
1261 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_admins` SET `password`='%s' WHERE `login`='%s' LIMIT 1",
1262 array($passHash, $login), __FUNCTION__, __LINE__);
1265 runFilterChain('post_admin_reset_pass', array('login' => $login, 'hash' => $passHash));
1268 return getMessage('ADMIN_PASSWORD_RESET_DONE');
1271 // Solves a task by given id number
1272 function adminSolveTask ($id) {
1273 // Update the task data
1274 adminUpdateTaskData($id, 'status', 'SOLVED');
1277 // Marks a given task as deleted
1278 function adminDeleteTask ($id) {
1279 // Update the task data
1280 adminUpdateTaskData($id, 'status', 'DELETED');
1283 // Function to update task data
1284 function adminUpdateTaskData ($id, $row, $data) {
1287 // Not an admin so redirect better
1288 redirectToUrl('index.php');
1291 // Is the id not set, then we need a backtrace here... :(
1293 // Initiate backtrace
1294 debug_report_bug(sprintf("id is invalid: %s. row=%s, data=%s",
1302 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_task_system` SET `%s`='%s' WHERE `id`=%s LIMIT 1",
1307 ), __FUNCTION__, __LINE__);
1310 // Checks wether if the admin menu has entries
1311 function ifAdminMenuHasEntries ($action) {
1314 // Is the entry set?
1315 isset($GLOBALS['admin_menu_has_entries'][$action])
1317 // And do we have a menu for this action?
1318 $GLOBALS['admin_menu_has_entries'][$action] === true
1320 // Login has always a menu
1326 // Setter for 'admin_menu_has_entries'
1327 function setAdminMenuHasEntries ($action, $hasEntries) {
1328 $GLOBALS['admin_menu_has_entries'][$action] = (bool) $hasEntries;
1331 // Creates a link to the user's admin-profile
1332 function adminCreateUserLink ($userid) {
1333 // Is the userid set correctly?
1335 // Create a link to that profile
1336 return '{%url=modules.php?module=admin&what=list_user&userid=' . bigintval($userid) . '%}';
1339 // Return a link to the user list
1340 return '{%url=modules.php?module=admin&what=list_user%}';
1343 // Generate a "link" for the given admin id (admin_id)
1344 function generateAdminLink ($adminId) {
1345 // No assigned admin is default
1346 $adminLink = '<span class="admin_note">{--ADMIN_NO_ADMIN_ASSIGNED--}</span>';
1348 // Zero? = Not assigned
1349 if (bigintval($adminId) > 0) {
1350 // Load admin's login
1351 $login = getAdminLogin($adminId);
1353 // Is the login valid?
1354 if ($login != '***') {
1355 // Is the extension there?
1356 if (isExtensionActive('admins')) {
1358 $adminLink = '<a href="' . generateEmailLink(getAdminEmail($adminId), 'admins') . '" title="{--ADMIN_CONTACT_LINK_TITLE--}">' . $login . '</a>';
1360 // Extension not found
1361 $adminLink = getMaskedMessage('EXTENSION_PROBLEM_NOT_INSTALLED', 'admins');
1365 $adminLink = '<div class="admin_note">' . getMaskedMessage('ADMIN_ID_404', $adminId) . '</div>';
1373 // Verifies if the current admin has confirmed to alter expert settings
1376 // 'failed' = Something goes wrong (default)
1377 // 'agreed' = Has verified and and confirmed it to see them
1378 // 'forbidden' = Has not the proper right to alter them
1379 // 'update' = Need to update extension 'admins'
1380 // 'ask' = A form was send to the admin
1381 function doVerifyExpertSettings () {
1382 // Default return status is failed
1385 // Is the extension installed and recent?
1386 if (isExtensionInstalledAndNewer('admins', '0.7.3')) {
1387 // Okay, load the status
1388 $expertSettings = getAminsExpertSettings();
1391 if ($expertSettings == 'Y') {
1392 // Okay, does he want to see them?
1393 if (getAminsExpertWarning() == 'Y') {
1396 // Is the element set, then we need to change the admin
1397 if (isPostRequestElementSet('expert_settings')) {
1398 // Get it and prepare final post data array
1399 $postData['login'][getCurrentAdminId()] = getAdminLogin(getCurrentAdminId());
1400 $postData['expert_warning'][getCurrentAdminId()] = 'N';
1402 // Change it in the admin
1403 adminsChangeAdminAccount($postData, 'expert_warning');
1406 unsetPostRequestElement('ok');
1413 loadTemplate('admin_expert_settings_form');
1424 $return = 'forbidden';
1427 // Out-dated extension or not installed
1431 // Output message for other status than ask/agreed
1432 if (($return != 'ask') && ($return != 'agreed')) {
1434 loadTemplate('admin_settings_saved', false, getMessage('ADMIN_EXPERT_SETTINGS_STATUS_' . strtoupper($return)));