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