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, NULL, NOW() or back-tick at the beginning?
260 if (is_null($value[$id])) {
262 $SQL .= '`' . $entry . '`=NULL, ';
263 } elseif ((bigintval($value[$id], true, false) === $value[$id]) || ($value[$id] == 'NOW()') || (substr($value[$id], 0, 1) == '`')) {
264 // No need for ticks (')
265 $SQL .= '`' . $entry . '`=' . $value[$id] . ', ';
267 // Strings need ticks (') around them
268 $SQL .= '`' . $entry . "`='" . SQL_ESCAPE($value[$id]) . "', ";
272 // Remove last 2 chars and finish query
273 $SQL = substr($SQL, 0, -2) . ' WHERE `id`=%s LIMIT 1';
276 SQL_QUERY_ESC($SQL, array(bigintval($id)), __FUNCTION__, __LINE__);
281 if (!empty($message)) {
282 loadTemplate('admin_settings_saved', false, $message);
286 runFilterChain('post_form_submited', postRequestArray());
289 // Make admin accounts editable
290 function adminsEditAdminAccount ($postData) {
291 // "Resolve" current's admin access mode
292 $currMode = getAdminDefaultAcl(getCurrentAdminId());
294 // Begin the edit loop
296 foreach ($postData['sel'] as $id => $selected) {
298 $id = bigintval($id);
300 // Get the admin's data
301 $result = SQL_QUERY_ESC("SELECT `login`, `email`, `default_acl` AS mode, `la_mode` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
302 array($id), __FUNCTION__, __LINE__);
303 if ((SQL_NUMROWS($result) == 1) && ($selected == 1)) {
305 $content = SQL_FETCHARRAY($result);
306 SQL_FREERESULT($result);
308 // Prepare some more data for the template
309 $content['id'] = $id;
311 // Shall we allow changing default ACL?
312 if ($currMode == 'allow') {
314 $content['mode'] = generateOptionList('/ARRAY/', array('allow', 'deny'), array('{--ADMINS_ALLOW_MODE--}', '{--ADMINS_DENY_MODE--}'), $content['mode']);
317 $content['mode'] = ' ';
319 $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']);
321 // Load row template and switch color
322 $OUT .= loadTemplate('admin_edit_admins_row', true, $content);
327 loadTemplate('admin_edit_admins', false, $OUT);
330 // Delete given admin accounts
331 function adminsDeleteAdminAccount ($postData) {
332 // Check if this account is the last one which cannot be deleted...
333 if (countSumTotalData('', 'admins', 'id', '', true) > 1) {
336 foreach ($postData['sel'] as $id => $selected) {
338 $id = bigintval($id);
340 // Get the admin's data
341 $result = SQL_QUERY_ESC("SELECT `login`, `email`, `default_acl` AS `mode`, `la_mode` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
342 array($id), __FUNCTION__, __LINE__);
344 // Do we have an entry?
345 if (SQL_NUMROWS($result) == 1) {
346 // Entry found, so load data
347 $content = SQL_FETCHARRAY($result);
348 $content['mode'] = '{--ADMINS_' . strtoupper($content['mode']) . '_MODE--}';
349 $content['la_mode'] = '{--ADMINS_' . strtoupper($content['la_mode']) . '_LA_SETTING--}';
351 // Prepare some more data
352 $content['id'] = $id;
354 // Load row template and switch color
355 $OUT .= loadTemplate('admin_delete_admins_row', true, $content);
359 SQL_FREERESULT($result);
363 loadTemplate('admin_delete_admins', false, $OUT);
365 // Cannot delete last account!
366 loadTemplate('admin_settings_saved', false, '{--ADMIN_ADMINS_CANNOT_DELETE_LAST--}');
370 // Remove the given accounts
371 function adminsRemoveAdminAccount ($postData) {
374 foreach ($postData['sel'] as $id => $del) {
376 $id = bigintval($id);
378 // Delete only when it's not your own account!
379 if (($del == 1) && (getCurrentAdminId() != $id)) {
380 // Rewrite his tasks to all admins
381 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_task_system` SET `assigned_admin`=0 WHERE `assigned_admin`=%s",
382 array($id), __FUNCTION__, __LINE__);
385 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
386 array($id), __FUNCTION__, __LINE__);
390 // Remove cache if cache system is activated
391 runFilterChain('post_form_deleted', postRequestArray());
394 // List all admin accounts
395 function adminsListAdminAccounts() {
396 // Select all admin accounts
397 $result = SQL_QUERY('SELECT `id`, `login`, `email`, `default_acl` AS mode, `la_mode` FROM `{?_MYSQL_PREFIX?}_admins` ORDER BY `login` ASC', __FUNCTION__, __LINE__);
399 while ($content = SQL_FETCHARRAY($result)) {
400 // Compile some variables
401 $content['mode'] = '{--ADMINS_' . strtoupper($content['mode']) . '_MODE--}';
402 $content['la_mode'] = '{--ADMINS_' . strtoupper($content['la_mode']) . '_LA_SETTING--}';
404 // Load row template and switch color
405 $OUT .= loadTemplate('admin_list_admins_row', true, $content);
409 SQL_FREERESULT($result);
412 loadTemplate('admin_list_admins', false, $OUT);
415 // Sends out mail to all administrators
416 // IMPORTANT: Please use sendAdminNotification() instead of calling this function directly
417 function sendAdminsEmails ($subj, $template, $content, $userid) {
418 // Trim template name
419 $template = trim($template);
421 // Load email template
422 $message = loadEmailTemplate($template, $content, $userid);
424 // Check which admin shall receive this mail
425 $result = SQL_QUERY_ESC("SELECT `admin_id` FROM `{?_MYSQL_PREFIX?}_admins_mails` WHERE `mail_template`='%s' ORDER BY `admin_id` ASC",
426 array($template), __FUNCTION__, __LINE__);
427 if (SQL_HASZERONUMS($result)) {
428 // Create new entry (to all admins)
429 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_admins_mails` (`admin_id`, `mail_template`) VALUES (0, '%s')",
430 array($template), __FUNCTION__, __LINE__);
433 // @TODO This can be, somehow, rewritten
435 while ($content = SQL_FETCHARRAY($result)) {
436 $adminIds[] = $content['admin_id'];
440 SQL_FREERESULT($result);
445 // "implode" ids and query string
446 $adminId = implode(',', $adminIds);
447 if ($adminId == '-1') {
448 if (isExtensionActive('events')) {
449 // Add line to user events
450 EVENTS_ADD_LINE($subj, $message, $userid);
452 // Log error for debug
453 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Extension 'events' missing: tpl=%s,subj=%s,userid=%s",
459 } elseif (($adminId == '0') || (empty($adminId))) {
460 // Select all email adresses
461 $result = SQL_QUERY('SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` ORDER BY `id` ASC',
462 __FUNCTION__, __LINE__);
464 // If Admin-Id is not "to-all" select
465 $result = SQL_QUERY_ESC("SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id` IN (%s) ORDER BY `id` ASC",
466 array($adminId), __FUNCTION__, __LINE__);
470 // Load email addresses and send away
471 while ($content = SQL_FETCHARRAY($result)) {
472 sendEmail($content['email'], $subj, $message);
476 SQL_FREERESULT($result);
479 // "Getter" for current admin's expert settings
480 function getAminsExpertSettings () {
481 // Default is has not the right
482 $data['expert_settings'] = 'N';
484 // Get current admin Id
485 $adminId = getCurrentAdminId();
487 // Lookup settings in cache
488 if (isset($GLOBALS['cache_array']['admin']['expert_settings'][$adminId])) {
490 $data['expert_settings'] = $GLOBALS['cache_array']['admin']['expert_settings'][$adminId];
493 incrementStatsEntry('cache_hits');
494 } elseif (!isExtensionInstalled('cache')) {
495 // Load from database
496 $result = SQL_QUERY_ESC("SELECT `expert_settings` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
497 array($adminId), __FUNCTION__, __LINE__);
500 if (SQL_NUMROWS($result) == 1) {
502 $data = SQL_FETCHARRAY($result);
505 $GLOBALS['cache_array']['admin']['expert_settings'][$adminId] = $data['expert_settings'];
509 SQL_FREERESULT($result);
513 return $data['expert_settings'];
516 // "Getter" for current admin's expert warning (if he wants to see them or not
517 function getAminsExpertWarning () {
518 // Default is has not the right
519 $data['expert_warning'] = 'N';
521 // Get current admin id
522 $adminId = getCurrentAdminId();
524 // Lookup warning in cache
525 if (isset($GLOBALS['cache_array']['admin']['expert_warning'][$adminId])) {
527 $data['expert_warning'] = $GLOBALS['cache_array']['admin']['expert_warning'][$adminId];
530 incrementStatsEntry('cache_hits');
531 } elseif (!isExtensionInstalled('cache')) {
532 // Load from database
533 $result = SQL_QUERY_ESC("SELECT `expert_warning` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
534 array($adminId), __FUNCTION__, __LINE__);
537 if (SQL_NUMROWS($result) == 1) {
539 $data = SQL_FETCHARRAY($result);
542 $GLOBALS['cache_array']['admin']['expert_warning'][$adminId] = $data['expert_warning'];
546 SQL_FREERESULT($result);
550 return $data['expert_warning'];
553 // Get login_failures number from administrator's login name
554 function getAdminLoginFailures ($adminId) {
555 // Admin login should not be empty
556 if (empty($adminId)) {
557 debug_report_bug(__FUNCTION__, __LINE__, 'adminId is empty.');
560 // By default no admin is found
561 $data['login_failures'] = '-1';
564 if (isset($GLOBALS['cache_array']['admin']['login_failures'][$adminId])) {
565 // Use it if found to save SQL queries
566 $data['login_failures'] = $GLOBALS['cache_array']['admin']['login_failures'][$adminId];
569 incrementStatsEntry('cache_hits');
570 } elseif (!isExtensionActive('cache')) {
571 // Load from database
572 $result = SQL_QUERY_ESC("SELECT `login_failures` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
573 array($adminId), __FUNCTION__, __LINE__);
575 // Do we have an entry?
576 if (SQL_NUMROWS($result) == 1) {
578 $data = SQL_FETCHARRAY($result);
582 SQL_FREERESULT($result);
585 // Return the login_failures
586 return $data['login_failures'];
589 // Get last_failure number from administrator's login name
590 function getAdminLastFailure ($adminId) {
591 // Admin login should not be empty
592 if (empty($adminId)) {
593 debug_report_bug(__FUNCTION__, __LINE__, 'adminId is empty.');
596 // By default no admin is found
597 $data['last_failure'] = '-1';
600 if (isset($GLOBALS['cache_array']['admin']['last_failure'][$adminId])) {
601 // Use it if found to save SQL queries
602 $data['last_failure'] = $GLOBALS['cache_array']['admin']['last_failure'][$adminId];
605 incrementStatsEntry('cache_hits');
606 } elseif (!isExtensionActive('cache')) {
607 // Load from database
608 $result = SQL_QUERY_ESC("SELECT UNIX_TIMESTAMP(`last_failure`) AS `last_failure` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
609 array($adminId), __FUNCTION__, __LINE__);
611 // Do we have an entry?
612 if (SQL_NUMROWS($result) == 1) {
614 $data = SQL_FETCHARRAY($result);
618 SQL_FREERESULT($result);
621 // Return the last_failure
622 return $data['last_failure'];
625 //-----------------------------------------------------------------------------
627 //-----------------------------------------------------------------------------
629 // Filter for adding extra data to the query
630 function FILTER_ADD_EXTRA_SQL_DATA ($add = '') {
631 // Is the admins extension updated? (should be!)
632 if (isExtensionInstalledAndNewer('admins', '0.3.0')) $add .= ', `default_acl` AS def_acl';
633 if (isExtensionInstalledAndNewer('admins', '0.6.7')) $add .= ', `la_mode`';
634 if (isExtensionInstalledAndNewer('admins', '0.7.2')) $add .= ', `login_failures`, UNIX_TIMESTAMP(`last_failure`) AS last_failure';
635 if (isExtensionInstalledAndNewer('admins', '0.7.3')) $add .= ', `expert_settings`, `expert_warning`';
641 // Reset the login failures
642 function FILTER_RESET_ADMINS_LOGIN_FAILURES ($data) {
643 // Store it in session
644 setSession('mailer_admin_failures' , getAdminLoginFailures($data['id']));
645 setSession('mailer_admin_last_failure', getAdminLastFailure($data['id']));
647 // Prepare update data
648 $postData['login'][getCurrentAdminId()] = $data['login'];
649 $postData['login_failures'][getCurrentAdminId()] = '0';
650 $postData['last_failure'][getCurrentAdminId()] = null;
652 // Change it in the admin
653 adminsChangeAdminAccount($postData);
655 // Always make sure the cache is destroyed
656 rebuildCache('admin');
658 // Return the data for further processing
662 // Count the login failure
663 function FILTER_COUNT_ADMINS_LOGIN_FAILURE ($data) {
664 // Prepare update data
665 $postData['login'][getCurrentAdminId()] = $data['login'];
666 $postData['login_failures'][getCurrentAdminId()] = '`login_failures`+1';
667 $postData['last_failure'][getCurrentAdminId()] = 'NOW()';
669 // Change it in the admin
670 adminsChangeAdminAccount($postData);
672 // Always make sure the cache is destroyed
673 rebuildCache('admin');
675 // Return the data for further processing
679 // Rehashes the given plain admin password and stores it the database
680 function FILTER_REHASH_ADMINS_PASSWORD ($data) {
682 $newHash = generateHash($data['plain_pass']);
684 // Prepare update data
685 $postData['login'][getCurrentAdminId()] = $data['login'];
686 $postData['password'][getCurrentAdminId()] = $newHash;
688 // Change it in the admin
689 adminsChangeAdminAccount($postData);
691 // Update cookie/session and data array
692 setSession('admin_md5', encodeHashForCookie($newHash));
693 $data['pass_hash'] = $newHash;
695 // Always make sure the cache is destroyed
696 rebuildCache('admin');
698 // Return the data for further processing