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