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