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, 2010 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 adminsCheckAdminAcl ($action, $what) {
45 // If action is login or logout allow allways!
47 if (($action == 'login') || ($action == 'logout')) return true;
53 $adminId = getCurrentAdminId();
55 // Get admin's defult access right
56 $default = getAdminDefaultAcl($adminId);
59 // Check for parent menu:
60 // First get it's action value
61 $parent_action = getActionFromModuleWhat('admin', $what);
63 // Check with this function...
64 $parent = adminsCheckAdminAcl($parent_action, '');
66 // Anything else is true!
70 // Shall I test for a main or sub menu? (action or what?)
72 if ((isExtensionInstalledAndNewer('cache', '0.1.2')) && (isset($GLOBALS['cache_array']['admin_acls'])) && (count($GLOBALS['cache_array']['admin_acls']) > 0)) {
74 if ((!empty($action)) && (isset($GLOBALS['cache_array']['admin_acls']['action_menu'][$adminId])) & ($GLOBALS['cache_array']['admin_acls']['action_menu'][$adminId] == $action)) {
75 // Main menu line found
76 $acl_mode = $GLOBALS['cache_array']['admin_acls']['access_mode'][$adminId];
79 incrementStatsEntry('cache_hits');
80 } elseif ((!empty($what)) && (isset($GLOBALS['cache_array']['admin_acls']['what_menu'][$adminId])) && ($GLOBALS['cache_array']['admin_acls']['what_menu'][$adminId] == $what)) {
82 $acl_mode = $GLOBALS['cache_array']['admin_acls']['access_mode'][$adminId];
85 incrementStatsEntry('cache_hits');
87 } elseif (!isExtensionActive('cache')) {
88 // Old version, so load it from database
90 if (!empty($action)) {
92 $result = SQL_QUERY_ESC("SELECT `access_mode` FROM `{?_MYSQL_PREFIX?}_admins_acls` WHERE `admin_id`=%s AND `action_menu`='%s' LIMIT 1",
93 array(bigintval($adminId), $action), __FUNCTION__, __LINE__);
94 } elseif (!empty($what)) {
96 $result = SQL_QUERY_ESC("SELECT `access_mode` FROM `{?_MYSQL_PREFIX?}_admins_acls` WHERE `admin_id`=%s AND `what_menu`='%s' LIMIT 1",
97 array(bigintval($adminId), $what), __FUNCTION__, __LINE__);
100 // Is an entry found?
101 if (SQL_NUMROWS($result) == 1) {
103 list($acl_mode) = SQL_FETCHROW($result);
107 SQL_FREERESULT($result);
110 // Check ACL and (maybe) allow
111 //* DEBUG: */ debugOutput('default='.$default.',acl_mode='.$acl_mode.',parent='.intval($parent));
112 if (($default == 'allow') || (($default == 'deny') && ($acl_mode == 'allow')) || ($parent === true) || (($default == '***') && ($acl_mode == 'failed') && ($parent === false))) {
118 //* DEBUG: */ debugOutput(__FUNCTION__.'['.__LINE__.']:act='.$action.',wht='.$what.',default='.$default.',acl_mode='.$acl_mode);
122 // Create email link to admins's account
123 function generateAdminEmailLink ($email, $mod = 'admin') {
125 if (strpos($email, '@') !== false) {
127 $result = SQL_QUERY_ESC("SELECT `id`
129 `{?_MYSQL_PREFIX?}_admins`
133 array($email), __FUNCTION__, __LINE__);
135 // Is there an entry?
136 if (SQL_NUMROWS($result) == 1) {
138 list($adminId) = SQL_FETCHROW($result);
140 // Rewrite email address to contact link
141 $email = '{%url=modules.php?module=' . $mod . '&what=admins_contct&admin=' . bigintval($adminId) . '%}';
145 SQL_FREERESULT($result);
146 } elseif ((is_int($email)) && ($email > 0)) {
148 $email = '{%url=modules.php?module=' . $mod . '&what=admins_contct&admin=' . bigintval($email) . '%}';
151 // Return rewritten (?) email address
155 // Change a lot admin account
156 function adminsChangeAdminAccount ($postData, $element = '') {
159 foreach ($postData['login'] as $id => $login) {
161 $id = bigintval($id);
163 // When both passwords match update admin account
164 if ((!empty($element)) && (isset($postData[$element]))) {
166 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_admins` SET `%s`='%s' WHERE `id`=%s LIMIT 1",
167 array($element, $postData[$element][$id], $id), __FUNCTION__, __LINE__);
169 // Admin account saved
170 $message = '{--ADMIN_ACCOUNT_SAVED--}';
171 } elseif ((isset($postData['pass1'])) && (isset($postData['pass2']))) {
172 // Update only if both passwords match
173 if (($postData['pass1'][$id] == $postData['pass2'][$id])) {
174 // Save only when both passwords are the same (also when they are empty)
175 $add = ''; $cache_update = 1;
178 $hash = generateHash($postData['pass1'][$id]);
180 // Save password when set
181 if (!empty($postData['pass1'][$id])) $add = sprintf(", `password`='%s'", SQL_ESCAPE($hash));
184 $adminId = getCurrentAdminId();
185 $salt = substr(getAdminHash(getAdminLogin($adminId)), 0, -40);
187 // Rewrite cookie when it's own account
188 if ($adminId == $id) {
189 // Set timeout cookie
190 setSession('admin_last', time());
192 if ($adminId != getSession('admin_id')) {
193 // Update login cookie
194 setSession('admin_id', $adminId);
196 // Update password cookie as well?
197 if (!empty($add)) setSession('admin_md5', $hash);
198 } elseif (generateHash($postData['pass1'][$id], $salt) != getSession('admin_md5')) {
199 // Update password cookie
200 setSession('admin_md5', $hash);
204 // Get default ACL from admin to check if we can allow him to change the default ACL
205 $default = getAdminDefaultAcl(getCurrentAdminId());
207 // Update admin account
208 if ($default == 'allow') {
209 // Allow changing default ACL
210 SQL_QUERY_ESC("UPDATE
211 `{?_MYSQL_PREFIX?}_admins`
213 `login`='%s'" . $add . ",
222 $postData['email'][$id],
223 $postData['mode'][$id],
224 $postData['la_mode'][$id],
226 ), __FUNCTION__, __LINE__);
228 // Do not allow it here
229 SQL_QUERY_ESC("UPDATE
230 `{?_MYSQL_PREFIX?}_admins`
232 `login`='%s'" . $add . ",
240 $postData['email'][$id],
241 $postData['la_mode'][$id],
243 ), __FUNCTION__, __LINE__);
246 // Admin account saved
247 $message = '{--ADMIN_ACCOUNT_SAVED--}';
249 // Passwords did not match
250 $message = '{--ADMINS_ERROR_PASS_MISMATCH--}';
253 // Update whole array
254 $SQL = 'UPDATE `{?_MYSQL_PREFIX?}_admins` SET ';
255 foreach ($postData as $entry => $value) {
256 // Skip login/id entry
257 if (in_array($entry, array('login', 'id'))) continue;
259 // Do we have a non-string (e.g. number, NOW() or back-tick at the beginning?
260 if ((bigintval($value[$id], true, false) === $value[$id]) || ($value[$id] == 'NOW()') || (substr($value[$id], 0, 1) == '`')) {
261 // No need for ticks (')
262 $SQL .= '`' . $entry . '`=' . $value[$id] . ',';
264 // Strings need ticks (') around them
265 $SQL .= '`' . $entry . "`='" . SQL_ESCAPE($value[$id]) . "',";
269 // Remove last tick and finish query
270 $SQL = substr($SQL, 0, -1) . ' WHERE `id`=%s LIMIT 1';
273 SQL_QUERY_ESC($SQL, array(bigintval($id)), __FUNCTION__, __LINE__);
278 if (!empty($message)) {
279 loadTemplate('admin_settings_saved', false, $message);
283 runFilterChain('post_form_submited', postRequestArray());
286 // Make admin accounts editable
287 function adminsEditAdminAccount ($postData) {
288 // "Resolve" current's admin access mode
289 $currMode = getAdminDefaultAcl(getCurrentAdminId());
291 // Begin the edit loop
293 foreach ($postData['sel'] as $id => $selected) {
295 $id = bigintval($id);
297 // Get the admin's data
298 $result = SQL_QUERY_ESC("SELECT `login`, `email`, `default_acl` AS mode, `la_mode` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
299 array($id), __FUNCTION__, __LINE__);
300 if ((SQL_NUMROWS($result) == 1) && ($selected == 1)) {
302 $content = SQL_FETCHARRAY($result);
303 SQL_FREERESULT($result);
305 // Prepare some more data for the template
306 $content['id'] = $id;
308 // Shall we allow changing default ACL?
309 if ($currMode == 'allow') {
311 $content['mode'] = generateOptionList('/ARRAY/', array('allow', 'deny'), array('{--ADMINS_ALLOW_MODE--}', '{--ADMINS_DENY_MODE--}'), $content['mode']);
314 $content['mode'] = ' ';
316 $content['la_mode'] = generateOptionList('/ARRAY/', array('global', 'OLD', 'NEW'), array('{--ADMINS_GLOBAL_LA_SETTING--}', '{--ADMINS_OLD_LA_SETTING--}', '{--ADMINS_NEW_LA_SETTING--}'), $content['la_mode']);
318 // Load row template and switch color
319 $OUT .= loadTemplate('admin_edit_admins_row', true, $content);
324 loadTemplate('admin_edit_admins', false, $OUT);
327 // Delete given admin accounts
328 function adminsDeleteAdminAccount ($postData) {
329 // Check if this account is the last one which cannot be deleted...
330 if (countSumTotalData('', 'admins', 'id', '', true) > 1) {
333 foreach ($postData['sel'] as $id => $selected) {
335 $id = bigintval($id);
337 // Get the admin's data
338 $result = SQL_QUERY_ESC("SELECT `login`, `email`, `default_acl` AS `mode`, `la_mode` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
339 array($id), __FUNCTION__, __LINE__);
341 // Do we have an entry?
342 if (SQL_NUMROWS($result) == 1) {
343 // Entry found, so load data
344 $content = SQL_FETCHARRAY($result);
345 $content['mode'] = '{--ADMINS_' . strtoupper($content['mode']) . '_MODE--}';
346 $content['la_mode'] = '{--ADMINS_' . strtoupper($content['la_mode']) . '_LA_SETTING--}';
348 // Prepare some more data
349 $content['id'] = $id;
351 // Load row template and switch color
352 $OUT .= loadTemplate('admin_delete_admins_row', true, $content);
356 SQL_FREERESULT($result);
360 loadTemplate('admin_delete_admins', false, $OUT);
362 // Cannot delete last account!
363 loadTemplate('admin_settings_saved', false, '{--ADMIN_ADMINS_CANNOT_DELETE_LAST--}');
367 // Remove the given accounts
368 function adminsRemoveAdminAccount ($postData) {
371 foreach ($postData['sel'] as $id => $del) {
373 $id = bigintval($id);
375 // Delete only when it's not your own account!
376 if (($del == 1) && (getCurrentAdminId() != $id)) {
377 // Rewrite his tasks to all admins
378 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_task_system` SET `assigned_admin`=0 WHERE `assigned_admin`=%s",
379 array($id), __FUNCTION__, __LINE__);
382 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
383 array($id), __FUNCTION__, __LINE__);
387 // Remove cache if cache system is activated
388 runFilterChain('post_form_deleted', postRequestArray());
391 // List all admin accounts
392 function adminsListAdminAccounts() {
393 // Select all admin accounts
394 $result = SQL_QUERY('SELECT `id`, `login`, `email`, `default_acl` AS mode, `la_mode` FROM `{?_MYSQL_PREFIX?}_admins` ORDER BY `login` ASC', __FUNCTION__, __LINE__);
396 while ($content = SQL_FETCHARRAY($result)) {
397 // Compile some variables
398 $content['mode'] = '{--ADMINS_' . strtoupper($content['mode']) . '_MODE--}';
399 $content['la_mode'] = '{--ADMINS_' . strtoupper($content['la_mode']) . '_LA_SETTING--}';
401 // Load row template and switch color
402 $OUT .= loadTemplate('admin_list_admins_row', true, $content);
406 SQL_FREERESULT($result);
409 loadTemplate('admin_list_admins', false, $OUT);
412 // Sends out mail to all administrators
413 // IMPORTANT: Please use sendAdminNotification() instead of calling this function directly
414 function sendAdminsEmails ($subj, $template, $content, $userid) {
415 // Trim template name
416 $template = trim($template);
418 // Load email template
419 $message = loadEmailTemplate($template, $content, $userid);
421 // Check which admin shall receive this mail
422 $result = SQL_QUERY_ESC("SELECT `admin_id` FROM `{?_MYSQL_PREFIX?}_admins_mails` WHERE `mail_template`='%s' ORDER BY `admin_id` ASC",
423 array($template), __FUNCTION__, __LINE__);
424 if (SQL_HASZERONUMS($result)) {
425 // Create new entry (to all admins)
426 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_admins_mails` (`admin_id`, `mail_template`) VALUES (0, '%s')",
427 array($template), __FUNCTION__, __LINE__);
430 // @TODO This can be, somehow, rewritten
432 while ($content = SQL_FETCHARRAY($result)) {
433 $adminIds[] = $content['admin_id'];
437 SQL_FREERESULT($result);
442 // "implode" ids and query string
443 $adminId = implode(',', $adminIds);
444 if ($adminId == '-1') {
445 if (isExtensionActive('events')) {
446 // Add line to user events
447 EVENTS_ADD_LINE($subj, $message, $userid);
449 // Log error for debug
450 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Extension 'events' missing: tpl=%s,subj=%s,userid=%s",
456 } elseif (($adminId == '0') || (empty($adminId))) {
457 // Select all email adresses
458 $result = SQL_QUERY('SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` ORDER BY `id` ASC',
459 __FUNCTION__, __LINE__);
461 // If Admin-Id is not "to-all" select
462 $result = SQL_QUERY_ESC("SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id` IN (%s) ORDER BY `id` ASC",
463 array($adminId), __FUNCTION__, __LINE__);
467 // Load email addresses and send away
468 while ($content = SQL_FETCHARRAY($result)) {
469 sendEmail($content['email'], $subj, $message);
473 SQL_FREERESULT($result);
476 // "Getter" for current admin's expert settings
477 function getAminsExpertSettings () {
478 // Default is has not the right
479 $data['expert_settings'] = 'N';
481 // Get current admin Id
482 $adminId = getCurrentAdminId();
484 // Lookup settings in cache
485 if (isset($GLOBALS['cache_array']['admin']['expert_settings'][$adminId])) {
487 $data['expert_settings'] = $GLOBALS['cache_array']['admin']['expert_settings'][$adminId];
490 incrementStatsEntry('cache_hits');
491 } elseif (!isExtensionInstalled('cache')) {
492 // Load from database
493 $result = SQL_QUERY_ESC("SELECT `expert_settings` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
494 array($adminId), __FUNCTION__, __LINE__);
497 if (SQL_NUMROWS($result) == 1) {
499 $data = SQL_FETCHARRAY($result);
502 $GLOBALS['cache_array']['admin']['expert_settings'][$adminId] = $data['expert_settings'];
506 SQL_FREERESULT($result);
510 return $data['expert_settings'];
513 // "Getter" for current admin's expert warning (if he wants to see them or not
514 function getAminsExpertWarning () {
515 // Default is has not the right
516 $data['expert_warning'] = 'N';
518 // Get current admin id
519 $adminId = getCurrentAdminId();
521 // Lookup warning in cache
522 if (isset($GLOBALS['cache_array']['admin']['expert_warning'][$adminId])) {
524 $data['expert_warning'] = $GLOBALS['cache_array']['admin']['expert_warning'][$adminId];
527 incrementStatsEntry('cache_hits');
528 } elseif (!isExtensionInstalled('cache')) {
529 // Load from database
530 $result = SQL_QUERY_ESC("SELECT `expert_warning` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
531 array($adminId), __FUNCTION__, __LINE__);
534 if (SQL_NUMROWS($result) == 1) {
536 $data = SQL_FETCHARRAY($result);
539 $GLOBALS['cache_array']['admin']['expert_warning'][$adminId] = $data['expert_warning'];
543 SQL_FREERESULT($result);
547 return $data['expert_warning'];
550 // Get login_failures number from administrator's login name
551 function getAdminLoginFailures ($adminId) {
552 // Admin login should not be empty
553 if (empty($adminId)) {
554 debug_report_bug(__FUNCTION__, __LINE__, 'adminId is empty.');
557 // By default no admin is found
558 $data['login_failures'] = '-1';
561 if (isset($GLOBALS['cache_array']['admin']['login_failures'][$adminId])) {
562 // Use it if found to save SQL queries
563 $data['login_failures'] = $GLOBALS['cache_array']['admin']['login_failures'][$adminId];
566 incrementStatsEntry('cache_hits');
567 } elseif (!isExtensionActive('cache')) {
568 // Load from database
569 $result = SQL_QUERY_ESC("SELECT `login_failures` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
570 array($adminId), __FUNCTION__, __LINE__);
572 // Do we have an entry?
573 if (SQL_NUMROWS($result) == 1) {
575 $data = SQL_FETCHARRAY($result);
579 SQL_FREERESULT($result);
582 // Return the login_failures
583 return $data['login_failures'];
586 // Get last_failure number from administrator's login name
587 function getAdminLastFailure ($adminId) {
588 // Admin login should not be empty
589 if (empty($adminId)) {
590 debug_report_bug(__FUNCTION__, __LINE__, 'adminId is empty.');
593 // By default no admin is found
594 $data['last_failure'] = '-1';
597 if (isset($GLOBALS['cache_array']['admin']['last_failure'][$adminId])) {
598 // Use it if found to save SQL queries
599 $data['last_failure'] = $GLOBALS['cache_array']['admin']['last_failure'][$adminId];
602 incrementStatsEntry('cache_hits');
603 } elseif (!isExtensionActive('cache')) {
604 // Load from database
605 $result = SQL_QUERY_ESC("SELECT UNIX_TIMESTAMP(`last_failure`) AS `last_failure` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
606 array($adminId), __FUNCTION__, __LINE__);
608 // Do we have an entry?
609 if (SQL_NUMROWS($result) == 1) {
611 $data = SQL_FETCHARRAY($result);
615 SQL_FREERESULT($result);
618 // Return the last_failure
619 return $data['last_failure'];
622 //-----------------------------------------------------------------------------
624 //-----------------------------------------------------------------------------
626 // Filter for adding extra data to the query
627 function FILTER_ADD_EXTRA_SQL_DATA ($add = '') {
628 // Is the admins extension updated? (should be!)
629 if (isExtensionInstalledAndNewer('admins', '0.3.0')) $add .= ', `default_acl` AS def_acl';
630 if (isExtensionInstalledAndNewer('admins', '0.6.7')) $add .= ', `la_mode`';
631 if (isExtensionInstalledAndNewer('admins', '0.7.2')) $add .= ', `login_failures`, UNIX_TIMESTAMP(`last_failure`) AS last_failure';
632 if (isExtensionInstalledAndNewer('admins', '0.7.3')) $add .= ', `expert_settings`, `expert_warning`';
638 // Reset the login failures
639 function FILTER_RESET_ADMINS_LOGIN_FAILURES ($data) {
640 // Store it in session
641 setSession('mailer_admin_failures' , getAdminLoginFailures($data['id']));
642 setSession('mailer_admin_last_failure', getAdminLastFailure($data['id']));
644 // Prepare update data
645 $postData['login'][getCurrentAdminId()] = $data['login'];
646 $postData['login_failures'][getCurrentAdminId()] = '0';
647 $postData['last_failure'][getCurrentAdminId()] = '0000-00-00 00:00:00';
649 // Change it in the admin
650 adminsChangeAdminAccount($postData);
652 // Always make sure the cache is destroyed
653 rebuildCache('admin');
655 // Return the data for further processing
659 // Count the login failure
660 function FILTER_COUNT_ADMINS_LOGIN_FAILURE ($data) {
661 // Prepare update data
662 $postData['login'][getCurrentAdminId()] = $data['login'];
663 $postData['login_failures'][getCurrentAdminId()] = '`login_failures`+1';
664 $postData['last_failure'][getCurrentAdminId()] = 'NOW()';
666 // Change it in the admin
667 adminsChangeAdminAccount($postData);
669 // Always make sure the cache is destroyed
670 rebuildCache('admin');
672 // Return the data for further processing
676 // Rehashes the given plain admin password and stores it the database
677 function FILTER_REHASH_ADMINS_PASSWORD ($data) {
679 $newHash = generateHash($data['plain_pass']);
681 // Prepare update data
682 $postData['login'][getCurrentAdminId()] = $data['login'];
683 $postData['password'][getCurrentAdminId()] = $newHash;
685 // Change it in the admin
686 adminsChangeAdminAccount($postData);
688 // Update cookie/session and data array
689 setSession('admin_md5', encodeHashForCookie($newHash));
690 $data['pass_hash'] = $newHash;
692 // Always make sure the cache is destroyed
693 rebuildCache('admin');
695 // Return the data for further processing