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