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 - 2012 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 // But default result is failed
57 $GLOBALS[__FUNCTION__][$adminId][$action][$what] = FALSE;
59 // Get admin's defult access right
60 $default = getAdminDefaultAcl($adminId);
63 // Check for parent menu:
64 // First get it's action value
65 $parent_action = getActionFromModuleWhat('admin', $what);
67 // Check with this function...
68 $parent = isAdminsAllowedByAcl($parent_action, '');
70 // Anything else is true!
74 // Shall I test for a main or sub menu? (action or what?)
76 if ((isExtensionInstalledAndNewer('cache', '0.1.2')) && (isset($GLOBALS['cache_array']['admin_acls'])) && (count($GLOBALS['cache_array']['admin_acls']) > 0)) {
78 if ((!empty($action)) && (isset($GLOBALS['cache_array']['admin_acls']['action_menu'][$adminId])) & (in_array($action, $GLOBALS['cache_array']['admin_acls']['action_menu'][$adminId]))) {
80 $key = array_search($action, $GLOBALS['cache_array']['admin_acls']['action_menu'][$adminId]);
82 // Main menu line found
83 $aclMode = $GLOBALS['cache_array']['admin_acls']['access_mode'][$adminId][$key];
86 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'action=' . $action . ',key=' . $key . ',acl_mode=' . $aclMode);
89 incrementStatsEntry('cache_hits');
90 } elseif ((!empty($what)) && (isset($GLOBALS['cache_array']['admin_acls']['what_menu'][$adminId])) && (in_array($what, $GLOBALS['cache_array']['admin_acls']['what_menu'][$adminId]))) {
92 $key = array_search($action, $GLOBALS['cache_array']['admin_acls']['what_menu'][$adminId]);
95 $aclMode = $GLOBALS['cache_array']['admin_acls']['access_mode'][$adminId][$key];
98 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'what=' . $what . ',key=' . $key . ',acl_mode=' . $aclMode);
101 incrementStatsEntry('cache_hits');
103 } elseif (!isExtensionActive('cache')) {
104 // Extension ext-cache is absent, so load it from database
106 if (!empty($action)) {
108 $result = SQL_QUERY_ESC("SELECT `access_mode` FROM `{?_MYSQL_PREFIX?}_admins_acls` WHERE `admin_id`=%s AND `action_menu`='%s' LIMIT 1",
109 array(bigintval($adminId), $action), __FUNCTION__, __LINE__);
110 } elseif (!empty($what)) {
112 $result = SQL_QUERY_ESC("SELECT `access_mode` FROM `{?_MYSQL_PREFIX?}_admins_acls` WHERE `admin_id`=%s AND `what_menu`='%s' LIMIT 1",
113 array(bigintval($adminId), $what), __FUNCTION__, __LINE__);
116 // Is an entry found?
117 if (SQL_NUMROWS($result) == 1) {
119 list($aclMode) = SQL_FETCHROW($result);
123 SQL_FREERESULT($result);
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 = SQL_QUERY_ESC("SELECT `id`
145 `{?_MYSQL_PREFIX?}_admins`
149 array($email), __FUNCTION__, __LINE__);
151 // Is there an entry?
152 if (SQL_NUMROWS($result) == 1) {
154 list($adminId) = SQL_FETCHROW($result);
156 // Call this function again
157 $email = generateAdminEmailLink($adminId, $mod);
161 SQL_FREERESULT($result);
162 } elseif (isValidUserId($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 SQL_QUERY_ESC("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'", SQL_ESCAPE($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 SQL_QUERY_ESC("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 SQL_QUERY_ESC("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 SQL_QUERY_ESC($SQL, array(bigintval($id)), __FUNCTION__, __LINE__);
290 if (SQL_AFFECTEDROWS() == 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 = SQL_QUERY_ESC("SELECT `login`, `email` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
326 array($id), __FUNCTION__, __LINE__);
327 if ((SQL_NUMROWS($result) == 1) && ($selected == 1)) {
329 $content = SQL_FETCHARRAY($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 SQL_FREERESULT($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 = SQL_QUERY_ESC("SELECT `login`, `email`, `default_acl` AS `access_mode`, `la_mode` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
419 array($id), __FUNCTION__, __LINE__);
421 // Is there an entry?
422 if (SQL_NUMROWS($result) == 1) {
423 // Entry found, so load data
424 $content = SQL_FETCHARRAY($result);
425 $content['access_mode'] = '{--ADMIN_ADMINS_ACCESS_MODE_' . strtoupper($content['access_mode']) . '--}';
426 $content['la_mode'] = '{--ADMIN_ADMINS_LA_MODE_' . strtoupper($content['la_mode']) . '--}';
428 // Prepare some more data
429 $content['id'] = $id;
431 // Load row template and switch color
432 $OUT .= loadTemplate('admin_delete_admins_row', TRUE, $content);
436 SQL_FREERESULT($result);
440 loadTemplate('admin_delete_admins', FALSE, $OUT);
442 // Cannot delete last account!
443 displayMessage('{--ADMIN_ADMINS_CANNOT_DELETE_LAST--}');
447 // Remove the given accounts
448 function adminsRemoveAdminAccount ($postData) {
451 foreach ($postData['sel'] as $id => $del) {
453 $id = bigintval($id);
455 // Delete only when it's not your own account!
456 if (($del == 1) && (getCurrentAdminId() != $id)) {
457 // Rewrite his tasks to all admins
458 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_task_system` SET `assigned_admin`=NULL WHERE `assigned_admin`=%s",
459 array($id), __FUNCTION__, __LINE__);
462 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
463 array($id), __FUNCTION__, __LINE__);
467 // Remove cache if cache system is activated
468 runFilterChain('post_form_deleted', postRequestArray());
471 // List all admin accounts
472 function adminsListAdminAccounts() {
473 // Select all admin accounts
474 $result = SQL_QUERY('SELECT
478 `default_acl` AS `access_mode`,
481 `{?_MYSQL_PREFIX?}_admins`
483 `login` ASC', __FUNCTION__, __LINE__);
485 while ($content = SQL_FETCHARRAY($result)) {
486 // Compile some variables
487 $content['access_mode'] = '{--ADMIN_ADMINS_ACCESS_MODE_' . strtoupper($content['access_mode']) . '--}';
488 $content['la_mode'] = '{--ADMIN_ADMINS_LA_MODE_' . strtoupper($content['la_mode']) . '--}';
490 // Load row template and switch color
491 $OUT .= loadTemplate('admin_list_admins_row', TRUE, $content);
495 SQL_FREERESULT($result);
498 loadTemplate('admin_list_admins', FALSE, $OUT);
501 // Sends out mail to all administrators
502 // IMPORTANT: Please use sendAdminNotification() instead of calling this function directly
503 function sendAdminsEmails ($subject, $template, $content, $userid) {
504 // Trim template name
505 $template = trim($template);
507 // Load email template
508 $message = loadEmailTemplate($template, $content, $userid);
510 // Check which admin shall receive this mail
511 $result = SQL_QUERY_ESC("SELECT `admin_id` FROM `{?_MYSQL_PREFIX?}_admins_mails` WHERE `mail_template`='%s' ORDER BY `admin_id` ASC",
512 array($template), __FUNCTION__, __LINE__);
515 if (SQL_HASZERONUMS($result)) {
516 // Is ext-admins' version at least 0.7.9?
517 if (isExtensionInstalledAndNewer('admins', '0.7.9')) {
518 // Create new entry (to all admins)
519 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_admins_mails` (`admin_id`, `mail_template`) VALUES (NULL, '%s')",
520 array($template), __FUNCTION__, __LINE__);
523 // Select all email adresses (default)
524 $result = SQL_QUERY('SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` ORDER BY `id` ASC',
525 __FUNCTION__, __LINE__);
528 // @TODO This can be, somehow, rewritten
530 while ($content = SQL_FETCHARRAY($result)) {
531 array_push($adminIds, $content['admin_id']);
535 SQL_FREERESULT($result);
540 // "implode" ids and query string
541 $adminId = implode(',', $adminIds);
543 // To which admin shall we sent it?
544 if ($adminId == '-1') {
546 if (isExtensionActive('events')) {
547 // Add line to user events
548 EVENTS_ADD_LINE($subject, $message, $userid);
550 // Log error for debug
551 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Extension 'ext-events' missing: template=%s,subj=%s,userid=%s",
558 // Abort here as below while() loop will cause problems
560 } elseif (($adminId == '0') || (empty($adminId))) {
561 // Select all email adresses
562 $result = SQL_QUERY('SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` ORDER BY `id` ASC',
563 __FUNCTION__, __LINE__);
565 // If Admin-Id is not "to-all" select
566 $result = SQL_QUERY_ESC("SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id` IN (%s) ORDER BY `id` ASC",
567 array($adminId), __FUNCTION__, __LINE__);
571 // Default is no special mail header
574 // Is the template a bug report?
575 if ($template == 'admin_report_bug') {
576 // Then set 'Reply-To:' again
577 $mailHeader = 'Reply-To: webmaster@mxchange.org' . PHP_EOL;
580 // Load email addresses and send away
581 while ($content = SQL_FETCHARRAY($result)) {
582 sendEmail($content['email'], $subject, $message, 'N', $mailHeader);
586 SQL_FREERESULT($result);
589 // "Getter" for current admin's expert settings
590 function getAminsExpertSettings () {
591 // Default is has not the right
592 $data['expert_settings'] = 'N';
594 // Get current admin Id
595 $adminId = getCurrentAdminId();
597 // Lookup settings in cache
598 if (isset($GLOBALS['cache_array']['admin']['expert_settings'][$adminId])) {
600 $data['expert_settings'] = $GLOBALS['cache_array']['admin']['expert_settings'][$adminId];
603 incrementStatsEntry('cache_hits');
604 } elseif (!isExtensionInstalled('cache')) {
605 // Load from database
606 $result = SQL_QUERY_ESC("SELECT `expert_settings` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
607 array($adminId), __FUNCTION__, __LINE__);
610 if (SQL_NUMROWS($result) == 1) {
612 $data = SQL_FETCHARRAY($result);
615 $GLOBALS['cache_array']['admin']['expert_settings'][$adminId] = $data['expert_settings'];
619 SQL_FREERESULT($result);
623 return $data['expert_settings'];
626 // "Getter" for current admin's expert warning (if he wants to see them or not
627 function getAminsExpertWarning () {
628 // Default is has not the right
629 $data['expert_warning'] = 'N';
631 // Get current admin id
632 $adminId = getCurrentAdminId();
634 // Lookup warning in cache
635 if (isset($GLOBALS['cache_array']['admin']['expert_warning'][$adminId])) {
637 $data['expert_warning'] = $GLOBALS['cache_array']['admin']['expert_warning'][$adminId];
640 incrementStatsEntry('cache_hits');
641 } elseif (!isExtensionInstalled('cache')) {
642 // Load from database
643 $result = SQL_QUERY_ESC("SELECT `expert_warning` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
644 array($adminId), __FUNCTION__, __LINE__);
647 if (SQL_NUMROWS($result) == 1) {
649 $data = SQL_FETCHARRAY($result);
652 $GLOBALS['cache_array']['admin']['expert_warning'][$adminId] = $data['expert_warning'];
656 SQL_FREERESULT($result);
660 return $data['expert_warning'];
663 // Get login_failures number from administrator's login name
664 function getAdminLoginFailures ($adminId) {
665 // Admin login should not be empty
666 if (empty($adminId)) {
667 reportBug(__FUNCTION__, __LINE__, 'adminId is empty.');
670 // By default no admin is found
671 $data['login_failures'] = -1;
674 if (isset($GLOBALS['cache_array']['admin']['login_failures'][$adminId])) {
675 // Use it if found to save SQL queries
676 $data['login_failures'] = $GLOBALS['cache_array']['admin']['login_failures'][$adminId];
679 incrementStatsEntry('cache_hits');
680 } elseif (!isExtensionActive('cache')) {
681 // Load from database
682 $result = SQL_QUERY_ESC("SELECT `login_failures` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
683 array($adminId), __FUNCTION__, __LINE__);
685 // Is there an entry?
686 if (SQL_NUMROWS($result) == 1) {
688 $data = SQL_FETCHARRAY($result);
692 SQL_FREERESULT($result);
695 // Return the login_failures
696 return $data['login_failures'];
699 // Get last_failure number from administrator's login name
700 function getAdminLastFailure ($adminId) {
701 // Admin login should not be empty
702 if (empty($adminId)) {
703 reportBug(__FUNCTION__, __LINE__, 'adminId is empty.');
706 // By default no admin is found
707 $data['last_failure'] = -1;
710 if (isset($GLOBALS['cache_array']['admin']['last_failure'][$adminId])) {
711 // Use it if found to save SQL queries
712 $data['last_failure'] = $GLOBALS['cache_array']['admin']['last_failure'][$adminId];
715 incrementStatsEntry('cache_hits');
716 } elseif (!isExtensionActive('cache')) {
717 // Load from database
718 $result = SQL_QUERY_ESC("SELECT UNIX_TIMESTAMP(`last_failure`) AS `last_failure` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
719 array($adminId), __FUNCTION__, __LINE__);
721 // Is there an entry?
722 if (SQL_NUMROWS($result) == 1) {
724 $data = SQL_FETCHARRAY($result);
728 SQL_FREERESULT($result);
731 // Return the last_failure
732 return $data['last_failure'];
735 //-----------------------------------------------------------------------------
737 //-----------------------------------------------------------------------------
739 // Wrapper function to check whether expert setting warning is enabled
740 function isAdminsExpertWarningEnabled () {
741 return (getAminsExpertWarning() == 'Y');
744 // Wrapper function to check whether expert setting is enabled
745 function isAdminsExpertSettingEnabled () {
746 return (getAminsExpertSettings() == 'Y');