2 /************************************************************************
3 * Mailer v0.2.1-FINAL Start: 06/30/2003 *
4 * =================== Last change: 11/27/2004 *
6 * -------------------------------------------------------------------- *
7 * File : admins_functions.php *
8 * -------------------------------------------------------------------- *
9 * Short description : Functions for the admins extension *
10 * -------------------------------------------------------------------- *
11 * Kurzbeschreibung : Funktionen fuer die admins-Erweiterung *
12 * -------------------------------------------------------------------- *
15 * $Tag:: 0.2.1-FINAL $ *
17 * -------------------------------------------------------------------- *
18 * Copyright (c) 2003 - 2009 by Roland Haeder *
19 * Copyright (c) 2009 - 2013 by Mailer Developer Team *
20 * For more information visit: http://mxchange.org *
22 * This program is free software; you can redistribute it and/or modify *
23 * it under the terms of the GNU General Public License as published by *
24 * the Free Software Foundation; either version 2 of the License, or *
25 * (at your option) any later version. *
27 * This program is distributed in the hope that it will be useful, *
28 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
29 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
30 * GNU General Public License for more details. *
32 * You should have received a copy of the GNU General Public License *
33 * along with this program; if not, write to the Free Software *
34 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
36 ************************************************************************/
38 // Some security stuff...
39 if (!defined('__SECURITY')) {
43 // Check ACL for menu combination
44 function isAdminsAllowedByAcl ($action, $what) {
46 $adminId = getCurrentAdminId();
48 if (($action == 'login') || ($action == 'logout')) {
49 // If action is login or logout allow allways!
51 } elseif (isset($GLOBALS[__FUNCTION__][$adminId][$action][$what])) {
52 // If we have cache, use it
53 return $GLOBALS[__FUNCTION__][$adminId][$action][$what];
56 // Get admin's defult access right
57 $default = getAdminDefaultAcl($adminId);
60 // Check for parent menu:
61 // First get it's action value
62 $parent_action = getActionFromModuleWhat('admin', $what);
64 // Check with this function...
65 $parent = isAdminsAllowedByAcl($parent_action, '');
67 // Anything else is true!
71 // Shall I test for a main or sub menu? (action or what?)
73 if ((isExtensionInstalledAndNewer('cache', '0.1.2')) && (isset($GLOBALS['cache_array']['admin_acls'])) && (count($GLOBALS['cache_array']['admin_acls']) > 0)) {
75 if ((!empty($action)) && (isset($GLOBALS['cache_array']['admin_acls']['action_menu'][$adminId])) & (in_array($action, $GLOBALS['cache_array']['admin_acls']['action_menu'][$adminId]))) {
77 $key = array_search($action, $GLOBALS['cache_array']['admin_acls']['action_menu'][$adminId]);
79 // Main menu line found
80 $aclMode = $GLOBALS['cache_array']['admin_acls']['access_mode'][$adminId][$key];
83 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'action=' . $action . ',key=' . $key . ',acl_mode=' . $aclMode);
86 incrementStatsEntry('cache_hits');
87 } elseif ((!empty($what)) && (isset($GLOBALS['cache_array']['admin_acls']['what_menu'][$adminId])) && (in_array($what, $GLOBALS['cache_array']['admin_acls']['what_menu'][$adminId]))) {
89 $key = array_search($action, $GLOBALS['cache_array']['admin_acls']['what_menu'][$adminId]);
92 $aclMode = $GLOBALS['cache_array']['admin_acls']['access_mode'][$adminId][$key];
95 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'what=' . $what . ',key=' . $key . ',acl_mode=' . $aclMode);
98 incrementStatsEntry('cache_hits');
100 } elseif (!isExtensionActive('cache')) {
101 // Extension ext-cache is absent, so load it from database
103 if (!empty($action)) {
105 $result = sqlQueryEscaped("SELECT `access_mode` FROM `{?_MYSQL_PREFIX?}_admins_acls` WHERE `admin_id`=%s AND `action_menu`='%s' LIMIT 1",
106 array(bigintval($adminId), $action), __FUNCTION__, __LINE__);
107 } elseif (!empty($what)) {
109 $result = sqlQueryEscaped("SELECT `access_mode` FROM `{?_MYSQL_PREFIX?}_admins_acls` WHERE `admin_id`=%s AND `what_menu`='%s' LIMIT 1",
110 array(bigintval($adminId), $what), __FUNCTION__, __LINE__);
113 // Is an entry found?
114 if (sqlNumRows($result) == 1) {
116 list($aclMode) = sqlFetchRow($result);
120 sqlFreeResult($result);
123 // But default result is failed
124 $GLOBALS[__FUNCTION__][$adminId][$action][$what] = FALSE;
126 // Check ACL and (maybe) allow
127 //* DEBUG: */ debugOutput('default='.$default.',acl_mode='.$aclMode.',parent='.intval($parent));
128 if ((($default == 'allow') && ($aclMode != 'deny')) || (($default == 'deny') && ($aclMode == 'allow')) || ($parent === TRUE) || (($default == 'NO-ACL') && ($aclMode == 'failed') && ($parent === FALSE))) {
130 $GLOBALS[__FUNCTION__][$adminId][$action][$what] = TRUE;
134 //* DEBUG: */ debugOutput(__FUNCTION__.'['.__LINE__.']:act='.$action.',wht='.$what.',default='.$default.',aclMode='.$aclMode);
135 return $GLOBALS[__FUNCTION__][$adminId][$action][$what];
138 // Create email link to admins's account
139 function generateAdminEmailLink ($email, $mod = 'admin') {
141 if (isInString('@', $email)) {
143 $result = sqlQueryEscaped("SELECT `id`
145 `{?_MYSQL_PREFIX?}_admins`
149 array($email), __FUNCTION__, __LINE__);
151 // Is there an entry?
152 if (sqlNumRows($result) == 1) {
154 list($adminId) = sqlFetchRow($result);
156 // Call this function again
157 $email = generateAdminEmailLink($adminId, $mod);
161 sqlFreeResult($result);
162 } elseif (isValidId($email)) {
164 $email = '{%url=modules.php?module=' . $mod . '&what=admins_contct&id=' . bigintval($email) . '%}';
166 // This is strange and needs fixing
167 reportBug(__FUNCTION__, __LINE__, 'email[' . gettype($email) . ']=' . $email . ',mod=' . $mod . ' - This should not happen.');
170 // Return rewritten (?) email address
174 // Change a lot admin account
175 function adminsChangeAdminAccount ($postData, $element = '', $displayMessage = TRUE) {
180 foreach ($postData['login'] as $id => $login) {
182 $id = bigintval($id);
183 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'id=' . $id . ',login=' . $login);
185 // When both passwords match update admin account
186 if ((!empty($element)) && (isset($postData[$element]))) {
188 sqlQueryEscaped("UPDATE `{?_MYSQL_PREFIX?}_admins` SET `%s`='%s' WHERE `id`=%s LIMIT 1",
191 $postData[$element][$id],
193 ), __FUNCTION__, __LINE__);
195 // Admin account saved
196 $message = '{--ADMIN_ACCOUNT_SAVED--}';
197 } elseif ((!empty($postData['password1'])) && (!empty($postData['password2']))) {
198 // Update only if both passwords match
199 if (($postData['password1'][$id] == $postData['password2'][$id])) {
200 // Save only when both passwords are the same (also when they are empty)
201 $add = ''; $cache_update = 1;
204 $hash = generateHash($postData['password1'][$id]);
206 // Save password when set
207 if (!empty($postData['password1'][$id])) {
208 $add = sprintf(",`password`='%s'", sqlEscapeString($hash));
212 $adminId = getCurrentAdminId();
213 $salt = substr(getAdminHash(getAdminLogin($adminId)), 0, -40);
215 // Rewrite cookie when it's own account
216 if ($adminId == $id) {
217 // Set timeout cookie
218 setAdminLast(time());
220 if ($adminId != getCurrentAdminId()) {
221 // Update login cookie
222 setAdminId($adminId);
224 // Update password cookie as well?
228 } elseif (generateHash($postData['password1'][$id], $salt) != getAdminMd5()) {
229 // Update password cookie
234 // Get default ACL from admin to check if we can allow him to change the default ACL
235 $default = getAdminDefaultAcl(getCurrentAdminId());
237 // Update admin account
238 if ($default == 'allow') {
239 // Allow changing default ACL
240 sqlQueryEscaped("UPDATE
241 `{?_MYSQL_PREFIX?}_admins`
243 `login`='%s'" . $add . ",
252 $postData['email'][$id],
253 $postData['access_mode'][$id],
254 $postData['la_mode'][$id],
256 ), __FUNCTION__, __LINE__);
258 // Do not allow it here
259 sqlQueryEscaped("UPDATE
260 `{?_MYSQL_PREFIX?}_admins`
262 `login`='%s'" . $add . ",
270 $postData['email'][$id],
271 $postData['la_mode'][$id],
273 ), __FUNCTION__, __LINE__);
276 // Admin account saved
277 $message = '{--ADMIN_ACCOUNT_SAVED--}';
279 // Passwords did not match
280 $message = '{--ADMIN_ADMINS_ERROR_PASS_MISMATCH--}';
283 // Update whole array
284 $SQL = getUpdateSqlFromArray($postData, 'admins', 'id', '%s', array('login', 'id'), $id);
287 sqlQueryEscaped($SQL, array(bigintval($id)), __FUNCTION__, __LINE__);
290 if (sqlAffectedRows() == 1) {
291 // Admin account saved
292 $message = '{--ADMIN_ACCOUNT_SAVED--}';
294 // Passwords did not match
295 $message = '{--ADMIN_ADMINS_ERROR_PASS_MISMATCH--}';
300 // Display message if not empty and allowed
301 if ((!empty($message)) && ($displayMessage === TRUE)) {
303 displayMessage($message);
307 runFilterChain('post_form_submited', postRequestArray());
313 // Make admin accounts editable
314 function adminsEditAdminAccount ($postData) {
315 // "Resolve" current's admin access mode
316 $currMode = getAdminDefaultAcl(getCurrentAdminId());
318 // Begin the edit loop
320 foreach ($postData['sel'] as $id => $selected) {
322 $id = bigintval($id);
324 // Get the admin's data
325 $result = sqlQueryEscaped('SELECT `login`, `email` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1',
326 array($id), __FUNCTION__, __LINE__);
327 if ((sqlNumRows($result) == 1) && ($selected == 1)) {
329 $content = sqlFetchArray($result);
331 // Prepare some more data for the template
332 $content['id'] = $id;
334 // Shall we allow changing default ACL?
335 if ($currMode == 'allow') {
337 $content['access_mode'] = '{%pipe,generateAdminAccessModeSelectionBox=' . $id . '%}';
340 $content['access_mode'] = ' ';
343 // Load row template and switch color
344 $OUT .= loadTemplate('admin_edit_admins_row', TRUE, $content);
348 sqlFreeResult($result);
352 loadTemplate('admin_edit_admins', FALSE, $OUT);
355 // Generate access mode selection box for given admin id
356 function generateAdminAccessModeSelectionBox ($adminId = NULL) {
357 // Start the selection box
358 $OUT = '<select name="access_mode[' . $adminId . ']" size="1" class="form_select">';
361 $OUT .= generateOptions(
367 '{--ADMIN_ADMINS_ACCESS_MODE_ALLOW--}',
368 '{--ADMIN_ADMINS_ACCESS_MODE_DENY--}'
370 getAdminDefaultAcl($adminId)
380 // Generate menu mode selection box for given admin it
381 function generateAdminMenuModeSelectionBox ($adminId = NULL) {
382 // Start the selection box
383 $OUT = '<select name="la_mode[{%pipe,convertNullToZero=' . convertZeroToNull($adminId) . '%}]" size="1" class="form_select">';
386 $OUT .= generateOptions(
393 '{--ADMIN_ADMINS_LA_MODE_GLOBAL--}',
394 '{--ADMIN_ADMINS_LA_MODE_OLD--}',
395 '{--ADMIN_ADMINS_LA_MODE_NEW--}'
397 getAdminMenuMode($adminId)
407 // Delete given admin accounts
408 function adminsDeleteAdminAccount ($postData) {
409 // Check if this account is the last one which cannot be deleted...
410 if (countSumTotalData('', 'admins', 'id', '', TRUE) > 1) {
413 foreach ($postData['sel'] as $id => $selected) {
415 $id = bigintval($id);
417 // Get the admin's data
418 $result = sqlQueryEscaped('SELECT
421 `default_acl` AS `access_mode`,
424 `{?_MYSQL_PREFIX?}_admins`
428 array($id), __FUNCTION__, __LINE__);
430 // Is there an entry?
431 if (sqlNumRows($result) == 1) {
432 // Entry found, so load data
433 $content = sqlFetchArray($result);
434 $content['access_mode'] = '{--ADMIN_ADMINS_ACCESS_MODE_' . strtoupper($content['access_mode']) . '--}';
435 $content['la_mode'] = '{--ADMIN_ADMINS_LA_MODE_' . strtoupper($content['la_mode']) . '--}';
437 // Prepare some more data
438 $content['id'] = $id;
440 // Load row template and switch color
441 $OUT .= loadTemplate('admin_delete_admins_row', TRUE, $content);
445 sqlFreeResult($result);
449 loadTemplate('admin_delete_admins', FALSE, $OUT);
451 // Cannot delete last account!
452 displayMessage('{--ADMIN_ADMINS_CANNOT_DELETE_LAST--}');
456 // Remove the given accounts
457 function adminsRemoveAdminAccount ($postData) {
460 foreach ($postData['sel'] as $id => $del) {
462 $id = bigintval($id);
464 // Delete only when it's not your own account!
465 if (($del == 1) && (getCurrentAdminId() != $id)) {
466 // Rewrite his tasks to all admins
467 sqlQueryEscaped('UPDATE `{?_MYSQL_PREFIX?}_task_system` SET `assigned_admin`=NULL WHERE `assigned_admin`=%s',
468 array($id), __FUNCTION__, __LINE__);
471 sqlQueryEscaped('DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1',
472 array($id), __FUNCTION__, __LINE__);
476 // Remove cache if cache system is activated
477 runFilterChain('post_form_deleted', postRequestArray());
480 // List all admin accounts
481 function adminsListAdminAccounts() {
482 // Select all admin accounts
483 $result = sqlQuery('SELECT
487 `default_acl` AS `access_mode`,
490 `{?_MYSQL_PREFIX?}_admins`
492 `login` ASC', __FUNCTION__, __LINE__);
494 while ($content = sqlFetchArray($result)) {
495 // Compile some variables
496 $content['access_mode'] = '{--ADMIN_ADMINS_ACCESS_MODE_' . strtoupper($content['access_mode']) . '--}';
497 $content['la_mode'] = '{--ADMIN_ADMINS_LA_MODE_' . strtoupper($content['la_mode']) . '--}';
499 // Load row template and switch color
500 $OUT .= loadTemplate('admin_list_admins_row', TRUE, $content);
504 sqlFreeResult($result);
507 loadTemplate('admin_list_admins', FALSE, $OUT);
510 // Sends out mail to all administrators
511 // IMPORTANT: Please use sendAdminNotification() instead of calling this function directly
512 function sendAdminsEmails ($subject, $template, $content, $userid) {
513 // Trim template name
514 $template = trim($template);
516 // Load email template
517 $message = loadEmailTemplate($template, $content, $userid);
519 // Check which admin shall receive this mail
520 $result = sqlQueryEscaped("SELECT `admin_id` FROM `{?_MYSQL_PREFIX?}_admins_mails` WHERE `mail_template`='%s' ORDER BY `admin_id` ASC",
521 array($template), __FUNCTION__, __LINE__);
524 if (ifSqlHasZeroNums($result)) {
525 // Is ext-admins' version at least 0.7.9?
526 if (isExtensionInstalledAndNewer('admins', '0.7.9')) {
527 // Create new entry (to all admins)
528 sqlQueryEscaped("INSERT INTO `{?_MYSQL_PREFIX?}_admins_mails` (`admin_id`, `mail_template`) VALUES (NULL, '%s')",
529 array($template), __FUNCTION__, __LINE__);
532 // Select all email adresses (default)
533 $result = sqlQuery('SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` ORDER BY `id` ASC',
534 __FUNCTION__, __LINE__);
537 // @TODO This can be, somehow, rewritten
539 while ($content = sqlFetchArray($result)) {
540 array_push($adminIds, $content['admin_id']);
544 sqlFreeResult($result);
549 // "implode" ids and query string
550 $adminId = implode(',', $adminIds);
552 // To which admin shall we sent it?
553 if ($adminId == '-1') {
555 if (isExtensionActive('events')) {
556 // Add line to user events
557 EVENTS_ADD_LINE($subject, $message, $userid);
559 // Log error for debug
560 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Extension 'ext-events' missing: template=%s,subj=%s,userid=%s",
567 // Abort here as below while() loop will cause problems
569 } elseif (($adminId == '0') || (empty($adminId))) {
570 // Select all email adresses
571 $result = sqlQuery('SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` ORDER BY `id` ASC',
572 __FUNCTION__, __LINE__);
574 // If Admin-Id is not "to-all" select
575 $result = sqlQueryEscaped('SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id` IN (%s) ORDER BY `id` ASC',
576 array($adminId), __FUNCTION__, __LINE__);
580 // Default is no special mail header
583 // Is the template a bug report?
584 if ($template == 'admin_report_bug') {
585 // Then set 'Reply-To:' again
586 $mailHeader = 'Reply-To: webmaster@mxchange.org' . PHP_EOL;
589 // Load email addresses and send away
590 while ($content = sqlFetchArray($result)) {
591 sendEmail($content['email'], $subject, $message, 'N', $mailHeader);
595 sqlFreeResult($result);
598 // "Getter" for current admin's expert settings
599 function getAminsExpertSettings () {
600 // Default is has not the right
601 $data['expert_settings'] = 'N';
603 // Get current admin Id
604 $adminId = getCurrentAdminId();
606 // Lookup settings in cache
607 if (isset($GLOBALS['cache_array']['admin']['expert_settings'][$adminId])) {
609 $data['expert_settings'] = $GLOBALS['cache_array']['admin']['expert_settings'][$adminId];
612 incrementStatsEntry('cache_hits');
613 } elseif (!isExtensionInstalled('cache')) {
614 // Load from database
615 $result = sqlQueryEscaped('SELECT `expert_settings` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1',
616 array($adminId), __FUNCTION__, __LINE__);
619 if (sqlNumRows($result) == 1) {
621 $data = sqlFetchArray($result);
624 $GLOBALS['cache_array']['admin']['expert_settings'][$adminId] = $data['expert_settings'];
628 sqlFreeResult($result);
632 return $data['expert_settings'];
635 // "Getter" for current admin's expert warning (if he wants to see them or not
636 function getAminsExpertWarning () {
637 // Default is has not the right
638 $data['expert_warning'] = 'N';
640 // Get current admin id
641 $adminId = getCurrentAdminId();
643 // Lookup warning in cache
644 if (isset($GLOBALS['cache_array']['admin']['expert_warning'][$adminId])) {
646 $data['expert_warning'] = $GLOBALS['cache_array']['admin']['expert_warning'][$adminId];
649 incrementStatsEntry('cache_hits');
650 } elseif (!isExtensionInstalled('cache')) {
651 // Load from database
652 $result = sqlQueryEscaped('SELECT `expert_warning` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1',
653 array($adminId), __FUNCTION__, __LINE__);
656 if (sqlNumRows($result) == 1) {
658 $data = sqlFetchArray($result);
661 $GLOBALS['cache_array']['admin']['expert_warning'][$adminId] = $data['expert_warning'];
665 sqlFreeResult($result);
669 return $data['expert_warning'];
672 // Get login_failures number from administrator's login name
673 function getAdminLoginFailures ($adminId) {
674 // Admin login should not be empty
675 if (empty($adminId)) {
676 reportBug(__FUNCTION__, __LINE__, 'adminId is empty.');
679 // By default no admin is found
680 $data['login_failures'] = -1;
683 if (isset($GLOBALS['cache_array']['admin']['login_failures'][$adminId])) {
684 // Use it if found to save SQL queries
685 $data['login_failures'] = $GLOBALS['cache_array']['admin']['login_failures'][$adminId];
688 incrementStatsEntry('cache_hits');
689 } elseif (!isExtensionActive('cache')) {
690 // Load from database
691 $result = sqlQueryEscaped('SELECT `login_failures` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1',
692 array($adminId), __FUNCTION__, __LINE__);
694 // Is there an entry?
695 if (sqlNumRows($result) == 1) {
697 $data = sqlFetchArray($result);
701 sqlFreeResult($result);
704 // Return the login_failures
705 return $data['login_failures'];
708 // Get last_failure number from administrator's login name
709 function getAdminLastFailure ($adminId) {
710 // Admin login should not be empty
711 if (empty($adminId)) {
712 reportBug(__FUNCTION__, __LINE__, 'adminId is empty.');
715 // By default no admin is found
716 $data['last_failure'] = -1;
719 if (isset($GLOBALS['cache_array']['admin']['last_failure'][$adminId])) {
720 // Use it if found to save SQL queries
721 $data['last_failure'] = $GLOBALS['cache_array']['admin']['last_failure'][$adminId];
724 incrementStatsEntry('cache_hits');
725 } elseif (!isExtensionActive('cache')) {
726 // Load from database
727 $result = sqlQueryEscaped('SELECT UNIX_TIMESTAMP(`last_failure`) AS `last_failure` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1',
728 array($adminId), __FUNCTION__, __LINE__);
730 // Is there an entry?
731 if (sqlNumRows($result) == 1) {
733 $data = sqlFetchArray($result);
737 sqlFreeResult($result);
740 // Return the last_failure
741 return $data['last_failure'];
744 //-----------------------------------------------------------------------------
746 //-----------------------------------------------------------------------------
748 // Wrapper function to check whether expert setting warning is enabled
749 function isAdminsExpertWarningEnabled () {
750 return (getAminsExpertWarning() == 'Y');
753 // Wrapper function to check whether expert setting is enabled
754 function isAdminsExpertSettingEnabled () {
755 return (getAminsExpertSettings() == 'Y');