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__][$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",
189 array($element, $postData[$element][$id], $id), __FUNCTION__, __LINE__);
191 // Admin account saved
192 $message = '{--ADMIN_ACCOUNT_SAVED--}';
193 } elseif ((!empty($postData['pass1'])) && (!empty($postData['pass2']))) {
194 // Update only if both passwords match
195 if (($postData['pass1'][$id] == $postData['pass2'][$id])) {
196 // Save only when both passwords are the same (also when they are empty)
197 $add = ''; $cache_update = 1;
200 $hash = generateHash($postData['pass1'][$id]);
202 // Save password when set
203 if (!empty($postData['pass1'][$id])) {
204 $add = sprintf(",`password`='%s'", SQL_ESCAPE($hash));
208 $adminId = getCurrentAdminId();
209 $salt = substr(getAdminHash(getAdminLogin($adminId)), 0, -40);
211 // Rewrite cookie when it's own account
212 if ($adminId == $id) {
213 // Set timeout cookie
214 setAdminLast(time());
216 if ($adminId != getCurrentAdminId()) {
217 // Update login cookie
218 setAdminId($adminId);
220 // Update password cookie as well?
224 } elseif (generateHash($postData['pass1'][$id], $salt) != getAdminMd5()) {
225 // Update password cookie
230 // Get default ACL from admin to check if we can allow him to change the default ACL
231 $default = getAdminDefaultAcl(getCurrentAdminId());
233 // Update admin account
234 if ($default == 'allow') {
235 // Allow changing default ACL
236 SQL_QUERY_ESC("UPDATE
237 `{?_MYSQL_PREFIX?}_admins`
239 `login`='%s'" . $add . ",
248 $postData['email'][$id],
249 $postData['access_mode'][$id],
250 $postData['la_mode'][$id],
252 ), __FUNCTION__, __LINE__);
254 // Do not allow it here
255 SQL_QUERY_ESC("UPDATE
256 `{?_MYSQL_PREFIX?}_admins`
258 `login`='%s'" . $add . ",
266 $postData['email'][$id],
267 $postData['la_mode'][$id],
269 ), __FUNCTION__, __LINE__);
272 // Admin account saved
273 $message = '{--ADMIN_ACCOUNT_SAVED--}';
275 // Passwords did not match
276 $message = '{--ADMIN_ADMINS_ERROR_PASS_MISMATCH--}';
279 // Update whole array
280 $SQL = getUpdateSqlFromArray($postData, 'admins', 'id', '%s', array('login', 'id'), $id);
283 SQL_QUERY_ESC($SQL, array(bigintval($id)), __FUNCTION__, __LINE__);
286 if (SQL_AFFECTEDROWS() == 1) {
287 // Admin account saved
288 $message = '{--ADMIN_ACCOUNT_SAVED--}';
290 // Passwords did not match
291 $message = '{--ADMIN_ADMINS_ERROR_PASS_MISMATCH--}';
296 // Display message if not empty and allowed
297 if ((!empty($message)) && ($displayMessage === true)) {
299 displayMessage($message);
303 runFilterChain('post_form_submited', postRequestArray());
309 // Make admin accounts editable
310 function adminsEditAdminAccount ($postData) {
311 // "Resolve" current's admin access mode
312 $currMode = getAdminDefaultAcl(getCurrentAdminId());
314 // Begin the edit loop
316 foreach ($postData['sel'] as $id => $selected) {
318 $id = bigintval($id);
320 // Get the admin's data
321 $result = SQL_QUERY_ESC("SELECT `login`,`email` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
322 array($id), __FUNCTION__, __LINE__);
323 if ((SQL_NUMROWS($result) == 1) && ($selected == 1)) {
325 $content = SQL_FETCHARRAY($result);
327 // Prepare some more data for the template
328 $content['id'] = $id;
330 // Shall we allow changing default ACL?
331 if ($currMode == 'allow') {
333 $content['access_mode'] = '{%pipe,generateAdminAccessModeSelectionBox=' . $id . '%}';
336 $content['access_mode'] = ' ';
339 // Load row template and switch color
340 $OUT .= loadTemplate('admin_edit_admins_row', true, $content);
344 SQL_FREERESULT($result);
348 loadTemplate('admin_edit_admins', false, $OUT);
351 // Generate access mode selection box for given admin id
352 function generateAdminAccessModeSelectionBox ($adminId = NULL) {
353 // Start the selection box
354 $OUT = '<select name="access_mode[' . $adminId . ']" size="1" class="form_select">';
357 $OUT .= generateOptions(
363 '{--ADMIN_ADMINS_ACCESS_MODE_ALLOW--}',
364 '{--ADMIN_ADMINS_ACCESS_MODE_DENY--}'
366 getAdminDefaultAcl($adminId)
376 // Generate menu mode selection box for given admin it
377 function generateAdminMenuModeSelectionBox ($adminId = NULL) {
378 // Start the selection box
379 $OUT = '<select name="la_mode[{%pipe,convertNullToZero=' . convertZeroToNull($adminId) . '%}]" size="1" class="form_select">';
382 $OUT .= generateOptions(
389 '{--ADMIN_ADMINS_LA_MODE_GLOBAL--}',
390 '{--ADMIN_ADMINS_LA_MODE_OLD--}',
391 '{--ADMIN_ADMINS_LA_MODE_NEW--}'
393 getAdminMenuMode($adminId)
403 // Delete given admin accounts
404 function adminsDeleteAdminAccount ($postData) {
405 // Check if this account is the last one which cannot be deleted...
406 if (countSumTotalData('', 'admins', 'id', '', true) > 1) {
409 foreach ($postData['sel'] as $id => $selected) {
411 $id = bigintval($id);
413 // Get the admin's data
414 $result = SQL_QUERY_ESC("SELECT `login`,`email`,`default_acl` AS `access_mode`,`la_mode` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
415 array($id), __FUNCTION__, __LINE__);
417 // Do we have an entry?
418 if (SQL_NUMROWS($result) == 1) {
419 // Entry found, so load data
420 $content = SQL_FETCHARRAY($result);
421 $content['access_mode'] = '{--ADMIN_ADMINS_ACCESS_MODE_' . strtoupper($content['access_mode']) . '--}';
422 $content['la_mode'] = '{--ADMIN_ADMINS_LA_MODE_' . strtoupper($content['la_mode']) . '--}';
424 // Prepare some more data
425 $content['id'] = $id;
427 // Load row template and switch color
428 $OUT .= loadTemplate('admin_delete_admins_row', true, $content);
432 SQL_FREERESULT($result);
436 loadTemplate('admin_delete_admins', false, $OUT);
438 // Cannot delete last account!
439 displayMessage('{--ADMIN_ADMINS_CANNOT_DELETE_LAST--}');
443 // Remove the given accounts
444 function adminsRemoveAdminAccount ($postData) {
447 foreach ($postData['sel'] as $id => $del) {
449 $id = bigintval($id);
451 // Delete only when it's not your own account!
452 if (($del == 1) && (getCurrentAdminId() != $id)) {
453 // Rewrite his tasks to all admins
454 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_task_system` SET `assigned_admin`=NULL WHERE `assigned_admin`=%s",
455 array($id), __FUNCTION__, __LINE__);
458 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
459 array($id), __FUNCTION__, __LINE__);
463 // Remove cache if cache system is activated
464 runFilterChain('post_form_deleted', postRequestArray());
467 // List all admin accounts
468 function adminsListAdminAccounts() {
469 // Select all admin accounts
470 $result = SQL_QUERY('SELECT
474 `default_acl` AS `access_mode`,
477 `{?_MYSQL_PREFIX?}_admins`
479 `login` ASC', __FUNCTION__, __LINE__);
481 while ($content = SQL_FETCHARRAY($result)) {
482 // Compile some variables
483 $content['access_mode'] = '{--ADMIN_ADMINS_ACCESS_MODE_' . strtoupper($content['access_mode']) . '--}';
484 $content['la_mode'] = '{--ADMIN_ADMINS_LA_MODE_' . strtoupper($content['la_mode']) . '--}';
486 // Load row template and switch color
487 $OUT .= loadTemplate('admin_list_admins_row', true, $content);
491 SQL_FREERESULT($result);
494 loadTemplate('admin_list_admins', false, $OUT);
497 // Sends out mail to all administrators
498 // IMPORTANT: Please use sendAdminNotification() instead of calling this function directly
499 function sendAdminsEmails ($subject, $template, $content, $userid) {
500 // Trim template name
501 $template = trim($template);
503 // Load email template
504 $message = loadEmailTemplate($template, $content, $userid);
506 // Check which admin shall receive this mail
507 $result = SQL_QUERY_ESC("SELECT `admin_id` FROM `{?_MYSQL_PREFIX?}_admins_mails` WHERE `mail_template`='%s' ORDER BY `admin_id` ASC",
508 array($template), __FUNCTION__, __LINE__);
511 if (SQL_HASZERONUMS($result)) {
512 // Create new entry (to all admins)
513 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_admins_mails` (`admin_id`,`mail_template`) VALUES (0, '%s')",
514 array($template), __FUNCTION__, __LINE__);
516 // Select all email adresses (default)
517 $result = SQL_QUERY('SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` ORDER BY `id` ASC',
518 __FUNCTION__, __LINE__);
521 // @TODO This can be, somehow, rewritten
523 while ($content = SQL_FETCHARRAY($result)) {
524 array_push($adminIds, $content['admin_id']);
528 SQL_FREERESULT($result);
533 // "implode" ids and query string
534 $adminId = implode(',', $adminIds);
536 // To which admin shall we sent it?
537 if ($adminId == '-1') {
539 if (isExtensionActive('events')) {
540 // Add line to user events
541 EVENTS_ADD_LINE($subject, $message, $userid);
543 // Log error for debug
544 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Extension 'ext-events' missing: template=%s,subj=%s,userid=%s",
550 } elseif (($adminId == '0') || (empty($adminId))) {
551 // Select all email adresses
552 $result = SQL_QUERY('SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` ORDER BY `id` ASC',
553 __FUNCTION__, __LINE__);
555 // If Admin-Id is not "to-all" select
556 $result = SQL_QUERY_ESC("SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id` IN (%s) ORDER BY `id` ASC",
557 array($adminId), __FUNCTION__, __LINE__);
561 // Default is no special mail header
564 // Is the template a bug report?
565 if ($template == 'admin_report_bug') {
566 // Then set 'Reply-To:' again
567 $mailHeader = 'Reply-To: webmaster@mxchange.org' . chr(10);
570 // Load email addresses and send away
571 while ($content = SQL_FETCHARRAY($result)) {
572 sendEmail($content['email'], $subject, $message, 'N', $mailHeader);
576 SQL_FREERESULT($result);
579 // "Getter" for current admin's expert settings
580 function getAminsExpertSettings () {
581 // Default is has not the right
582 $data['expert_settings'] = 'N';
584 // Get current admin Id
585 $adminId = getCurrentAdminId();
587 // Lookup settings in cache
588 if (isset($GLOBALS['cache_array']['admin']['expert_settings'][$adminId])) {
590 $data['expert_settings'] = $GLOBALS['cache_array']['admin']['expert_settings'][$adminId];
593 incrementStatsEntry('cache_hits');
594 } elseif (!isExtensionInstalled('cache')) {
595 // Load from database
596 $result = SQL_QUERY_ESC("SELECT `expert_settings` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
597 array($adminId), __FUNCTION__, __LINE__);
600 if (SQL_NUMROWS($result) == 1) {
602 $data = SQL_FETCHARRAY($result);
605 $GLOBALS['cache_array']['admin']['expert_settings'][$adminId] = $data['expert_settings'];
609 SQL_FREERESULT($result);
613 return $data['expert_settings'];
616 // "Getter" for current admin's expert warning (if he wants to see them or not
617 function getAminsExpertWarning () {
618 // Default is has not the right
619 $data['expert_warning'] = 'N';
621 // Get current admin id
622 $adminId = getCurrentAdminId();
624 // Lookup warning in cache
625 if (isset($GLOBALS['cache_array']['admin']['expert_warning'][$adminId])) {
627 $data['expert_warning'] = $GLOBALS['cache_array']['admin']['expert_warning'][$adminId];
630 incrementStatsEntry('cache_hits');
631 } elseif (!isExtensionInstalled('cache')) {
632 // Load from database
633 $result = SQL_QUERY_ESC("SELECT `expert_warning` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
634 array($adminId), __FUNCTION__, __LINE__);
637 if (SQL_NUMROWS($result) == 1) {
639 $data = SQL_FETCHARRAY($result);
642 $GLOBALS['cache_array']['admin']['expert_warning'][$adminId] = $data['expert_warning'];
646 SQL_FREERESULT($result);
650 return $data['expert_warning'];
653 // Get login_failures number from administrator's login name
654 function getAdminLoginFailures ($adminId) {
655 // Admin login should not be empty
656 if (empty($adminId)) {
657 reportBug(__FUNCTION__, __LINE__, 'adminId is empty.');
660 // By default no admin is found
661 $data['login_failures'] = -1;
664 if (isset($GLOBALS['cache_array']['admin']['login_failures'][$adminId])) {
665 // Use it if found to save SQL queries
666 $data['login_failures'] = $GLOBALS['cache_array']['admin']['login_failures'][$adminId];
669 incrementStatsEntry('cache_hits');
670 } elseif (!isExtensionActive('cache')) {
671 // Load from database
672 $result = SQL_QUERY_ESC("SELECT `login_failures` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
673 array($adminId), __FUNCTION__, __LINE__);
675 // Do we have an entry?
676 if (SQL_NUMROWS($result) == 1) {
678 $data = SQL_FETCHARRAY($result);
682 SQL_FREERESULT($result);
685 // Return the login_failures
686 return $data['login_failures'];
689 // Get last_failure number from administrator's login name
690 function getAdminLastFailure ($adminId) {
691 // Admin login should not be empty
692 if (empty($adminId)) {
693 reportBug(__FUNCTION__, __LINE__, 'adminId is empty.');
696 // By default no admin is found
697 $data['last_failure'] = -1;
700 if (isset($GLOBALS['cache_array']['admin']['last_failure'][$adminId])) {
701 // Use it if found to save SQL queries
702 $data['last_failure'] = $GLOBALS['cache_array']['admin']['last_failure'][$adminId];
705 incrementStatsEntry('cache_hits');
706 } elseif (!isExtensionActive('cache')) {
707 // Load from database
708 $result = SQL_QUERY_ESC("SELECT UNIX_TIMESTAMP(`last_failure`) AS `last_failure` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
709 array($adminId), __FUNCTION__, __LINE__);
711 // Do we have an entry?
712 if (SQL_NUMROWS($result) == 1) {
714 $data = SQL_FETCHARRAY($result);
718 SQL_FREERESULT($result);
721 // Return the last_failure
722 return $data['last_failure'];
725 //-----------------------------------------------------------------------------
727 //-----------------------------------------------------------------------------
729 // Wrapper function to check whether expert setting warning is enabled
730 function isAdminsExpertWarningEnabled () {
731 return (getAminsExpertWarning() == 'Y');