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