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