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