Deprecated 'replacer' removed. Now we use EL code instead (there are a lot example...
[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, NULL, NOW() or back-tick at the beginning?
260                                 if (is_null($value[$id])) {
261                                         // NULL detected
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] . ', ';
266                                 } else {
267                                         // Strings need ticks (') around them
268                                         $SQL .= '`' . $entry . "`='" . SQL_ESCAPE($value[$id]) . "', ";
269                                 }
270                         } // END - foreach
271
272                         // Remove last 2 chars and finish query
273                         $SQL = substr($SQL, 0, -2) . ' WHERE `id`=%s LIMIT 1';
274
275                         // Run it
276                         SQL_QUERY_ESC($SQL, array(bigintval($id)), __FUNCTION__, __LINE__);
277                 }
278         } // END - foreach
279
280         // Display message
281         if (!empty($message)) {
282                 loadTemplate('admin_settings_saved', false, $message);
283         } // END - if
284
285         // Remove cache file
286         runFilterChain('post_form_submited', postRequestArray());
287 }
288
289 // Make admin accounts editable
290 function adminsEditAdminAccount ($postData) {
291         // "Resolve" current's admin access mode
292         $currMode = getAdminDefaultAcl(getCurrentAdminId());
293
294         // Begin the edit loop
295         $OUT = '';
296         foreach ($postData['sel'] as $id => $selected) {
297                 // Secure id number
298                 $id = bigintval($id);
299
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)) {
304                         // Entry found
305                         $content = SQL_FETCHARRAY($result);
306                         SQL_FREERESULT($result);
307
308                         // Prepare some more data for the template
309                         $content['id'] = $id;
310
311                         // Shall we allow changing default ACL?
312                         if ($currMode == 'allow') {
313                                 // Allow chaning it
314                                 $content['mode']    = generateOptionList('/ARRAY/', array('allow', 'deny'), array('{--ADMINS_ALLOW_MODE--}', '{--ADMINS_DENY_MODE--}'), $content['mode']);
315                         } else {
316                                 // Don't allow it
317                                 $content['mode'] = '&nbsp;';
318                         }
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']);
320
321                         // Load row template and switch color
322                         $OUT .= loadTemplate('admin_edit_admins_row', true, $content);
323                 } // END - if
324         } // END - foreach
325
326         // Load template
327         loadTemplate('admin_edit_admins', false, $OUT);
328 }
329
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) {
334                 // Delete accounts
335                 $OUT = '';
336                 foreach ($postData['sel'] as $id => $selected) {
337                         // Secure id number
338                         $id = bigintval($id);
339
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__);
343
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--}';
350
351                                 // Prepare some more data
352                                 $content['id'] = $id;
353
354                                 // Load row template and switch color
355                                 $OUT .= loadTemplate('admin_delete_admins_row', true, $content);
356                         } // END - if
357
358                         // Free result
359                         SQL_FREERESULT($result);
360                 } // END - foreach
361
362                 // Load template
363                 loadTemplate('admin_delete_admins', false, $OUT);
364         } else {
365                 // Cannot delete last account!
366                 loadTemplate('admin_settings_saved', false, '{--ADMIN_ADMINS_CANNOT_DELETE_LAST--}');
367         }
368 }
369
370 // Remove the given accounts
371 function adminsRemoveAdminAccount ($postData) {
372         // Begin removal
373         $cache_update = '0';
374         foreach ($postData['sel'] as $id => $del) {
375                 // Secure id number
376                 $id = bigintval($id);
377
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__);
383
384                         // Remove account
385                         SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
386                                 array($id), __FUNCTION__, __LINE__);
387                 }
388         }
389
390         // Remove cache if cache system is activated
391         runFilterChain('post_form_deleted', postRequestArray());
392 }
393
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__);
398         $OUT = '';
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--}';
403
404                 // Load row template and switch color
405                 $OUT .= loadTemplate('admin_list_admins_row', true, $content);
406         } // END - while
407
408         // Free memory
409         SQL_FREERESULT($result);
410
411         // Load template
412         loadTemplate('admin_list_admins', false, $OUT);
413 }
414
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);
420
421         // Load email template
422         $message = loadEmailTemplate($template, $content, $userid);
423
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__);
431         } else {
432                 // Load admin ids...
433                 // @TODO This can be, somehow, rewritten
434                 $adminIds = array();
435                 while ($content = SQL_FETCHARRAY($result)) {
436                         $adminIds[] = $content['admin_id'];
437                 } // END - while
438
439                 // Free memory
440                 SQL_FREERESULT($result);
441
442                 // Init result
443                 $result = false;
444
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);
451                         } else {
452                                 // Log error for debug
453                                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Extension 'events' missing: tpl=%s,subj=%s,userid=%s",
454                                         $template,
455                                         $subj,
456                                         $userid
457                                 ));
458                         }
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__);
463                 } else {
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__);
467                 }
468         }
469
470         // Load email addresses and send away
471         while ($content = SQL_FETCHARRAY($result)) {
472                 sendEmail($content['email'], $subj, $message);
473         } // END - while
474
475         // Free memory
476         SQL_FREERESULT($result);
477 }
478
479 // "Getter" for current admin's expert settings
480 function getAminsExpertSettings () {
481         // Default is has not the right
482         $data['expert_settings'] = 'N';
483
484         // Get current admin Id
485         $adminId = getCurrentAdminId();
486
487         // Lookup settings in cache
488         if (isset($GLOBALS['cache_array']['admin']['expert_settings'][$adminId])) {
489                 // Use cache
490                 $data['expert_settings'] = $GLOBALS['cache_array']['admin']['expert_settings'][$adminId];
491
492                 // Update cache hits
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__);
498
499                 // Entry found?
500                 if (SQL_NUMROWS($result) == 1) {
501                         // Fetch data
502                         $data = SQL_FETCHARRAY($result);
503
504                         // Set cache
505                         $GLOBALS['cache_array']['admin']['expert_settings'][$adminId] = $data['expert_settings'];
506                 } // END - if
507
508                 // Free memory
509                 SQL_FREERESULT($result);
510         }
511
512         // Return the result
513         return $data['expert_settings'];
514 }
515
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';
520
521         // Get current admin id
522         $adminId = getCurrentAdminId();
523
524         // Lookup warning in cache
525         if (isset($GLOBALS['cache_array']['admin']['expert_warning'][$adminId])) {
526                 // Use cache
527                 $data['expert_warning'] = $GLOBALS['cache_array']['admin']['expert_warning'][$adminId];
528
529                 // Update cache hits
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__);
535
536                 // Entry found?
537                 if (SQL_NUMROWS($result) == 1) {
538                         // Fetch data
539                         $data = SQL_FETCHARRAY($result);
540
541                         // Set cache
542                         $GLOBALS['cache_array']['admin']['expert_warning'][$adminId] = $data['expert_warning'];
543                 } // END - if
544
545                 // Free memory
546                 SQL_FREERESULT($result);
547         }
548
549         // Return the result
550         return $data['expert_warning'];
551 }
552
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.');
558         } // END - if
559
560         // By default no admin is found
561         $data['login_failures'] = '-1';
562
563         // Check cache
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];
567
568                 // Update cache hits
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__);
574
575                 // Do we have an entry?
576                 if (SQL_NUMROWS($result) == 1) {
577                         // Get it
578                         $data = SQL_FETCHARRAY($result);
579                 } // END - if
580
581                 // Free result
582                 SQL_FREERESULT($result);
583         }
584
585         // Return the login_failures
586         return $data['login_failures'];
587 }
588
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.');
594         } // END - if
595
596         // By default no admin is found
597         $data['last_failure'] = '-1';
598
599         // Check cache
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];
603
604                 // Update cache hits
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__);
610
611                 // Do we have an entry?
612                 if (SQL_NUMROWS($result) == 1) {
613                         // Get it
614                         $data = SQL_FETCHARRAY($result);
615                 } // END - if
616
617                 // Free result
618                 SQL_FREERESULT($result);
619         }
620
621         // Return the last_failure
622         return $data['last_failure'];
623 }
624
625 //-----------------------------------------------------------------------------
626 //                                Filter Functions
627 //-----------------------------------------------------------------------------
628
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`';
636
637         // Return it
638         return $add;
639 }
640
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']));
646
647         // Prepare update data
648         $postData['login'][getCurrentAdminId()]          = $data['login'];
649         $postData['login_failures'][getCurrentAdminId()] = '0';
650         $postData['last_failure'][getCurrentAdminId()]   = null;
651
652         // Change it in the admin
653         adminsChangeAdminAccount($postData);
654
655         // Always make sure the cache is destroyed
656         rebuildCache('admin');
657
658         // Return the data for further processing
659         return $data;
660 }
661
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()';
668
669         // Change it in the admin
670         adminsChangeAdminAccount($postData);
671
672         // Always make sure the cache is destroyed
673         rebuildCache('admin');
674
675         // Return the data for further processing
676         return $data;
677 }
678
679 // Rehashes the given plain admin password and stores it the database
680 function FILTER_REHASH_ADMINS_PASSWORD ($data) {
681         // Generate new hash
682         $newHash = generateHash($data['plain_pass']);
683
684         // Prepare update data
685         $postData['login'][getCurrentAdminId()]    = $data['login'];
686         $postData['password'][getCurrentAdminId()] = $newHash;
687
688         // Change it in the admin
689         adminsChangeAdminAccount($postData);
690
691         // Update cookie/session and data array
692         setSession('admin_md5', encodeHashForCookie($newHash));
693         $data['pass_hash'] = $newHash;
694
695         // Always make sure the cache is destroyed
696         rebuildCache('admin');
697
698         // Return the data for further processing
699         return $data;
700 }
701
702 // [EOF]
703 ?>