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 * Needs to be in all Files and every File needs "svn propset *
18 * svn:keywords Date Revision" (autoprobset!) at least!!!!!! *
19 * -------------------------------------------------------------------- *
20 * Copyright (c) 2003 - 2009 by Roland Haeder *
21 * Copyright (c) 2009, 2010 by Mailer Developer Team *
22 * For more information visit: http://www.mxchange.org *
24 * This program is free software; you can redistribute it and/or modify *
25 * it under the terms of the GNU General Public License as published by *
26 * the Free Software Foundation; either version 2 of the License, or *
27 * (at your option) any later version. *
29 * This program is distributed in the hope that it will be useful, *
30 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
31 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
32 * GNU General Public License for more details. *
34 * You should have received a copy of the GNU General Public License *
35 * along with this program; if not, write to the Free Software *
36 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
38 ************************************************************************/
40 // Some security stuff...
41 if (!defined('__SECURITY')) {
45 // Check ACL for menu combination
46 function adminsCheckAdminAcl ($action, $what) {
47 // If action is login or logout allow allways!
49 if (($action == 'login') || ($action == 'logout')) return true;
55 $adminId = getCurrentAdminId();
57 // Get admin's defult access right
58 $default = getAdminDefaultAcl($adminId);
61 // Check for parent menu:
62 // First get it's action value
63 $parent_action = getActionFromModuleWhat('admin', $what);
65 // Check with this function...
66 $parent = adminsCheckAdminAcl($parent_action, '');
68 // Anything else is true!
72 // Shall I test for a main or sub menu? (action or what?)
74 if ((isExtensionInstalledAndNewer('cache', '0.1.2')) && (isset($GLOBALS['cache_array']['admin_acls'])) && (count($GLOBALS['cache_array']['admin_acls']) > 0)) {
76 if ((!empty($action)) && (isset($GLOBALS['cache_array']['admin_acls']['action_menu'][$adminId])) & ($GLOBALS['cache_array']['admin_acls']['action_menu'][$adminId] == $action)) {
77 // Main menu line found
78 $acl_mode = $GLOBALS['cache_array']['admin_acls']['access_mode'][$adminId];
81 incrementStatsEntry('cache_hits');
82 } elseif ((!empty($what)) && (isset($GLOBALS['cache_array']['admin_acls']['what_menu'][$adminId])) && ($GLOBALS['cache_array']['admin_acls']['what_menu'][$adminId] == $what)) {
84 $acl_mode = $GLOBALS['cache_array']['admin_acls']['access_mode'][$adminId];
87 incrementStatsEntry('cache_hits');
89 } elseif (!isExtensionActive('cache')) {
90 // Old version, so load it from database
92 if (!empty($action)) {
94 $result = SQL_QUERY_ESC("SELECT `access_mode` FROM `{?_MYSQL_PREFIX?}_admins_acls` WHERE `admin_id`=%s AND `action_menu`='%s' LIMIT 1",
95 array(bigintval($adminId), $action), __FUNCTION__, __LINE__);
96 } elseif (!empty($what)) {
98 $result = SQL_QUERY_ESC("SELECT `access_mode` FROM `{?_MYSQL_PREFIX?}_admins_acls` WHERE `admin_id`=%s AND `what_menu`='%s' LIMIT 1",
99 array(bigintval($adminId), $what), __FUNCTION__, __LINE__);
102 // Is an entry found?
103 if (SQL_NUMROWS($result) == 1) {
105 list($acl_mode) = SQL_FETCHROW($result);
109 SQL_FREERESULT($result);
112 // Check ACL and (maybe) allow
113 //* DEBUG: */ debugOutput('default='.$default.',acl_mode='.$acl_mode.',parent='.intval($parent));
114 if (($default == 'allow') || (($default == 'deny') && ($acl_mode == 'allow')) || ($parent === true) || (($default == '***') && ($acl_mode == 'failed') && ($parent === false))) {
120 //* DEBUG: */ debugOutput(__FUNCTION__.'['.__LINE__.']:act='.$action.',wht='.$what.',default='.$default.',acl_mode='.$acl_mode);
124 // Create email link to admins's account
125 function generateAdminEmailLink ($email, $mod = 'admin') {
127 if (strpos($email, '@') !== false) {
129 $result = SQL_QUERY_ESC("SELECT `id`
131 `{?_MYSQL_PREFIX?}_admins`
135 array($email), __FUNCTION__, __LINE__);
137 // Is there an entry?
138 if (SQL_NUMROWS($result) == 1) {
140 list($adminId) = SQL_FETCHROW($result);
142 // Rewrite email address to contact link
143 $email = '{%url=modules.php?module=' . $mod . '&what=admins_contct&admin=' . bigintval($adminId) . '%}';
147 SQL_FREERESULT($result);
148 } elseif ((is_int($email)) && ($email > 0)) {
150 $email = '{%url=modules.php?module=' . $mod . '&what=admins_contct&admin=' . bigintval($email) . '%}';
153 // Return rewritten (?) email address
157 // Change a lot admin account
158 function adminsChangeAdminAccount ($postData, $element = '') {
161 foreach ($postData['login'] as $id => $login) {
163 $id = bigintval($id);
165 // When both passwords match update admin account
166 if ((!empty($element)) && (isset($postData[$element]))) {
168 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_admins` SET `%s`='%s' WHERE `id`=%s LIMIT 1",
169 array($element, $postData[$element][$id], $id), __FUNCTION__, __LINE__);
171 // Admin account saved
172 $message = '{--ADMIN_ACCOUNT_SAVED--}';
173 } elseif ((isset($postData['pass1'])) && (isset($postData['pass2']))) {
174 // Update only if both passwords match
175 if (($postData['pass1'][$id] == $postData['pass2'][$id])) {
176 // Save only when both passwords are the same (also when they are empty)
177 $add = ''; $cache_update = 1;
180 $hash = generateHash($postData['pass1'][$id]);
182 // Save password when set
183 if (!empty($postData['pass1'][$id])) $add = sprintf(", `password`='%s'", SQL_ESCAPE($hash));
186 $adminId = getCurrentAdminId();
187 $salt = substr(getAdminHash(getAdminLogin($adminId)), 0, -40);
189 // Rewrite cookie when it's own account
190 if ($adminId == $id) {
191 // Set timeout cookie
192 setSession('admin_last', time());
194 if ($adminId != getSession('admin_id')) {
195 // Update login cookie
196 setSession('admin_id', $adminId);
198 // Update password cookie as well?
199 if (!empty($add)) setSession('admin_md5', $hash);
200 } elseif (generateHash($postData['pass1'][$id], $salt) != getSession('admin_md5')) {
201 // Update password cookie
202 setSession('admin_md5', $hash);
206 // Get default ACL from admin to check if we can allow him to change the default ACL
207 $default = getAdminDefaultAcl(getCurrentAdminId());
209 // Update admin account
210 if ($default == 'allow') {
211 // Allow changing default ACL
212 SQL_QUERY_ESC("UPDATE
213 `{?_MYSQL_PREFIX?}_admins`
215 `login`='%s'" . $add . ",
224 $postData['email'][$id],
225 $postData['mode'][$id],
226 $postData['la_mode'][$id],
228 ), __FUNCTION__, __LINE__);
230 // Do not allow it here
231 SQL_QUERY_ESC("UPDATE
232 `{?_MYSQL_PREFIX?}_admins`
234 `login`='%s'" . $add . ",
242 $postData['email'][$id],
243 $postData['la_mode'][$id],
245 ), __FUNCTION__, __LINE__);
248 // Admin account saved
249 $message = '{--ADMIN_ACCOUNT_SAVED--}';
251 // Passwords did not match
252 $message = '{--ADMINS_ERROR_PASS_MISMATCH--}';
255 // Update whole array
256 $SQL = 'UPDATE `{?_MYSQL_PREFIX?}_admins` SET ';
257 foreach ($postData as $entry => $value) {
258 // Skip login/id entry
259 if (in_array($entry, array('login', 'id'))) continue;
261 // Do we have a non-string (e.g. number, NOW() or back-tick at the beginning?
262 if ((bigintval($value[$id], true, false) === $value[$id]) || ($value[$id] == 'NOW()') || (substr($value[$id], 0, 1) == '`')) {
263 // No need for ticks (')
264 $SQL .= '`' . $entry . '`=' . $value[$id] . ',';
266 // Strings need ticks (') around them
267 $SQL .= '`' . $entry . "`='" . SQL_ESCAPE($value[$id]) . "',";
271 // Remove last tick and finish query
272 $SQL = substr($SQL, 0, -1) . ' WHERE `id`=%s LIMIT 1';
275 SQL_QUERY_ESC($SQL, array(bigintval($id)), __FUNCTION__, __LINE__);
280 if (!empty($message)) {
281 loadTemplate('admin_settings_saved', false, $message);
285 runFilterChain('post_admin_edited', postRequestArray());
288 // Make admin accounts editable
289 function adminsEditAdminAccount ($postData) {
290 // "Resolve" current's admin access mode
291 $currMode = getAdminDefaultAcl(getCurrentAdminId());
293 // Begin the edit loop
295 foreach ($postData['sel'] as $id => $selected) {
297 $id = bigintval($id);
299 // Get the admin's data
300 $result = SQL_QUERY_ESC("SELECT `login`, `email`, `default_acl` AS mode, `la_mode` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
301 array($id), __FUNCTION__, __LINE__);
302 if ((SQL_NUMROWS($result) == 1) && ($selected == 1)) {
304 $content = SQL_FETCHARRAY($result);
305 SQL_FREERESULT($result);
307 // Prepare some more data for the template
308 $content['id'] = $id;
310 // Shall we allow changing default ACL?
311 if ($currMode == 'allow') {
313 $content['mode'] = generateOptionList('/ARRAY/', array('allow', 'deny'), array('{--ADMINS_ALLOW_MODE--}', '{--ADMINS_DENY_MODE--}'), $content['mode']);
316 $content['mode'] = ' ';
318 $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']);
320 // Load row template and switch color
321 $OUT .= loadTemplate('admin_edit_admins_row', true, $content);
326 loadTemplate('admin_edit_admins', false, $OUT);
329 // Delete given admin accounts
330 function adminsDeleteAdminAccount ($postData) {
331 // Check if this account is the last one which cannot be deleted...
332 $result_main = SQL_QUERY("SELECT `id` FROM `{?_MYSQL_PREFIX?}_admins`", __FUNCTION__, __LINE__);
333 $accounts = SQL_NUMROWS($result_main);
334 SQL_FREERESULT($result_main);
338 foreach ($postData['sel'] as $id => $selected) {
340 $id = bigintval($id);
342 // Get the admin's data
343 $result = SQL_QUERY_ESC("SELECT login, email, default_acl AS mode, la_mode FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
344 array($id), __FUNCTION__, __LINE__);
345 if (SQL_NUMROWS($result) == 1) {
347 $content = SQL_FETCHARRAY($result);
348 SQL_FREERESULT($result);
349 $content['mode'] = '{--ADMINS_' . strtoupper($content['mode']) . '_MODE--}';
350 $content['la_mode'] = '{--ADMINS_' . strtoupper($content['la_mode']) . '_LA_SETTING--}';
352 // Prepare some more data
353 $content['id'] = $id;
355 // Load row template and switch color
356 $OUT .= loadTemplate('admin_del_admins_row', true, $content);
361 loadTemplate('admin_del_admins', false, $OUT);
363 // Cannot delete last account!
364 loadTemplate('admin_settings_saved', false, '{--ADMIN_ADMINS_CANNOT_DELETE_LAST--}');
368 // Remove the given accounts
369 function adminsRemoveAdminAccount ($postData) {
372 foreach ($postData['sel'] as $id => $del) {
374 $id = bigintval($id);
376 // Delete only when it's not your own account!
377 if (($del == 1) && (getCurrentAdminId() != $id)) {
378 // Rewrite his tasks to all admins
379 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_task_system` SET `assigned_admin`=0 WHERE `assigned_admin`=%s",
380 array($id), __FUNCTION__, __LINE__);
383 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
384 array($id), __FUNCTION__, __LINE__);
388 // Remove cache if cache system is activated
389 runFilterChain('post_admin_deleted', postRequestArray());
392 // List all admin accounts
393 function adminsListAdminAccounts() {
394 // Select all admin accounts
395 $result = SQL_QUERY("SELECT `id`, `login`, `email`, `default_acl` AS mode, `la_mode` FROM `{?_MYSQL_PREFIX?}_admins` ORDER BY `login` ASC", __FUNCTION__, __LINE__);
397 while ($content = SQL_FETCHARRAY($result)) {
398 // Compile some variables
399 $content['mode'] = '{--ADMINS_' . strtoupper($content['mode']) . '_MODE--}';
400 $content['la_mode'] = '{--ADMINS_' . strtoupper($content['la_mode']) . '_LA_SETTING--}';
402 // Prepare some more data
403 $content['email_link'] = generateEmailLink($content['id'], 'admins');
405 // Load row template and switch color
406 $OUT .= loadTemplate('admin_list_admins_row', true, $content);
410 SQL_FREERESULT($result);
413 loadTemplate('admin_list_admins', false, $OUT);
416 // Sends out mail to all administrators
417 // IMPORTANT: Please use sendAdminNotification() instead of calling this function directly
418 function sendAdminsEmails ($subj, $template, $content, $userid) {
419 // Trim template name
420 $template = trim($template);
422 // Load email template
423 $message = loadEmailTemplate($template, $content, $userid);
425 // Check which admin shall receive this mail
426 $result = SQL_QUERY_ESC("SELECT `admin_id` FROM `{?_MYSQL_PREFIX?}_admins_mails` WHERE `mail_template`='%s' ORDER BY `admin_id` ASC",
427 array($template), __FUNCTION__, __LINE__);
428 if (SQL_HASZERONUMS($result)) {
429 // Create new entry (to all admins)
430 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_admins_mails` (`admin_id`, `mail_template`) VALUES (0, '%s')",
431 array($template), __FUNCTION__, __LINE__);
434 // @TODO This can be, somehow, rewritten
436 while ($content = SQL_FETCHARRAY($result)) {
437 $adminIds[] = $content['admin_id'];
441 SQL_FREERESULT($result);
446 // "implode" ids and query string
447 $adminId = implode(',', $adminIds);
448 if ($adminId == '-1') {
449 if (isExtensionActive('events')) {
450 // Add line to user events
451 EVENTS_ADD_LINE($subj, $message, $userid);
453 // Log error for debug
454 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Extension 'events' missing: tpl=%s,subj=%s,userid=%s",
460 } elseif (($adminId == '0') || (empty($adminId))) {
461 // Select all email adresses
462 $result = SQL_QUERY("SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` ORDER BY `id` ASC",
463 __FUNCTION__, __LINE__);
465 // If Admin-Id is not "to-all" select
466 $result = SQL_QUERY_ESC("SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id` IN (%s) ORDER BY `id` ASC",
467 array($adminId), __FUNCTION__, __LINE__);
471 // Load email addresses and send away
472 while ($content = SQL_FETCHARRAY($result)) {
473 sendEmail($content['email'], $subj, $message);
477 SQL_FREERESULT($result);
480 // "Getter" for current admin's expert settings
481 function getAminsExpertSettings () {
482 // Default is has not the right
483 $data['expert_settings'] = 'N';
485 // Get current admin login
486 $admin = getAdminLogin(getCurrentAdminId());
488 // Lookup settings in cache
489 if (isset($GLOBALS['cache_array']['admin']['expert_settings'][$admin])) {
491 $data['expert_settings'] = $GLOBALS['cache_array']['admin']['expert_settings'][$admin];
494 incrementStatsEntry('cache_hits');
495 } elseif (!isExtensionInstalled('cache')) {
496 // Load from database
497 $result = SQL_QUERY_ESC("SELECT `expert_settings` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
498 array($admin), __FUNCTION__, __LINE__);
501 if (SQL_NUMROWS($result) == 1) {
503 $data = SQL_FETCHARRAY($result);
506 $GLOBALS['cache_array']['admin']['expert_settings'][$admin] = $data['expert_settings'];
510 SQL_FREERESULT($result);
514 return $data['expert_settings'];
517 // "Getter" for current admin's expert warning (if he wants to see them or not
518 function getAminsExpertWarning () {
519 // Default is has not the right
520 $data['expert_warning'] = 'N';
522 // Get current admin login
523 $admin = getAdminLogin(getCurrentAdminId());
525 // Lookup warning in cache
526 if (isset($GLOBALS['cache_array']['admin']['expert_warning'][$admin])) {
528 $data['expert_warning'] = $GLOBALS['cache_array']['admin']['expert_warning'][$admin];
531 incrementStatsEntry('cache_hits');
532 } elseif (!isExtensionInstalled('cache')) {
533 // Load from database
534 $result = SQL_QUERY_ESC("SELECT `expert_warning` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
535 array($admin), __FUNCTION__, __LINE__);
538 if (SQL_NUMROWS($result) == 1) {
540 $data = SQL_FETCHARRAY($result);
543 $GLOBALS['cache_array']['admin']['expert_warning'][$admin] = $data['expert_warning'];
547 SQL_FREERESULT($result);
551 return $data['expert_warning'];
554 // Get login_failures number from administrator's login name
555 function getAdminLoginFailures ($adminLogin) {
556 // Admin login should not be empty
557 if (empty($adminLogin)) {
558 debug_report_bug(__FUNCTION__, __LINE__, 'adminLogin is empty.');
561 // By default no admin is found
562 $data['login_failures'] = '-1';
565 if (isset($GLOBALS['cache_array']['admin']['login_failures'][$adminLogin])) {
566 // Use it if found to save SQL queries
567 $data['login_failures'] = $GLOBALS['cache_array']['admin']['login_failures'][$adminLogin];
570 incrementStatsEntry('cache_hits');
571 } elseif (!isExtensionActive('cache')) {
572 // Load from database
573 $result = SQL_QUERY_ESC("SELECT `login_failures` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
574 array($adminLogin), __FUNCTION__, __LINE__);
576 // Do we have an entry?
577 if (SQL_NUMROWS($result) == 1) {
579 $data = SQL_FETCHARRAY($result);
583 SQL_FREERESULT($result);
586 // Return the login_failures
587 return $data['login_failures'];
590 // Get last_failure number from administrator's login name
591 function getAdminLastFailure ($adminLogin) {
592 // Admin login should not be empty
593 if (empty($adminLogin)) {
594 debug_report_bug(__FUNCTION__, __LINE__, 'adminLogin is empty.');
597 // By default no admin is found
598 $data['last_failure'] = '-1';
601 if (isset($GLOBALS['cache_array']['admin']['last_failure'][$adminLogin])) {
602 // Use it if found to save SQL queries
603 $data['last_failure'] = $GLOBALS['cache_array']['admin']['last_failure'][$adminLogin];
606 incrementStatsEntry('cache_hits');
607 } elseif (!isExtensionActive('cache')) {
608 // Load from database
609 $result = SQL_QUERY_ESC("SELECT UNIX_TIMESTAMP(`last_failure`) AS `last_failure` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
610 array($adminLogin), __FUNCTION__, __LINE__);
612 // Do we have an entry?
613 if (SQL_NUMROWS($result) == 1) {
615 $data = SQL_FETCHARRAY($result);
619 SQL_FREERESULT($result);
622 // Return the last_failure
623 return $data['last_failure'];
626 //*****************************************************************************
627 // Below only filter functions
628 //*****************************************************************************
630 // Filter for adding extra data to the query
631 function FILTER_ADD_EXTRA_SQL_DATA ($add = '') {
632 // Is the admins extension updated? (should be!)
633 if (isExtensionInstalledAndNewer('admins', '0.3.0')) $add .= ', `default_acl` AS def_acl';
634 if (isExtensionInstalledAndNewer('admins', '0.6.7')) $add .= ', `la_mode`';
635 if (isExtensionInstalledAndNewer('admins', '0.7.2')) $add .= ', `login_failures`, UNIX_TIMESTAMP(`last_failure`) AS last_failure';
636 if (isExtensionInstalledAndNewer('admins', '0.7.3')) $add .= ', `expert_settings`, `expert_warning`';
642 // Reset the login failures
643 function FILTER_RESET_ADMINS_LOGIN_FAILURES ($data) {
644 // Store it in session
645 setSession('mailer_admin_failures' , getAdminLoginFailures($data['login']));
646 setSession('mailer_admin_last_failure', getAdminLastFailure($data['login']));
648 // Prepare update data
649 $postData['login'][getCurrentAdminId()] = $data['login'];
650 $postData['login_failures'][getCurrentAdminId()] = '0';
651 $postData['last_failure'][getCurrentAdminId()] = '0000-00-00 00:00:00';
653 // Change it in the admin
654 adminsChangeAdminAccount($postData);
656 // Always make sure the cache is destroyed
657 rebuildCache('admin');
659 // Return the data for further processing
663 // Count the login failure
664 function FILTER_COUNT_ADMINS_LOGIN_FAILURE ($data) {
665 // Prepare update data
666 $postData['login'][getCurrentAdminId()] = $data['login'];
667 $postData['login_failures'][getCurrentAdminId()] = '`login_failures`+1';
668 $postData['last_failure'][getCurrentAdminId()] = 'NOW()';
670 // Change it in the admin
671 adminsChangeAdminAccount($postData);
673 // Always make sure the cache is destroyed
674 rebuildCache('admin');
676 // Return the data for further processing
680 // Rehashes the given plain admin password and stores it the database
681 function FILTER_REHASH_ADMINS_PASSWORD ($data) {
683 $newHash = generateHash($data['plain_pass']);
685 // Prepare update data
686 $postData['login'][getCurrentAdminId()] = $data['login'];
687 $postData['password'][getCurrentAdminId()] = $newHash;
689 // Change it in the admin
690 adminsChangeAdminAccount($postData);
692 // Update cookie/session and data array
693 setSession('admin_md5', encodeHashForCookie($newHash));
694 $data['pass_hash'] = $newHash;
696 // Always make sure the cache is destroyed
697 rebuildCache('admin');
699 // Return the data for further processing