]> git.mxchange.org Git - mailer.git/blob - inc/libs/admins_functions.php
Even more rewrites/fixes from EL branch (please report any broken part after you...
[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  * Needs to be in all Files and every File needs "svn propset           *
18  * svn:keywords Date Revision" (autoprobset!) at least!!!!!!            *
19  * -------------------------------------------------------------------- *
20  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
21  * Copyright (c) 2009, 2010 by Mailer Developer Team                    *
22  * For more information visit: http://www.mxchange.org                  *
23  *                                                                      *
24  * This program is free software; you can redistribute it and/or modify *
25  * it under the terms of the GNU General Public License as published by *
26  * the Free Software Foundation; either version 2 of the License, or    *
27  * (at your option) any later version.                                  *
28  *                                                                      *
29  * This program is distributed in the hope that it will be useful,      *
30  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
31  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
32  * GNU General Public License for more details.                         *
33  *                                                                      *
34  * You should have received a copy of the GNU General Public License    *
35  * along with this program; if not, write to the Free Software          *
36  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
37  * MA  02110-1301  USA                                                  *
38  ************************************************************************/
39
40 // Some security stuff...
41 if (!defined('__SECURITY')) {
42         die();
43 }
44
45 // Check ACL for menu combination
46 function adminsCheckAdminAcl ($action, $what) {
47         // If action is login or logout allow allways!
48         $default = 'allow';
49         if (($action == 'login') || ($action == 'logout')) return true;
50
51         // Default is deny
52         $ret = false;
53
54         // Get admin's id
55         $adminId = getCurrentAdminId();
56
57         // Get admin's defult access right
58         $default = getAdminDefaultAcl($adminId);
59
60         if (!empty($what)) {
61                 // Check for parent menu:
62                 // First get it's action value
63                 $parent_action = getActionFromModuleWhat('admin', $what);
64
65                 // Check with this function...
66                 $parent = adminsCheckAdminAcl($parent_action, '');
67         } else {
68                 // Anything else is true!
69                 $parent = false;
70         }
71
72         // Shall I test for a main or sub menu? (action or what?)
73         $acl_mode = 'failed';
74         if ((isExtensionInstalledAndNewer('cache', '0.1.2')) && (isset($GLOBALS['cache_array']['admin_acls'])) && (count($GLOBALS['cache_array']['admin_acls']) > 0)) {
75                 // Lookup in cache
76                 if ((!empty($action)) && (isset($GLOBALS['cache_array']['admin_acls']['action_menu'][$adminId])) & ($GLOBALS['cache_array']['admin_acls']['action_menu'][$adminId] == $action)) {
77                         // Main menu line found
78                         $acl_mode = $GLOBALS['cache_array']['admin_acls']['access_mode'][$adminId];
79
80                         // Count cache hits
81                         incrementStatsEntry('cache_hits');
82                 } elseif ((!empty($what)) && (isset($GLOBALS['cache_array']['admin_acls']['what_menu'][$adminId])) && ($GLOBALS['cache_array']['admin_acls']['what_menu'][$adminId] == $what)) {
83                         // Check sub menu
84                         $acl_mode = $GLOBALS['cache_array']['admin_acls']['access_mode'][$adminId];
85
86                         // Count cache hits
87                         incrementStatsEntry('cache_hits');
88                 }
89         } elseif (!isExtensionActive('cache')) {
90                 // Old version, so load it from database
91                 $result = false;
92                 if (!empty($action)) {
93                         // Main menu
94                         $result = SQL_QUERY_ESC("SELECT `access_mode` FROM `{?_MYSQL_PREFIX?}_admins_acls` WHERE `admin_id`=%s AND `action_menu`='%s' LIMIT 1",
95                                 array(bigintval($adminId), $action), __FUNCTION__, __LINE__);
96                 } elseif (!empty($what)) {
97                         // Sub menu
98                         $result = SQL_QUERY_ESC("SELECT `access_mode` FROM `{?_MYSQL_PREFIX?}_admins_acls` WHERE `admin_id`=%s AND `what_menu`='%s' LIMIT 1",
99                                 array(bigintval($adminId), $what), __FUNCTION__, __LINE__);
100                 }
101
102                 // Is an entry found?
103                 if (SQL_NUMROWS($result) == 1) {
104                         // Load ACL
105                         list($acl_mode) = SQL_FETCHROW($result);
106                 } // END - if
107
108                 // Free memory
109                 SQL_FREERESULT($result);
110         }
111
112         // Check ACL and (maybe) allow
113         //* DEBUG: */ print 'default='.$default.',acl_mode='.$acl_mode.',parent='.intval($parent).'<br />';
114         if (($default == 'allow') || (($default == 'deny') && ($acl_mode == 'allow')) || ($parent === true) || (($default == '***') && ($acl_mode == 'failed') && ($parent === false))) {
115                 // Access is granted
116                 $ret = true;
117         } // END - if
118
119         // Return value
120         //* DEBUG: */ outputHtml(__FUNCTION__."[".__LINE__."]:act={$action},wht={$whatOR},default={$default},acl_mode={$acl_mode}<br />");
121         return $ret;
122 }
123
124 // Create email link to admins's account
125 function generateAdminEmailLink ($email, $mod = 'admin') {
126         // Is it an email?
127         if (strpos($email, '@') !== false) {
128                 // Create email link
129                 $result = SQL_QUERY_ESC("SELECT `id`
130 FROM
131         `{?_MYSQL_PREFIX?}_admins`
132 WHERE
133         `email`='%s'
134 LIMIT 1",
135                 array($email), __FUNCTION__, __LINE__);
136
137                 // Is there an entry?
138                 if (SQL_NUMROWS($result) == 1) {
139                         // Load userid
140                         list($adminId) = SQL_FETCHROW($result);
141
142                         // Rewrite email address to contact link
143                         $email = '{%url=modules.php?module=' . $mod . '&amp;what=admins_contct&amp;admin=' . bigintval($adminId) . '%}';
144                 } // END - if
145
146                 // Free memory
147                 SQL_FREERESULT($result);
148         } elseif ((is_int($email)) && ($email > 0)) {
149                 // Direct id given
150                 $email = '{%url=modules.php?module=' . $mod . '&amp;what=admins_contct&amp;admin=' . bigintval($email) . '%}';
151         }
152
153         // Return rewritten (?) email address
154         return $email;
155 }
156
157 // Change a lot admin account
158 function adminsChangeAdminAccount ($postData, $element = '') {
159         // Begin the update
160         $cache_update = '0';
161         foreach ($postData['login'] as $id => $login) {
162                 // Secure id number
163                 $id = bigintval($id);
164
165                 // When both passwords match update admin account
166                 if ((!empty($element)) && (isset($postData[$element]))) {
167                         // Save this setting
168                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_admins` SET `%s`='%s' WHERE `id`=%s LIMIT 1",
169                                 array($element, $postData[$element][$id], $id), __FILE__, __LINE__);
170
171                         // Admin account saved
172                         $message = getMessage('ADMIN_ACCOUNT_SAVED');
173                 } elseif ((isset($postData['pass1'])) && (isset($postData['pass2']))) {
174                         // Update only if both passwords match
175                         if (($postData['pass1'][$id] == $postData['pass2'][$id])) {
176                                 // Save only when both passwords are the same (also when they are empty)
177                                 $add = ''; $cache_update = 1;
178
179                                 // Generate hash
180                                 $hash = generateHash($postData['pass1'][$id]);
181
182                                 // Save password when set
183                                 if (!empty($postData['pass1'][$id])) $add = sprintf(", `password`='%s'", SQL_ESCAPE($hash));
184
185                                 // Get admin's id
186                                 $adminId = getCurrentAdminId();
187                                 $salt = substr(getAdminHash(getAdminLogin($adminId)), 0, -40);
188
189                                 // Rewrite cookie when it's own account
190                                 if ($adminId == $id) {
191                                         // Set timeout cookie
192                                         setSession('admin_last', time());
193
194                                         if ($login != getSession('admin_login')) {
195                                                 // Update login cookie
196                                                 setSession('admin_login', $login);
197
198                                                 // Update password cookie as well?
199                                                 if (!empty($add)) setSession('admin_md5', $hash);
200                                         } elseif (generateHash($postData['pass1'][$id], $salt) != getSession('admin_md5')) {
201                                                 // Update password cookie
202                                                 setSession('admin_md5', $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 = getMessage('ADMIN_ACCOUNT_SAVED');
250                         } else {
251                                 // Passwords did not match
252                                 $message = getMessage('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, NOW() or back-tick at the beginning?
262                                 if ((bigintval($value[$id], true, false) === $value[$id]) || ($value[$id] == 'NOW()') || (substr($value[$id], 0, 1) == '`'))  {
263                                         // No need for ticks (')
264                                         $SQL .= '`' . $entry . '`=' . $value[$id] . ',';
265                                 } else {
266                                         // Strings need ticks (') around them
267                                         $SQL .= '`' . $entry . "`='" . SQL_ESCAPE($value[$id]) . "',";
268                                 }
269                         } // END - foreach
270
271                         // Remove last tick and finish query
272                         $SQL = substr($SQL, 0, -1) . ' WHERE `id`=%s LIMIT 1';
273
274                         // Run it
275                         SQL_QUERY_ESC($SQL, array(bigintval($id)), __FUNCTION__, __LINE__);
276                 }
277         } // END - foreach
278
279         // Display message
280         if (!empty($message)) {
281                 loadTemplate('admin_settings_saved', false, $message);
282         } // END - if
283
284         // Remove cache file
285         runFilterChain('post_admin_edited', postRequestArray());
286 }
287
288 // Make admin accounts editable
289 function adminsEditAdminAccount ($postData) {
290         // "Resolve" current's admin access mode
291         $currMode = getAdminDefaultAcl(getCurrentAdminId());
292
293         // Begin the edit loop
294         $OUT = ''; $SW = 2;
295         foreach ($postData['sel'] as $id => $selected) {
296                 // Secure id number
297                 $id = bigintval($id);
298
299                 // Get the admin's data
300                 $result = SQL_QUERY_ESC("SELECT `login`, `email`, `default_acl` AS mode, `la_mode` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
301                         array($id), __FUNCTION__, __LINE__);
302                 if ((SQL_NUMROWS($result) == 1) && ($selected == 1)) {
303                         // Entry found
304                         $content = SQL_FETCHARRAY($result);
305                         SQL_FREERESULT($result);
306
307                         // Prepare some more data for the template
308                         $content['sw'] = $SW;
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(getMessage('ADMINS_ALLOW_MODE'), getMessage('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(getMessage('ADMINS_GLOBAL_LA_SETTING'), getMessage('ADMINS_OLD_LA_SETTING'), getMessage('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                         $SW = 3 - $SW;
324                 }
325         }
326
327         // Load template
328         loadTemplate('admin_edit_admins', false, $OUT);
329 }
330
331 // Delete given admin accounts
332 function adminsDeleteAdminAccount ($postData) {
333         // Check if this account is the last one which cannot be deleted...
334         $result_main = SQL_QUERY("SELECT `id` FROM `{?_MYSQL_PREFIX?}_admins`", __FUNCTION__, __LINE__);
335         $accounts = SQL_NUMROWS($result_main);
336         SQL_FREERESULT($result_main);
337         if ($accounts > 1) {
338                 // Delete accounts
339                 $OUT = ''; $SW = 2;
340                 foreach ($postData['sel'] as $id => $selected) {
341                         // Secure id number
342                         $id = bigintval($id);
343
344                         // Get the admin's data
345                         $result = SQL_QUERY_ESC("SELECT login, email, default_acl AS mode, la_mode FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
346                                 array($id), __FUNCTION__, __LINE__);
347                         if (SQL_NUMROWS($result) == 1) {
348                                 // Entry found
349                                 $content = SQL_FETCHARRAY($result);
350                                 SQL_FREERESULT($result);
351                                 $content['mode'] = getMessage('ADMINS_'.strtoupper($content['mode']).'_MODE');
352                                 $content['la_mode'] = getMessage('ADMINS_'.strtoupper($content['la_mode']).'_LA_SETTING');
353
354                                 // Prepare some more data
355                                 $content['sw'] = $SW;
356                                 $content['id'] = $id;
357
358                                 // Load row template and switch color
359                                 $OUT .= loadTemplate('admin_del_admins_row', true, $content);
360                                 $SW = 3 - $SW;
361                         }
362                 }
363
364                 // Load template
365                 loadTemplate('admin_del_admins', false, $OUT);
366         } else {
367                 // Cannot delete last account!
368                 loadTemplate('admin_settings_saved', false, getMessage('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`=0 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_admin_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 = ''; $SW = 2;
401         while ($content = SQL_FETCHARRAY($result)) {
402                 // Compile some variables
403                 $content['mode'] = getMessage('ADMINS_'.strtoupper($content['mode']).'_MODE');
404                 $content['la_mode'] = getMessage('ADMINS_'.strtoupper($content['la_mode']).'_LA_SETTING');
405
406                 // Prepare some more data
407                 $content['sw']         = $SW;
408                 $content['email_link'] = generateEmailLink($content['id'], 'admins');
409
410                 // Load row template and switch color
411                 $OUT .= loadTemplate('admin_list_admins_row', true, $content);
412                 $SW = 3 - $SW;
413         }
414
415         // Free memory
416         SQL_FREERESULT($result);
417
418         // Load template
419         loadTemplate('admin_list_admins', false, $OUT);
420 }
421
422 // Sends out mail to all administrators
423 // IMPORTANT: Please use sendAdminNotification() instead of calling this function directly
424 function sendAdminsEmails ($subj, $template, $content, $userid) {
425         // Trim template name
426         $template = trim($template);
427
428         // Load email template
429         $message = loadEmailTemplate($template, $content, $userid);
430
431         // Check which admin shall receive this mail
432         $result = SQL_QUERY_ESC("SELECT `admin_id` FROM `{?_MYSQL_PREFIX?}_admins_mails` WHERE `mail_template`='%s' ORDER BY `admin_id` ASC",
433                 array($template), __FUNCTION__, __LINE__);
434         if (SQL_HASZERONUMS($result)) {
435                 // Create new entry (to all admins)
436                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_admins_mails` (`admin_id`, `mail_template`) VALUES (0, '%s')",
437                         array($template), __FUNCTION__, __LINE__);
438         } else {
439                 // Load admin ids...
440                 // @TODO This can be, somehow, rewritten
441                 $adminIds = array();
442                 while ($content = SQL_FETCHARRAY($result)) {
443                         $adminIds[] = $content['admin_id'];
444                 } // END - while
445
446                 // Free memory
447                 SQL_FREERESULT($result);
448
449                 // Init result
450                 $result = false;
451
452                 // "implode" ids and query string
453                 $adminId = implode(',', $adminIds);
454                 if ($adminId == '-1') {
455                         if (isExtensionActive('events')) {
456                                 // Add line to user events
457                                 EVENTS_ADD_LINE($subj, $message, $userid);
458                         } else {
459                                 // Log error for debug
460                                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Extension 'events' missing: tpl=%s,subj=%s,userid=%s",
461                                         $template,
462                                         $subj,
463                                         $userid
464                                 ));
465                         }
466                 } elseif (($adminId == '0') || (empty($adminId))) {
467                         // Select all email adresses
468                         $result = SQL_QUERY("SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` ORDER BY `id` ASC",
469                                 __FUNCTION__, __LINE__);
470                 } else {
471                         // If Admin-Id is not "to-all" select
472                         $result = SQL_QUERY_ESC("SELECT `email` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id` IN (%s) ORDER BY `id` ASC",
473                                 array($adminId), __FUNCTION__, __LINE__);
474                 }
475         }
476
477         // Load email addresses and send away
478         while ($content = SQL_FETCHARRAY($result)) {
479                 sendEmail($content['email'], $subj, $message);
480         } // END - while
481
482         // Free memory
483         SQL_FREERESULT($result);
484 }
485
486 // "Getter" for current admin's expert settings
487 function getAminsExpertSettings () {
488         // Default is has not the right
489         $data['expert_settings'] = 'N';
490
491         // Get current admin login
492         $admin = getAdminLogin(getCurrentAdminId());
493
494         // Lookup settings in cache
495         if (isset($GLOBALS['cache_array']['admin']['expert_settings'][$admin])) {
496                 // Use cache
497                 $data['expert_settings'] = $GLOBALS['cache_array']['admin']['expert_settings'][$admin];
498
499                 // Update cache hits
500                 incrementStatsEntry('cache_hits');
501         } elseif (!isExtensionInstalled('cache')) {
502                 // Load from database
503                 $result = SQL_QUERY_ESC("SELECT `expert_settings` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
504                         array($admin), __FUNCTION__, __LINE__);
505
506                 // Entry found?
507                 if (SQL_NUMROWS($result) == 1) {
508                         // Fetch data
509                         $data = SQL_FETCHARRAY($result);
510
511                         // Set cache
512                         $GLOBALS['cache_array']['admin']['expert_settings'][$admin] = $data['expert_settings'];
513                 } // END - if
514
515                 // Free memory
516                 SQL_FREERESULT($result);
517         }
518
519         // Return the result
520         return $data['expert_settings'];
521 }
522
523 // "Getter" for current admin's expert warning (if he wants to see them or not
524 function getAminsExpertWarning () {
525         // Default is has not the right
526         $data['expert_warning'] = 'N';
527
528         // Get current admin login
529         $admin = getAdminLogin(getCurrentAdminId());
530
531         // Lookup warning in cache
532         if (isset($GLOBALS['cache_array']['admin']['expert_warning'][$admin])) {
533                 // Use cache
534                 $data['expert_warning'] = $GLOBALS['cache_array']['admin']['expert_warning'][$admin];
535
536                 // Update cache hits
537                 incrementStatsEntry('cache_hits');
538         } elseif (!isExtensionInstalled('cache')) {
539                 // Load from database
540                 $result = SQL_QUERY_ESC("SELECT `expert_warning` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
541                         array($admin), __FUNCTION__, __LINE__);
542
543                 // Entry found?
544                 if (SQL_NUMROWS($result) == 1) {
545                         // Fetch data
546                         $data = SQL_FETCHARRAY($result);
547
548                         // Set cache
549                         $GLOBALS['cache_array']['admin']['expert_warning'][$admin] = $data['expert_warning'];
550                 } // END - if
551
552                 // Free memory
553                 SQL_FREERESULT($result);
554         }
555
556         // Return the result
557         return $data['expert_warning'];
558 }
559
560 // Get login_failures number from administrator's login name
561 function getAdminLoginFailures ($adminLogin) {
562         // Admin login should not be empty
563         if (empty($adminLogin)) {
564                 debug_report_bug('adminLogin is empty.');
565         } // END - if
566
567         // By default no admin is found
568         $data['login_failures'] = '-1';
569
570         // Check cache
571         if (isset($GLOBALS['cache_array']['admin']['login_failures'][$adminLogin])) {
572                 // Use it if found to save SQL queries
573                 $data['login_failures'] = $GLOBALS['cache_array']['admin']['login_failures'][$adminLogin];
574
575                 // Update cache hits
576                 incrementStatsEntry('cache_hits');
577         } elseif (!isExtensionActive('cache')) {
578                 // Load from database
579                 $result = SQL_QUERY_ESC("SELECT `login_failures` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
580                         array($adminLogin), __FUNCTION__, __LINE__);
581
582                 // Do we have an entry?
583                 if (SQL_NUMROWS($result) == 1) {
584                         // Get it
585                         $data = SQL_FETCHARRAY($result);
586                 } // END - if
587
588                 // Free result
589                 SQL_FREERESULT($result);
590         }
591
592         // Return the login_failures
593         return $data['login_failures'];
594 }
595
596 // Get last_failure number from administrator's login name
597 function getAdminLastFailure ($adminLogin) {
598         // Admin login should not be empty
599         if (empty($adminLogin)) {
600                 debug_report_bug('adminLogin is empty.');
601         } // END - if
602
603         // By default no admin is found
604         $data['last_failure'] = '-1';
605
606         // Check cache
607         if (isset($GLOBALS['cache_array']['admin']['last_failure'][$adminLogin])) {
608                 // Use it if found to save SQL queries
609                 $data['last_failure'] = $GLOBALS['cache_array']['admin']['last_failure'][$adminLogin];
610
611                 // Update cache hits
612                 incrementStatsEntry('cache_hits');
613         } elseif (!isExtensionActive('cache')) {
614                 // Load from database
615                 $result = SQL_QUERY_ESC("SELECT UNIX_TIMESTAMP(`last_failure`) AS `last_failure` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
616                         array($adminLogin), __FUNCTION__, __LINE__);
617
618                 // Do we have an entry?
619                 if (SQL_NUMROWS($result) == 1) {
620                         // Get it
621                         $data = SQL_FETCHARRAY($result);
622                 } // END - if
623
624                 // Free result
625                 SQL_FREERESULT($result);
626         }
627
628         // Return the last_failure
629         return $data['last_failure'];
630 }
631
632 //*****************************************************************************
633 //                     Below only filter functions
634 //*****************************************************************************
635
636 // Filter for adding extra data to the query
637 function FILTER_ADD_EXTRA_SQL_DATA ($add = '') {
638         // Is the admins extension updated? (should be!)
639         if (isExtensionInstalledAndNewer('admins', '0.3.0')) $add .= ', `default_acl` AS def_acl';
640         if (isExtensionInstalledAndNewer('admins', '0.6.7')) $add .= ', `la_mode`';
641         if (isExtensionInstalledAndNewer('admins', '0.7.2')) $add .= ', `login_failures`, UNIX_TIMESTAMP(`last_failure`) AS last_failure';
642         if (isExtensionInstalledAndNewer('admins', '0.7.3')) $add .= ', `expert_settings`, `expert_warning`';
643
644         // Return it
645         return $add;
646 }
647
648 // Reset the login failures
649 function FILTER_RESET_ADMINS_LOGIN_FAILURES ($data) {
650         // Store it in session
651         setSession('mailer_admin_failures'    , getAdminLoginFailures($data['login']));
652         setSession('mailer_admin_last_failure', getAdminLastFailure($data['login']));
653
654         // Prepare update data
655         $postData['login'][getCurrentAdminId()]          = $data['login'];
656         $postData['login_failures'][getCurrentAdminId()] = '0';
657         $postData['last_failure'][getCurrentAdminId()]   = '0000-00-00 00:00:00';
658
659         // Change it in the admin
660         adminsChangeAdminAccount($postData);
661
662         // Always make sure the cache is destroyed
663         rebuildCache('admin');
664
665         // Return the data for further processing
666         return $data;
667 }
668
669 // Count the login failure
670 function FILTER_COUNT_ADMINS_LOGIN_FAILURE ($data) {
671         // Prepare update data
672         $postData['login'][getCurrentAdminId()]          = $data['login'];
673         $postData['login_failures'][getCurrentAdminId()] = '`login_failures`+1';
674         $postData['last_failure'][getCurrentAdminId()]   = 'NOW()';
675
676         // Change it in the admin
677         adminsChangeAdminAccount($postData);
678
679         // Always make sure the cache is destroyed
680         rebuildCache('admin');
681
682         // Return the data for further processing
683         return $data;
684 }
685
686 // Rehashes the given plain admin password and stores it the database
687 function FILTER_REHASH_ADMINS_PASSWORD ($data) {
688         // Generate new hash
689         $newHash = generateHash($data['plain_pass']);
690
691         // Prepare update data
692         $postData['login'][getCurrentAdminId()]    = $data['login'];
693         $postData['password'][getCurrentAdminId()] = $newHash;
694
695         // Change it in the admin
696         adminsChangeAdminAccount($postData);
697
698         // Update cookie/session and data array
699         setSession('admin_md5', encodeHashForCookie($newHash));
700         $data['pass_hash'] = $newHash;
701
702         // Always make sure the cache is destroyed
703         rebuildCache('admin');
704
705         // Return the data for further processing
706         return $data;
707 }
708
709 // [EOF]
710 ?>