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 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 setAdminLast(time());
192 if ($adminId != getCurrentAdminId()) {
193 // Update login cookie
194 setAdminId($adminId);
196 // Update password cookie as well?
200 } elseif (generateHash($postData['pass1'][$id], $salt) != getAdminMd5()) {
201 // Update password cookie
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 = '{--ADMIN_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, NULL, NOW() or back-tick at the beginning?
262 if (is_null($value[$id])) {
264 $SQL .= '`' . $entry . '`=NULL, ';
265 } elseif ((bigintval($value[$id], true, false) === $value[$id]) || ($value[$id] == 'NOW()') || (substr($value[$id], 0, 1) == '`')) {
266 // No need for ticks (')
267 $SQL .= '`' . $entry . '`=' . $value[$id] . ', ';
269 // Strings need ticks (') around them
270 $SQL .= '`' . $entry . "`='" . SQL_ESCAPE($value[$id]) . "', ";
274 // Remove last 2 chars and finish query
275 $SQL = substr($SQL, 0, -2) . ' WHERE `id`=%s LIMIT 1';
278 SQL_QUERY_ESC($SQL, array(bigintval($id)), __FUNCTION__, __LINE__);
283 if (!empty($message)) {
284 displayMessage($message);
288 runFilterChain('post_form_submited', postRequestArray());
291 // Make admin accounts editable
292 function adminsEditAdminAccount ($postData) {
293 // "Resolve" current's admin access mode
294 $currMode = getAdminDefaultAcl(getCurrentAdminId());
296 // Begin the edit loop
298 foreach ($postData['sel'] as $id => $selected) {
300 $id = bigintval($id);
302 // Get the admin's data
303 $result = SQL_QUERY_ESC("SELECT `login`, `email`, `default_acl` AS mode, `la_mode` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
304 array($id), __FUNCTION__, __LINE__);
305 if ((SQL_NUMROWS($result) == 1) && ($selected == 1)) {
307 $content = SQL_FETCHARRAY($result);
308 SQL_FREERESULT($result);
310 // Prepare some more data for the template
311 $content['id'] = $id;
313 // Shall we allow changing default ACL?
314 if ($currMode == 'allow') {
316 $content['mode'] = generateOptionList('/ARRAY/', array('allow', 'deny'), array('{--ADMIN_ADMINS_MODE_ALLOW--}', '{--ADMIN_ADMINS_MODE_DENY--}'), $content['mode']);
319 $content['mode'] = ' ';
321 $content['la_mode'] = generateOptionList('/ARRAY/', array('global', 'OLD', 'NEW'), array('{--ADMIN_ADMINS_LA_MODE_GLOBAL--}', '{--ADMIN_ADMINS_LA_MODE_OLD--}', '{--ADMINS_NEW_LA_SETTING--}'), $content['la_mode']);
323 // Load row template and switch color
324 $OUT .= loadTemplate('admin_edit_admins_row', true, $content);
329 loadTemplate('admin_edit_admins', false, $OUT);
332 // Delete given admin accounts
333 function adminsDeleteAdminAccount ($postData) {
334 // Check if this account is the last one which cannot be deleted...
335 if (countSumTotalData('', 'admins', 'id', '', true) > 1) {
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__);
346 // Do we have an entry?
347 if (SQL_NUMROWS($result) == 1) {
348 // Entry found, so load data
349 $content = SQL_FETCHARRAY($result);
350 $content['mode'] = '{--ADMIN_ADMINS_MODE_' . strtoupper($content['mode']) . '--}';
351 $content['la_mode'] = '{--ADMIN_ADMINS_LA_MODE_' . strtoupper($content['la_mode']) . '--}';
353 // Prepare some more data
354 $content['id'] = $id;
356 // Load row template and switch color
357 $OUT .= loadTemplate('admin_delete_admins_row', true, $content);
361 SQL_FREERESULT($result);
365 loadTemplate('admin_delete_admins', false, $OUT);
367 // Cannot delete last account!
368 displayMessage('{--ADMIN_ADMINS_CANNOT_DELETE_LAST--}');
372 // Remove the given accounts
373 function adminsRemoveAdminAccount ($postData) {
376 foreach ($postData['sel'] as $id => $del) {
378 $id = bigintval($id);
380 // Delete only when it's not your own account!
381 if (($del == 1) && (getCurrentAdminId() != $id)) {
382 // Rewrite his tasks to all admins
383 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_task_system` SET `assigned_admin`=NULL WHERE `assigned_admin`=%s",
384 array($id), __FUNCTION__, __LINE__);
387 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
388 array($id), __FUNCTION__, __LINE__);
392 // Remove cache if cache system is activated
393 runFilterChain('post_form_deleted', postRequestArray());
396 // List all admin accounts
397 function adminsListAdminAccounts() {
398 // Select all admin accounts
399 $result = SQL_QUERY('SELECT `id`, `login`, `email`, `default_acl` AS mode, `la_mode` FROM `{?_MYSQL_PREFIX?}_admins` ORDER BY `login` ASC', __FUNCTION__, __LINE__);
401 while ($content = SQL_FETCHARRAY($result)) {
402 // Compile some variables
403 $content['mode'] = '{--ADMINS_' . strtoupper($content['mode']) . '_MODE--}';
404 $content['la_mode'] = '{--ADMINS_' . strtoupper($content['la_mode']) . '_LA_SETTING--}';
406 // Load row template and switch color
407 $OUT .= loadTemplate('admin_list_admins_row', true, $content);
411 SQL_FREERESULT($result);
414 loadTemplate('admin_list_admins', false, $OUT);
417 // Sends out mail to all administrators
418 // IMPORTANT: Please use sendAdminNotification() instead of calling this function directly
419 function sendAdminsEmails ($subj, $template, $content, $userid) {
420 // Trim template name
421 $template = trim($template);
423 // Load email template
424 $message = loadEmailTemplate($template, $content, $userid);
426 // Check which admin shall receive this mail
427 $result = SQL_QUERY_ESC("SELECT `admin_id` FROM `{?_MYSQL_PREFIX?}_admins_mails` WHERE `mail_template`='%s' ORDER BY `admin_id` ASC",
428 array($template), __FUNCTION__, __LINE__);
429 if (SQL_HASZERONUMS($result)) {
430 // Create new entry (to all admins)
431 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_admins_mails` (`admin_id`, `mail_template`) VALUES (0, '%s')",
432 array($template), __FUNCTION__, __LINE__);
435 // @TODO This can be, somehow, rewritten
437 while ($content = SQL_FETCHARRAY($result)) {
438 $adminIds[] = $content['admin_id'];
442 SQL_FREERESULT($result);
447 // "implode" ids and query string
448 $adminId = implode(',', $adminIds);
449 if ($adminId == '-1') {
450 if (isExtensionActive('events')) {
451 // Add line to user events
452 EVENTS_ADD_LINE($subj, $message, $userid);
454 // Log error for debug
455 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Extension 'events' missing: tpl=%s,subj=%s,userid=%s",
461 } elseif (($adminId == '0') || (empty($adminId))) {
462 // Select all email adresses
463 $result = SQL_QUERY('SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` ORDER BY `id` ASC',
464 __FUNCTION__, __LINE__);
466 // If Admin-Id is not "to-all" select
467 $result = SQL_QUERY_ESC("SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id` IN (%s) ORDER BY `id` ASC",
468 array($adminId), __FUNCTION__, __LINE__);
472 // Load email addresses and send away
473 while ($content = SQL_FETCHARRAY($result)) {
474 sendEmail($content['email'], $subj, $message);
478 SQL_FREERESULT($result);
481 // "Getter" for current admin's expert settings
482 function getAminsExpertSettings () {
483 // Default is has not the right
484 $data['expert_settings'] = 'N';
486 // Get current admin Id
487 $adminId = getCurrentAdminId();
489 // Lookup settings in cache
490 if (isset($GLOBALS['cache_array']['admin']['expert_settings'][$adminId])) {
492 $data['expert_settings'] = $GLOBALS['cache_array']['admin']['expert_settings'][$adminId];
495 incrementStatsEntry('cache_hits');
496 } elseif (!isExtensionInstalled('cache')) {
497 // Load from database
498 $result = SQL_QUERY_ESC("SELECT `expert_settings` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
499 array($adminId), __FUNCTION__, __LINE__);
502 if (SQL_NUMROWS($result) == 1) {
504 $data = SQL_FETCHARRAY($result);
507 $GLOBALS['cache_array']['admin']['expert_settings'][$adminId] = $data['expert_settings'];
511 SQL_FREERESULT($result);
515 return $data['expert_settings'];
518 // "Getter" for current admin's expert warning (if he wants to see them or not
519 function getAminsExpertWarning () {
520 // Default is has not the right
521 $data['expert_warning'] = 'N';
523 // Get current admin id
524 $adminId = getCurrentAdminId();
526 // Lookup warning in cache
527 if (isset($GLOBALS['cache_array']['admin']['expert_warning'][$adminId])) {
529 $data['expert_warning'] = $GLOBALS['cache_array']['admin']['expert_warning'][$adminId];
532 incrementStatsEntry('cache_hits');
533 } elseif (!isExtensionInstalled('cache')) {
534 // Load from database
535 $result = SQL_QUERY_ESC("SELECT `expert_warning` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
536 array($adminId), __FUNCTION__, __LINE__);
539 if (SQL_NUMROWS($result) == 1) {
541 $data = SQL_FETCHARRAY($result);
544 $GLOBALS['cache_array']['admin']['expert_warning'][$adminId] = $data['expert_warning'];
548 SQL_FREERESULT($result);
552 return $data['expert_warning'];
555 // Get login_failures number from administrator's login name
556 function getAdminLoginFailures ($adminId) {
557 // Admin login should not be empty
558 if (empty($adminId)) {
559 debug_report_bug(__FUNCTION__, __LINE__, 'adminId is empty.');
562 // By default no admin is found
563 $data['login_failures'] = '-1';
566 if (isset($GLOBALS['cache_array']['admin']['login_failures'][$adminId])) {
567 // Use it if found to save SQL queries
568 $data['login_failures'] = $GLOBALS['cache_array']['admin']['login_failures'][$adminId];
571 incrementStatsEntry('cache_hits');
572 } elseif (!isExtensionActive('cache')) {
573 // Load from database
574 $result = SQL_QUERY_ESC("SELECT `login_failures` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
575 array($adminId), __FUNCTION__, __LINE__);
577 // Do we have an entry?
578 if (SQL_NUMROWS($result) == 1) {
580 $data = SQL_FETCHARRAY($result);
584 SQL_FREERESULT($result);
587 // Return the login_failures
588 return $data['login_failures'];
591 // Get last_failure number from administrator's login name
592 function getAdminLastFailure ($adminId) {
593 // Admin login should not be empty
594 if (empty($adminId)) {
595 debug_report_bug(__FUNCTION__, __LINE__, 'adminId is empty.');
598 // By default no admin is found
599 $data['last_failure'] = '-1';
602 if (isset($GLOBALS['cache_array']['admin']['last_failure'][$adminId])) {
603 // Use it if found to save SQL queries
604 $data['last_failure'] = $GLOBALS['cache_array']['admin']['last_failure'][$adminId];
607 incrementStatsEntry('cache_hits');
608 } elseif (!isExtensionActive('cache')) {
609 // Load from database
610 $result = SQL_QUERY_ESC("SELECT UNIX_TIMESTAMP(`last_failure`) AS `last_failure` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
611 array($adminId), __FUNCTION__, __LINE__);
613 // Do we have an entry?
614 if (SQL_NUMROWS($result) == 1) {
616 $data = SQL_FETCHARRAY($result);
620 SQL_FREERESULT($result);
623 // Return the last_failure
624 return $data['last_failure'];
627 // ---------------------------------------------------------------------------
629 // ---------------------------------------------------------------------------
631 // Wrapper function to check wether expert setting warning is enabled
632 function isAdminsExpertWarningEnabled () {
633 return (getAminsExpertWarning() == 'Y');