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