1175558a7ebb152577835f2a7df5af50760ce388
[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 - 2011 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                                         setAdminLast(time());
191
192                                         if ($adminId != getCurrentAdminId()) {
193                                                 // Update login cookie
194                                                 setAdminId($adminId);
195
196                                                 // Update password cookie as well?
197                                                 if (!empty($add)) {
198                                                         setAdminMd5($hash);
199                                                 } // END - if
200                                         } elseif (generateHash($postData['pass1'][$id], $salt) != getAdminMd5()) {
201                                                 // Update password cookie
202                                                 setAdminMd5($hash);
203                                         }
204                                 } // END - if
205
206                                 // Get default ACL from admin to check if we can allow him to change the default ACL
207                                 $default = getAdminDefaultAcl(getCurrentAdminId());
208
209                                 // Update admin account
210                                 if ($default == 'allow') {
211                                         // Allow changing default ACL
212                                         SQL_QUERY_ESC("UPDATE
213         `{?_MYSQL_PREFIX?}_admins`
214 SET
215         `login`='%s'" . $add . ",
216         `email`='%s',
217         `default_acl`='%s',
218         `la_mode`='%s'
219 WHERE
220         `id`=%s
221 LIMIT 1",
222                                         array(
223                                                 $login,
224                                                 $postData['email'][$id],
225                                                 $postData['mode'][$id],
226                                                 $postData['la_mode'][$id],
227                                                 $id
228                                         ), __FUNCTION__, __LINE__);
229                                 } else {
230                                         // Do not allow it here
231                                         SQL_QUERY_ESC("UPDATE
232         `{?_MYSQL_PREFIX?}_admins`
233 SET
234         `login`='%s'" . $add . ",
235         `email`='%s',
236         `la_mode`='%s'
237 WHERE
238         `id`=%s
239 LIMIT 1",
240                                         array(
241                                                 $login,
242                                                 $postData['email'][$id],
243                                                 $postData['la_mode'][$id],
244                                                 $id
245                                         ), __FUNCTION__, __LINE__);
246                                 }
247
248                                 // Admin account saved
249                                 $message = '{--ADMIN_ACCOUNT_SAVED--}';
250                         } else {
251                                 // Passwords did not match
252                                 $message = '{--ADMINS_ERROR_PASS_MISMATCH--}';
253                         }
254                 } else {
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;
260
261                                 // Do we have a non-string (e.g. number, NULL, NOW() or back-tick at the beginning?
262                                 if (is_null($value[$id])) {
263                                         // NULL detected
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] . ', ';
268                                 } else {
269                                         // Strings need ticks (') around them
270                                         $SQL .= '`' . $entry . "`='" . SQL_ESCAPE($value[$id]) . "', ";
271                                 }
272                         } // END - foreach
273
274                         // Remove last 2 chars and finish query
275                         $SQL = substr($SQL, 0, -2) . ' WHERE `id`=%s LIMIT 1';
276
277                         // Run it
278                         SQL_QUERY_ESC($SQL, array(bigintval($id)), __FUNCTION__, __LINE__);
279                 }
280         } // END - foreach
281
282         // Display message
283         if (!empty($message)) {
284                 displayMessage($message);
285         } // END - if
286
287         // Remove cache file
288         runFilterChain('post_form_submited', postRequestArray());
289 }
290
291 // Make admin accounts editable
292 function adminsEditAdminAccount ($postData) {
293         // "Resolve" current's admin access mode
294         $currMode = getAdminDefaultAcl(getCurrentAdminId());
295
296         // Begin the edit loop
297         $OUT = '';
298         foreach ($postData['sel'] as $id => $selected) {
299                 // Secure id number
300                 $id = bigintval($id);
301
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)) {
306                         // Entry found
307                         $content = SQL_FETCHARRAY($result);
308                         SQL_FREERESULT($result);
309
310                         // Prepare some more data for the template
311                         $content['id'] = $id;
312
313                         // Shall we allow changing default ACL?
314                         if ($currMode == 'allow') {
315                                 // Allow chaning it
316                                 $content['mode']    = generateOptionList('/ARRAY/', array('allow', 'deny'), array('{--ADMINS_ALLOW_MODE--}', '{--ADMINS_DENY_MODE--}'), $content['mode']);
317                         } else {
318                                 // Don't allow it
319                                 $content['mode'] = '&nbsp;';
320                         }
321                         $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']);
322
323                         // Load row template and switch color
324                         $OUT .= loadTemplate('admin_edit_admins_row', true, $content);
325                 } // END - if
326         } // END - foreach
327
328         // Load template
329         loadTemplate('admin_edit_admins', false, $OUT);
330 }
331
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) {
336                 // Delete accounts
337                 $OUT = '';
338                 foreach ($postData['sel'] as $id => $selected) {
339                         // Secure id number
340                         $id = bigintval($id);
341
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
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']    = '{--ADMINS_' . strtoupper($content['mode'])    . '_MODE--}';
351                                 $content['la_mode'] = '{--ADMINS_' . strtoupper($content['la_mode']) . '_LA_SETTING--}';
352
353                                 // Prepare some more data
354                                 $content['id'] = $id;
355
356                                 // Load row template and switch color
357                                 $OUT .= loadTemplate('admin_delete_admins_row', true, $content);
358                         } // END - if
359
360                         // Free result
361                         SQL_FREERESULT($result);
362                 } // END - foreach
363
364                 // Load template
365                 loadTemplate('admin_delete_admins', false, $OUT);
366         } else {
367                 // Cannot delete last account!
368                 displayMessage('{--ADMIN_ADMINS_CANNOT_DELETE_LAST--}');
369         }
370 }
371
372 // Remove the given accounts
373 function adminsRemoveAdminAccount ($postData) {
374         // Begin removal
375         $cache_update = '0';
376         foreach ($postData['sel'] as $id => $del) {
377                 // Secure id number
378                 $id = bigintval($id);
379
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__);
385
386                         // Remove account
387                         SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
388                                 array($id), __FUNCTION__, __LINE__);
389                 }
390         }
391
392         // Remove cache if cache system is activated
393         runFilterChain('post_form_deleted', postRequestArray());
394 }
395
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__);
400         $OUT = '';
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--}';
405
406                 // Load row template and switch color
407                 $OUT .= loadTemplate('admin_list_admins_row', true, $content);
408         } // END - while
409
410         // Free memory
411         SQL_FREERESULT($result);
412
413         // Load template
414         loadTemplate('admin_list_admins', false, $OUT);
415 }
416
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);
422
423         // Load email template
424         $message = loadEmailTemplate($template, $content, $userid);
425
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__);
433         } else {
434                 // Load admin ids...
435                 // @TODO This can be, somehow, rewritten
436                 $adminIds = array();
437                 while ($content = SQL_FETCHARRAY($result)) {
438                         $adminIds[] = $content['admin_id'];
439                 } // END - while
440
441                 // Free memory
442                 SQL_FREERESULT($result);
443
444                 // Init result
445                 $result = false;
446
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);
453                         } else {
454                                 // Log error for debug
455                                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Extension 'events' missing: tpl=%s,subj=%s,userid=%s",
456                                         $template,
457                                         $subj,
458                                         $userid
459                                 ));
460                         }
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__);
465                 } else {
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__);
469                 }
470         }
471
472         // Load email addresses and send away
473         while ($content = SQL_FETCHARRAY($result)) {
474                 sendEmail($content['email'], $subj, $message);
475         } // END - while
476
477         // Free memory
478         SQL_FREERESULT($result);
479 }
480
481 // "Getter" for current admin's expert settings
482 function getAminsExpertSettings () {
483         // Default is has not the right
484         $data['expert_settings'] = 'N';
485
486         // Get current admin Id
487         $adminId = getCurrentAdminId();
488
489         // Lookup settings in cache
490         if (isset($GLOBALS['cache_array']['admin']['expert_settings'][$adminId])) {
491                 // Use cache
492                 $data['expert_settings'] = $GLOBALS['cache_array']['admin']['expert_settings'][$adminId];
493
494                 // Update cache hits
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__);
500
501                 // Entry found?
502                 if (SQL_NUMROWS($result) == 1) {
503                         // Fetch data
504                         $data = SQL_FETCHARRAY($result);
505
506                         // Set cache
507                         $GLOBALS['cache_array']['admin']['expert_settings'][$adminId] = $data['expert_settings'];
508                 } // END - if
509
510                 // Free memory
511                 SQL_FREERESULT($result);
512         }
513
514         // Return the result
515         return $data['expert_settings'];
516 }
517
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';
522
523         // Get current admin id
524         $adminId = getCurrentAdminId();
525
526         // Lookup warning in cache
527         if (isset($GLOBALS['cache_array']['admin']['expert_warning'][$adminId])) {
528                 // Use cache
529                 $data['expert_warning'] = $GLOBALS['cache_array']['admin']['expert_warning'][$adminId];
530
531                 // Update cache hits
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__);
537
538                 // Entry found?
539                 if (SQL_NUMROWS($result) == 1) {
540                         // Fetch data
541                         $data = SQL_FETCHARRAY($result);
542
543                         // Set cache
544                         $GLOBALS['cache_array']['admin']['expert_warning'][$adminId] = $data['expert_warning'];
545                 } // END - if
546
547                 // Free memory
548                 SQL_FREERESULT($result);
549         }
550
551         // Return the result
552         return $data['expert_warning'];
553 }
554
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.');
560         } // END - if
561
562         // By default no admin is found
563         $data['login_failures'] = '-1';
564
565         // Check cache
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];
569
570                 // Update cache hits
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__);
576
577                 // Do we have an entry?
578                 if (SQL_NUMROWS($result) == 1) {
579                         // Get it
580                         $data = SQL_FETCHARRAY($result);
581                 } // END - if
582
583                 // Free result
584                 SQL_FREERESULT($result);
585         }
586
587         // Return the login_failures
588         return $data['login_failures'];
589 }
590
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.');
596         } // END - if
597
598         // By default no admin is found
599         $data['last_failure'] = '-1';
600
601         // Check cache
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];
605
606                 // Update cache hits
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__);
612
613                 // Do we have an entry?
614                 if (SQL_NUMROWS($result) == 1) {
615                         // Get it
616                         $data = SQL_FETCHARRAY($result);
617                 } // END - if
618
619                 // Free result
620                 SQL_FREERESULT($result);
621         }
622
623         // Return the last_failure
624         return $data['last_failure'];
625 }
626
627 //-----------------------------------------------------------------------------
628 //                                Filter Functions
629 //-----------------------------------------------------------------------------
630
631 // Filter for adding extra data to the query
632 function FILTER_ADD_EXTRA_SQL_DATA ($add = '') {
633         // Is the admins extension updated? (should be!)
634         if (isExtensionInstalledAndNewer('admins', '0.3.0')) $add .= ', `default_acl` AS def_acl';
635         if (isExtensionInstalledAndNewer('admins', '0.6.7')) $add .= ', `la_mode`';
636         if (isExtensionInstalledAndNewer('admins', '0.7.2')) $add .= ', `login_failures`, UNIX_TIMESTAMP(`last_failure`) AS last_failure';
637         if (isExtensionInstalledAndNewer('admins', '0.7.3')) $add .= ', `expert_settings`, `expert_warning`';
638
639         // Return it
640         return $add;
641 }
642
643 // Reset the login failures
644 function FILTER_RESET_ADMINS_LOGIN_FAILURES ($data) {
645         // Store it in session
646         setSession('mailer_admin_failures'    , getAdminLoginFailures($data['id']));
647         setSession('mailer_admin_last_failure', getAdminLastFailure($data['id']));
648
649         // Prepare update data
650         $postData['login'][getCurrentAdminId()]          = $data['login'];
651         $postData['login_failures'][getCurrentAdminId()] = '0';
652         $postData['last_failure'][getCurrentAdminId()]   = null;
653
654         // Change it in the admin
655         adminsChangeAdminAccount($postData);
656
657         // Always make sure the cache is destroyed
658         rebuildCache('admin');
659
660         // Return the data for further processing
661         return $data;
662 }
663
664 // Count the login failure
665 function FILTER_COUNT_ADMINS_LOGIN_FAILURE ($data) {
666         // Prepare update data
667         $postData['login'][getCurrentAdminId()]          = $data['login'];
668         $postData['login_failures'][getCurrentAdminId()] = '`login_failures`+1';
669         $postData['last_failure'][getCurrentAdminId()]   = 'NOW()';
670
671         // Change it in the admin
672         adminsChangeAdminAccount($postData);
673
674         // Always make sure the cache is destroyed
675         rebuildCache('admin');
676
677         // Return the data for further processing
678         return $data;
679 }
680
681 // Rehashes the given plain admin password and stores it the database
682 function FILTER_REHASH_ADMINS_PASSWORD ($data) {
683         // Generate new hash
684         $newHash = generateHash($data['plain_pass']);
685
686         // Prepare update data
687         $postData['login'][getCurrentAdminId()]    = $data['login'];
688         $postData['password'][getCurrentAdminId()] = $newHash;
689
690         // Change it in the admin
691         adminsChangeAdminAccount($postData);
692
693         // Update cookie/session and data array
694         setAdminMd5(encodeHashForCookie($newHash));
695         $data['pass_hash'] = $newHash;
696
697         // Always make sure the cache is destroyed
698         rebuildCache('admin');
699
700         // Return the data for further processing
701         return $data;
702 }
703
704 // ---------------------------------------------------------------------------
705 //                             Wrapper functions
706 // ---------------------------------------------------------------------------
707
708 // Wrapper function to check wether expert setting warning is enabled
709 function isAdminsExpertWarningEnabled () {
710         return (getAminsExpertWarning() == 'Y');
711 }
712
713 // [EOF]
714 ?>