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