Caching again rewritten, admin functions fixed:
[mailer.git] / inc / modules / admin / admin-inc.php
1 <?php
2 /************************************************************************
3  * MXChange v0.2.1                                    Start: 08/31/2003 *
4  * ===============                              Last change: 11/23/2004 *
5  *                                                                      *
6  * -------------------------------------------------------------------- *
7  * File              : admin-inc.php                                    *
8  * -------------------------------------------------------------------- *
9  * Short description : Administrative related functions                 *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Fuer die Administration benoetigte Funktionen    *
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 } // END - if
43
44 // Register an administrator account
45 function addAdminAccount ($user, $md5, $email) {
46         // Login does already exist
47         $ret = 'already';
48
49         // Lookup the admin
50         $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
51                 array($user), __FUNCTION__, __LINE__);
52
53         // Is the entry there?
54         if (SQL_NUMROWS($result) == 0) {
55                 // Ok, let's create the admin login
56                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_admins` (login, password, email) VALUES ('%s', '%s', '%s')",
57                 array($user, $md5, $email), __FUNCTION__, __LINE__);
58                 $ret = 'done';
59         } // END - if
60
61         // Free memory
62         SQL_FREERESULT($result);
63
64         // Return result
65         return $ret;
66 }
67
68 // Only be executed on login procedure!
69 function ifAdminLoginDataIsValid ($admin, $password) {
70         // By default no admin is found
71         $ret = '404';
72
73         // Get admin id
74         $adminId = getAdminId($admin);
75
76         // Init array with admin id by default
77         $data = array('admin_id' => $adminId);
78
79         // Is the cache valid?
80         if (isAdminHashSet($admin)) {
81                 // Get password from cache
82                 $data['password'] = getAdminHash($admin);
83                 $ret = 'pass';
84                 incrementStatsEntry('cache_hits');
85
86                 // Include more admins data?
87                 if ((isExtensionInstalledAndNewer('admins', '0.7.2')) && (isset($GLOBALS['cache_array']['admin']['login_failures'][$adminId]))) {
88                         // Load them here
89                         $data['login_failures'] = $GLOBALS['cache_array']['admin']['login_failures'][$adminId];
90                         $data['last_failure']   = $GLOBALS['cache_array']['admin']['last_failure'][$adminId];
91                 } // END - if
92         } elseif (!isExtensionActive('cache')) {
93                 // Add extra data via filter now
94                 $add = runFilterChain('sql_admin_extra_data');
95
96                 // Get password from DB
97                 $result = SQL_QUERY_ESC("SELECT `password`" . $add . " FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
98                         array($adminId), __FUNCTION__, __LINE__);
99
100                 // Entry found?
101                 if (SQL_NUMROWS($result) == 1) {
102                         // Login password found
103                         $ret = 'pass';
104
105                         // Fetch data
106                         $data = SQL_FETCHARRAY($result);
107                 } // END - if
108
109                 // Free result
110                 SQL_FREERESULT($result);
111         }
112
113         //* DEBUG: */ outputHtml("*".$data['password'].'/'.md5($password).'/'.$ret."<br />");
114         if ((isset($data['password'])) && (strlen($data['password']) == 32) && ($data['password'] == md5($password))) {
115                 // Generate new hash
116                 $data['password'] = generateHash($password);
117
118                 // Is the sql_patches not installed, than we cannot have a valid hashed password here!
119                 if (($ret == 'pass') && ((isExtensionInstalledAndOlder('sql_patches', '0.3.6')) || (!isExtensionInstalled('sql_patches')))) $ret = 'done';
120         } elseif ((isExtensionInstalledAndOlder('sql_patches', '0.3.6')) || (!isExtensionInstalled('sql_patches'))) {
121                 // Old hashing way
122                 return $ret;
123         } elseif (!isset($data['password'])) {
124                 // Password not found, so no valid login!
125                 return $ret;
126         }
127
128         // Generate salt of password
129         $salt = substr($data['password'], 0, -40);
130
131         // Check if password is same
132         //* DEBUG: */ outputHtml("*".$ret.','.$data['password'].','.$password.','.$salt."*<br />");
133         if (($ret == 'pass') && ($data['password'] == generateHash($password, $salt)) && ((!empty($salt))) || ($data['password'] == $password)) {
134                 // Re-hash the plain passord with new random salt
135                 $data['password'] = generateHash($password);
136
137                 // Do we have 0.7.0 of admins or later?
138                 // Remmeber login failures if available
139                 if ((isExtensionInstalledAndNewer('admins', '0.7.2')) && (isset($data['login_failures']))) {
140                         // Store it in session
141                         setSession('mxchange_admin_failures', $data['login_failures']);
142                         setSession('mxchange_admin_last_fail', $data['last_failure']);
143
144                         // Update password and reset login failures
145                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_admins` SET `password`='%s',`login_failures`=0,`last_failure`='0000-00-00 00:00:00' WHERE `id`=%s LIMIT 1",
146                                 array($data['password'], $adminId), __FUNCTION__, __LINE__);
147                 } else {
148                         // Update password
149                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_admins` SET `password`='%s' WHERE `id`=%s LIMIT 1",
150                                 array($data['password'], $adminId), __FUNCTION__, __LINE__);
151                 }
152
153                 // Rebuild cache
154                 rebuildCacheFile('admin', 'admin');
155
156                 // Login has failed by default... ;-)
157                 $ret = 'failed1';
158
159                 // Password matches so login here
160                 if (doAdminLogin($admin, $data['password'])) {
161                         // All done now
162                         $ret = 'done';
163                 } // END - if
164         } elseif ((empty($salt)) && ($ret == 'pass')) {
165                 // Something bad went wrong
166                 $ret = 'failed_salt';
167         } elseif ($ret == 'done') {
168                 // Try to login here if we have the old hashing way (sql_patches not installed?)
169                 if (!doAdminLogin($admin, $data['password'])) {
170                         // Something went wrong
171                         $ret = 'failed2';
172                 } // END - if
173         }
174
175         // Count login failure if admins extension version is 0.7.0+
176         if (($ret == 'pass') && (getExtensionVersion('admins') >= '0.7.0')) {
177                 // Update counter
178                 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_admins` SET login_failures=login_failures+1,last_failure=NOW() WHERE `id`=%s LIMIT 1",
179                 array($adminId), __FUNCTION__, __LINE__);
180
181                 // Rebuild cache
182                 rebuildCacheFile('admin', 'admin');
183         } // END - if
184
185         // Return the result
186         //* DEBUG: */ die("RETURN=".$ret);
187         return $ret;
188 }
189
190 // Try to login the admin by setting some session/cookie variables
191 function doAdminLogin ($adminLogin, $passHash) {
192         // Reset failure counter on matching admins version
193         if ((isExtensionInstalledAndNewer('admins', '0.7.0')) && ((isExtensionOlder('sql_patches', '0.3.6')) || (!isExtensionInstalled('sql_patches')))) {
194                 // Reset counter on out-dated sql_patches version
195                 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_admins` SET `login_failures`=0, `last_failure`='0000-00-00 00:00:00' WHERE `login`='%s' LIMIT 1",
196                         array($adminLogin), __FUNCTION__, __LINE__);
197
198                 // Rebuild cache
199                 rebuildCacheFile('admin', 'admin');
200         } // END - if
201
202         // Now set all session variables and return the result
203         return ((
204                 setSession('admin_md5', generatePassString($passHash))
205         ) && (
206                 setSession('admin_login', $adminLogin)
207         ) && (
208                 setSession('admin_last', time())
209         ) && (
210                 setSession('admin_to', bigintval(postRequestElement('timeout')))
211         ));
212 }
213
214 // Only be executed on cookie checking
215 function ifAdminCookiesAreValid ($admin, $password) {
216         // By default no admin cookies are found
217         $ret  = '404';
218         $pass = '';
219
220         // Get hash
221         $pass = getAdminHash($admin);
222         if ($pass != '-1') $ret = 'pass';
223
224         //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):".generatePassString($pass).'('.strlen($pass).")/".$password.'('.strlen($password).")<br />");
225
226         // Check if password matches
227         if (($ret == 'pass') && ((generatePassString($pass) == $password) || ($pass == $password) || ((strlen($pass) == 32) && (md5($password) == $pass)))) {
228                 // Passwords matches!
229                 $ret = 'done';
230         } // END - if
231
232         // Return result
233         return $ret;
234 }
235
236 // Do an admin action
237 function doAdminAction ($what) {
238         //* DEBUG: */ outputHtml(__LINE__."*".$what.'/'.getModule().'/'.getAction().'/'.getWhat()."*<br />");
239
240         // Remove any spaces from variable
241         if (empty($what)) {
242                 // Default admin action is the overview page
243                 $what = 'overview';
244         } else {
245                 // Compile out some chars
246                 $what = compileCode($what, false, false, false);
247         }
248
249         // Get action value
250         $action = getModeAction(getModule(), $what);
251
252         // Define admin login name and ID number
253         $content['login'] = getSession('admin_login');
254         $content['id']    = getCurrentAdminId();
255
256         // Preload templates
257         if (isExtensionActive('admins')) {
258                 $content['welcome'] = loadTemplate('admin_welcome_admins', true, $content);
259         } else {
260                 $content['welcome'] = loadTemplate('admin_welcome', true, $content);
261         }
262         $content['footer'] = loadTemplate('admin_footer' , true, $content);
263         $content['menu']   = addAdminMenu($action, $what, true);
264
265         // Tableset header
266         loadTemplate('admin_main_header', false, $content);
267
268         // Check if action/what pair is valid
269         $result_action = SQL_QUERY_ESC("SELECT
270         `id`
271 FROM
272         `{?_MYSQL_PREFIX?}_admin_menu`
273 WHERE
274         `action`='%s' AND
275         (
276                 (
277                         `what`='%s' AND `what` != 'overview'
278                 ) OR (
279                         (
280                                 `what`='' OR `what` IS NULL
281                         ) AND (
282                                 '%s'='overview'
283                         )
284                 )
285         )
286 LIMIT 1", array($action, $what, $what), __FUNCTION__, __LINE__);
287         if (SQL_NUMROWS($result_action) == 1) {
288                 // Is valid but does the inlcude file exists?
289                 $inc = sprintf("inc/modules/admin/action-%s.php", $action);
290                 if ((isIncludeReadable($inc)) && (isMenuActionValid('admin', $action, $what)) && ($GLOBALS['acl_allow'] === true)) {
291                         // Ok, we finally load the admin action module
292                         loadInclude($inc);
293                 } elseif ($GLOBALS['acl_allow'] === false) {
294                         // Access denied
295                         loadTemplate('admin_menu_failed', false, sprintf(getMessage('ADMIN_ACCESS_DENIED'), $what));
296                 } else {
297                         // Include file not found! :-(
298                         loadTemplate('admin_menu_failed', false, sprintf(getMessage('ADMIN_ACTION_404'), $action));
299                 }
300         } else {
301                 // Invalid action/what pair found!
302                 loadTemplate('admin_menu_failed', false, sprintf(getMessage('ADMIN_ACTION_INVALID'), $action.'/'.$what));
303         }
304
305         // Free memory
306         SQL_FREERESULT($result_action);
307
308         // Tableset footer
309         loadTemplate('admin_main_footer', false, $content);
310 }
311
312 // Adds an admin menu
313 function addAdminMenu ($action, $what, $return=false) {
314         // Init variables
315         $SUB = false;
316         $OUT = '';
317
318         // Menu descriptions
319         $GLOBALS['menu']['description'] = array();
320         $GLOBALS['menu']['title'] = array();
321
322         // Build main menu
323         $result_main = SQL_QUERY("SELECT
324         `action`, `title`, `descr`
325 FROM
326         `{?_MYSQL_PREFIX?}_admin_menu`
327 WHERE
328         (`what`='' OR `what` IS NULL)
329 ORDER BY
330         `sort` ASC,
331         `id` DESC", __FUNCTION__, __LINE__);
332         if (SQL_NUMROWS($result_main) > 0) {
333                 $OUT = "<div style=\"height:7px\" class=\"seperator\">&nbsp;</div>\n";
334                 $OUT .= "<ul class=\"admin_menu_main\">\n";
335                 // @TODO Rewrite this to $content = SQL_FETCHARRAY()
336                 while (list($menu, $title, $descr) = SQL_FETCHROW($result_main)) {
337                         if ((isExtensionActive('admins')) && (getExtensionVersion('admins') > '0.2.0')) {
338                                 $ACL = adminsCheckAdminAcl($menu, '');
339                         } else {
340                                 // @TODO ACL is 'allow'... hmmm
341                                 $ACL = true;
342                         }
343
344                         if ($ACL === true) {
345                                 if ($SUB === false) {
346                                         // Insert compiled menu title and description
347                                         $GLOBALS['menu']['title'][$menu]      = $title;
348                                         $GLOBALS['menu']['description'][$menu] = $descr;
349                                 }
350                                 $OUT .= "<li class=\"admin_menu\">
351 <div class=\"nobr\"><strong>&middot;</strong>&nbsp;";
352
353                                 if (($menu == $action) && (empty($what))) {
354                                         $OUT .= "<strong>";
355                                 } else {
356                                         $OUT .= "[<a href=\"{?URL?}/modules.php?module=admin&amp;action=".$menu."\">";
357                                 }
358
359                                 $OUT .= $title;
360
361                                 if (($menu == $action) && (empty($what))) {
362                                         $OUT .= "</strong>";
363                                 } else {
364                                         $OUT .= "</a>]";
365                                 }
366
367                                 $OUT .= "</div>
368 </li>\n";
369
370                                 // Check for menu entries
371                                 $result_what = SQL_QUERY_ESC("SELECT
372         `what`, `title`, `descr`
373 FROM
374         `{?_MYSQL_PREFIX?}_admin_menu`
375 WHERE
376         `action`='%s' AND
377         `what` != '' AND
378         `what` IS NOT NULL
379 ORDER BY
380         `sort` ASC,
381         `id` DESC",
382                                         array($menu), __FUNCTION__, __LINE__);
383
384                                 // Remember the count for later checks
385                                 setAdminMenuHasEntries($menu, ((SQL_NUMROWS($result_what) > 0) && ($action == $menu)));
386
387                                 // Do we have entries?
388                                 if ((ifAdminMenuHasEntries($menu)) && (SQL_NUMROWS($result_what) > 0)) {
389                                         $GLOBALS['menu']['description'] = array();
390                                         $GLOBALS['menu']['title'] = array(); $SUB = true;
391                                         $OUT .= "<li class=\"admin_menu_sub\"><ul class=\"admin_menu_sub\">\n";
392                                         // @TODO Rewrite this to $content = SQL_FETCHARRAY()
393                                         while (list($what_sub, $title_what, $desc_what) = SQL_FETCHROW($result_what)) {
394                                                 // Check for access level
395                                                 if ((isExtensionActive('admins')) && (getExtensionVersion('admins') > '0.2.0')) {
396                                                         $ACL = adminsCheckAdminAcl('', $what_sub);
397                                                 } else {
398                                                         // @TODO ACL is 'allow'... hmmm
399                                                         $ACL = true;
400                                                 }
401
402                                                 // Filename
403                                                 $inc = sprintf("inc/modules/admin/what-%s.php", $what_sub);
404
405                                                 // Is the file readable?
406                                                 $readable = isIncludeReadable($inc);
407
408                                                 // Access allowed?
409                                                 if ($ACL === true) {
410                                                         // Insert compiled title and description
411                                                         $GLOBALS['menu']['title'][$what_sub]      = $title_what;
412                                                         $GLOBALS['menu']['description'][$what_sub] = $desc_what;
413                                                         $OUT .= "<li class=\"admin_menu\">
414                 <div class=\"nobr\"><strong>--&gt;</strong>&nbsp;";
415                                                         if ($readable === true) {
416                                                                 if ($what == $what_sub) {
417                                                                         $OUT .= "<strong>";
418                                                                 } else {
419                                                                         $OUT .= "[<a href=\"{?URL?}/modules.php?module=admin&amp;what=".$what_sub."\">";
420                                                                 }
421                                                         } else {
422                                                                 $OUT .= "<em style=\"cursor:help\" class=\"admin_note\" title=\"{--MENU_WHAT_404--}\">";
423                                                         }
424
425                                                         $OUT .= $title_what;
426
427                                                         if ($readable === true) {
428                                                                 if ($what == $what_sub) {
429                                                                         $OUT .= "</strong>";
430                                                                 } else {
431                                                                         $OUT .= "</a>]";
432                                                                 }
433                                                         } else {
434                                                                 $OUT .= "</em>";
435                                                         }
436                                                         $OUT .= "</div>
437 </li>\n";
438                                                 } // END - if
439                                         } // END - while
440
441                                         // Free memory
442                                         SQL_FREERESULT($result_what);
443                                         $OUT .= "</ul>
444 </li>\n";
445                                 } // END - if
446
447                                 $OUT .= "<li style=\"height:7px\" class=\"seperator\">&nbsp;</li>\n";
448                         } // END - if
449                 } // END - while
450
451                 // Free memory
452                 SQL_FREERESULT($result_main);
453                 $OUT .= "</ul>\n";
454         }
455
456         // Is there a cache instance again?
457         // Return or output content?
458         if ($return === true) {
459                 return $OUT;
460         } else {
461                 outputHtml($OUT);
462         }
463 }
464
465 // Create member selection box
466 function addMemberSelectionBox ($def='0', $add_all=false, $return=false, $none=false, $field='userid') {
467         // Output selection form with all confirmed user accounts listed
468         $result = SQL_QUERY("SELECT `userid`, `surname`, `family` FROM `{?_MYSQL_PREFIX?}_user_data` ORDER BY `userid` ASC", __FUNCTION__, __LINE__);
469
470         // Default output
471         $OUT = '';
472
473         // USe this only for adding points (e.g. adding refs really makes no sence ;-) )
474         if ($add_all === true)   $OUT = "      <option value=\"all\">{--ALL_MEMBERS--}</option>\n";
475          elseif ($none === true) $OUT = "      <option value=\"0\">{--SELECT_NONE--}</option>\n";
476
477         while ($content = SQL_FETCHARRAY($result)) {
478                 $OUT .= "      <option value=\"".bigintval($content['userid'])."\"";
479                 if ($def == $content['userid']) $OUT .= ' selected="selected"';
480                 $OUT .= ">".$content['surname']." ".$content['family']." (".bigintval($content['userid']).")</option>\n";
481         } // END - while
482
483         // Free memory
484         SQL_FREERESULT($result);
485
486         if ($return === false) {
487                 // Remeber options in constant
488                 $content['member_selection'] = $OUT;
489                 $content['what']             = getWhat();
490
491                 // Load template
492                 loadTemplate('admin_member_selection_box', false, $content);
493         } else {
494                 // Return content in selection frame
495                 return "<select class=\"admin_select\" name=\"".$field."\" size=\"1\">\n".$OUT."</select>\n";
496         }
497 }
498
499 // Create a menu selection box for given menu system
500 // @TODO Try to rewrite this to adminAddMenuSelectionBox()
501 // @DEPRECATED
502 function adminMenuSelectionBox_DEPRECATED ($mode, $default = '', $defid = '') {
503         $what = "`what` != ''";
504         if ($mode == 'action') $what = "(`what`='' OR `what` IS NULL) AND action !='login'";
505         $result = SQL_QUERY_ESC("SELECT %s, title FROM `{?_MYSQL_PREFIX?}_admin_menu` WHERE ".$what." ORDER BY `sort`",
506                 array($mode), __FUNCTION__, __LINE__);
507         if (SQL_NUMROWS($result) > 0) {
508                 // Load menu as selection
509                 $OUT = "<select name=\"".$mode."_menu";
510                 if ((!empty($defid)) || ($defid == '0')) $OUT .= "[".$defid."]";
511                 $OUT .= "\" size=\"1\" class=\"admin_select\">
512         <option value=\"\">{--SELECT_NONE--}</option>\n";
513                 // @TODO Try to rewrite this to $content = SQL_FETCHARRAY(). Please look some lines above for the dynamic query
514                 while (list($menu, $title) = SQL_FETCHROW($result)) {
515                         $OUT .= "  <option value=\"".$menu."\"";
516                         if ((!empty($default)) && ($default == $menu)) $OUT .= ' selected="selected"';
517                         $OUT .= ">".$title."</option>\n";
518                 } // END - while
519
520                 // Free memory
521                 SQL_FREERESULT($result);
522                 $OUT .= "</select>\n";
523         } else {
524                 // No menus???
525                 $OUT = getMessage('ADMIN_PROBLEM_NO_MENU');
526         }
527
528         // Return output
529         return $OUT;
530 }
531
532 // Wrapper for $_POST and adminSaveSettings
533 function adminSaveSettingsFromPostData ($tableName = "_config", $whereStatement = "config=0", $translateComma = array(), $alwaysAdd = false) {
534         // Get the array
535         $postData = postRequestArray();
536
537         // Call the lower function
538         adminSaveSettings($postData, $tableName, $whereStatement, $translateComma, $alwaysAdd);
539 }
540
541 // Save settings to the database
542 function adminSaveSettings (&$postData, $tableName = "_config", $whereStatement = "config=0", $translateComma = array(), $alwaysAdd = false) {
543         // Prepare all arrays, variables
544         $DATA = array();
545         $skip = false;
546
547         // Now, walk through all entries and prepare them for saving
548         foreach ($postData as $id => $val) {
549                 // Process only formular field but not submit buttons ;)
550                 if ($id != 'ok') {
551                         // Do not save the ok value
552                         convertSelectionsToTimestamp($postData, $DATA, $id, $skip);
553
554                         // Shall we process this ID? It muss not be empty, of course
555                         if (($skip === false) && (!empty($id))) {
556                                 // Save this entry
557                                 $val = compileCode($val);
558
559                                 // Translate the value? (comma to dot!)
560                                 if ((is_array($translateComma)) && (in_array($id, $translateComma))) {
561                                         // Then do it here... :)
562                                         $val = convertCommaToDot($val);
563                                 } // END - if
564
565                                 // Shall we add numbers or strings?
566                                 $test = (float)$val;
567                                 if ("".$val."" == ''.$test."") {
568                                         // Add numbers
569                                         $DATA[] = sprintf("`%s`=%s", $id, $test);
570                                 } else {
571                                         // Add strings
572                                         $DATA[] = sprintf("`%s`='%s'", $id, trim($val));
573                                 }
574
575                                 // Update current configuration
576                                 setConfigEntry($id, $val);
577                         } // END - if
578                 } // END - if
579         } // END - foreach
580
581         // Check if entry does exist
582         $result = false;
583         if ($alwaysAdd === false) {
584                 if (!empty($whereStatement)) {
585                         $result = SQL_QUERY("SELECT * FROM `{?_MYSQL_PREFIX?}".$tableName."` WHERE ".$whereStatement." LIMIT 1", __FUNCTION__, __LINE__);
586                 } else {
587                         $result = SQL_QUERY("SELECT * FROM `{?_MYSQL_PREFIX?}".$tableName."` LIMIT 1", __FUNCTION__, __LINE__);
588                 }
589         } // END - if
590
591         if (SQL_NUMROWS($result) == 1) {
592                 // "Implode" all data to single string
593                 $DATA_UPDATE = implode(", ", $DATA);
594
595                 // Generate SQL string
596                 $sql = sprintf("UPDATE `{?_MYSQL_PREFIX?}%s` SET %s WHERE %s LIMIT 1",
597                 $tableName,
598                 $DATA_UPDATE,
599                 $whereStatement
600                 );
601         } else {
602                 // Add Line (does only work with auto_increment!
603                 $KEYs = array(); $values = array();
604                 foreach ($DATA as $entry) {
605                         // Split up
606                         $line = explode('=', $entry);
607                         $KEYs[] = $line[0]; $values[] = $line[1];
608                 } // END - foreach
609
610                 // Add both in one line
611                 $KEYs = implode(", ", $KEYs);
612                 $values = implode(", ", $values);
613
614                 // Generate SQL string
615                 $sql = sprintf("INSERT INTO {?_MYSQL_PREFIX?}%s (%s) VALUES (%s)",
616                 $tableName,
617                 $KEYs,
618                 $values
619                 );
620         }
621
622         // Free memory
623         SQL_FREERESULT($result);
624
625         // Simply run generated SQL string
626         SQL_QUERY($sql, __FUNCTION__, __LINE__);
627
628         // Rebuild cache
629         rebuildCacheFile('config', 'config');
630
631         // Settings saved
632         loadTemplate('admin_settings_saved', false, getMessage('SETTINGS_SAVED'));
633 }
634
635 // Generate a selection box
636 function adminAddMenuSelectionBox ($menu, $type, $name, $default = '') {
637         // Open the requested menu directory
638         $menuArray = getArrayFromDirectory(sprintf("inc/modules/%s/", $menu), '', false, false);
639
640         // Init the selection box
641         $OUT = "<select name=\"".$name."\" class=\"admin_select\" size=\"1\">
642         <option value=\"\">{--IS_TOP_MENU--}</option>\n";
643
644         // Walk through all files
645         foreach ($menuArray as $file) {
646                 // Is this a PHP script?
647                 if ((!isDirectory($file)) && (strpos($file, "".$type.'-') > -1) && (strpos($file, '.php') > 0)) {
648                         // Then test if the file is readable
649                         $test = sprintf("inc/modules/%s/%s", $menu, $file);
650
651                         // Is the file there?
652                         if (isIncludeReadable($test)) {
653                                 // Extract the value for what=xxx
654                                 $part = substr($file, (strlen($type) + 1));
655                                 $part = substr($part, 0, -4);
656
657                                 // Is that part different from the overview?
658                                 if ($part != 'overview') {
659                                         $OUT .= "       <option value=\"".$part."\"";
660                                         if ($part == $default) $OUT .= ' selected="selected"';
661                                         $OUT .= ">".$part."</option>\n";
662                                 } // END - if
663                         } // END - if
664                 } // END - if
665         } // END - foreach
666
667         // Close selection box
668         $OUT .= "</select>\n";
669
670         // Return contents
671         return $OUT;
672 }
673
674 // Creates a user-profile link for the admin. This function can also be used for many other purposes
675 function generateUserProfileLink ($userid, $title = '', $what = 'list_user') {
676         if (($title == '') && ($title != '0')) {
677                 // Set userid as title
678                 $title = $userid;
679         } // END - if
680
681         if (($title == '0') && ($what == 'list_refs')) {
682                 // Return title again
683                 return $title;
684         } // END - if
685
686         // Return link
687         //* DEBUG: */ outputHtml("a:".$title."<br />");
688         return '[<a href="{?URL?}/modules.php?module=admin&amp;what=' . $what . '&amp;userid=' . $userid . '" title="{--ADMIN_USER_PROFILE_TITLE--}">' . $title . '</a>]';
689 }
690
691 // Check "logical-area-mode"
692 function adminGetMenuMode () {
693         // Set the global mode as the mode for all admins
694         $mode = getConfig('admin_menu');
695         $ADMIN = $mode;
696
697         // Get admin id
698         $adminId = getCurrentAdminId();
699
700         // Check individual settings of current admin
701         if (isset($GLOBALS['cache_array']['admin']['la_mode'][$adminId])) {
702                 // Load from cache
703                 $ADMIN = $GLOBALS['cache_array']['admin']['la_mode'][$adminId];
704                 incrementStatsEntry('cache_hits');
705         } elseif (isExtensionInstalledAndNewer('admins', '0.6.7')) {
706                 // Load from database when version of 'admins' is enough
707                 $result = SQL_QUERY_ESC("SELECT la_mode FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
708                         array($adminId), __FUNCTION__, __LINE__);
709                 if (SQL_NUMROWS($result) == 1) {
710                         // Load data
711                         list($ADMIN) = SQL_FETCHROW($result);
712                 }
713
714                 // Free memory
715                 SQL_FREERESULT($result);
716         }
717
718         // Check what the admin wants and set it when it's not the global mode
719         if ($ADMIN != 'global') $mode = $ADMIN;
720
721         // Return admin-menu's mode
722         return $mode;
723 }
724
725 // Change activation status
726 function adminChangeActivationStatus ($IDs, $table, $row, $idRow = 'id') {
727         $cnt = 0; $newStatus = 'Y';
728         if ((is_array($IDs)) && (count($IDs) > 0)) {
729                 // "Walk" all through and count them
730                 foreach ($IDs as $id => $selected) {
731                         // Secure the ID number
732                         $id = bigintval($id);
733
734                         // Should always be set... ;-)
735                         if (!empty($selected)) {
736                                 // Determine new status
737                                 $result = SQL_QUERY_ESC("SELECT %s FROM `{?_MYSQL_PREFIX?}_%s` WHERE %s=%s LIMIT 1",
738                                 array($row, $table, $idRow, $id), __FUNCTION__, __LINE__);
739
740                                 // Row found?
741                                 if (SQL_NUMROWS($result) == 1) {
742                                         // Load the status
743                                         list($currStatus) = SQL_FETCHROW($result);
744
745                                         // And switch it N<->Y
746                                         if ($currStatus == 'Y') $newStatus = 'N'; else $newStatus = 'Y';
747
748                                         // Change this status
749                                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s` SET %s='%s' WHERE %s=%s LIMIT 1",
750                                         array($table, $row, $newStatus, $idRow, $id), __FUNCTION__, __LINE__);
751
752                                         // Count up affected rows
753                                         $cnt += SQL_AFFECTEDROWS();
754                                 } // END - if
755
756                                 // Free the result
757                                 SQL_FREERESULT($result);
758                         } // END - if
759                 } // END - foreach
760
761                 // Output status
762                 loadTemplate('admin_settings_saved', false, sprintf(getMessage('ADMIN_STATUS_CHANGED'), $cnt, count($IDs)));
763         } else {
764                 // Nothing selected!
765                 loadTemplate('admin_settings_saved', false, getMessage('ADMIN_NOTHING_SELECTED_CHANGE'));
766         }
767 }
768
769 // Send mails for del/edit/lock build modes
770 function sendAdminBuildMails ($mode, $table, $content, $id, $subjectPart = '') {
771         // Default subject is the subject part
772         $subject = $subjectPart;
773
774         // Is the subject part not set?
775         if (empty($subjectPart)) {
776                 // Then use it from the mode
777                 $subject = strtoupper($mode);
778         } // END - if
779
780         // Is the raw userid set?
781         if (postRequestElement('userid_raw', $id) > 0) {
782                 // Generate subject
783                 $subjectLine = getMessage('MEMBER_'.strtoupper($subject).'_'.strtoupper($table).'_SUBJECT');
784
785                 // Load email template
786                 if (!empty($subjectPart)) {
787                         $mail = loadEmailTemplate('member_' . $mode . '_' . strtolower($subjectPart) . '_' . $table, $content);
788                 } else {
789                         $mail = loadEmailTemplate('member_' . $mode . '_' . $table, $content);
790                 }
791
792                 // Send email out
793                 sendEmail(postRequestElement('userid_raw', $id), $subjectLine, $mail);
794         } // END - if
795
796         // Generate subject
797         $subjectLine = getMessage('ADMIN_'.strtoupper($subject).'_'.strtoupper($table).'_SUBJECT');
798
799         // Send admin notification out
800         if (!empty($subjectPart)) {
801                 sendAdminNotification($subjectLine, 'admin_' . $mode . '_' . strtolower($subjectPart) . '_' . $table, $content, postRequestElement('userid_raw', $id));
802         } else {
803                 sendAdminNotification($subjectLine, 'admin_' . $mode . '_' . $table, $content, postRequestElement('userid_raw', $id));
804         }
805 }
806
807 // Build a special template list
808 function adminListBuilder ($listType, $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn) {
809         $OUT = ''; $SW = 2;
810
811         // "Walk" through all entries
812         foreach ($IDs as $id => $selected) {
813                 // Secure ID number
814                 $id = bigintval($id);
815
816                 // Get result from a given column array and table name
817                 $result = SQL_RESULT_FROM_ARRAY($table, $columns, $idColumn, $id, __FUNCTION__, __LINE__);
818
819                 // Is there one entry?
820                 if (SQL_NUMROWS($result) == 1) {
821                         // Load all data
822                         $content = SQL_FETCHARRAY($result);
823
824                         // Filter all data
825                         foreach ($content as $key => $value) {
826                                 // Search index
827                                 $idx = array_search($key, $columns, true);
828
829                                 // Do we have a userid?
830                                 if ($key == 'userid') {
831                                         // Add it again as raw id
832                                         $content['userid'] = bigintval($value);
833                                 } // END - if
834
835                                 // Handle the call in external function
836                                 $content[$key] = handleExtraValues($filterFunctions[$idx], $value, $extraValues[$idx]);
837                         } // END - foreach
838
839                         // Add color switching
840                         $content['sw'] = $SW;
841
842                         // Then list it
843                         $OUT .= loadTemplate(sprintf("admin_%s_%s_row",
844                         $listType,
845                         $table
846                         ), true, $content
847                         );
848
849                         // Switch color
850                         $SW = 3 - $SW;
851                 } // END - if
852
853                 // Free the result
854                 SQL_FREERESULT($result);
855         } // END - foreach
856
857         // Load master template
858         loadTemplate(sprintf("admin_%s_%s",
859         $listType,
860         $table
861         ), false, $OUT
862         );
863 }
864
865 // Change status of "build" list
866 function adminBuilderStatusHandler ($mode, $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray) {
867         // All valid entries? (We hope so here!)
868         if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues)) && (count($statusArray) > 0)) {
869                 // "Walk" through all entries
870                 foreach ($IDs as $id => $sel) {
871                         // Construct SQL query
872                         $sql = sprintf("UPDATE `{?_MYSQL_PREFIX?}_%s` SET", SQL_ESCAPE($table));
873
874                         // Load data of entry
875                         $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_%s` WHERE %s=%s LIMIT 1",
876                                 array($table, $idColumn, $id), __FUNCTION__, __LINE__);
877
878                         // Fetch the data
879                         $content = SQL_FETCHARRAY($result);
880
881                         // Free the result
882                         SQL_FREERESULT($result);
883
884                         // Add all status entries (e.g. status column last_updated or so)
885                         $newStatus = 'UNKNOWN';
886                         $oldStatus = 'UNKNOWN';
887                         $statusColumn = 'unknown';
888                         foreach ($statusArray as $column => $statusInfo) {
889                                 // Does the entry exist?
890                                 if ((isset($content[$column])) && (isset($statusInfo[$content[$column]]))) {
891                                         // Add these entries for update
892                                         $sql .= sprintf(" %s='%s',", SQL_ESCAPE($column), SQL_ESCAPE($statusInfo[$content[$column]]));
893
894                                         // Remember status
895                                         if ($statusColumn == 'unknown') {
896                                                 // Always (!!!) change status column first!
897                                                 $oldStatus = $content[$column];
898                                                 $newStatus = $statusInfo[$oldStatus];
899                                                 $statusColumn = $column;
900                                         } // END - if
901                                 } elseif (isset($content[$column])) {
902                                         // Unfinished!
903                                         app_die(__FUNCTION__, __LINE__, ":UNFINISHED: id={$id}/{$column}[".gettype($statusInfo)."] = {$content[$column]}");
904                                 }
905                         } // END - foreach
906
907                         // Add other columns as well
908                         foreach (postRequestArray() as $key => $entries) {
909                                 // Skip id, raw userid and 'do_$mode'
910                                 if (!in_array($key, array($idColumn, 'userid_raw', ('do_'.$mode)))) {
911                                         // Are there brackets () at the end?
912                                         if (substr($entries[$id], -2, 2) == "()") {
913                                                 // Direct SQL command found
914                                                 $sql .= sprintf(" %s=%s,", SQL_ESCAPE($key), SQL_ESCAPE($entries[$id]));
915                                         } else {
916                                                 // Add regular entry
917                                                 $sql .= sprintf(" %s='%s',", SQL_ESCAPE($key), SQL_ESCAPE($entries[$id]));
918
919                                                 // Add entry
920                                                 $content[$key] = $entries[$id];
921                                         }
922                                 } // END - if
923                         } // END - foreach
924
925                         // Finish SQL statement
926                         $sql = substr($sql, 0, -1) . sprintf(" WHERE `%s`=%s AND `%s`='%s' LIMIT 1",
927                                 $idColumn,
928                                 bigintval($id),
929                                 $statusColumn,
930                                 $oldStatus
931                         );
932
933                         // Run the SQL
934                         SQL_QUERY($sql, __FUNCTION__, __LINE__);
935
936                         // Do we have an URL?
937                         if (isset($content['url'])) {
938                                 // Then add a framekiller test as well
939                                 $content['frametester'] = generateFrametesterUrl($content['url']);
940                         } // END - if
941
942                         // Send "build mails" out
943                         sendAdminBuildMails($mode, $table, $content, $id, $statusInfo[$content[$column]]);
944                 } // END - foreach
945         } // END - if
946 }
947
948 // Delete rows by given ID numbers
949 function adminDeleteEntriesConfirm ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $deleteNow=false, $idColumn='id', $userIdColumn='userid') {
950         // All valid entries? (We hope so here!)
951         if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues))) {
952                 // Shall we delete here or list for deletion?
953                 if ($deleteNow === true) {
954                         // The base SQL command:
955                         $sql = "DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_%s` WHERE %s IN (%s)";
956
957                         // Delete them all
958                         $idList = '';
959                         foreach ($IDs as $id => $sel) {
960                                 // Is there a userid?
961                                 if (isPostRequestElementSet('userid_raw', $id)) {
962                                         // Load all data from that id
963                                         $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_%s` WHERE %s=%s LIMIT 1",
964                                         array($table, $idColumn, $id), __FUNCTION__, __LINE__);
965
966                                         // Fetch the data
967                                         $content = SQL_FETCHARRAY($result);
968
969                                         // Free the result
970                                         SQL_FREERESULT($result);
971
972                                         // Send "build mails" out
973                                         sendAdminBuildMails('del', $table, $content, $id);
974                                 } // END - if
975
976                                 // Add id number
977                                 $idList .= $id . ',';
978                         } // END - foreach
979
980                         // Run the query
981                         SQL_QUERY($sql, array($table, $idColumn, substr($idList, 0, -1)), __FUNCTION__, __LINE__);
982
983                         // Was this fine?
984                         if (SQL_AFFECTEDROWS() == count($IDs)) {
985                                 // All deleted
986                                 loadTemplate('admin_settings_saved', false, getMessage('ADMIN_ALL_ENTRIES_REMOVED'));
987                         } else {
988                                 // Some are still there :(
989                                 loadTemplate('admin_settings_saved', false, sprintf(getMessage('ADMIN_SOME_ENTRIES_NOT_DELETED'), SQL_AFFECTEDROWS(), count($IDs)));
990                         }
991                 } else {
992                         // List for deletion confirmation
993                         adminListBuilder('del', $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
994                 }
995         } // END - if
996 }
997
998 // Edit rows by given ID numbers
999 function adminEditEntriesConfirm ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $editNow=false, $idColumn='id', $userIdColumn='userid') {
1000         // All valid entries? (We hope so here!)
1001         if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues))) {
1002                 // Shall we change here or list for editing?
1003                 if ($editNow === true) {
1004                         // Change them all
1005                         $affected = 0;
1006                         foreach ($IDs as $id => $sel) {
1007                                 // Prepare content array (new values)
1008                                 $content = array();
1009
1010                                 // Prepare SQL for this row
1011                                 $sql = sprintf("UPDATE `{?_MYSQL_PREFIX?}_%s` SET",
1012                                         SQL_ESCAPE($table)
1013                                 );
1014                                 foreach (postRequestArray() as $key => $entries) {
1015                                         // Skip raw userid which is always invalid
1016                                         if ($key == 'userid_raw') {
1017                                                 // Continue with next field
1018                                                 continue;
1019                                         } // END - if
1020
1021                                         // Is entries an array?
1022                                         if (($key != $idColumn) && (is_array($entries)) && (isset($entries[$id]))) {
1023                                                 // Add this entry to content
1024                                                 $content[$key] = $entries[$id];
1025
1026                                                 // Send data through the filter function if found
1027                                                 if ((isset($filterFunctions[$key])) && (isset($extraValues[$key]))) {
1028                                                         // Filter function set!
1029                                                         $entries[$id] = handleExtraValues($filterFunctions[$key], $entries[$id], $extraValues[$key]);
1030                                                 } // END - if
1031
1032                                                 // Then add this value
1033                                                 $sql .= sprintf(" `%s`='%s',",
1034                                                 SQL_ESCAPE($key),
1035                                                 SQL_ESCAPE($entries[$id])
1036                                                 );
1037                                         } elseif (($key != $idColumn) && (!is_array($entries))) {
1038                                                 // Add normal entries as well!
1039                                                 $content[$key] =  $entries;
1040                                         }
1041
1042                                         // Do we have an URL?
1043                                         if ($key == 'url') {
1044                                                 // Then add a framekiller test as well
1045                                                 $content['frametester'] = generateFrametesterUrl($content[$key]);
1046                                         } // END - if
1047                                 } // END - foreach
1048
1049                                 // Finish SQL command
1050                                 $sql = substr($sql, 0, -1) . " WHERE `".$idColumn."`=".bigintval($id)." LIMIT 1";
1051
1052                                 // Run this query
1053                                 SQL_QUERY($sql, __FUNCTION__, __LINE__);
1054
1055                                 // Add affected rows
1056                                 $affected += SQL_AFFECTEDROWS();
1057
1058                                 // Load all data from that id
1059                                 $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`=%s LIMIT 1",
1060                                         array($table, $idColumn, $id), __FUNCTION__, __LINE__);
1061
1062                                 // Fetch the data and merge it into $content
1063                                 $content = merge_array($content, SQL_FETCHARRAY($result));
1064
1065                                 // Free the result
1066                                 SQL_FREERESULT($result);
1067
1068                                 // Send "build mails" out
1069                                 sendAdminBuildMails('edit', $table, $content, $id);
1070                         } // END - foreach
1071
1072                         // Was this fine?
1073                         if ($affected == count($IDs)) {
1074                                 // All deleted
1075                                 loadTemplate('admin_settings_saved', false, getMessage('ADMIN_ALL_ENTRIES_EDITED'));
1076                         } else {
1077                                 // Some are still there :(
1078                                 loadTemplate('admin_settings_saved', false, sprintf(getMessage('ADMIN_SOME_ENTRIES_NOT_EDITED'), $affected, count($IDs)));
1079                         }
1080                 } else {
1081                         // List for editing
1082                         adminListBuilder('edit', $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1083                 }
1084         } // END - if
1085 }
1086
1087 // Un-/lock rows by given ID numbers
1088 function adminLockEntriesConfirm ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $statusArray=array(), $lockNow=false, $idColumn='id', $userIdColumn='userid') {
1089         // All valid entries? (We hope so here!)
1090         if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues)) && (($lockNow === false) || (count($statusArray) == 1))) {
1091                 // Shall we un-/lock here or list for locking?
1092                 if ($lockNow === true) {
1093                         // Un-/lock entries
1094                         adminBuilderStatusHandler("lock", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray);
1095                 } else {
1096                         // List for editing
1097                         adminListBuilder("lock", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1098                 }
1099         } // END - if
1100 }
1101
1102 // Undelete rows by given ID numbers
1103 function adminUndeleteEntriesConfirm ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $statusArray=array(), $undeleteNow=false, $idColumn='id', $userIdColumn='userid') {
1104         // All valid entries? (We hope so here!)
1105         if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues)) && (($undeleteNow === false) || (count($statusArray) == 1))) {
1106                 // Shall we un-/lock here or list for locking?
1107                 if ($undeleteNow === true) {
1108                         // Undelete entries
1109                         adminBuilderStatusHandler("undelete", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray);
1110                 } else {
1111                         // List for editing
1112                         adminListBuilder("undelete", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1113                 }
1114         } // END - if
1115 }
1116
1117 // Checks proxy settins by fetching check-updates3.php from www.mxchange.org
1118 function adminTestProxySettings ($settingsArray) {
1119         // Set temporary the new settings
1120         mergeConfig($settingsArray);
1121
1122         // Now get the test URL
1123         $content = sendGetRequest('check-updates3.php');
1124
1125         // Is the first line with "200 OK"?
1126         $valid = (strpos($content[0], '200 OK') !== false);
1127
1128         // Return result
1129         return $valid;
1130 }
1131
1132 // Sends out a link to the given email adress so the admin can reset his/her password
1133 function sendAdminPasswordResetLink ($email) {
1134         // Init output
1135         $OUT = '';
1136
1137         // Compile out security characters (must be for looking up!)
1138         $email = compileCode($email);
1139
1140         // Look up administator login
1141         $result = SQL_QUERY_ESC("SELECT `id`, `login`, `password` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `email`='%s' LIMIT 1",
1142                 array($email), __FUNCTION__, __LINE__);
1143
1144         // Is there an account?
1145         if (SQL_NUMROWS($result) == 0) {
1146                 // No account found!
1147                 return getMessage('ADMIN_NO_LOGIN_WITH_EMAIL');
1148         } // END - if
1149
1150         // Load all data
1151         $content = SQL_FETCHARRAY($result);
1152
1153         // Free result
1154         SQL_FREERESULT($result);
1155
1156         // Generate hash for reset link
1157         $content['hash'] = generateHash(getConfig('URL').':'.$content['id'].':'.$content['login'].':'.$content['password'], substr($content['password'], 10));
1158
1159         // Remove some data
1160         unset($content['id']);
1161         unset($content['password']);
1162
1163         // Prepare email
1164         $mailText = loadEmailTemplate('admin_reset_password', $content);
1165
1166         // Send it out
1167         sendEmail($email, getMessage('ADMIN_RESET_PASS_LINK_SUBJ'), $mailText);
1168
1169         // Prepare output
1170         return getMessage('ADMIN_RESET_LINK_SENT');
1171 }
1172
1173 // Validate hash and login for password reset
1174 function adminResetValidateHashLogin ($hash, $login) {
1175         // By default nothing validates... ;)
1176         $valid = false;
1177
1178         // Compile the login for lookup
1179         $login = compileCode($login);
1180
1181         // Then try to find that user
1182         $result = SQL_QUERY_ESC("SELECT `id`, `password`, `email` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
1183         array($login), __FUNCTION__, __LINE__);
1184
1185         // Is an account here?
1186         if (SQL_NUMROWS($result) == 1) {
1187                 // Load all data
1188                 $content = SQL_FETCHARRAY($result);
1189
1190                 // Generate hash again
1191                 $hashFromData = generateHash(getConfig('URL').':'.$content['id'].':'.$login.':'.$content['password'], substr($content['password'], 10));
1192
1193                 // Does both match?
1194                 $valid = ($hash == $hashFromData);
1195         } // END - if
1196
1197         // Free result
1198         SQL_FREERESULT($result);
1199
1200         // Return result
1201         return $valid;
1202 }
1203
1204 // Reset the password for the login. Do NOT call this function without calling above function first!
1205 function doResetAdminPassword ($login, $password) {
1206         // Init hash
1207         $passHash = '';
1208
1209         // Now check if we have sql_patches installed
1210         if (getExtensionVersion('sql_patches') >= '0.3.6') {
1211                 // Use new way of hashing
1212                 $passHash = generateHash($password);
1213         } else {
1214                 // Old MD5 method
1215                 $passHash = md5($password);
1216         }
1217
1218         // Update database
1219         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_admins` SET `password`='%s' WHERE `login`='%s' LIMIT 1",
1220                 array($passHash, $login), __FUNCTION__, __LINE__);
1221
1222         // Run filters
1223         runFilterChain('post_admin_reset_pass', array('login' => $login, 'hash' => $passHash));
1224
1225         // Return output
1226         return getMessage('ADMIN_PASSWORD_RESET_DONE');
1227 }
1228
1229 // Solves a task by given id number
1230 function adminSolveTask ($id) {
1231         // Update the task data
1232         adminUpdateTaskData($id, 'status', 'SOLVED');
1233 }
1234
1235 // Marks a given task as deleted
1236 function adminDeleteTask ($id) {
1237         // Update the task data
1238         adminUpdateTaskData($id, 'status', 'DELETED');
1239 }
1240
1241 // Function to update task data
1242 function adminUpdateTaskData ($id, $row, $data) {
1243         // Should be admin!
1244         if (!isAdmin()) {
1245                 // Not an admin so redirect better
1246                 redirectToUrl('index.php');
1247         } // END - if
1248
1249         // Is the id not set, then we need a backtrace here... :(
1250         if ($id <= 0) {
1251                 // Initiate backtrace
1252                 debug_report_bug(sprintf("id is invalid: %s. row=%s, data=%s",
1253                         $id,
1254                         $row,
1255                         $data
1256                 ));
1257         } // END - if
1258
1259         // Update the task
1260         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_task_system` SET `%s`='%s' WHERE `id`=%s LIMIT 1",
1261                 array($row, $data, bigintval($id)), __FUNCTION__, __LINE__);
1262 }
1263
1264 // Checks wether if the admin menu has entries
1265 function ifAdminMenuHasEntries ($action) {
1266         return (
1267                 ((
1268                         isset($GLOBALS['admin_menu_has_entries'][$action])
1269                 ) && (
1270                         $GLOBALS['admin_menu_has_entries'][$action] === true
1271                 )) || (
1272                         $action == 'login'
1273                 )
1274         );
1275 }
1276
1277 // Setter for 'admin_menu_has_entries'
1278 function setAdminMenuHasEntries ($action, $hasEntries) {
1279         $GLOBALS['admin_menu_has_entries'][$action] = (bool) $hasEntries;
1280 }
1281
1282 // Creates a link to the user's admin-profile
1283 function adminCreateUserLink ($userid) {
1284         // Is the userid set correctly?
1285         if ($userid > 0) {
1286                 // Create a link to that profile
1287                 return '{?URL?}/modules.php?module=admin&amp;what=list_user&amp;userid='.bigintval($userid);
1288         } // END - if
1289
1290         // Return a link to the user list
1291         return '{?URL?}/modules.php?module=admin&amp;what=list_user';
1292 }
1293
1294 // -----------------------------------------------------------------------------
1295 // ---                           Filter functions                            ---
1296 // -----------------------------------------------------------------------------
1297
1298 // Filter for checking admin ACL
1299 function FILTER_CHECK_ADMIN_ACL () {
1300         // Extension not installed so it's always allowed to access everywhere!
1301         $ret = true;
1302
1303         // Ok, Cookie-Update done
1304         if ((isExtensionInstalledAndNewer('admins', '0.3.0')) && (isExtensionActive('admins'))) {
1305                 // Check if action GET variable was set
1306                 $action = getAction();
1307                 if (isWhatSet()) {
1308                         // Get action value by what-value
1309                         $action = getModeAction('admin', getWhat());
1310                 } // END - if
1311
1312                 // Check for access control line of current menu entry
1313                 $ret = adminsCheckAdminAcl($action, getWhat());
1314         } // END - if
1315
1316         // Set it here
1317         $GLOBALS['acl_allow'] = $ret;
1318 }
1319
1320 // [EOF]
1321 ?>