Renamed function so it might be more understandable
[mailer.git] / inc / libs / admins_functions.php
1 <?php
2 /************************************************************************
3  * Mailer v0.2.1-FINAL                                Start: 06/30/2003 *
4  * ===================                          Last change: 11/27/2004 *
5  *                                                                      *
6  * -------------------------------------------------------------------- *
7  * File              : admins_functions.php                             *
8  * -------------------------------------------------------------------- *
9  * Short description : Functions for the admins extension               *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Funktionen fuer die admins-Erweiterung           *
12  * -------------------------------------------------------------------- *
13  * $Revision::                                                        $ *
14  * $Date::                                                            $ *
15  * $Tag:: 0.2.1-FINAL                                                 $ *
16  * $Author::                                                          $ *
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                  *
21  *                                                                      *
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.                                  *
26  *                                                                      *
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.                         *
31  *                                                                      *
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,               *
35  * MA  02110-1301  USA                                                  *
36  ************************************************************************/
37
38 // Some security stuff...
39 if (!defined('__SECURITY')) {
40         die();
41 }
42
43 // Check ACL for menu combination
44 function adminsCheckAdminAcl ($action, $what) {
45         // If action is login or logout allow allways!
46         $default = 'allow';
47         if (($action == 'login') || ($action == 'logout')) return true;
48
49         // Default is deny
50         $ret = false;
51
52         // Get admin's id
53         $adminId = getCurrentAdminId();
54
55         // Get admin's defult access right
56         $default = getAdminDefaultAcl($adminId);
57
58         if (!empty($what)) {
59                 // Check for parent menu:
60                 // First get it's action value
61                 $parent_action = getActionFromModuleWhat('admin', $what);
62
63                 // Check with this function...
64                 $parent = adminsCheckAdminAcl($parent_action, '');
65         } else {
66                 // Anything else is true!
67                 $parent = false;
68         }
69
70         // Shall I test for a main or sub menu? (action or what?)
71         $acl_mode = 'failed';
72         if ((isExtensionInstalledAndNewer('cache', '0.1.2')) && (isset($GLOBALS['cache_array']['admin_acls'])) && (count($GLOBALS['cache_array']['admin_acls']) > 0)) {
73                 // Lookup in cache
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];
77
78                         // Count cache hits
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)) {
81                         // Check sub menu
82                         $acl_mode = $GLOBALS['cache_array']['admin_acls']['access_mode'][$adminId];
83
84                         // Count cache hits
85                         incrementStatsEntry('cache_hits');
86                 }
87         } elseif (!isExtensionActive('cache')) {
88                 // Old version, so load it from database
89                 $result = false;
90                 if (!empty($action)) {
91                         // Main menu
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)) {
95                         // Sub menu
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__);
98                 }
99
100                 // Is an entry found?
101                 if (SQL_NUMROWS($result) == 1) {
102                         // Load ACL
103                         list($acl_mode) = SQL_FETCHROW($result);
104                 } // END - if
105
106                 // Free memory
107                 SQL_FREERESULT($result);
108         }
109
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))) {
113                 // Access is granted
114                 $ret = true;
115         } // END - if
116
117         // Return value
118         //* DEBUG: */ debugOutput(__FUNCTION__.'['.__LINE__.']:act='.$action.',wht='.$what.',default='.$default.',acl_mode='.$acl_mode);
119         return $ret;
120 }
121
122 // Create email link to admins's account
123 function generateAdminEmailLink ($email, $mod = 'admin') {
124         // Is it an email?
125         if (strpos($email, '@') !== false) {
126                 // Create email link
127                 $result = SQL_QUERY_ESC("SELECT `id`
128 FROM
129         `{?_MYSQL_PREFIX?}_admins`
130 WHERE
131         `email`='%s'
132 LIMIT 1",
133                 array($email), __FUNCTION__, __LINE__);
134
135                 // Is there an entry?
136                 if (SQL_NUMROWS($result) == 1) {
137                         // Load userid
138                         list($adminId) = SQL_FETCHROW($result);
139
140                         // Rewrite email address to contact link
141                         $email = '{%url=modules.php?module=' . $mod . '&amp;what=admins_contct&amp;admin=' . bigintval($adminId) . '%}';
142                 } // END - if
143
144                 // Free memory
145                 SQL_FREERESULT($result);
146         } elseif ((is_int($email)) && ($email > 0)) {
147                 // Direct id given
148                 $email = '{%url=modules.php?module=' . $mod . '&amp;what=admins_contct&amp;admin=' . bigintval($email) . '%}';
149         }
150
151         // Return rewritten (?) email address
152         return $email;
153 }
154
155 // Change a lot admin account
156 function adminsChangeAdminAccount ($postData, $element = '') {
157         // Begin the update
158         $cache_update = '0';
159         foreach ($postData['login'] as $id => $login) {
160                 // Secure id number
161                 $id = bigintval($id);
162
163                 // When both passwords match update admin account
164                 if ((!empty($element)) && (isset($postData[$element]))) {
165                         // Save this setting
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__);
168
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;
176
177                                 // Generate hash
178                                 $hash = generateHash($postData['pass1'][$id]);
179
180                                 // Save password when set
181                                 if (!empty($postData['pass1'][$id])) $add = sprintf(", `password`='%s'", SQL_ESCAPE($hash));
182
183                                 // Get admin's id
184                                 $adminId = getCurrentAdminId();
185                                 $salt = substr(getAdminHash(getAdminLogin($adminId)), 0, -40);
186
187                                 // Rewrite cookie when it's own account
188                                 if ($adminId == $id) {
189                                         // Set timeout cookie
190                                         setSession('admin_last', time());
191
192                                         if ($adminId != getSession('admin_id')) {
193                                                 // Update login cookie
194                                                 setSession('admin_id', $adminId);
195
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);
201                                         }
202                                 } // END - if
203
204                                 // Get default ACL from admin to check if we can allow him to change the default ACL
205                                 $default = getAdminDefaultAcl(getCurrentAdminId());
206
207                                 // Update admin account
208                                 if ($default == 'allow') {
209                                         // Allow changing default ACL
210                                         SQL_QUERY_ESC("UPDATE
211         `{?_MYSQL_PREFIX?}_admins`
212 SET
213         `login`='%s'" . $add . ",
214         `email`='%s',
215         `default_acl`='%s',
216         `la_mode`='%s'
217 WHERE
218         `id`=%s
219 LIMIT 1",
220                                         array(
221                                                 $login,
222                                                 $postData['email'][$id],
223                                                 $postData['mode'][$id],
224                                                 $postData['la_mode'][$id],
225                                                 $id
226                                         ), __FUNCTION__, __LINE__);
227                                 } else {
228                                         // Do not allow it here
229                                         SQL_QUERY_ESC("UPDATE
230         `{?_MYSQL_PREFIX?}_admins`
231 SET
232         `login`='%s'" . $add . ",
233         `email`='%s',
234         `la_mode`='%s'
235 WHERE
236         `id`=%s
237 LIMIT 1",
238                                         array(
239                                                 $login,
240                                                 $postData['email'][$id],
241                                                 $postData['la_mode'][$id],
242                                                 $id
243                                         ), __FUNCTION__, __LINE__);
244                                 }
245
246                                 // Admin account saved
247                                 $message = '{--ADMIN_ACCOUNT_SAVED--}';
248                         } else {
249                                 // Passwords did not match
250                                 $message = '{--ADMINS_ERROR_PASS_MISMATCH--}';
251                         }
252                 } else {
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;
258
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] . ',';
263                                 } else {
264                                         // Strings need ticks (') around them
265                                         $SQL .= '`' . $entry . "`='" . SQL_ESCAPE($value[$id]) . "',";
266                                 }
267                         } // END - foreach
268
269                         // Remove last tick and finish query
270                         $SQL = substr($SQL, 0, -1) . ' WHERE `id`=%s LIMIT 1';
271
272                         // Run it
273                         SQL_QUERY_ESC($SQL, array(bigintval($id)), __FUNCTION__, __LINE__);
274                 }
275         } // END - foreach
276
277         // Display message
278         if (!empty($message)) {
279                 loadTemplate('admin_settings_saved', false, $message);
280         } // END - if
281
282         // Remove cache file
283         runFilterChain('post_form_submited', postRequestArray());
284 }
285
286 // Make admin accounts editable
287 function adminsEditAdminAccount ($postData) {
288         // "Resolve" current's admin access mode
289         $currMode = getAdminDefaultAcl(getCurrentAdminId());
290
291         // Begin the edit loop
292         $OUT = '';
293         foreach ($postData['sel'] as $id => $selected) {
294                 // Secure id number
295                 $id = bigintval($id);
296
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)) {
301                         // Entry found
302                         $content = SQL_FETCHARRAY($result);
303                         SQL_FREERESULT($result);
304
305                         // Prepare some more data for the template
306                         $content['id'] = $id;
307
308                         // Shall we allow changing default ACL?
309                         if ($currMode == 'allow') {
310                                 // Allow chaning it
311                                 $content['mode']    = generateOptionList('/ARRAY/', array('allow', 'deny'), array('{--ADMINS_ALLOW_MODE--}', '{--ADMINS_DENY_MODE--}'), $content['mode']);
312                         } else {
313                                 // Don't allow it
314                                 $content['mode'] = '&nbsp;';
315                         }
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']);
317
318                         // Load row template and switch color
319                         $OUT .= loadTemplate('admin_edit_admins_row', true, $content);
320                 } // END - if
321         } // END - foreach
322
323         // Load template
324         loadTemplate('admin_edit_admins', false, $OUT);
325 }
326
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) {
331                 // Delete accounts
332                 $OUT = '';
333                 foreach ($postData['sel'] as $id => $selected) {
334                         // Secure id number
335                         $id = bigintval($id);
336
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__);
340
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--}';
347
348                                 // Prepare some more data
349                                 $content['id'] = $id;
350
351                                 // Load row template and switch color
352                                 $OUT .= loadTemplate('admin_delete_admins_row', true, $content);
353                         } // END - if
354
355                         // Free result
356                         SQL_FREERESULT($result);
357                 } // END - foreach
358
359                 // Load template
360                 loadTemplate('admin_delete_admins', false, $OUT);
361         } else {
362                 // Cannot delete last account!
363                 loadTemplate('admin_settings_saved', false, '{--ADMIN_ADMINS_CANNOT_DELETE_LAST--}');
364         }
365 }
366
367 // Remove the given accounts
368 function adminsRemoveAdminAccount ($postData) {
369         // Begin removal
370         $cache_update = '0';
371         foreach ($postData['sel'] as $id => $del) {
372                 // Secure id number
373                 $id = bigintval($id);
374
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__);
380
381                         // Remove account
382                         SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
383                                 array($id), __FUNCTION__, __LINE__);
384                 }
385         }
386
387         // Remove cache if cache system is activated
388         runFilterChain('post_form_deleted', postRequestArray());
389 }
390
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__);
395         $OUT = '';
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--}';
400
401                 // Load row template and switch color
402                 $OUT .= loadTemplate('admin_list_admins_row', true, $content);
403         } // END - while
404
405         // Free memory
406         SQL_FREERESULT($result);
407
408         // Load template
409         loadTemplate('admin_list_admins', false, $OUT);
410 }
411
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);
417
418         // Load email template
419         $message = loadEmailTemplate($template, $content, $userid);
420
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__);
428         } else {
429                 // Load admin ids...
430                 // @TODO This can be, somehow, rewritten
431                 $adminIds = array();
432                 while ($content = SQL_FETCHARRAY($result)) {
433                         $adminIds[] = $content['admin_id'];
434                 } // END - while
435
436                 // Free memory
437                 SQL_FREERESULT($result);
438
439                 // Init result
440                 $result = false;
441
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);
448                         } else {
449                                 // Log error for debug
450                                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Extension 'events' missing: tpl=%s,subj=%s,userid=%s",
451                                         $template,
452                                         $subj,
453                                         $userid
454                                 ));
455                         }
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__);
460                 } else {
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__);
464                 }
465         }
466
467         // Load email addresses and send away
468         while ($content = SQL_FETCHARRAY($result)) {
469                 sendEmail($content['email'], $subj, $message);
470         } // END - while
471
472         // Free memory
473         SQL_FREERESULT($result);
474 }
475
476 // "Getter" for current admin's expert settings
477 function getAminsExpertSettings () {
478         // Default is has not the right
479         $data['expert_settings'] = 'N';
480
481         // Get current admin Id
482         $adminId = getCurrentAdminId();
483
484         // Lookup settings in cache
485         if (isset($GLOBALS['cache_array']['admin']['expert_settings'][$adminId])) {
486                 // Use cache
487                 $data['expert_settings'] = $GLOBALS['cache_array']['admin']['expert_settings'][$adminId];
488
489                 // Update cache hits
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__);
495
496                 // Entry found?
497                 if (SQL_NUMROWS($result) == 1) {
498                         // Fetch data
499                         $data = SQL_FETCHARRAY($result);
500
501                         // Set cache
502                         $GLOBALS['cache_array']['admin']['expert_settings'][$adminId] = $data['expert_settings'];
503                 } // END - if
504
505                 // Free memory
506                 SQL_FREERESULT($result);
507         }
508
509         // Return the result
510         return $data['expert_settings'];
511 }
512
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';
517
518         // Get current admin id
519         $adminId = getCurrentAdminId();
520
521         // Lookup warning in cache
522         if (isset($GLOBALS['cache_array']['admin']['expert_warning'][$adminId])) {
523                 // Use cache
524                 $data['expert_warning'] = $GLOBALS['cache_array']['admin']['expert_warning'][$adminId];
525
526                 // Update cache hits
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__);
532
533                 // Entry found?
534                 if (SQL_NUMROWS($result) == 1) {
535                         // Fetch data
536                         $data = SQL_FETCHARRAY($result);
537
538                         // Set cache
539                         $GLOBALS['cache_array']['admin']['expert_warning'][$adminId] = $data['expert_warning'];
540                 } // END - if
541
542                 // Free memory
543                 SQL_FREERESULT($result);
544         }
545
546         // Return the result
547         return $data['expert_warning'];
548 }
549
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.');
555         } // END - if
556
557         // By default no admin is found
558         $data['login_failures'] = '-1';
559
560         // Check cache
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];
564
565                 // Update cache hits
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__);
571
572                 // Do we have an entry?
573                 if (SQL_NUMROWS($result) == 1) {
574                         // Get it
575                         $data = SQL_FETCHARRAY($result);
576                 } // END - if
577
578                 // Free result
579                 SQL_FREERESULT($result);
580         }
581
582         // Return the login_failures
583         return $data['login_failures'];
584 }
585
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.');
591         } // END - if
592
593         // By default no admin is found
594         $data['last_failure'] = '-1';
595
596         // Check cache
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];
600
601                 // Update cache hits
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__);
607
608                 // Do we have an entry?
609                 if (SQL_NUMROWS($result) == 1) {
610                         // Get it
611                         $data = SQL_FETCHARRAY($result);
612                 } // END - if
613
614                 // Free result
615                 SQL_FREERESULT($result);
616         }
617
618         // Return the last_failure
619         return $data['last_failure'];
620 }
621
622 //-----------------------------------------------------------------------------
623 //                                Filter Functions
624 //-----------------------------------------------------------------------------
625
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`';
633
634         // Return it
635         return $add;
636 }
637
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']));
643
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';
648
649         // Change it in the admin
650         adminsChangeAdminAccount($postData);
651
652         // Always make sure the cache is destroyed
653         rebuildCache('admin');
654
655         // Return the data for further processing
656         return $data;
657 }
658
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()';
665
666         // Change it in the admin
667         adminsChangeAdminAccount($postData);
668
669         // Always make sure the cache is destroyed
670         rebuildCache('admin');
671
672         // Return the data for further processing
673         return $data;
674 }
675
676 // Rehashes the given plain admin password and stores it the database
677 function FILTER_REHASH_ADMINS_PASSWORD ($data) {
678         // Generate new hash
679         $newHash = generateHash($data['plain_pass']);
680
681         // Prepare update data
682         $postData['login'][getCurrentAdminId()]    = $data['login'];
683         $postData['password'][getCurrentAdminId()] = $newHash;
684
685         // Change it in the admin
686         adminsChangeAdminAccount($postData);
687
688         // Update cookie/session and data array
689         setSession('admin_md5', encodeHashForCookie($newHash));
690         $data['pass_hash'] = $newHash;
691
692         // Always make sure the cache is destroyed
693         rebuildCache('admin');
694
695         // Return the data for further processing
696         return $data;
697 }
698
699 // [EOF]
700 ?>