Admin menu has now a JavaScript "effect":
[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  * -------------------------------------------------------------------- *
18  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
19  * Copyright (c) 2009 - 2011 by Mailer Developer Team                   *
20  * For more information visit: http://mxchange.org                      *
21  *                                                                      *
22  * This program is free software; you can redistribute it and/or modify *
23  * it under the terms of the GNU General Public License as published by *
24  * the Free Software Foundation; either version 2 of the License, or    *
25  * (at your option) any later version.                                  *
26  *                                                                      *
27  * This program is distributed in the hope that it will be useful,      *
28  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
29  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
30  * GNU General Public License for more details.                         *
31  *                                                                      *
32  * You should have received a copy of the GNU General Public License    *
33  * along with this program; if not, write to the Free Software          *
34  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
35  * MA  02110-1301  USA                                                  *
36  ************************************************************************/
37
38 // Some security stuff...
39 if (!defined('__SECURITY')) {
40         die();
41 } // END - if
42
43 // Register an administrator account
44 function addAdminAccount ($adminLogin, $passHash, $adminEmail) {
45         // Login does already exist
46         $ret = 'already';
47
48         // Lookup the admin
49         $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
50                 array($adminLogin), __FUNCTION__, __LINE__);
51
52         // Is the entry there?
53         if (SQL_HASZERONUMS($result)) {
54                 // Ok, let's create the admin login
55                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_admins` (`login`,`password`,`email`) VALUES ('%s', '%s', '%s')",
56                         array(
57                                 $adminLogin,
58                                 $passHash,
59                                 $adminEmail
60                         ), __FUNCTION__, __LINE__);
61
62                 // All done
63                 $ret = 'done';
64         } // END - if
65
66         // Free memory
67         SQL_FREERESULT($result);
68
69         // Return result
70         return $ret;
71 }
72
73 // This function will be executed when the admin is not logged in and has submitted his login data
74 function ifAdminLoginDataIsValid ($adminLogin, $adminPassword) {
75         // First of all, no admin login is found, so the admin hash is null
76         $ret = '404';
77         $adminHash = NULL;
78
79         // Get admin id from login
80         $adminId = getAdminId($adminLogin);
81
82         // Continue only with found admin ids
83         if ($adminId > 0) {
84                 // Then we need to lookup the login name by getting the admin hash
85                 $adminHash = getAdminHash($adminId);
86
87                 // If this is fine, we can continue
88                 if ($adminHash != '-1') {
89                         // Get admin id and set it as current
90                         setCurrentAdminId($adminId);
91
92                         // Now, we need to encode the password in the same way the one is encoded in database
93                         $testHash = generateHash($adminPassword, $adminHash);
94
95                         // If they both match, the login data is valid
96                         if ($testHash == $adminHash) {
97                                 // All fine
98                                 $ret = 'done';
99                         } else {
100                                 // Did not match!
101                                 $ret = 'password';
102                         }
103                 } // END - if
104         } // END - if
105
106         // Prepare data array
107         $data = array(
108                 'id'         => $adminId,
109                 'login'      => $adminLogin,
110                 'plain_pass' => $adminPassword,
111                 'pass_hash'  => $adminHash
112         );
113
114         // Run a special filter
115         runFilterChain('do_admin_login_' . $ret, $data);
116
117         // Return status
118         return $ret;
119 }
120
121 // Only be executed on cookie checking
122 function ifAdminCookiesAreValid ($adminLogin, $passHash) {
123         // First of all, no admin login is found
124         $ret = '404';
125
126         // Then we need to lookup the login name by getting the admin hash
127         $adminHash = getAdminHash($adminLogin);
128
129         // If this is fine, we can continue
130         if ($adminHash != '-1') {
131                 // Now, we need to encode the password in the same way the one is encoded in database
132                 $testHash = encodeHashForCookie($adminHash);
133                 //* DEBUG: */ debugOutput('adminLogin=' . $adminLogin . ',passHash='.$passHash.',adminHash='.$adminHash.',testHash='.$testHash);
134
135                 // If they both match, the login data is valid
136                 if ($testHash == $passHash) {
137                         // All fine
138                         $ret = 'done';
139                 } else {
140                         // Set status
141                         $ret = 'password';
142                 }
143         } // END - if
144
145         // Return status
146         //* DEBUG: */ debugOutput('ret='.$ret);
147         return $ret;
148 }
149
150 // Do an admin action
151 function doAdminAction () {
152         // Get default what
153         $what = getWhat();
154
155         //* DEBUG: */ debugOutput(__LINE__.'*'.$what.'/'.getModule().'/'.getAction().'/'.getWhat().'*');
156
157         // Remove any spaces from variable
158         if (empty($what)) {
159                 // Default admin action is the overview page
160                 $what = 'overview';
161         } else {
162                 // Secure it
163                 $what = secureString($what);
164         }
165
166         // Get action value
167         $action = getActionFromModuleWhat(getModule(), $what);
168
169         // Load welcome template
170         if (isExtensionActive('admins')) {
171                 // @TODO This and the next getCurrentAdminId() call might be moved into the templates?
172                 $content['welcome'] = loadTemplate('admin_welcome_admins', true, getCurrentAdminId());
173         } else {
174                 $content['welcome'] = loadTemplate('admin_welcome', true, getCurrentAdminId());
175         }
176
177         // Load header, footer, render menu
178         $content['header'] = loadTemplate('admin_header' , true, $content);
179         $content['footer'] = loadTemplate('admin_footer' , true, $content);
180         $content['menu']   = addAdminMenu($action, $what);
181
182         // Load main template
183         loadTemplate('admin_main', false, $content);
184
185         // Check if action/what pair is valid
186         $result_action = SQL_QUERY_ESC("SELECT
187         `id`
188 FROM
189         `{?_MYSQL_PREFIX?}_admin_menu`
190 WHERE
191         `action`='%s' AND
192         (
193                 (
194                         `what`='%s' AND `what` != 'overview'
195                 ) OR (
196                         (
197                                 `what`='' OR `what` IS NULL
198                         ) AND (
199                                 '%s'='overview'
200                         )
201                 )
202         )
203 LIMIT 1",
204                 array(
205                         $action,
206                         $what,
207                         $what
208                 ), __FUNCTION__, __LINE__);
209
210         // Do we have an entry?
211         if (SQL_NUMROWS($result_action) == 1) {
212                 // Is valid but does the inlcude file exists?
213                 $inc = sprintf("inc/modules/admin/action-%s.php", $action);
214                 if ((isIncludeReadable($inc)) && (isMenuActionValid('admin', $action, $what)) && ($GLOBALS['acl_allow'] === true)) {
215                         // Ok, we finally load the admin action module
216                         loadInclude($inc);
217                 } elseif ($GLOBALS['acl_allow'] === false) {
218                         // Access denied
219                         loadTemplate('admin_menu_failed', false, '{%message,ADMIN_ACCESS_DENIED=' . $what . '%}');
220                 } else {
221                         // Include file not found :-(
222                         loadTemplate('admin_menu_failed', false, '{%message,ADMIN_ACTION_404=' . $action . '%}');
223                 }
224         } else {
225                 // Invalid action/what pair found
226                 loadTemplate('admin_menu_failed', false, '{%message,ADMIN_ACTION_INVALID=' . $action . '/' . $what . '%}');
227         }
228
229         // Free memory
230         SQL_FREERESULT($result_action);
231
232         // Tableset footer
233         loadTemplate('admin_main_footer', false, $content);
234 }
235
236 // Checks wether current admin is allowed to access given action/what combination
237 // (only one is allowed to be null!)
238 function isAdminAllowedAccessMenu ($action, $what = NULL) {
239         // Do we have cache?
240         if (!isset($GLOBALS[__FUNCTION__][$action][$what])) {
241                 // ACL is always 'allow' when no ext-admins is installed
242                 // @TODO This can be rewritten into a filter
243                 $GLOBALS[__FUNCTION__][$action][$what] = ((!isExtensionInstalledAndNewer('admins', '0.2.0')) || (isAdminsAllowedByAcl($action, $what)));
244         } // END - if
245
246         // Return the cached value
247         return $GLOBALS[__FUNCTION__][$action][$what];
248 }
249
250 // Adds an admin menu
251 function addAdminMenu ($action, $what) {
252         // Init variables
253         $SUB = false;
254         $OUT = '';
255
256         // Menu descriptions
257         $GLOBALS['menu']['description'] = array();
258         $GLOBALS['menu']['title']       = array();
259
260         // Build main menu
261         $result_main = SQL_QUERY("SELECT
262         `action` AS `main_action`,
263         `title` AS `main_title`,
264         `descr` AS `main_descr`
265 FROM
266         `{?_MYSQL_PREFIX?}_admin_menu`
267 WHERE
268         (`what`='' OR `what` IS NULL)
269 ORDER BY
270         `sort` ASC,
271         `id` DESC", __FUNCTION__, __LINE__);
272
273         // Do we have entries?
274         if (!SQL_HASZERONUMS($result_main)) {
275                 $OUT .= '<ul class="admin_menu_main">';
276
277                 // Load all 'action' menus
278                 while ($mainContent = SQL_FETCHARRAY($result_main)) {
279                         // Filename
280                         $inc = sprintf("inc/modules/admin/action-%s.php", $mainContent['main_action']);
281
282                         // Is the file readable?
283                         $readable = isIncludeReadable($inc);
284
285                         // Is the current admin allowed to access this 'action' menu?
286                         if (isAdminAllowedAccessMenu($mainContent['main_action'])) {
287                                 if ($SUB === false) {
288                                         // Insert compiled menu title and description
289                                         $GLOBALS['menu']['title'][$mainContent['main_action']]       = $mainContent['main_title'];
290                                         $GLOBALS['menu']['description'][$mainContent['main_action']] = $mainContent['main_descr'];
291                                 } // END - if
292                                 $OUT .= '<li class="admin_menu"' . addJavaScriptMenuContent('admin', $mainContent['main_action'], $action, $what) . '>
293 <div class="nobr"><strong>&middot;</strong>&nbsp;';
294
295                                 if ($readable === true) {
296                                         if (($mainContent['main_action'] == $action) && (empty($what))) {
297                                                 $OUT .= '<strong>';
298                                         } else {
299                                                 $OUT .= '[<a href="{%url=modules.php?module=admin&amp;action=' . $mainContent['main_action'] . '%}">';
300                                         }
301                                 } else {
302                                         $OUT .= '<span class="bad" style="cursor:help" title="{%message,ADMIN_MENU_ACTION_404_TITLE=' . $mainContent['main_action'] . '%}">';
303                                 }
304
305                                 $OUT .= $mainContent['main_title'];
306
307                                 if ($readable === true) {
308                                         if (($mainContent['main_action'] == $action) && (empty($what))) {
309                                                 $OUT .= '</strong>';
310                                         } else {
311                                                 $OUT .= '</a>]';
312                                         }
313                                 } else {
314                                         $OUT .= '</span>';
315                                 }
316
317                                 $OUT .= '</div>
318 </li>';
319
320                                 // Add sub menu
321                                 $OUT .= addAdminSubMenu($mainContent, $action, $what);
322                         } // END - if
323                 } // END - while
324
325                 // Close ul-tag
326                 $OUT .= '</ul>';
327
328                 // Free memory
329                 SQL_FREERESULT($result_main);
330         } // END - if
331
332         // Return content
333         return $OUT;
334 }
335
336 // Add admin sub menu
337 function addAdminSubMenu ($mainContent, $action, $what) {
338         // Init content
339         $OUT = '';
340
341         // Check for menu entries
342         $result_what = SQL_QUERY_ESC("SELECT
343         `what` AS `sub_what`,
344         `title` AS `sub_title`,
345         `descr` AS `sub_descr`
346 FROM
347         `{?_MYSQL_PREFIX?}_admin_menu`
348 WHERE
349         `action`='%s' AND
350         `what` != '' AND
351         `what` IS NOT NULL
352 ORDER BY
353         `sort` ASC,
354         `id` DESC",
355                 array($mainContent['main_action']), __FUNCTION__, __LINE__);
356
357         // Remember the count for later checks
358         setAdminMenuHasEntries($mainContent['main_action'], ((!SQL_HASZERONUMS($result_what)) && (($action == $mainContent['main_action']) || (isAdminMenuJavascriptEnabled()))));
359
360         // Start li-tag for sub menu content
361         $OUT .= '<li class="admin_menu_sub" id="action_menu_' . $mainContent['main_action'] . '"' . addStyleMenuContent('admin', $mainContent['main_action'], $action) . '>';
362
363         // Do we have entries?
364         if (ifAdminMenuHasEntries($mainContent['main_action'])) {
365                 // Sub menu has been called
366                 $SUB = true;
367                 $OUT .= '<ul class="admin_menu_sub">';
368
369                 // Load all entries
370                 while ($subContent = SQL_FETCHARRAY($result_what)) {
371                         // Filename
372                         $inc = sprintf("inc/modules/admin/what-%s.php", $subContent['sub_what']);
373
374                         // Is the file readable?
375                         $readable = isIncludeReadable($inc);
376
377                         // Is the current admin allowed to access this 'what' menu?
378                         if (isAdminAllowedAccessMenu(NULL, $subContent['sub_what'])) {
379                                 // Insert compiled title and description
380                                 $GLOBALS['menu']['title'][$subContent['sub_what']]       = $subContent['sub_title'];
381                                 $GLOBALS['menu']['description'][$subContent['sub_what']] = $subContent['sub_descr'];
382                                 $OUT .= '<li class="admin_menu">
383 <div class="nobr"><strong>--&gt;</strong>&nbsp;';
384                                 if ($readable === true) {
385                                         if ($what == $subContent['sub_what']) {
386                                                 $OUT .= '<strong>';
387                                         } else {
388                                                 $OUT .= '[<a href="{%url=modules.php?module=admin&amp;what=' . $subContent['sub_what'] . '%}">';
389                                         }
390                                 } else {
391                                         $OUT .= '<span class="bad" style="cursor:help" title="{%message,ADMIN_MENU_WHAT_404_TITLE=' . $subContent['sub_what'] . '%}">';
392                                 }
393
394                                 $OUT .= $subContent['sub_title'];
395
396                                 if ($readable === true) {
397                                         if ($what == $subContent['sub_what']) {
398                                                 $OUT .= '</strong>';
399                                         } else {
400                                                 $OUT .= '</a>]';
401                                         }
402                                 } else {
403                                         $OUT .= '</span>';
404                                 }
405                                 $OUT .= '</div>
406 </li>';
407                         } // END - if
408                 } // END - while
409
410                 // Free memory
411                 SQL_FREERESULT($result_what);
412                 $OUT .= '</ul>';
413         } // END - if
414
415         // Close li-tag
416         $OUT .= '</li>';
417
418         // Return content
419         return $OUT;
420 }
421
422 // Create an admin selection box form
423 function addAdminSelectionBox ($adminId = NULL, $special = '') {
424         // Default is email as "special column"
425         $ADD = ',`email` AS `special`';
426
427         // Is a special column given?
428         if (!empty($special)) {
429                 // Additional column for SQL query
430                 $ADD = ',`' . $special . '` AS `special`';
431         } // END - if
432
433         // Query all entries
434         $result = SQL_QUERY('SELECT
435         `id`,
436         `login`
437         ' . $ADD . '
438 FROM
439         `{?_MYSQL_PREFIX?}_admins`
440 ORDER BY
441         `login` ASC', __FUNCTION__, __LINE__);
442
443         // Init output
444         $OUT = '';
445
446         // Load all entries
447         while ($content = SQL_FETCHARRAY($result)) {
448                 // Add the entry
449                 $OUT .= loadTemplate('select_admins_option', true, $content);
450         } // END - if
451
452         // Free memory
453         SQL_FREERESULT($result);
454
455         // Add form to content
456         $content['form_selection'] = $OUT;
457
458         // Output form
459         loadTemplate('select_admins_box', false, $content);
460 }
461
462 // Create a member selection box
463 function addMemberSelectionBox ($userid = NULL, $add_all = false, $return = false, $none = false, $field = 'userid') {
464         // Output selection form with all confirmed user accounts listed
465         $result = SQL_QUERY('SELECT
466         `userid`,`surname`,`family`
467 FROM
468         `{?_MYSQL_PREFIX?}_user_data`
469 ORDER BY
470         `userid` ASC', __FUNCTION__, __LINE__);
471
472         // Default output
473         $OUT = '';
474
475         // USe this only for adding points (e.g. adding refs really makes no sence ;-) )
476         if ($add_all === true) {
477                 $OUT = '      <option value="all">{--ALL_MEMBERS--}</option>';
478         } elseif ($none === true) {
479                 $OUT = '      <option value="0">{--SELECT_NONE--}</option>';
480         }
481
482         // Load all entries
483         while ($content = SQL_FETCHARRAY($result)) {
484                 $OUT .= '<option value="' . bigintval($content['userid']) . '"';
485                 if ($userid == $content['userid']) $OUT .= ' selected="selected"';
486                 $OUT .= '>' . $content['surname'] . ' ' . $content['family'] . ' (' . bigintval($content['userid']) . ')</option>';
487         } // END - while
488
489         // Free memory
490         SQL_FREERESULT($result);
491
492         if ($return === false) {
493                 // Remeber options in constant
494                 $content['form_selection'] = $OUT;
495                 $content['what']           = '{%pipe,getWhat%}';
496
497                 // Load template
498                 loadTemplate('admin_form_selection_box', false, $content);
499         } else {
500                 // Return content in selection frame
501                 return '<select class="form_select" name="' . handleFieldWithBraces($field) . '" size="1">' . $OUT . '</select>';
502         }
503 }
504
505 // Create a menu selection box for given menu system
506 // @TODO Try to rewrite this to adminAddMenuSelectionBox()
507 // @DEPRECATED
508 function adminMenuSelectionBox_DEPRECATED ($mode, $default = '', $defid = '') {
509         $what = "`what` != '' AND `what` IS NOT NULL";
510         if ($mode == 'action') $what = "(`what`='' OR `what` IS NULL) AND `action` != 'login'";
511
512         $result = SQL_QUERY_ESC("SELECT `%s` AS `menu`,`title` FROM `{?_MYSQL_PREFIX?}_admin_menu` WHERE ".$what." ORDER BY `sort` ASC",
513                 array($mode), __FUNCTION__, __LINE__);
514         if (!SQL_HASZERONUMS($result)) {
515                 // Load menu as selection
516                 $OUT = '<select name="' . $mode . '_menu';
517                 if ((!empty($defid)) || ($defid == '0')) $OUT .= '[' . $defid . ']';
518                 $OUT .= '" size="1" class="form_select">
519         <option value="">{--SELECT_NONE--}</option>';
520                 // Load all entries
521                 while ($content = SQL_FETCHARRAY($result)) {
522                         $OUT .= '<option value="' . $content['menu'] . '"';
523                         if ((!empty($default)) && ($default == $content['menu'])) $OUT .= ' selected="selected"';
524                         $OUT .= '>' . $content['title'] . '</option>';
525                 } // END - while
526
527                 // Free memory
528                 SQL_FREERESULT($result);
529
530                 // Add closing select-tag
531                 $OUT .= '</select>';
532         } else {
533                 // No menus???
534                 $OUT = '{--ADMIN_PROBLEM_NO_MENU--}';
535         }
536
537         // Return output
538         return $OUT;
539 }
540
541 // Wrapper for $_POST and adminSaveSettings
542 function adminSaveSettingsFromPostData ($tableName = '_config', $whereStatement = '`config`=0', $translateComma = array(), $alwaysAdd = false, $displayMessage = true) {
543         // Get the array
544         $postData = postRequestArray();
545
546         // Call the lower function
547         adminSaveSettings($postData, $tableName, $whereStatement, $translateComma, $alwaysAdd, $displayMessage);
548 }
549
550 // Save settings to the database
551 function adminSaveSettings (&$postData, $tableName = '_config', $whereStatement = '`config`=0', $translateComma = array(), $alwaysAdd = false, $displayMessage = true) {
552         // Prepare all arrays, variables
553         $tableData = array();
554         $skip = false;
555
556         // Now, walk through all entries and prepare them for saving
557         foreach ($postData as $id => $val) {
558                 // Process only formular field but not submit buttons ;)
559                 if ($id != 'ok') {
560                         // Do not save the ok value
561                         convertSelectionsToEpocheTime($postData, $tableData, $id, $skip);
562
563                         // Shall we process this id? It muss not be empty, of course
564                         if (($skip === false) && (!empty($id)) && ((!isset($GLOBALS['skip_config'][$id]))) || ($tableName != '_config')) {
565                                 // Translate the value? (comma to dot!)
566                                 if ((is_array($translateComma)) && (in_array($id, $translateComma))) {
567                                         // Then do it here... :)
568                                         $val = convertCommaToDot($val);
569                                 } // END - if
570
571                                 // Shall we add numbers or strings?
572                                 $test = (float) $val;
573                                 if ('' . $val . '' == '' . $test . '') {
574                                         // Add numbers
575                                         $tableData[] = sprintf("`%s`=%s", $id, $test);
576                                 } elseif (is_null($val)) {
577                                         // Add NULL
578                                         $tableData[] = sprintf("`%s`=NULL", $id);
579                                 } else {
580                                         // Add strings
581                                         $tableData[] = sprintf("`%s`='%s'", $id, trim($val));
582                                 }
583
584                                 // Do not add a config entry twice
585                                 $GLOBALS['skip_config'][$id] = true;
586
587                                 // Update current configuration
588                                 setConfigEntry($id, $val);
589                         } // END - if
590                 } // END - if
591         } // END - foreach
592
593         // Check if entry does exist
594         $result = false;
595         if ($alwaysAdd === false) {
596                 if (!empty($whereStatement)) {
597                         $result = SQL_QUERY("SELECT * FROM `{?_MYSQL_PREFIX?}" . $tableName . "` WHERE " . $whereStatement . " LIMIT 1", __FUNCTION__, __LINE__);
598                 } else {
599                         $result = SQL_QUERY("SELECT * FROM `{?_MYSQL_PREFIX?}" . $tableName . "` LIMIT 1", __FUNCTION__, __LINE__);
600                 }
601         } // END - if
602
603         if (SQL_NUMROWS($result) == 1) {
604                 // "Implode" all data to single string
605                 $updatedData = implode(', ', $tableData);
606
607                 // Generate SQL string
608                 $sql = sprintf("UPDATE `{?_MYSQL_PREFIX?}%s` SET %s WHERE %s LIMIT 1",
609                         $tableName,
610                         $updatedData,
611                         $whereStatement
612                 );
613         } else {
614                 // Add Line (does only work with AUTO_INCREMENT!
615                 $keys = array(); $values = array();
616                 foreach ($tableData as $entry) {
617                         // Split up
618                         $line = explode('=', $entry);
619                         $keys[] = $line[0];
620                         $values[] = $line[1];
621                 } // END - foreach
622
623                 // Add both in one line
624                 $keys = implode('`,`', $keys);
625                 $values = implode(', ', $values);
626
627                 // Generate SQL string
628                 $sql = sprintf("INSERT INTO `{?_MYSQL_PREFIX?}%s` (%s) VALUES (%s)",
629                         $tableName,
630                         $keys,
631                         $values
632                 );
633         }
634
635         // Free memory
636         SQL_FREERESULT($result);
637
638         // Simply run generated SQL string
639         SQL_QUERY($sql, __FUNCTION__, __LINE__);
640
641         // Remember affected rows
642         $affected = SQL_AFFECTEDROWS();
643
644         // Rebuild cache
645         rebuildCache('config', 'config');
646
647         // Settings saved, so display message?
648         if ($displayMessage === true) displayMessage('{--SETTINGS_SAVED--}');
649
650         // Return affected rows
651         return $affected;
652 }
653
654 // Generate a selection box
655 function adminAddMenuSelectionBox ($menu, $type, $name, $default = '') {
656         // Open the requested menu directory
657         $menuArray = getArrayFromDirectory(sprintf("inc/modules/%s/", $menu), $type . '-', false, false);
658
659         // Init the selection box
660         $OUT = '<select name="' . $name . '" class="form_select" size="1"><option value="">{--ADMIN_IS_TOP_MENU--}</option>';
661
662         // Walk through all files
663         foreach ($menuArray as $file) {
664                 // Is this a PHP script?
665                 if ((!isDirectory($file)) && (isInString('' . $type . '-', $file)) && (isInString('.php', $file))) {
666                         // Then test if the file is readable
667                         $test = sprintf("inc/modules/%s/%s", $menu, $file);
668
669                         // Is the file there?
670                         if (isIncludeReadable($test)) {
671                                 // Extract the value for what=xxx
672                                 $part = substr($file, (strlen($type) + 1));
673                                 $part = substr($part, 0, -4);
674
675                                 // Is that part different from the overview?
676                                 if ($part != 'overview') {
677                                         $OUT .= '<option value="' . $part . '"';
678                                         if ($part == $default) $OUT .= ' selected="selected"';
679                                         $OUT .= '>' . $part . '</option>';
680                                 } // END - if
681                         } // END - if
682                 } // END - if
683         } // END - foreach
684
685         // Close selection box
686         $OUT .= '</select>';
687
688         // Return contents
689         return $OUT;
690 }
691
692 // Creates a user-profile link for the admin. This function can also be used for many other purposes
693 function generateUserProfileLink ($userid, $title = '', $what = 'list_user') {
694         if (($title == '') && (isValidUserId($userid))) {
695                 // Set userid as title
696                 $title = $userid;
697         } elseif (!isValidUserId($userid)) {
698                 // User id zero is invalid
699                 return '<strong>' . makeNullToZero($userid) . '</strong>';
700         }
701
702         if (($title == '0') && ($what == 'list_refs')) {
703                 // Return title again
704                 return $title;
705         } elseif (isExtensionActive('nickname')) {
706                 // Get nickname
707                 $nick = getNickname($userid);
708
709                 // Is it not empty, use it as title else the userid
710                 if (!empty($nick)) {
711                         $title = $nick . '(' . $userid . ')';
712                 } else {
713                         $title = $userid;
714                 }
715         }
716
717         // Return link
718         return '[<a href="{%url=modules.php?module=admin&amp;what=' . $what . '&amp;userid=' . $userid . '%}" title="{--ADMIN_USER_PROFILE_TITLE--}">' . $title . '</a>]';
719 }
720
721 // Check "logical-area-mode"
722 function adminGetMenuMode () {
723         // Set the default menu mode as the mode for all admins
724         $mode = 'global';
725
726         // If sql_patches is up-to-date enough, use the configuration
727         if (isExtensionInstalledAndNewer('sql_patches', '0.3.2')) {
728                 $mode = getAdminMenu();
729         } // END - if
730
731         // Backup it
732         $adminMode = $mode;
733
734         // Get admin id
735         $adminId = getCurrentAdminId();
736
737         // Check individual settings of current admin
738         if (isset($GLOBALS['cache_array']['admin']['la_mode'][$adminId])) {
739                 // Load from cache
740                 $adminMode = $GLOBALS['cache_array']['admin']['la_mode'][$adminId];
741                 incrementStatsEntry('cache_hits');
742         } elseif (isExtensionInstalledAndNewer('admins', '0.6.7')) {
743                 // Load from database when version of 'admins' is enough
744                 $result = SQL_QUERY_ESC("SELECT `la_mode` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
745                         array($adminId), __FUNCTION__, __LINE__);
746
747                 // Do we have an entry?
748                 if (SQL_NUMROWS($result) == 1) {
749                         // Load data
750                         list($adminMode) = SQL_FETCHROW($result);
751                 } // END - if
752
753                 // Free memory
754                 SQL_FREERESULT($result);
755         }
756
757         // Check what the admin wants and set it when it's not the default mode
758         if ($adminMode != 'global') {
759                 $mode = $adminMode;
760         } // END - if
761
762         // Return admin-menu's mode
763         return $mode;
764 }
765
766 // Change activation status
767 function adminChangeActivationStatus ($IDs, $table, $row, $idRow = 'id') {
768         $count = '0';
769         if ((is_array($IDs)) && (count($IDs) > 0)) {
770                 // "Walk" all through and count them
771                 foreach ($IDs as $id => $selected) {
772                         // Secure the id number
773                         $id = bigintval($id);
774
775                         // Should always be set... ;-)
776                         if (!empty($selected)) {
777                                 // Determine new status
778                                 $result = SQL_QUERY_ESC("SELECT %s FROM `{?_MYSQL_PREFIX?}_%s` WHERE %s=%s LIMIT 1",
779                                         array(
780                                                 $row,
781                                                 $table,
782                                                 $idRow,
783                                                 $id
784                                         ), __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                                         $newStatus = convertBooleanToYesNo(!($currStatus == 'Y'));
793
794                                         // Change this status
795                                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s` SET %s='%s' WHERE %s=%s LIMIT 1",
796                                                 array(
797                                                         $table,
798                                                         $row,
799                                                         $newStatus,
800                                                         $idRow,
801                                                         $id
802                                                 ), __FUNCTION__, __LINE__);
803
804                                         // Count up affected rows
805                                         $count += SQL_AFFECTEDROWS();
806                                 } // END - if
807
808                                 // Free the result
809                                 SQL_FREERESULT($result);
810                         } // END - if
811                 } // END - foreach
812
813                 // Output status
814                 displayMessage(sprintf(getMessage('ADMIN_STATUS_CHANGED'), $count, count($IDs)));
815         } else {
816                 // Nothing selected!
817                 displayMessage('{--ADMIN_NOTHING_SELECTED_CHANGE--}');
818         }
819 }
820
821 // Send mails for del/edit/lock build modes
822 function sendAdminBuildMails ($mode, $tableName, $content, $id, $subjectPart = '', $userIdColumn = array('userid')) {
823         // $tableName must be an array
824         if ((!is_array($tableName)) || (count($tableName) != 1)) {
825                 // $tableName is no array
826                 debug_report_bug(__FUNCTION__, __LINE__, 'tableName[]=' . gettype($tableName) . '!=array');
827         } elseif ((!is_array($userIdColumn)) || (count($userIdColumn) != 1)) {
828                 // $tableName is no array
829                 debug_report_bug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array');
830         } // END - if
831
832         // Default subject is the subject part
833         $subject = $subjectPart;
834
835         // Is the subject part not set?
836         if (empty($subjectPart)) {
837                 // Then use it from the mode
838                 $subject = strtoupper($mode);
839         } // END - if
840
841         // Is the raw userid set?
842         if (postRequestElement($userIdColumn[0], $id) > 0) {
843                 // Load email template
844                 if (!empty($subjectPart)) {
845                         $mail = loadEmailTemplate('member_' . $mode . '_' . strtolower($subjectPart) . '_' . $tableName[0], $content);
846                 } else {
847                         $mail = loadEmailTemplate('member_' . $mode . '_' . $tableName[0], $content);
848                 }
849
850                 // Send email out
851                 sendEmail(postRequestElement($userIdColumn[0], $id), strtoupper('{--MEMBER_' . $subject . '_' . $tableName[0] . '_SUBJECT--}'), $mail);
852         } // END - if
853
854         // Generate subject
855         $subject = strtoupper('{--ADMIN_' . $subject . '_' . $tableName[0] . '_SUBJECT--}');
856
857         // Send admin notification out
858         if (!empty($subjectPart)) {
859                 sendAdminNotification($subject, 'admin_' . $mode . '_' . strtolower($subjectPart) . '_' . $tableName[0], $content, postRequestElement($userIdColumn[0], $id));
860         } else {
861                 sendAdminNotification($subject, 'admin_' . $mode . '_' . $tableName[0], $content, postRequestElement($userIdColumn[0], $id));
862         }
863 }
864
865 // Build a special template list
866 function adminListBuilder ($listType, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId = array('userid')) {
867         // $tableName and $idColumn must bove be arrays!
868         if ((!is_array($tableName)) || (count($tableName) != 1)) {
869                 // $tableName is no array
870                 debug_report_bug(__FUNCTION__, __LINE__, 'tableName[]=' . gettype($tableName) . '!=array');
871         } elseif (!is_array($idColumn)) {
872                 // $idColumn is no array
873                 debug_report_bug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array');
874         } elseif ((!is_array($userIdColumn)) || (count($userIdColumn) != 1)) {
875                 // $tableName is no array
876                 debug_report_bug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array');
877         }
878
879         // Init row output
880         $OUT = '';
881
882         // "Walk" through all entries
883         //* DEBUG: */ debug_report_bug(__FUNCTION__, __LINE__, 'listType=<pre>'.print_r($listType,true).'</pre>,tableName<pre>'.print_r($tableName,true).'</pre>,columns=<pre>'.print_r($columns,true).'</pre>,filterFunctions=<pre>'.print_r($filterFunctions,true).'</pre>,extraValues=<pre>'.print_r($extraValues,true).'</pre>,idColumn=<pre>'.print_r($idColumn,true).'</pre>,userIdColumn=<pre>'.print_r($userIdColumn,true).'</pre>,rawUserId=<pre>'.print_r($rawUserId,true).'</pre>');
884         foreach (postRequestElement($idColumn[0]) as $id => $selected) {
885                 // Secure id number
886                 $id = bigintval($id);
887
888                 // Get result from a given column array and table name
889                 $result = SQL_RESULT_FROM_ARRAY($tableName[0], $columns, $idColumn[0], $id, __FUNCTION__, __LINE__);
890
891                 // Is there one entry?
892                 if (SQL_NUMROWS($result) == 1) {
893                         // Load all data
894                         $content = SQL_FETCHARRAY($result);
895
896                         // Filter all data
897                         foreach ($content as $key => $value) {
898                                 // Search index
899                                 $idx = searchXmlArray($key, $columns, 'column');
900
901                                 // Skip any missing entries
902                                 if ($idx === false) {
903                                         // Skip this one
904                                         //* DEBUG: */ debug_report_bug(__FUNCTION__, __LINE__, 'key=' . $key . ' - SKIPPED!');
905                                         continue;
906                                 } // END - if
907
908                                 // Do we have a userid?
909                                 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',userIdColumn=' . $userIdColumn[0]);
910                                 if ($key == $userIdColumn[0]) {
911                                         // Add it again as raw id
912                                         //* DEBUG: */ debug_report_bug(__FUNCTION__, __LINE__, 'key=' . $key . ',userIdColumn=' . $userIdColumn[0]);
913                                         $content[$userIdColumn[0]] = makeZeroToNull($value);
914                                         $content[$userIdColumn[0] . '_raw'] = $content[$userIdColumn[0]];
915                                 } // END - if
916
917                                 // If the key matches the idColumn variable, we need to temporary remember it
918                                 //* DEBUG: */ debugOutput('key=' . $key . ',idColumn=' . $idColumn[0] . ',value=' . $value);
919                                 if ($key == $idColumn[0]) {
920                                         // Found, so remember it
921                                         $GLOBALS['admin_list_builder_id_value'] = $value;
922                                 } // END - if
923
924                                 // Do we have a call-back function and extra-value pair?
925                                 if ((isset($filterFunctions[$idx])) && (isset($extraValues[$idx]))) {
926                                         // Handle the call in external function
927                                         //* DEBUG: */ debugOutput('key=' . $key . ',fucntion=' . $filterFunctions[$idx] . ',value=' . $value);
928                                         $content[$key] = handleExtraValues(
929                                                 $filterFunctions[$idx],
930                                                 $value,
931                                                 $extraValues[$idx]
932                                         );
933                                 } elseif ((isset($columns[$idx]['name'])) && (isset($filterFunctions[$columns[$idx]['name']])) && (isset($extraValues[$columns[$idx]['name']]))) {
934                                         // Handle the call in external function
935                                         //* DEBUG: */ debugOutput('key=' . $key . ',fucntion=' . $filterFunctions[$columns[$idx]['name']] . ',value=' . $value);
936                                         $content[$key] = handleExtraValues(
937                                                 $filterFunctions[$columns[$idx]['name']],
938                                                 $value,
939                                                 $extraValues[$columns[$idx]['name']]
940                                         );
941                                 }
942                         } // END - foreach
943
944                         // Then list it
945                         $OUT .= loadTemplate(sprintf("admin_%s_%s_row",
946                                 $listType,
947                                 $tableName[0]
948                                 ), true, $content
949                         );
950                 } // END - if
951
952                 // Free the result
953                 SQL_FREERESULT($result);
954         } // END - foreach
955
956         // Load master template
957         loadTemplate(sprintf("admin_%s_%s",
958                 $listType,
959                 $tableName[0]
960                 ), false, $OUT
961         );
962 }
963
964 // Change status of "build" list
965 function adminBuilderStatusHandler ($mode, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray, $rawUserId = array('userid')) {
966         // $tableName must be an array
967         if ((!is_array($tableName)) || (count($tableName) != 1)) {
968                 // No tableName specified
969                 debug_report_bug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array');
970         } elseif (!is_array($idColumn)) {
971                 // $idColumn is no array
972                 debug_report_bug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array');
973         } elseif ((!is_array($userIdColumn)) || (count($userIdColumn) != 1)) {
974                 // $tableName is no array
975                 debug_report_bug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array');
976         } // END - if
977
978         // All valid entries? (We hope so here!)
979         if ((count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues)) && (count($statusArray) > 0)) {
980                 // "Walk" through all entries
981                 foreach (postRequestElement($idColumn[0]) as $id => $sel) {
982                         // Construct SQL query
983                         $sql = sprintf("UPDATE `{?_MYSQL_PREFIX?}_%s` SET", SQL_ESCAPE($tableName[0]));
984
985                         // Load data of entry
986                         $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`=%s LIMIT 1",
987                                 array(
988                                         $tableName[0],
989                                         $idColumn[0],
990                                         $id
991                                 ), __FUNCTION__, __LINE__);
992
993                         // Fetch the data
994                         $content = SQL_FETCHARRAY($result);
995
996                         // Free the result
997                         SQL_FREERESULT($result);
998
999                         // Add all status entries (e.g. status column last_updated or so)
1000                         $newStatus = 'UNKNOWN';
1001                         $oldStatus = 'UNKNOWN';
1002                         $statusColumn = 'unknown';
1003                         foreach ($statusArray as $column => $statusInfo) {
1004                                 // Does the entry exist?
1005                                 if ((isset($content[$column])) && (isset($statusInfo[$content[$column]]))) {
1006                                         // Add these entries for update
1007                                         $sql .= sprintf(" `%s`='%s',", SQL_ESCAPE($column), SQL_ESCAPE($statusInfo[$content[$column]]));
1008
1009                                         // Remember status
1010                                         if ($statusColumn == 'unknown') {
1011                                                 // Always (!!!) change status column first!
1012                                                 $oldStatus = $content[$column];
1013                                                 $newStatus = $statusInfo[$oldStatus];
1014                                                 $statusColumn = $column;
1015                                         } // END - if
1016                                 } elseif (isset($content[$column])) {
1017                                         // Unfinished!
1018                                         debug_report_bug(__FUNCTION__, __LINE__, ':UNFINISHED: id=' . $id . ',column=' . $column . '[' . gettype($statusInfo) . '] = ' . $content[$column]);
1019                                 }
1020                         } // END - foreach
1021
1022                         // Add other columns as well
1023                         foreach (postRequestArray() as $key => $entries) {
1024                                 // Debug message
1025                                 logDebugMessage(__FUNCTION__, __LINE__, 'Found entry: ' . $key);
1026
1027                                 // Skip id, raw userid and 'do_$mode'
1028                                 if (!in_array($key, array($idColumn[0], $rawUserId[0], ('do_' . $mode)))) {
1029                                         // Are there brackets () at the end?
1030                                         if (substr($entries[$id], -2, 2) == '()') {
1031                                                 // Direct SQL command found
1032                                                 $sql .= sprintf(" `%s`=%s,", SQL_ESCAPE($key), SQL_ESCAPE($entries[$id]));
1033                                         } else {
1034                                                 // Add regular entry
1035                                                 $sql .= sprintf(" `%s`='%s',", SQL_ESCAPE($key), SQL_ESCAPE($entries[$id]));
1036
1037                                                 // Add entry
1038                                                 $content[$key] = $entries[$id];
1039                                         }
1040                                 } else {
1041                                         // Skipped entry
1042                                         logDebugMessage(__FUNCTION__, __LINE__, 'Skipped: ' . $key);
1043                                 }
1044                         } // END - foreach
1045
1046                         // Finish SQL statement
1047                         $sql = substr($sql, 0, -1) . sprintf(" WHERE `%s`=%s AND `%s`='%s' LIMIT 1",
1048                                 $idColumn[0],
1049                                 bigintval($id),
1050                                 $statusColumn,
1051                                 $oldStatus
1052                         );
1053
1054                         // Run the SQL
1055                         SQL_QUERY($sql, __FUNCTION__, __LINE__);
1056
1057                         // Do we have an URL?
1058                         if (isset($content['url'])) {
1059                                 // Then add a framekiller test as well
1060                                 $content['frametester'] = generateFrametesterUrl($content['url']);
1061                         } // END - if
1062
1063                         // Send "build mails" out
1064                         sendAdminBuildMails($mode, $tableName, $content, $id, $statusInfo[$content[$column]], $userIdColumn);
1065                 } // END - foreach
1066         } // END - if
1067 }
1068
1069 // Delete rows by given id numbers
1070 function adminDeleteEntriesConfirm ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $deleteNow = array(false), $idColumn = array('id'), $userIdColumn = array('userid'), $rawUserId = array('userid')) {
1071         // $tableName must be an array
1072         if ((!is_array($tableName)) || (count($tableName) != 1)) {
1073                 // No tableName specified
1074                 debug_report_bug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array');
1075         } elseif (!is_array($idColumn)) {
1076                 // $idColumn is no array
1077                 debug_report_bug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array');
1078         } elseif (!is_array($userIdColumn)) {
1079                 // $userIdColumn is no array
1080                 debug_report_bug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array');
1081         } elseif (!is_array($deleteNow)) {
1082                 // $deleteNow is no array
1083                 debug_report_bug(__FUNCTION__, __LINE__, 'deleteNow[]=' . gettype($deleteNow) . '!=array');
1084         } // END - if
1085
1086         // All valid entries? (We hope so here!)
1087         if ((count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues))) {
1088                 // Shall we delete here or list for deletion?
1089                 if ($deleteNow[0] === true) {
1090                         // The base SQL command:
1091                         $sql = "DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s` IN (%s)";
1092
1093                         // Delete them all
1094                         $idList = '';
1095                         foreach (postRequestElement($idColumn[0]) as $id => $sel) {
1096                                 // Is there a userid?
1097                                 if (isPostRequestElementSet($rawUserId[0], $id)) {
1098                                         // Load all data from that id
1099                                         $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`=%s LIMIT 1",
1100                                                 array(
1101                                                         $tableName[0],
1102                                                         $idColumn[0],
1103                                                         $id
1104                                                 ), __FUNCTION__, __LINE__);
1105
1106                                         // Fetch the data
1107                                         $content = SQL_FETCHARRAY($result);
1108
1109                                         // Free the result
1110                                         SQL_FREERESULT($result);
1111
1112                                         // Send "build mails" out
1113                                         sendAdminBuildMails('delete', $tableName, $content, $id, '', $userIdColumn);
1114                                 } // END - if
1115
1116                                 // Add id number
1117                                 $idList .= $id . ',';
1118                         } // END - foreach
1119
1120                         // Run the query
1121                         SQL_QUERY_ESC($sql, array($tableName[0], $idColumn[0], substr($idList, 0, -1)), __FUNCTION__, __LINE__);
1122
1123                         // Was this fine?
1124                         if (SQL_AFFECTEDROWS() == count(postRequestElement($idColumn[0]))) {
1125                                 // All deleted
1126                                 displayMessage('{--ADMIN_ALL_ENTRIES_REMOVED--}');
1127                         } else {
1128                                 // Some are still there :(
1129                                 displayMessage(sprintf(getMessage('ADMIN_SOME_ENTRIES_NOT_DELETED'), SQL_AFFECTEDROWS(), count(postRequestElement($idColumn[0]))));
1130                         }
1131                 } else {
1132                         // List for deletion confirmation
1133                         adminListBuilder('delete', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1134                 }
1135         } // END - if
1136 }
1137
1138 // Edit rows by given id numbers
1139 function adminEditEntriesConfirm ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $editNow = array(false), $idColumn = array('id'), $userIdColumn = array('userid'), $rawUserId = array('userid')) {
1140         // $tableName must be an array
1141         if ((!is_array($tableName)) || (count($tableName) != 1)) {
1142                 // No tableName specified
1143                 debug_report_bug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array');
1144         } elseif (!is_array($idColumn)) {
1145                 // $idColumn is no array
1146                 debug_report_bug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array');
1147         } elseif (!is_array($userIdColumn)) {
1148                 // $userIdColumn is no array
1149                 debug_report_bug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array');
1150         } elseif (!is_array($editNow)) {
1151                 // $editNow is no array
1152                 debug_report_bug(__FUNCTION__, __LINE__, 'editNow[]=' . gettype($editNow) . '!=array');
1153         } // END - if
1154
1155         // All valid entries? (We hope so here!)
1156         //* DEBUG: */ debug_report_bug(__FUNCTION__, __LINE__, 'idColumn=<pre>'.print_r($idColumn,true).'</pre>,tableName<pre>'.print_r($tableName,true).'</pre>,columns=<pre>'.print_r($columns,true).'</pre>,filterFunctions=<pre>'.print_r($filterFunctions,true).'</pre>,extraValues=<pre>'.print_r($extraValues,true).'</pre>,editNow=<pre>'.print_r($editNow,true).'</pre>,userIdColumn=<pre>'.print_r($userIdColumn,true).'</pre>,rawUserId=<pre>'.print_r($rawUserId,true).'</pre>');
1157         //if ((count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues))) {
1158         if (true) {
1159                 // Shall we change here or list for editing?
1160                 if ($editNow[0] === true) {
1161                         // Change them all
1162                         $affected = '0';
1163                         foreach (postRequestElement($idColumn[0]) as $id => $sel) {
1164                                 // Prepare content array (new values)
1165                                 $content = array();
1166
1167                                 // Prepare SQL for this row
1168                                 $sql = sprintf("UPDATE `{?_MYSQL_PREFIX?}_%s` SET",
1169                                         SQL_ESCAPE($tableName[0])
1170                                 );
1171                                 foreach (postRequestArray() as $key => $entries) {
1172                                         // Skip raw userid which is always invalid
1173                                         if ($key == $rawUserId[0]) {
1174                                                 // Continue with next field
1175                                                 continue;
1176                                         } // END - if
1177
1178                                         // Is entries an array?
1179                                         if (($key != $idColumn[0]) && (is_array($entries)) && (isset($entries[$id]))) {
1180                                                 // Add this entry to content
1181                                                 $content[$key] = $entries[$id];
1182
1183                                                 // Send data through the filter function if found
1184                                                 if ((isset($filterFunctions[$key])) && (isset($extraValues[$key]))) {
1185                                                         // Filter function set!
1186                                                         $entries[$id] = handleExtraValues($filterFunctions[$key], $entries[$id], $extraValues[$key]);
1187                                                 } // END - if
1188
1189                                                 // Then add this value
1190                                                 $sql .= sprintf(" `%s`='%s',",
1191                                                         SQL_ESCAPE($key),
1192                                                         SQL_ESCAPE($entries[$id])
1193                                                 );
1194                                         } elseif (($key != $idColumn[0]) && (!is_array($entries))) {
1195                                                 // Add normal entries as well!
1196                                                 $content[$key] =  $entries;
1197                                         }
1198
1199                                         // Do we have an URL?
1200                                         if ($key == 'url') {
1201                                                 // Then add a framekiller test as well
1202                                                 $content['frametester'] = generateFrametesterUrl($content[$key]);
1203                                         } // END - if
1204                                 } // END - foreach
1205
1206                                 // Finish SQL command
1207                                 $sql = substr($sql, 0, -1) . " WHERE `" . $idColumn[0] . "`=" . bigintval($id) . " LIMIT 1";
1208
1209                                 // Run this query
1210                                 SQL_QUERY($sql, __FUNCTION__, __LINE__);
1211
1212                                 // Add affected rows
1213                                 $affected += SQL_AFFECTEDROWS();
1214
1215                                 // Load all data from that id
1216                                 $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`=%s LIMIT 1",
1217                                         array(
1218                                                 $tableName[0],
1219                                                 $idColumn[0],
1220                                                 $id
1221                                         ), __FUNCTION__, __LINE__);
1222
1223                                 // Fetch the data and merge it into $content
1224                                 $content = merge_array($content, SQL_FETCHARRAY($result));
1225
1226                                 // Free the result
1227                                 SQL_FREERESULT($result);
1228
1229                                 // Send "build mails" out
1230                                 sendAdminBuildMails('edit', $tableName, $content, $id, '', $userIdColumn);
1231                         } // END - foreach
1232
1233                         // Was this fine?
1234                         if ($affected == count(postRequestElement($idColumn[0]))) {
1235                                 // All deleted
1236                                 displayMessage('{--ADMIN_ALL_ENTRIES_EDITED--}');
1237                         } else {
1238                                 // Some are still there :(
1239                                 displayMessage(sprintf(getMessage('ADMIN_SOME_ENTRIES_NOT_EDITED'), $affected, count(postRequestElement($idColumn[0]))));
1240                         }
1241                 } else {
1242                         // List for editing
1243                         adminListBuilder('edit', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1244                 }
1245         } else {
1246                 // Maybe some invalid parameters
1247                 debug_report_bug(__FUNCTION__, __LINE__, 'tableName=' . $tableName[0] . ',columns[]=' . gettype($columns) . ',filterFunctions[]=' . gettype($filterFunctions) . ',extraValues[]=' . gettype($extraValues) . ',idColumn=' . $idColumn[0] . ',userIdColumn=' . $userIdColumn[0] . ' - INVALID!');
1248         }
1249 }
1250
1251 // Un-/lock rows by given id numbers
1252 function adminLockEntriesConfirm ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $statusArray = array(), $lockNow = array(false), $idColumn = array('id'), $userIdColumn = array('userid')) {
1253         // $tableName must be an array
1254         if ((!is_array($tableName)) || (count($tableName) != 1)) {
1255                 // No tableName specified
1256                 debug_report_bug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array');
1257         } elseif (!is_array($idColumn)) {
1258                 // $idColumn is no array
1259                 debug_report_bug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array');
1260         } elseif (!is_array($lockNow)) {
1261                 // $lockNow is no array
1262                 debug_report_bug(__FUNCTION__, __LINE__, 'lockNow[]=' . gettype($lockNow) . '!=array');
1263         } // END - if
1264
1265         // All valid entries? (We hope so here!)
1266         if ((count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues)) && (($lockNow[0] === false) || (count($statusArray) == 1))) {
1267                 // Shall we un-/lock here or list for locking?
1268                 if ($lockNow[0] === true) {
1269                         // Un-/lock entries
1270                         adminBuilderStatusHandler('lock', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray);
1271                 } else {
1272                         // List for editing
1273                         adminListBuilder('lock', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1274                 }
1275         } // END - if
1276 }
1277
1278 // Undelete rows by given id numbers
1279 function adminUndeleteEntriesConfirm ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $statusArray = array(), $undeleteNow = array(false), $idColumn = array('id'), $userIdColumn = array('userid')) {
1280         // $tableName must be an array
1281         if ((!is_array($tableName)) || (count($tableName) != 1)) {
1282                 // No tableName specified
1283                 debug_report_bug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array');
1284         } elseif (!is_array($idColumn)) {
1285                 // $idColumn is no array
1286                 debug_report_bug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array');
1287         } elseif (!is_array($undeleteNow)) {
1288                 // $undeleteNow is no array
1289                 debug_report_bug(__FUNCTION__, __LINE__, 'undeleteNow[]=' . gettype($undeleteNow) . '!=array');
1290         } // END - if
1291
1292         // All valid entries? (We hope so here!)
1293         if ((count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues)) && (($undeleteNow[0] === false) || (count($statusArray) == 1))) {
1294                 // Shall we un-/lock here or list for locking?
1295                 if ($undeleteNow[0] === true) {
1296                         // Undelete entries
1297                         adminBuilderStatusHandler('undelete', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray);
1298                 } else {
1299                         // List for editing
1300                         adminListBuilder('undelete', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1301                 }
1302         } // END - if
1303 }
1304
1305 // Adds a given entry to the database
1306 function adminAddEntries ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array()) {
1307         //* DEBUG: */ die('columns=<pre>'.print_r($columns,true).'</pre>,filterFunctions=<pre>'.print_r($filterFunctions,true).'</pre>,extraValues=<pre>'.print_r($extraValues,true).'</pre>,POST=<pre>'.print_r($_POST,true).'</pre>');
1308         // Verify that tableName and columns are not empty
1309         if ((!is_array($tableName)) || (count($tableName) != 1)) {
1310                 // No tableName specified
1311                 debug_report_bug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array');
1312         } elseif (count($columns) == 0) {
1313                 // No columns specified
1314                 debug_report_bug(__FUNCTION__, __LINE__, 'columns is not given. Please fix your XML.');
1315         }
1316
1317         // Init columns and value elements
1318         $sqlColumns = array();
1319         $sqlValues  = array();
1320
1321         // Add columns and values
1322         foreach ($columns as $key => $columnName) {
1323                 // Copy entry to final arrays
1324                 $sqlColumns[$key] = $columnName;
1325                 $sqlValues[$key]  = postRequestElement($columnName);
1326                 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key='.$key.',columnName='.$columnName.',filterFunctions='.$filterFunctions[$key].',extraValues='.intval(isset($extraValues[$key])).',extraValuesName='.intval(isset($extraValues[$columnName . '_list'])).'<br />');
1327
1328                 // Send data through the filter function if found
1329                 if ((isset($filterFunctions[$key])) && (isset($extraValues[$key . '_list']))) {
1330                         // Filter function set!
1331                         $sqlValues[$key] = call_user_func_array($filterFunctions[$key], merge_array(array($columnName), $extraValues[$key . '_list']));
1332                 } // END - if
1333         } // END - foreach
1334
1335         // Build the SQL query
1336         $SQL = 'INSERT INTO `{?_MYSQL_PREFIX?}_' . $tableName[0] . '` (`' . implode('`,`', $sqlColumns) . "`) VALUES ('" . implode("','", $sqlValues) . "')";
1337
1338         // Run the SQL query
1339         SQL_QUERY($SQL, __FUNCTION__, __LINE__);
1340
1341         // Entry has been added?
1342         if (!SQL_HASZEROAFFECTED()) {
1343                 // Display success message
1344                 displayMessage('{--ADMIN_ENTRY_ADDED--}');
1345         } else {
1346                 // Display failed message
1347                 displayMessage('{--ADMIN_ENTRY_NOT_ADDED--}');
1348         }
1349 }
1350
1351 // List all given rows (callback function from XML)
1352 function adminListEntries ($tableTemplate, $rowTemplate, $noEntryMessageId, $tableName, $columns, $whereColumns, $orderByColumns, $callbackColumns, $extraParameters = array()) {
1353         // Verify that tableName and columns are not empty
1354         if ((!is_array($tableName)) || (count($tableName) != 1)) {
1355                 // No tableName specified
1356                 debug_report_bug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array,tableTemplate=' . $tableTemplate . ',rowTemplate=' . $rowTemplate);
1357         } elseif (count($columns) == 0) {
1358                 // No columns specified
1359                 debug_report_bug(__FUNCTION__, __LINE__, 'columns is not given. Please fix your XML,tableTemplate=' . $tableTemplate . ',rowTemplate=' . $rowTemplate . ',tableName[0]=' . $tableName[0]);
1360         }
1361
1362         // This is the minimum query, so at least columns and tableName must have entries
1363         $SQL = 'SELECT ';
1364
1365         // Get the sql part back from given array
1366         $SQL .= getSqlPartFromXmlArray($columns);
1367
1368         // Remove last commata and add FROM statement
1369         $SQL .= ' FROM `{?_MYSQL_PREFIX?}_' . $tableName[0] . '`';
1370
1371         // Do we have entries from whereColumns to add?
1372         if (count($whereColumns) > 0) {
1373                 // Then add these as well
1374                 if (count($whereColumns) == 1) {
1375                         // One entry found
1376                         $SQL .= ' WHERE ';
1377
1378                         // Table/alias included?
1379                         if (!empty($whereColumns[0]['table'])) {
1380                                 // Add it as well
1381                                 $SQL .= $whereColumns[0]['table'] . '.';
1382                         } // END - if
1383
1384                         // Add the rest
1385                         $SQL .= '`' . $whereColumns[0]['column'] . '`' . $whereColumns[0]['condition'] . "'" . $whereColumns[0]['look_for'] . "'";
1386                 } else {
1387                         // More than one entry -> Unsupported
1388                         debug_report_bug(__FUNCTION__, __LINE__, 'More than one WHERE statement found. This is currently not supported.');
1389                 }
1390         } // END - if
1391
1392         // Do we have entries from orderByColumns to add?
1393         if (count($orderByColumns) > 0) {
1394                 // Add them as well
1395                 $SQL .= ' ORDER BY ';
1396                 foreach ($orderByColumns as $orderByColumn => $array) {
1397                         // Get keys (table/alias) and values (sorting itself)
1398                         $table   = trim(implode('', array_keys($array)));
1399                         $sorting = trim(implode('', array_keys($array)));
1400
1401                         // table/alias can be omitted
1402                         if (!empty($table)) {
1403                                 // table/alias is given
1404                                 $SQL .= $table . '.';
1405                         } // END - if
1406
1407                         // Add order-by column
1408                         $SQL .= '`' . $orderByColumn . '` ' . $sorting . ',';
1409                 } // END - foreach
1410
1411                 // Remove last column
1412                 $SQL = substr($SQL, 0, -1);
1413         } // END - if
1414
1415         // Now handle all over to the inner function which will execute the listing
1416         doAdminListEntries($SQL, $tableTemplate, $noEntryMessageId, $rowTemplate, $callbackColumns, $extraParameters);
1417 }
1418
1419 // Do the listing of entries
1420 function doAdminListEntries ($SQL, $tableTemplate, $noEntryMessageId, $rowTemplate, $callbackColumns, $extraParameters = array()) {
1421         // Run the SQL query
1422         $result = SQL_QUERY($SQL, __FUNCTION__, __LINE__);
1423
1424         // Do we have some URLs left?
1425         if (!SQL_HASZERONUMS($result)) {
1426                 // List all URLs
1427                 $OUT = '';
1428                 while ($content = SQL_FETCHARRAY($result)) {
1429                         // "Translate" content
1430                         foreach ($callbackColumns as $columnName => $callbackFunction) {
1431                                 // Fill the callback arguments
1432                                 $args = array($content[$columnName]);
1433
1434                                 // Do we have more to add?
1435                                 if (isset($extraParameters[$columnName])) {
1436                                         // Add them as well
1437                                         $args = merge_array($args, $extraParameters[$columnName]);
1438                                 } // END - if
1439
1440                                 // Call the callback-function
1441                                 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'callbackFunction=' . $callbackFunction . ',args=<pre>'.print_r($args, true).'</pre>');
1442                                 // @TODO If we can rewrite the EL sub-system to support more than one parameter, this call_user_func_array() can be avoided
1443                                 $content[$columnName] = call_user_func_array($callbackFunction, $args);
1444                         } // END - foreach
1445
1446                         // Load row template
1447                         $OUT .= loadTemplate(trim($rowTemplate[0]), true, $content);
1448                 } // END - while
1449
1450                 // Load main template
1451                 loadTemplate(trim($tableTemplate[0]), false, $OUT);
1452         } else {
1453                 // No URLs in surfbar
1454                 displayMessage('{--' .$noEntryMessageId[0] . '--}');
1455         }
1456
1457         // Free result
1458         SQL_FREERESULT($result);
1459 }
1460
1461 // Checks proxy settins by fetching check-updates3.php from mxchange.org
1462 function adminTestProxySettings ($settingsArray) {
1463         // Set temporary the new settings
1464         mergeConfig($settingsArray);
1465
1466         // Now get the test URL
1467         $content = sendGetRequest('check-updates3.php');
1468
1469         // Is the first line with "200 OK"?
1470         $valid = isInString('200 OK', $content[0]);
1471
1472         // Return result
1473         return $valid;
1474 }
1475
1476 // Sends out a link to the given email adress so the admin can reset his/her password
1477 function sendAdminPasswordResetLink ($email) {
1478         // Init output
1479         $OUT = '';
1480
1481         // Look up administator login
1482         $result = SQL_QUERY_ESC("SELECT `id`,`login`,`password` FROM `{?_MYSQL_PREFIX?}_admins` WHERE '%s' REGEXP `email` LIMIT 1",
1483                 array($email), __FUNCTION__, __LINE__);
1484
1485         // Is there an account?
1486         if (SQL_HASZERONUMS($result)) {
1487                 // No account found
1488                 return '{--ADMIN_NO_LOGIN_WITH_EMAIL--}';
1489         } // END - if
1490
1491         // Load all data
1492         $content = SQL_FETCHARRAY($result);
1493
1494         // Free result
1495         SQL_FREERESULT($result);
1496
1497         // Generate hash for reset link
1498         $content['hash'] = generateHash(getUrl() . getEncryptSeparator() . $content['id'] . getEncryptSeparator() . $content['login'] . getEncryptSeparator() . $content['password'], substr($content['password'], getSaltLength()));
1499
1500         // Remove some data
1501         unset($content['id']);
1502         unset($content['password']);
1503
1504         // Prepare email
1505         $mailText = loadEmailTemplate('admin_reset_password', $content);
1506
1507         // Send it out
1508         sendEmail($email, '{--ADMIN_RESET_PASSWORD_LINK_SUBJECT--}', $mailText);
1509
1510         // Prepare output
1511         return '{--ADMIN_RESET_PASSWORD_LINK_SENT--}';
1512 }
1513
1514 // Validate hash and login for password reset
1515 function adminResetValidateHashLogin ($hash, $login) {
1516         // By default nothing validates... ;)
1517         $valid = false;
1518
1519         // Then try to find that user
1520         $result = SQL_QUERY_ESC("SELECT `id`,`password`,`email` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
1521                 array($login), __FUNCTION__, __LINE__);
1522
1523         // Is an account here?
1524         if (SQL_NUMROWS($result) == 1) {
1525                 // Load all data
1526                 $content = SQL_FETCHARRAY($result);
1527
1528                 // Generate hash again
1529                 $hashFromData = generateHash(getUrl() . getEncryptSeparator() . $content['id'] . getEncryptSeparator() . $login . getEncryptSeparator() . $content['password'], substr($content['password'], getSaltLength()));
1530
1531                 // Does both match?
1532                 $valid = ($hash == $hashFromData);
1533         } // END - if
1534
1535         // Free result
1536         SQL_FREERESULT($result);
1537
1538         // Return result
1539         return $valid;
1540 }
1541
1542 // Reset the password for the login. Do NOT call this function without calling above function first!
1543 function doResetAdminPassword ($login, $password) {
1544         // Generate hash (we already check for sql_patches in generateHash())
1545         $passHash = generateHash($password);
1546
1547         // Prepare fake POST data
1548         $postData = array(
1549                 'login'    => array(getAdminId($login) => $login),
1550                 'password' => array(getAdminId($login) => $passHash),
1551         );
1552
1553         // Update database
1554         $message = adminsChangeAdminAccount($postData, '', false);
1555
1556         // Run filters
1557         runFilterChain('post_form_reset_pass', array('login' => $login, 'hash' => $passHash, 'message' => $message));
1558
1559         // Return output
1560         return '{--ADMIN_PASSWORD_RESET_DONE--}';
1561 }
1562
1563 // Solves a task by given id number
1564 function adminSolveTask ($id) {
1565         // Update the task data
1566         adminUpdateTaskData($id, 'status', 'SOLVED');
1567 }
1568
1569 // Marks a given task as deleted
1570 function adminDeleteTask ($id) {
1571         // Update the task data
1572         adminUpdateTaskData($id, 'status', 'DELETED');
1573 }
1574
1575 // Function to update task data
1576 function adminUpdateTaskData ($id, $row, $data) {
1577         // Should be admin and valid id
1578         if (!isAdmin()) {
1579                 // Not an admin so redirect better
1580                 debug_report_bug(__FUNCTION__, __LINE__, 'id=' . $id . ',row=' . $row . ',data=' . $data . ' - isAdmin()=false');
1581         } elseif ($id <= 0) {
1582                 // Initiate backtrace
1583                 debug_report_bug(__FUNCTION__, __LINE__, sprintf("id is invalid: %s. row=%s, data=%s",
1584                         $id,
1585                         $row,
1586                         $data
1587                 ));
1588         } // END - if
1589
1590         // Update the task
1591         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_task_system` SET `%s`='%s' WHERE `id`=%s LIMIT 1",
1592                 array(
1593                         $row,
1594                         $data,
1595                         bigintval($id)
1596                 ), __FUNCTION__, __LINE__);
1597 }
1598
1599 // Checks wether if the admin menu has entries
1600 function ifAdminMenuHasEntries ($action) {
1601         return (
1602                 ((
1603                         // Is the entry set?
1604                         isset($GLOBALS['admin_menu_has_entries'][$action])
1605                 ) && (
1606                         // And do we have a menu for this action?
1607                         $GLOBALS['admin_menu_has_entries'][$action] === true
1608                 )) || (
1609                         // Login has always a menu
1610                         $action == 'login'
1611                 )
1612         );
1613 }
1614
1615 // Setter for 'admin_menu_has_entries'
1616 function setAdminMenuHasEntries ($action, $hasEntries) {
1617         $GLOBALS['admin_menu_has_entries'][$action] = (bool) $hasEntries;
1618 }
1619
1620 // Creates a link to the user's admin-profile
1621 function adminCreateUserLink ($userid) {
1622         // Is the userid set correctly?
1623         if (isValidUserId($userid)) {
1624                 // Create a link to that profile
1625                 return '{%url=modules.php?module=admin&amp;what=list_user&amp;userid=' . bigintval($userid) . '%}';
1626         } // END - if
1627
1628         // Return a link to the user list
1629         return '{%url=modules.php?module=admin&amp;what=list_user%}';
1630 }
1631
1632 // Generate a "link" for the given admin id (admin_id)
1633 function generateAdminLink ($adminId) {
1634         // No assigned admin is default
1635         $adminLink = '{--ADMIN_NO_ADMIN_ASSIGNED--}';
1636
1637         // Zero? = Not assigned
1638         if (bigintval($adminId) > 0) {
1639                 // Load admin's login
1640                 $login = getAdminLogin($adminId);
1641
1642                 // Is the login valid?
1643                 if ($login != '***') {
1644                         // Is the extension there?
1645                         if (isExtensionActive('admins')) {
1646                                 // Admin found
1647                                 $adminLink = '<a href="' . generateEmailLink(getAdminEmail($adminId), 'admins') . '" title="{--ADMIN_CONTACT_LINK_TITLE--}">' . $login . '</a>';
1648                         } else {
1649                                 // Extension not found
1650                                 $adminLink = '{%message,ADMIN_TASK_ROW_EXTENSION_NOT_INSTALLED=admins%}';
1651                         }
1652                 } else {
1653                         // Maybe deleted?
1654                         $adminLink = '<div class="bad">{%message,ADMIN_ID_404=' . $adminId . '%}</div>';
1655                 }
1656         } // END - if
1657
1658         // Return result
1659         return $adminLink;
1660 }
1661
1662 // Verifies if the current admin has confirmed to alter expert settings
1663 //
1664 // Return values:
1665 // 'failed'    = Something goes wrong (default)
1666 // 'agreed'    = Has verified and and confirmed it to see them
1667 // 'forbidden' = Has not the proper right to alter them
1668 // 'update'    = Need to update extension 'admins'
1669 // 'ask'       = A form was send to the admin
1670 function doVerifyExpertSettings () {
1671         // Default return status is failed
1672         $return = 'failed';
1673
1674         // Is the extension installed and recent?
1675         if (isExtensionInstalledAndNewer('admins', '0.7.3')) {
1676                 // Okay, load the status
1677                 $expertSettings = getAminsExpertSettings();
1678
1679                 // Is he allowed?
1680                 if ($expertSettings == 'Y') {
1681                         // Okay, does he want to see them?
1682                         if (isAdminsExpertWarningEnabled()) {
1683                                 // Ask for them
1684                                 if (isFormSent()) {
1685                                         // Is the element set, then we need to change the admin
1686                                         if (isPostRequestElementSet('expert_settings')) {
1687                                                 // Get it and prepare final post data array
1688                                                 $postData['login'][getCurrentAdminId()] = getCurrentAdminLogin();
1689                                                 $postData['expert_warning'][getCurrentAdminId()] = 'N';
1690
1691                                                 // Change it in the admin
1692                                                 adminsChangeAdminAccount($postData, 'expert_warning');
1693
1694                                                 // Clear form
1695                                                 unsetPostRequestElement('ok');
1696                                         } // END - if
1697
1698                                         // All fine!
1699                                         $return = 'agreed';
1700                                 } else {
1701                                         // Send form
1702                                         loadTemplate('admin_expert_settings_form');
1703
1704                                         // Asked for it
1705                                         $return = 'ask';
1706                                 }
1707                         } else {
1708                                 // Do not display
1709                                 $return = 'agreed';
1710                         }
1711                 } else {
1712                         // Forbidden
1713                         $return = 'forbidden';
1714                 }
1715         } else {
1716                 // Out-dated extension or not installed
1717                 $return = 'update';
1718         }
1719
1720         // Output message for other status than ask/agreed
1721         if (($return != 'ask') && ($return != 'agreed')) {
1722                 // Output message
1723                 displayMessage('{--ADMIN_EXPERT_SETTINGS_STATUS_' . strtoupper($return) . '--}');
1724         } // END - if
1725
1726         // Return status
1727         return $return;
1728 }
1729
1730 // Generate link to unconfirmed mails for admin
1731 function generateUnconfirmedAdminLink ($id, $unconfirmed, $type = 'bid') {
1732         // Init output
1733         $OUT = $unconfirmed;
1734
1735         // Do we have unconfirmed mails?
1736         if ($unconfirmed > 0) {
1737                 // Add link to list_unconfirmed what-file
1738                 $OUT = '<a href="{%url=modules.php?module=admin&amp;what=list_unconfirmed&amp;' . $type . '=' . $id . '%}">{%pipe,translateComma=' . $unconfirmed . '%}</a>';
1739         } // END - if
1740
1741         // Return it
1742         return $OUT;
1743 }
1744
1745 // Generates a navigation row for listing emails
1746 function addEmailNavigation ($numPages, $offset, $show_form, $colspan, $return=false) {
1747         // Don't do anything if $numPages is 1
1748         if ($numPages == 1) {
1749                 // Abort here with empty content
1750                 return '';
1751         } // END - if
1752
1753         $TOP = '';
1754         if ($show_form === false) {
1755                 $TOP = ' top';
1756         } // END - if
1757
1758         $NAV = '';
1759         for ($page = 1; $page <= $numPages; $page++) {
1760                 // Is the page currently selected or shall we generate a link to it?
1761                 if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
1762                         // Is currently selected, so only highlight it
1763                         $NAV .= '<strong>-';
1764                 } else {
1765                         // Open anchor tag and add base URL
1766                         $NAV .= '<a href="{%url=modules.php?module=admin&amp;what=' . getWhat() . '&amp;page=' . $page . '&amp;offset=' . $offset;
1767
1768                         // Add userid when we shall show all mails from a single member
1769                         if ((isGetRequestElementSet('userid')) && (isValidUserId(getRequestElement('userid')))) $NAV .= '&amp;userid=' . bigintval(getRequestElement('userid'));
1770
1771                         // Close open anchor tag
1772                         $NAV .= '%}">';
1773                 }
1774                 $NAV .= $page;
1775                 if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
1776                         // Is currently selected, so only highlight it
1777                         $NAV .= '-</strong>';
1778                 } else {
1779                         // Close anchor tag
1780                         $NAV .= '</a>';
1781                 }
1782
1783                 // Add separator if we have not yet reached total pages
1784                 if ($page < $numPages) {
1785                         // Add it
1786                         $NAV .= '|';
1787                 } // END - if
1788         } // END - for
1789
1790         // Define constants only once
1791         $content['nav']  = $NAV;
1792         $content['span'] = $colspan;
1793         $content['top']  = $TOP;
1794
1795         // Load navigation template
1796         $OUT = loadTemplate('admin_email_nav_row', true, $content);
1797
1798         if ($return === true) {
1799                 // Return generated HTML-Code
1800                 return $OUT;
1801         } else {
1802                 // Output HTML-Code
1803                 outputHtml($OUT);
1804         }
1805 }
1806
1807 // Process menu editing form
1808 function adminProcessMenuEditForm ($type, $subMenu) {
1809         // An action is done...
1810         foreach (postRequestElement('sel') as $sel => $menu) {
1811                 $AND = "(`what` = '' OR `what` IS NULL)";
1812
1813                 $sel = bigintval($sel);
1814
1815                 if (!empty($subMenu)) {
1816                         $AND = "`action`='" . $subMenu . "'";
1817                 } // END - if
1818
1819                 switch (postRequestElement('ok')) {
1820                         case 'edit': // Edit menu
1821                                 // Shall we update a menu or sub menu?
1822                                 if (!isGetRequestElementSet('sub')) {
1823                                         // Update with 'what'=null
1824                                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET `title`='%s',`action`='%s',`what`=NULL WHERE ".$AND." AND `id`=%s LIMIT 1",
1825                                                 array(
1826                                                         $type,
1827                                                         $menu,
1828                                                         postRequestElement('sel_action', $sel),
1829                                                         $sel
1830                                                 ), __FUNCTION__, __LINE__);
1831                                 } else {
1832                                         // Update with selected 'what'
1833                                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET `title`='%s',`action`='%s',`what`='%s' WHERE ".$AND." AND `id`=%s LIMIT 1",
1834                                                 array(
1835                                                         $type,
1836                                                         $menu,
1837                                                         postRequestElement('sel_action', $sel),
1838                                                         postRequestElement('sel_what', $sel),
1839                                                         $sel
1840                                                 ), __FUNCTION__, __LINE__);
1841                                 }
1842                                 break;
1843
1844                         case 'delete': // Delete menu
1845                                 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE ".$AND." AND `id`=%s LIMIT 1",
1846                                         array(
1847                                                 $type,
1848                                                 $sel
1849                                         ), __FUNCTION__, __LINE__);
1850                                 break;
1851
1852                         case 'status': // Change status of menus
1853                                 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET `visible`='%s',`locked`='%s' WHERE ".$AND." AND `id`=%s LIMIT 1",
1854                                         array(
1855                                                 $type,
1856                                                 postRequestElement('visible', $sel),
1857                                                 postRequestElement('locked', $sel),
1858                                                 $sel
1859                                         ), __FUNCTION__, __LINE__);
1860                                 break;
1861
1862                         default: // Unexpected action
1863                                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unsupported action %s detected.", postRequestElement('ok')));
1864                                 displayMessage('{%message,ADMIN_UNKNOWN_OKAY=' . postRequestElement('ok') . '%}');
1865                                 break;
1866                 } // END - switch
1867         } // END - foreach
1868
1869         // Load template
1870         displayMessage('{--SETTINGS_SAVED--}');
1871 }
1872
1873 // Handle weightning
1874 function doAdminProcessMenuWeightning ($type, $AND) {
1875         // Are there all required (generalized) GET parameter?
1876         if ((isGetRequestElementSet('act')) && (isGetRequestElementSet('tid')) && (isGetRequestElementSet('fid'))) {
1877                 // Init variables
1878                 $tid = ''; $fid = '';
1879
1880                 // Get ids
1881                 if (isGetRequestElementSet('w')) {
1882                         // Sub menus selected
1883                         $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `action`='%s' AND `sort`=%s LIMIT 1",
1884                                 array(
1885                                         $type,
1886                                         getRequestElement('act'),
1887                                         bigintval(getRequestElement('tid'))
1888                                 ), __FUNCTION__, __LINE__);
1889                         list($tid) = SQL_FETCHROW($result);
1890                         SQL_FREERESULT($result);
1891                         $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `action`='%s' AND `sort`=%s LIMIT 1",
1892                                 array(
1893                                         $type,
1894                                         getRequestElement('act'),
1895                                         bigintval(getRequestElement('fid'))
1896                                 ), __FUNCTION__, __LINE__);
1897                         list($fid) = SQL_FETCHROW($result);
1898                         SQL_FREERESULT($result);
1899                 } else {
1900                         // Main menu selected
1901                         $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE (`what`='' OR `what` IS NULL) AND `sort`=%s LIMIT 1",
1902                                 array(
1903                                         $type,
1904                                         bigintval(getRequestElement('tid'))
1905                                 ), __FUNCTION__, __LINE__);
1906                         list($tid) = SQL_FETCHROW($result);
1907                         SQL_FREERESULT($result);
1908                         $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE (`what`='' OR `what` IS NULL) AND `sort`=%s LIMIT 1",
1909                                 array(
1910                                         $type,
1911                                         bigintval(getRequestElement('fid'))
1912                                 ), __FUNCTION__, __LINE__);
1913                         list($fid) = SQL_FETCHROW($result);
1914                         SQL_FREERESULT($result);
1915                 }
1916
1917                 if ((!empty($tid)) && (!empty($fid))) {
1918                         // Sort menu
1919                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET `sort`=%s WHERE ".$AND." AND `id`=%s LIMIT 1",
1920                                 array(
1921                                         $type,
1922                                         bigintval(getRequestElement('tid')),
1923                                         bigintval($fid)
1924                                 ), __FUNCTION__, __LINE__);
1925                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET `sort`=%s WHERE ".$AND." AND `id`=%s LIMIT 1",
1926                                 array(
1927                                         $type,
1928                                         bigintval(getRequestElement('fid')),
1929                                         bigintval($tid)
1930                                 ), __FUNCTION__, __LINE__);
1931                 } // END - if
1932         } // END - if
1933 }
1934
1935 // [EOF]
1936 ?>