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