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 - 2011 by Mailer Developer Team *
20 * For more information visit: http://www.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 (strpos($email, '@') !== false) {
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 // Rewrite email address to contact link
157 $email = '{%url=modules.php?module=' . $mod . '&what=admins_contct&admin=' . bigintval($adminId) . '%}';
161 SQL_FREERESULT($result);
162 } elseif ((is_int($email)) && ($email > 0)) {
164 $email = '{%url=modules.php?module=' . $mod . '&what=admins_contct&admin=' . bigintval($email) . '%}';
167 // Return rewritten (?) email address
171 // Change a lot admin account
172 function adminsChangeAdminAccount ($postData, $element = '', $displayMessage = true) {
177 foreach ($postData['login'] as $id => $login) {
179 $id = bigintval($id);
180 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'id=' . $id . ',login=' . $login);
182 // When both passwords match update admin account
183 if ((!empty($element)) && (isset($postData[$element]))) {
185 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_admins` SET `%s`='%s' WHERE `id`=%s LIMIT 1",
186 array($element, $postData[$element][$id], $id), __FUNCTION__, __LINE__);
188 // Admin account saved
189 $message = '{--ADMIN_ACCOUNT_SAVED--}';
190 } elseif ((!empty($postData['pass1'])) && (!empty($postData['pass2']))) {
191 // Update only if both passwords match
192 if (($postData['pass1'][$id] == $postData['pass2'][$id])) {
193 // Save only when both passwords are the same (also when they are empty)
194 $add = ''; $cache_update = 1;
197 $hash = generateHash($postData['pass1'][$id]);
199 // Save password when set
200 if (!empty($postData['pass1'][$id])) {
201 $add = sprintf(", `password`='%s'", SQL_ESCAPE($hash));
205 $adminId = getCurrentAdminId();
206 $salt = substr(getAdminHash(getAdminLogin($adminId)), 0, -40);
208 // Rewrite cookie when it's own account
209 if ($adminId == $id) {
210 // Set timeout cookie
211 setAdminLast(time());
213 if ($adminId != getCurrentAdminId()) {
214 // Update login cookie
215 setAdminId($adminId);
217 // Update password cookie as well?
221 } elseif (generateHash($postData['pass1'][$id], $salt) != getAdminMd5()) {
222 // Update password cookie
227 // Get default ACL from admin to check if we can allow him to change the default ACL
228 $default = getAdminDefaultAcl(getCurrentAdminId());
230 // Update admin account
231 if ($default == 'allow') {
232 // Allow changing default ACL
233 SQL_QUERY_ESC("UPDATE
234 `{?_MYSQL_PREFIX?}_admins`
236 `login`='%s'" . $add . ",
245 $postData['email'][$id],
246 $postData['mode'][$id],
247 $postData['la_mode'][$id],
249 ), __FUNCTION__, __LINE__);
251 // Do not allow it here
252 SQL_QUERY_ESC("UPDATE
253 `{?_MYSQL_PREFIX?}_admins`
255 `login`='%s'" . $add . ",
263 $postData['email'][$id],
264 $postData['la_mode'][$id],
266 ), __FUNCTION__, __LINE__);
269 // Admin account saved
270 $message = '{--ADMIN_ACCOUNT_SAVED--}';
272 // Passwords did not match
273 $message = '{--ADMIN_ADMINS_ERROR_PASS_MISMATCH--}';
276 // Update whole array
277 $SQL = 'UPDATE `{?_MYSQL_PREFIX?}_admins` SET ';
278 foreach ($postData as $entry => $value) {
279 // Skip login/id entry
280 if (in_array($entry, array('login', 'id'))) {
284 // Do we have a non-string (e.g. number, NULL, NOW() or back-tick at the beginning?
285 if (is_null($value[$id])) {
287 $SQL .= '`' . $entry . '`=NULL, ';
288 } elseif ((bigintval($value[$id], true, false) === $value[$id]) || ($value[$id] == 'NOW()') || (substr($value[$id], 0, 1) == '`')) {
289 // No need for ticks (')
290 $SQL .= '`' . $entry . '`=' . $value[$id] . ', ';
292 // Strings need ticks (') around them
293 $SQL .= '`' . $entry . "`='" . SQL_ESCAPE($value[$id]) . "', ";
297 // Remove last 2 chars and finish query
298 $SQL = substr($SQL, 0, -2) . ' WHERE `id`=%s LIMIT 1';
301 SQL_QUERY_ESC($SQL, array(bigintval($id)), __FUNCTION__, __LINE__);
304 if (SQL_AFFECTEDROWS() == 1) {
305 // Admin account saved
306 $message = '{--ADMIN_ACCOUNT_SAVED--}';
308 // Passwords did not match
309 $message = '{--ADMIN_ADMINS_ERROR_PASS_MISMATCH--}';
315 if (!empty($message)) {
316 if ($displayMessage === true) {
317 displayMessage($message);
322 runFilterChain('post_form_submited', postRequestArray());
328 // Make admin accounts editable
329 function adminsEditAdminAccount ($postData) {
330 // "Resolve" current's admin access mode
331 $currMode = getAdminDefaultAcl(getCurrentAdminId());
333 // Begin the edit loop
335 foreach ($postData['sel'] as $id => $selected) {
337 $id = bigintval($id);
339 // Get the admin's data
340 $result = SQL_QUERY_ESC("SELECT `login`,`email`,`default_acl` AS mode, `la_mode` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
341 array($id), __FUNCTION__, __LINE__);
342 if ((SQL_NUMROWS($result) == 1) && ($selected == 1)) {
344 $content = SQL_FETCHARRAY($result);
345 SQL_FREERESULT($result);
347 // Prepare some more data for the template
348 $content['id'] = $id;
350 // Shall we allow changing default ACL?
351 if ($currMode == 'allow') {
353 $content['mode'] = generateOptionList('/ARRAY/', array('allow', 'deny'), array('{--ADMIN_ADMINS_ACCESS_MODE_ALLOW--}', '{--ADMIN_ADMINS_ACCESS_MODE_DENY--}'), $content['mode']);
356 $content['mode'] = ' ';
358 $content['la_mode'] = generateOptionList('/ARRAY/', array('global', 'OLD', 'NEW'), array('{--ADMIN_ADMINS_LA_MODE_GLOBAL--}', '{--ADMIN_ADMINS_LA_MODE_OLD--}', '{--ADMIN_ADMINS_LA_MODE_NEW--}'), $content['la_mode']);
360 // Load row template and switch color
361 $OUT .= loadTemplate('admin_edit_admins_row', true, $content);
366 loadTemplate('admin_edit_admins', false, $OUT);
369 // Delete given admin accounts
370 function adminsDeleteAdminAccount ($postData) {
371 // Check if this account is the last one which cannot be deleted...
372 if (countSumTotalData('', 'admins', 'id', '', true) > 1) {
375 foreach ($postData['sel'] as $id => $selected) {
377 $id = bigintval($id);
379 // Get the admin's data
380 $result = SQL_QUERY_ESC("SELECT `login`,`email`,`default_acl` AS `mode`,`la_mode` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
381 array($id), __FUNCTION__, __LINE__);
383 // Do we have an entry?
384 if (SQL_NUMROWS($result) == 1) {
385 // Entry found, so load data
386 $content = SQL_FETCHARRAY($result);
387 $content['mode'] = '{--ADMIN_ADMINS_ACCESS_MODE_' . strtoupper($content['mode']) . '--}';
388 $content['la_mode'] = '{--ADMIN_ADMINS_LA_MODE_' . strtoupper($content['la_mode']) . '--}';
390 // Prepare some more data
391 $content['id'] = $id;
393 // Load row template and switch color
394 $OUT .= loadTemplate('admin_delete_admins_row', true, $content);
398 SQL_FREERESULT($result);
402 loadTemplate('admin_delete_admins', false, $OUT);
404 // Cannot delete last account!
405 displayMessage('{--ADMIN_ADMINS_CANNOT_DELETE_LAST--}');
409 // Remove the given accounts
410 function adminsRemoveAdminAccount ($postData) {
413 foreach ($postData['sel'] as $id => $del) {
415 $id = bigintval($id);
417 // Delete only when it's not your own account!
418 if (($del == 1) && (getCurrentAdminId() != $id)) {
419 // Rewrite his tasks to all admins
420 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_task_system` SET `assigned_admin`=NULL WHERE `assigned_admin`=%s",
421 array($id), __FUNCTION__, __LINE__);
424 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
425 array($id), __FUNCTION__, __LINE__);
429 // Remove cache if cache system is activated
430 runFilterChain('post_form_deleted', postRequestArray());
433 // List all admin accounts
434 function adminsListAdminAccounts() {
435 // Select all admin accounts
436 $result = SQL_QUERY('SELECT `id`,`login`,`email`,`default_acl` AS mode, `la_mode` FROM `{?_MYSQL_PREFIX?}_admins` ORDER BY `login` ASC', __FUNCTION__, __LINE__);
438 while ($content = SQL_FETCHARRAY($result)) {
439 // Compile some variables
440 $content['mode'] = '{--ADMIN_ADMINS_ACCESS_MODE_' . strtoupper($content['mode']) . '--}';
441 $content['la_mode'] = '{--ADMIN_ADMINS_LA_MODE_' . strtoupper($content['la_mode']) . '--}';
443 // Load row template and switch color
444 $OUT .= loadTemplate('admin_list_admins_row', true, $content);
448 SQL_FREERESULT($result);
451 loadTemplate('admin_list_admins', false, $OUT);
454 // Sends out mail to all administrators
455 // IMPORTANT: Please use sendAdminNotification() instead of calling this function directly
456 function sendAdminsEmails ($subj, $template, $content, $userid) {
457 // Trim template name
458 $template = trim($template);
460 // Load email template
461 $message = loadEmailTemplate($template, $content, $userid);
463 // Check which admin shall receive this mail
464 $result = SQL_QUERY_ESC("SELECT `admin_id` FROM `{?_MYSQL_PREFIX?}_admins_mails` WHERE `mail_template`='%s' ORDER BY `admin_id` ASC",
465 array($template), __FUNCTION__, __LINE__);
468 if (SQL_HASZERONUMS($result)) {
469 // Create new entry (to all admins)
470 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_admins_mails` (`admin_id`,`mail_template`) VALUES (0, '%s')",
471 array($template), __FUNCTION__, __LINE__);
474 // @TODO This can be, somehow, rewritten
476 while ($content = SQL_FETCHARRAY($result)) {
477 $adminIds[] = $content['admin_id'];
481 SQL_FREERESULT($result);
486 // "implode" ids and query string
487 $adminId = implode(',', $adminIds);
488 if ($adminId == '-1') {
489 if (isExtensionActive('events')) {
490 // Add line to user events
491 EVENTS_ADD_LINE($subj, $message, $userid);
493 // Log error for debug
494 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Extension 'events' missing: tpl=%s,subj=%s,userid=%s",
500 } elseif (($adminId == '0') || (empty($adminId))) {
501 // Select all email adresses
502 $result = SQL_QUERY('SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` ORDER BY `id` ASC',
503 __FUNCTION__, __LINE__);
505 // If Admin-Id is not "to-all" select
506 $result = SQL_QUERY_ESC("SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id` IN (%s) ORDER BY `id` ASC",
507 array($adminId), __FUNCTION__, __LINE__);
511 // Load email addresses and send away
512 while ($content = SQL_FETCHARRAY($result)) {
513 sendEmail($content['email'], $subj, $message);
517 SQL_FREERESULT($result);
520 // "Getter" for current admin's expert settings
521 function getAminsExpertSettings () {
522 // Default is has not the right
523 $data['expert_settings'] = 'N';
525 // Get current admin Id
526 $adminId = getCurrentAdminId();
528 // Lookup settings in cache
529 if (isset($GLOBALS['cache_array']['admin']['expert_settings'][$adminId])) {
531 $data['expert_settings'] = $GLOBALS['cache_array']['admin']['expert_settings'][$adminId];
534 incrementStatsEntry('cache_hits');
535 } elseif (!isExtensionInstalled('cache')) {
536 // Load from database
537 $result = SQL_QUERY_ESC("SELECT `expert_settings` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
538 array($adminId), __FUNCTION__, __LINE__);
541 if (SQL_NUMROWS($result) == 1) {
543 $data = SQL_FETCHARRAY($result);
546 $GLOBALS['cache_array']['admin']['expert_settings'][$adminId] = $data['expert_settings'];
550 SQL_FREERESULT($result);
554 return $data['expert_settings'];
557 // "Getter" for current admin's expert warning (if he wants to see them or not
558 function getAminsExpertWarning () {
559 // Default is has not the right
560 $data['expert_warning'] = 'N';
562 // Get current admin id
563 $adminId = getCurrentAdminId();
565 // Lookup warning in cache
566 if (isset($GLOBALS['cache_array']['admin']['expert_warning'][$adminId])) {
568 $data['expert_warning'] = $GLOBALS['cache_array']['admin']['expert_warning'][$adminId];
571 incrementStatsEntry('cache_hits');
572 } elseif (!isExtensionInstalled('cache')) {
573 // Load from database
574 $result = SQL_QUERY_ESC("SELECT `expert_warning` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
575 array($adminId), __FUNCTION__, __LINE__);
578 if (SQL_NUMROWS($result) == 1) {
580 $data = SQL_FETCHARRAY($result);
583 $GLOBALS['cache_array']['admin']['expert_warning'][$adminId] = $data['expert_warning'];
587 SQL_FREERESULT($result);
591 return $data['expert_warning'];
594 // Get login_failures number from administrator's login name
595 function getAdminLoginFailures ($adminId) {
596 // Admin login should not be empty
597 if (empty($adminId)) {
598 debug_report_bug(__FUNCTION__, __LINE__, 'adminId is empty.');
601 // By default no admin is found
602 $data['login_failures'] = -1;
605 if (isset($GLOBALS['cache_array']['admin']['login_failures'][$adminId])) {
606 // Use it if found to save SQL queries
607 $data['login_failures'] = $GLOBALS['cache_array']['admin']['login_failures'][$adminId];
610 incrementStatsEntry('cache_hits');
611 } elseif (!isExtensionActive('cache')) {
612 // Load from database
613 $result = SQL_QUERY_ESC("SELECT `login_failures` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
614 array($adminId), __FUNCTION__, __LINE__);
616 // Do we have an entry?
617 if (SQL_NUMROWS($result) == 1) {
619 $data = SQL_FETCHARRAY($result);
623 SQL_FREERESULT($result);
626 // Return the login_failures
627 return $data['login_failures'];
630 // Get last_failure number from administrator's login name
631 function getAdminLastFailure ($adminId) {
632 // Admin login should not be empty
633 if (empty($adminId)) {
634 debug_report_bug(__FUNCTION__, __LINE__, 'adminId is empty.');
637 // By default no admin is found
638 $data['last_failure'] = -1;
641 if (isset($GLOBALS['cache_array']['admin']['last_failure'][$adminId])) {
642 // Use it if found to save SQL queries
643 $data['last_failure'] = $GLOBALS['cache_array']['admin']['last_failure'][$adminId];
646 incrementStatsEntry('cache_hits');
647 } elseif (!isExtensionActive('cache')) {
648 // Load from database
649 $result = SQL_QUERY_ESC("SELECT UNIX_TIMESTAMP(`last_failure`) AS `last_failure` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
650 array($adminId), __FUNCTION__, __LINE__);
652 // Do we have an entry?
653 if (SQL_NUMROWS($result) == 1) {
655 $data = SQL_FETCHARRAY($result);
659 SQL_FREERESULT($result);
662 // Return the last_failure
663 return $data['last_failure'];
666 //-----------------------------------------------------------------------------
668 //-----------------------------------------------------------------------------
670 // Wrapper function to check wether expert setting warning is enabled
671 function isAdminsExpertWarningEnabled () {
672 return (getAminsExpertWarning() == 'Y');