Generalized more 'builder' functions, added XML template for editing user sub ids
[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         // Is there 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         // Is there 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         // Are there 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         // Are there entries?
354         if (ifAdminMenuHasEntries($mainContent['main_action'])) {
355                 // Sub menu has been called
356                 $SUB = true;
357
358                 // Are there 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                 // Is there 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         // Call inner (general) function
880         doGenericListBuilder('admin', $listType, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId);
881 }
882
883 // Change status of "build" list
884 function adminBuilderStatusHandler ($mode, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray, $rawUserId = array('userid'), $cacheFiles = array()) {
885         // $tableName must be an array
886         if ((!is_array($tableName)) || (count($tableName) != 1)) {
887                 // No tableName specified
888                 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
889         } elseif (!is_array($idColumn)) {
890                 // $idColumn is no array
891                 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
892         } elseif ((!is_array($userIdColumn)) || (count($userIdColumn) != 1)) {
893                 // $tableName is no array
894                 reportBug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array: userIdColumn=' . $userIdColumn);
895         } // END - if
896
897         // "Walk" through all entries
898         foreach (postRequestElement($idColumn[0]) as $id => $sel) {
899                 // Construct SQL query
900                 $sql = sprintf("UPDATE `{?_MYSQL_PREFIX?}_%s` SET", SQL_ESCAPE($tableName[0]));
901
902                 // Load data of entry
903                 $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`=%s LIMIT 1",
904                         array(
905                                 $tableName[0],
906                                 $idColumn[0],
907                                 $id
908                         ), __FUNCTION__, __LINE__);
909
910                 // Fetch the data
911                 $content = SQL_FETCHARRAY($result);
912
913                 // Free the result
914                 SQL_FREERESULT($result);
915
916                 // Add all status entries (e.g. status column last_updated or so)
917                 $newStatus = 'UNKNOWN';
918                 $oldStatus = 'UNKNOWN';
919                 $statusColumn = 'unknown';
920                 foreach ($statusArray as $column => $statusInfo) {
921                         // Does the entry exist?
922                         if ((isset($content[$column])) && (isset($statusInfo[$content[$column]]))) {
923                                 // Add these entries for update
924                                 $sql .= sprintf(" `%s`='%s',", SQL_ESCAPE($column), SQL_ESCAPE($statusInfo[$content[$column]]));
925
926                                 // Remember status
927                                 if ($statusColumn == 'unknown') {
928                                         // Always (!!!) change status column first!
929                                         $oldStatus = $content[$column];
930                                         $newStatus = $statusInfo[$oldStatus];
931                                         $statusColumn = $column;
932                                 } // END - if
933                         } elseif (isset($content[$column])) {
934                                 // Unfinished!
935                                 reportBug(__FUNCTION__, __LINE__, ':UNFINISHED: id=' . $id . ',column=' . $column . '[' . gettype($statusInfo) . '] = ' . $content[$column]);
936                         }
937                 } // END - foreach
938
939                 // Add other columns as well
940                 foreach (postRequestArray() as $key => $entries) {
941                         // Debug message
942                         logDebugMessage(__FUNCTION__, __LINE__, 'Found entry: ' . $key);
943
944                         // Skip id, raw userid and 'do_$mode'
945                         if (!in_array($key, array($idColumn[0], $rawUserId[0], ('do_' . $mode)))) {
946                                 // Are there brackets () at the end?
947                                 if (substr($entries[$id], -2, 2) == '()') {
948                                         // Direct SQL command found
949                                         $sql .= sprintf(" `%s`=%s,", SQL_ESCAPE($key), SQL_ESCAPE($entries[$id]));
950                                 } else {
951                                         // Add regular entry
952                                         $sql .= sprintf(" `%s`='%s',", SQL_ESCAPE($key), SQL_ESCAPE($entries[$id]));
953
954                                         // Add entry
955                                         $content[$key] = $entries[$id];
956                                 }
957                         } else {
958                                 // Skipped entry
959                                 logDebugMessage(__FUNCTION__, __LINE__, 'Skipped: ' . $key);
960                         }
961                 } // END - foreach
962
963                 // Finish SQL statement
964                 $sql = substr($sql, 0, -1) . sprintf(" WHERE `%s`=%s AND `%s`='%s' LIMIT 1",
965                         $idColumn[0],
966                         bigintval($id),
967                         $statusColumn,
968                         $oldStatus
969                 );
970
971                 // Run the SQL
972                 SQL_QUERY($sql, __FUNCTION__, __LINE__);
973
974                 // Send "build mails" out
975                 sendAdminBuildMails($mode, $tableName, $content, $id, $statusInfo[$content[$column]], $userIdColumn);
976         } // END - foreach
977 }
978
979 // Delete rows by given id numbers
980 function adminDeleteEntriesConfirm ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $deleteNow = array(false), $idColumn = array('id'), $userIdColumn = array('userid'), $rawUserId = array('userid'), $cacheFiles = array()) {
981         // $tableName must be an array
982         if ((!is_array($tableName)) || (count($tableName) != 1)) {
983                 // No tableName specified
984                 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
985         } elseif (!is_array($idColumn)) {
986                 // $idColumn is no array
987                 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
988         } elseif (!is_array($userIdColumn)) {
989                 // $userIdColumn is no array
990                 reportBug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array: userIdColumn=' . $userIdColumn);
991         } elseif (!is_array($deleteNow)) {
992                 // $deleteNow is no array
993                 reportBug(__FUNCTION__, __LINE__, 'deleteNow[]=' . gettype($deleteNow) . '!=array: userIdColumn=' . $userIdColumn);
994         } // END - if
995
996         // Shall we delete here or list for deletion?
997         if ($deleteNow[0] === true) {
998                 // The base SQL command:
999                 $sql = "DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s` IN (%s)";
1000
1001                 // Delete them all
1002                 $idList = '';
1003                 foreach (postRequestElement($idColumn[0]) as $id => $sel) {
1004                         // Is there a userid?
1005                         if (isPostRequestElementSet($rawUserId[0], $id)) {
1006                                 // Load all data from that id
1007                                 $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`=%s LIMIT 1",
1008                                         array(
1009                                                 $tableName[0],
1010                                                 $idColumn[0],
1011                                                 $id
1012                                         ), __FUNCTION__, __LINE__);
1013
1014                                 // Fetch the data
1015                                 $content = SQL_FETCHARRAY($result);
1016
1017                                 // Free the result
1018                                 SQL_FREERESULT($result);
1019
1020                                 // Send "build mails" out
1021                                 sendAdminBuildMails('delete', $tableName, $content, $id, '', $userIdColumn);
1022                         } // END - if
1023
1024                         // Add id number
1025                         $idList .= $id . ',';
1026                 } // END - foreach
1027
1028                 // Run the query
1029                 SQL_QUERY_ESC($sql, array($tableName[0], $idColumn[0], substr($idList, 0, -1)), __FUNCTION__, __LINE__);
1030
1031                 // Was this fine?
1032                 if (SQL_AFFECTEDROWS() == countPostSelection($idColumn[0])) {
1033                         // All deleted
1034                         displayMessage('{--ADMIN_ALL_ENTRIES_REMOVED--}');
1035                 } else {
1036                         // Some are still there :(
1037                         displayMessage(sprintf(getMessage('ADMIN_SOME_ENTRIES_NOT_DELETED'), SQL_AFFECTEDROWS(), countPostSelection($idColumn[0])));
1038                 }
1039         } else {
1040                 // List for deletion confirmation
1041                 adminListBuilder('delete', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1042         }
1043 }
1044
1045 // Edit rows by given id numbers
1046 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()) {
1047         // $tableName must be an array
1048         if ((!is_array($tableName)) || (count($tableName) != 1)) {
1049                 // No tableName specified
1050                 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
1051         } elseif (!is_array($idColumn)) {
1052                 // $idColumn is no array
1053                 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
1054         } elseif (!is_array($userIdColumn)) {
1055                 // $userIdColumn is no array
1056                 reportBug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array: userIdColumn=' . $userIdColumn);
1057         } elseif (!is_array($editNow)) {
1058                 // $editNow is no array
1059                 reportBug(__FUNCTION__, __LINE__, 'editNow[]=' . gettype($editNow) . '!=array: userIdColumn=' . $userIdColumn);
1060         } // END - if
1061
1062         // Shall we change here or list for editing?
1063         if ($editNow[0] === true) {
1064                 // Call generic change method
1065                 $affected = doGenericEditEntriesConfirm($tableName, $columns, $filterFunctions, $extraValues, $timeColumns, $editNow, $idColumn, $userIdColumn, $rawUserId, $cacheFiles);
1066
1067                 // Was this fine?
1068                 if ($affected == countPostSelection($idColumn[0])) {
1069                         // All deleted
1070                         displayMessage('{--ADMIN_ALL_ENTRIES_EDITED--}');
1071                 } else {
1072                         // Some are still there :(
1073                         displayMessage(sprintf(getMessage('ADMIN_SOME_ENTRIES_NOT_EDITED'), $affected, countPostSelection($idColumn[0])));
1074                 }
1075         } else {
1076                 // List for editing
1077                 adminListBuilder('edit', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1078         }
1079 }
1080
1081 // Un-/lock rows by given id numbers
1082 function adminLockEntriesConfirm ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $statusArray = array(), $lockNow = array(false), $idColumn = array('id'), $userIdColumn = array('userid')) {
1083         // $tableName must be an array
1084         if ((!is_array($tableName)) || (count($tableName) != 1)) {
1085                 // No tableName specified
1086                 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
1087         } elseif (!is_array($idColumn)) {
1088                 // $idColumn is no array
1089                 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
1090         } elseif (!is_array($lockNow)) {
1091                 // $lockNow is no array
1092                 reportBug(__FUNCTION__, __LINE__, 'lockNow[]=' . gettype($lockNow) . '!=array: userIdColumn=' . $userIdColumn);
1093         } // END - if
1094
1095         // Shall we un-/lock here or list for locking?
1096         if ($lockNow[0] === true) {
1097                 // Un-/lock entries
1098                 adminBuilderStatusHandler('lock', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray);
1099         } else {
1100                 // List for editing
1101                 adminListBuilder('lock', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1102         }
1103 }
1104
1105 // Undelete rows by given id numbers
1106 function adminUndeleteEntriesConfirm ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $statusArray = array(), $undeleteNow = array(false), $idColumn = array('id'), $userIdColumn = array('userid')) {
1107         // $tableName must be an array
1108         if ((!is_array($tableName)) || (count($tableName) != 1)) {
1109                 // No tableName specified
1110                 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
1111         } elseif (!is_array($idColumn)) {
1112                 // $idColumn is no array
1113                 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
1114         } elseif (!is_array($undeleteNow)) {
1115                 // $undeleteNow is no array
1116                 reportBug(__FUNCTION__, __LINE__, 'undeleteNow[]=' . gettype($undeleteNow) . '!=array: userIdColumn=' . $userIdColumn);
1117         } // END - if
1118
1119         // Shall we un-/lock here or list for locking?
1120         if ($undeleteNow[0] === true) {
1121                 // Undelete entries
1122                 adminBuilderStatusHandler('undelete', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray);
1123         } else {
1124                 // List for editing
1125                 adminListBuilder('undelete', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1126         }
1127 }
1128
1129 // Adds a given entry to the database
1130 function adminAddEntries ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $timeColumns = array(), $columnIndex = NULL) {
1131         // Call inner function
1132         doGenericAddEntries($tableName, $columns, $filterFunctions, $extraValues, $timeColumns, $columnIndex);
1133
1134         // Entry has been added?
1135         if ((!SQL_HASZEROAFFECTED()) && ($GLOBALS['__XML_PARSE_RESULT'] === true)) {
1136                 // Display success message
1137                 displayMessage('{--ADMIN_ENTRY_ADDED--}');
1138         } else {
1139                 // Display failed message
1140                 displayMessage('{--ADMIN_ENTRY_NOT_ADDED--}');
1141         }
1142 }
1143
1144 // Checks proxy settins by fetching check-updates3.php from mxchange.org
1145 function adminTestProxySettings ($settingsArray) {
1146         // Set temporary the new settings
1147         mergeConfig($settingsArray);
1148
1149         // Now get the test URL
1150         $content = sendGetRequest('check-updates3.php');
1151
1152         // Is the first line with "200 OK"?
1153         $valid = isInString('200 OK', $content[0]);
1154
1155         // Return result
1156         return $valid;
1157 }
1158
1159 // Sends out a link to the given email adress so the admin can reset his/her password
1160 function sendAdminPasswordResetLink ($email) {
1161         // Init output
1162         $OUT = '';
1163
1164         // Look up administator login
1165         $result = SQL_QUERY_ESC("SELECT `id`,`login`,`password` FROM `{?_MYSQL_PREFIX?}_admins` WHERE '%s' REGEXP `email` LIMIT 1",
1166                 array($email), __FUNCTION__, __LINE__);
1167
1168         // Is there an account?
1169         if (SQL_HASZERONUMS($result)) {
1170                 // No account found
1171                 return '{--ADMIN_NO_LOGIN_WITH_EMAIL--}';
1172         } // END - if
1173
1174         // Load all data
1175         $content = SQL_FETCHARRAY($result);
1176
1177         // Free result
1178         SQL_FREERESULT($result);
1179
1180         // Generate hash for reset link
1181         $content['hash'] = generateHash(getUrl() . getEncryptSeparator() . $content['id'] . getEncryptSeparator() . $content['login'] . getEncryptSeparator() . $content['password'], substr($content['password'], getSaltLength()));
1182
1183         // Remove some data
1184         unset($content['id']);
1185         unset($content['password']);
1186
1187         // Prepare email
1188         $mailText = loadEmailTemplate('admin_reset_password', $content);
1189
1190         // Send it out
1191         sendEmail($email, '{--ADMIN_RESET_PASSWORD_LINK_SUBJECT--}', $mailText);
1192
1193         // Prepare output
1194         return '{--ADMIN_RESET_PASSWORD_LINK_SENT--}';
1195 }
1196
1197 // Validate hash and login for password reset
1198 function adminResetValidateHashLogin ($hash, $login) {
1199         // By default nothing validates... ;)
1200         $valid = false;
1201
1202         // Then try to find that user
1203         $result = SQL_QUERY_ESC("SELECT `id`,`password`,`email` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
1204                 array($login), __FUNCTION__, __LINE__);
1205
1206         // Is an account here?
1207         if (SQL_NUMROWS($result) == 1) {
1208                 // Load all data
1209                 $content = SQL_FETCHARRAY($result);
1210
1211                 // Generate hash again
1212                 $hashFromData = generateHash(getUrl() . getEncryptSeparator() . $content['id'] . getEncryptSeparator() . $login . getEncryptSeparator() . $content['password'], substr($content['password'], getSaltLength()));
1213
1214                 // Does both match?
1215                 $valid = ($hash == $hashFromData);
1216         } // END - if
1217
1218         // Free result
1219         SQL_FREERESULT($result);
1220
1221         // Return result
1222         return $valid;
1223 }
1224
1225 // Reset the password for the login. Do NOT call this function without calling above function first!
1226 function doResetAdminPassword ($login, $password) {
1227         // Generate hash (we already check for sql_patches in generateHash())
1228         $passHash = generateHash($password);
1229
1230         // Prepare fake POST data
1231         $postData = array(
1232                 'login'    => array(getAdminId($login) => $login),
1233                 'password' => array(getAdminId($login) => $passHash),
1234         );
1235
1236         // Update database
1237         $message = adminsChangeAdminAccount($postData, '', false);
1238
1239         // Run filters
1240         runFilterChain('post_form_reset_pass', array('login' => $login, 'hash' => $passHash, 'message' => $message));
1241
1242         // Return output
1243         return '{--ADMIN_PASSWORD_RESET_DONE--}';
1244 }
1245
1246 // Solves a task by given id number
1247 function adminSolveTask ($id) {
1248         // Update the task data
1249         adminUpdateTaskData($id, 'status', 'SOLVED');
1250 }
1251
1252 // Marks a given task as deleted
1253 function adminDeleteTask ($id) {
1254         // Update the task data
1255         adminUpdateTaskData($id, 'status', 'DELETED');
1256 }
1257
1258 // Function to update task data
1259 function adminUpdateTaskData ($id, $row, $data) {
1260         // Should be admin and valid id
1261         if (!isAdmin()) {
1262                 // Not an admin so redirect better
1263                 reportBug(__FUNCTION__, __LINE__, 'id=' . $id . ',row=' . $row . ',data=' . $data . ' - isAdmin()=false');
1264         } elseif ($id <= 0) {
1265                 // Initiate backtrace
1266                 reportBug(__FUNCTION__, __LINE__, sprintf("id is invalid: %s. row=%s, data=%s",
1267                         $id,
1268                         $row,
1269                         $data
1270                 ));
1271         } // END - if
1272
1273         // Update the task
1274         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_task_system` SET `%s`='%s' WHERE `id`=%s LIMIT 1",
1275                 array(
1276                         $row,
1277                         $data,
1278                         bigintval($id)
1279                 ), __FUNCTION__, __LINE__);
1280 }
1281
1282 // Checks whether if the admin menu has entries
1283 function ifAdminMenuHasEntries ($action) {
1284         return (
1285                 ((
1286                         // Is the entry set?
1287                         isset($GLOBALS['admin_menu_has_entries'][$action])
1288                 ) && (
1289                         // And do we have a menu for this action?
1290                         $GLOBALS['admin_menu_has_entries'][$action] === true
1291                 )) || (
1292                         // Login has always a menu
1293                         $action == 'login'
1294                 )
1295         );
1296 }
1297
1298 // Setter for 'admin_menu_has_entries'
1299 function setAdminMenuHasEntries ($action, $hasEntries) {
1300         $GLOBALS['admin_menu_has_entries'][$action] = (bool) $hasEntries;
1301 }
1302
1303 // Creates a link to the user's admin-profile
1304 function adminCreateUserLink ($userid) {
1305         // Is the userid set correctly?
1306         if (isValidUserId($userid)) {
1307                 // Create a link to that profile
1308                 return '{%url=modules.php?module=admin&amp;what=list_user&amp;userid=' . bigintval($userid) . '%}';
1309         } // END - if
1310
1311         // Return a link to the user list
1312         return '{%url=modules.php?module=admin&amp;what=list_user%}';
1313 }
1314
1315 // Generate a "link" for the given admin id (admin_id)
1316 function generateAdminLink ($adminId) {
1317         // No assigned admin is default
1318         $adminLink = '{--ADMIN_NO_ADMIN_ASSIGNED--}';
1319
1320         // Zero? = Not assigned
1321         if (isValidUserId($adminId)) {
1322                 // Load admin's login
1323                 $login = getAdminLogin($adminId);
1324
1325                 // Is the login valid?
1326                 if ($login != '***') {
1327                         // Is the extension there?
1328                         if (isExtensionActive('admins')) {
1329                                 // Admin found
1330                                 $adminLink = '<a href="' . generateEmailLink(getAdminEmail($adminId), 'admins') . '" title="{--ADMIN_CONTACT_LINK_TITLE--}">' . $login . '</a>';
1331                         } else {
1332                                 // Extension not found
1333                                 $adminLink = '{%message,ADMIN_TASK_ROW_EXTENSION_NOT_INSTALLED=admins%}';
1334                         }
1335                 } else {
1336                         // Maybe deleted?
1337                         $adminLink = '<div class="bad">{%message,ADMIN_ID_404=' . $adminId . '%}</div>';
1338                 }
1339         } // END - if
1340
1341         // Return result
1342         return $adminLink;
1343 }
1344
1345 // Verifies if the current admin has confirmed to alter expert settings
1346 //
1347 // Return values:
1348 // 'failed'    = Something goes wrong (default)
1349 // 'agreed'    = Has verified and and confirmed it to see them
1350 // 'forbidden' = Has not the proper right to alter them
1351 // 'update'    = Need to update extension 'admins'
1352 // 'ask'       = A form was send to the admin
1353 function doVerifyExpertSettings () {
1354         // Default return status is failed
1355         $return = 'failed';
1356
1357         // Is the extension installed and recent?
1358         if (isExtensionInstalledAndNewer('admins', '0.7.3')) {
1359                 // Okay, load the status
1360                 $expertSettings = getAminsExpertSettings();
1361
1362                 // Is he allowed?
1363                 if ($expertSettings == 'Y') {
1364                         // Okay, does he want to see them?
1365                         if (isAdminsExpertWarningEnabled()) {
1366                                 // Ask for them
1367                                 if (isFormSent()) {
1368                                         // Is the element set, then we need to change the admin
1369                                         if (isPostRequestElementSet('expert_settings')) {
1370                                                 // Get it and prepare final post data array
1371                                                 $postData['login'][getCurrentAdminId()] = getCurrentAdminLogin();
1372                                                 $postData['expert_warning'][getCurrentAdminId()] = 'N';
1373
1374                                                 // Change it in the admin
1375                                                 adminsChangeAdminAccount($postData, 'expert_warning');
1376
1377                                                 // Clear form
1378                                                 unsetPostRequestElement('ok');
1379                                         } // END - if
1380
1381                                         // All fine!
1382                                         $return = 'agreed';
1383                                 } else {
1384                                         // Send form
1385                                         loadTemplate('admin_expert_settings_form');
1386
1387                                         // Asked for it
1388                                         $return = 'ask';
1389                                 }
1390                         } else {
1391                                 // Do not display
1392                                 $return = 'agreed';
1393                         }
1394                 } else {
1395                         // Forbidden
1396                         $return = 'forbidden';
1397                 }
1398         } else {
1399                 // Out-dated extension or not installed
1400                 $return = 'update';
1401         }
1402
1403         // Output message for other status than ask/agreed
1404         if (($return != 'ask') && ($return != 'agreed')) {
1405                 // Output message
1406                 displayMessage('{--ADMIN_EXPERT_SETTINGS_STATUS_' . strtoupper($return) . '--}');
1407         } // END - if
1408
1409         // Return status
1410         return $return;
1411 }
1412
1413 // Generate link to unconfirmed mails for admin
1414 function generateUnconfirmedAdminLink ($id, $unconfirmed, $type = 'bid') {
1415         // Init output
1416         $OUT = $unconfirmed;
1417
1418         // Is there unconfirmed mails?
1419         if ($unconfirmed > 0) {
1420                 // Add link to list_unconfirmed what-file
1421                 $OUT = '<a href="{%url=modules.php?module=admin&amp;what=list_unconfirmed&amp;' . $type . '=' . $id . '%}">{%pipe,translateComma=' . $unconfirmed . '%}</a>';
1422         } // END - if
1423
1424         // Return it
1425         return $OUT;
1426 }
1427
1428 // Generates a navigation row for listing emails
1429 function addEmailNavigation ($numPages, $offset, $show_form, $colspan, $return=false) {
1430         // Don't do anything if $numPages is 1
1431         if ($numPages == 1) {
1432                 // Abort here with empty content
1433                 return '';
1434         } // END - if
1435
1436         $TOP = '';
1437         if ($show_form === false) {
1438                 $TOP = ' top';
1439         } // END - if
1440
1441         $NAV = '';
1442         for ($page = 1; $page <= $numPages; $page++) {
1443                 // Is the page currently selected or shall we generate a link to it?
1444                 if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
1445                         // Is currently selected, so only highlight it
1446                         $NAV .= '<strong>-';
1447                 } else {
1448                         // Open anchor tag and add base URL
1449                         $NAV .= '<a href="{%url=modules.php?module=admin&amp;what=' . getWhat() . '&amp;page=' . $page . '&amp;offset=' . $offset;
1450
1451                         // Add userid when we shall show all mails from a single member
1452                         if ((isGetRequestElementSet('userid')) && (isValidUserId(getRequestElement('userid')))) $NAV .= '&amp;userid=' . bigintval(getRequestElement('userid'));
1453
1454                         // Close open anchor tag
1455                         $NAV .= '%}">';
1456                 }
1457                 $NAV .= $page;
1458                 if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
1459                         // Is currently selected, so only highlight it
1460                         $NAV .= '-</strong>';
1461                 } else {
1462                         // Close anchor tag
1463                         $NAV .= '</a>';
1464                 }
1465
1466                 // Add separator if we have not yet reached total pages
1467                 if ($page < $numPages) {
1468                         // Add it
1469                         $NAV .= '|';
1470                 } // END - if
1471         } // END - for
1472
1473         // Define constants only once
1474         $content['nav']  = $NAV;
1475         $content['span'] = $colspan;
1476         $content['top']  = $TOP;
1477
1478         // Load navigation template
1479         $OUT = loadTemplate('admin_email_nav_row', true, $content);
1480
1481         if ($return === true) {
1482                 // Return generated HTML-Code
1483                 return $OUT;
1484         } else {
1485                 // Output HTML-Code
1486                 outputHtml($OUT);
1487         }
1488 }
1489
1490 // Process menu editing form
1491 function adminProcessMenuEditForm ($type, $subMenu) {
1492         // An action is done...
1493         foreach (postRequestElement('sel') as $sel => $menu) {
1494                 $AND = "(`what` = '' OR `what` IS NULL)";
1495
1496                 $sel = bigintval($sel);
1497
1498                 if (!empty($subMenu)) {
1499                         $AND = "`action`='" . $subMenu . "'";
1500                 } // END - if
1501
1502                 switch (postRequestElement('ok')) {
1503                         case 'edit': // Edit menu
1504                                 // Shall we update a menu or sub menu?
1505                                 if (!isGetRequestElementSet('sub')) {
1506                                         // Update with 'what'=null
1507                                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET `title`='%s',`action`='%s',`what`=NULL WHERE ".$AND." AND `id`=%s LIMIT 1",
1508                                                 array(
1509                                                         $type,
1510                                                         $menu,
1511                                                         postRequestElement('sel_action', $sel),
1512                                                         $sel
1513                                                 ), __FUNCTION__, __LINE__);
1514                                 } else {
1515                                         // Update with selected 'what'
1516                                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET `title`='%s',`action`='%s',`what`='%s' WHERE ".$AND." AND `id`=%s LIMIT 1",
1517                                                 array(
1518                                                         $type,
1519                                                         $menu,
1520                                                         postRequestElement('sel_action', $sel),
1521                                                         postRequestElement('sel_what', $sel),
1522                                                         $sel
1523                                                 ), __FUNCTION__, __LINE__);
1524                                 }
1525                                 break;
1526
1527                         case 'delete': // Delete menu
1528                                 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE ".$AND." AND `id`=%s LIMIT 1",
1529                                         array(
1530                                                 $type,
1531                                                 $sel
1532                                         ), __FUNCTION__, __LINE__);
1533                                 break;
1534
1535                         case 'status': // Change status of menus
1536                                 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET `visible`='%s',`locked`='%s' WHERE ".$AND." AND `id`=%s LIMIT 1",
1537                                         array(
1538                                                 $type,
1539                                                 postRequestElement('visible', $sel),
1540                                                 postRequestElement('locked', $sel),
1541                                                 $sel
1542                                         ), __FUNCTION__, __LINE__);
1543                                 break;
1544
1545                         default: // Unexpected action
1546                                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unsupported action %s detected.", postRequestElement('ok')));
1547                                 displayMessage('{%message,ADMIN_UNKNOWN_OKAY=' . postRequestElement('ok') . '%}');
1548                                 break;
1549                 } // END - switch
1550         } // END - foreach
1551
1552         // Load template
1553         displayMessage('{--SETTINGS_SAVED--}');
1554 }
1555
1556 // Handle weightning
1557 function doAdminProcessMenuWeightning ($type, $AND) {
1558         // Are there all required (generalized) GET parameter?
1559         if ((isGetRequestElementSet('act')) && (isGetRequestElementSet('tid')) && (isGetRequestElementSet('fid'))) {
1560                 // Init variables
1561                 $tid = ''; $fid = '';
1562
1563                 // Get ids
1564                 if (isGetRequestElementSet('w')) {
1565                         // Sub menus selected
1566                         $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `action`='%s' AND `sort`=%s LIMIT 1",
1567                                 array(
1568                                         $type,
1569                                         getRequestElement('act'),
1570                                         bigintval(getRequestElement('tid'))
1571                                 ), __FUNCTION__, __LINE__);
1572                         list($tid) = SQL_FETCHROW($result);
1573                         SQL_FREERESULT($result);
1574                         $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `action`='%s' AND `sort`=%s LIMIT 1",
1575                                 array(
1576                                         $type,
1577                                         getRequestElement('act'),
1578                                         bigintval(getRequestElement('fid'))
1579                                 ), __FUNCTION__, __LINE__);
1580                         list($fid) = SQL_FETCHROW($result);
1581                         SQL_FREERESULT($result);
1582                 } else {
1583                         // Main menu selected
1584                         $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE (`what`='' OR `what` IS NULL) AND `sort`=%s LIMIT 1",
1585                                 array(
1586                                         $type,
1587                                         bigintval(getRequestElement('tid'))
1588                                 ), __FUNCTION__, __LINE__);
1589                         list($tid) = SQL_FETCHROW($result);
1590                         SQL_FREERESULT($result);
1591                         $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE (`what`='' OR `what` IS NULL) AND `sort`=%s LIMIT 1",
1592                                 array(
1593                                         $type,
1594                                         bigintval(getRequestElement('fid'))
1595                                 ), __FUNCTION__, __LINE__);
1596                         list($fid) = SQL_FETCHROW($result);
1597                         SQL_FREERESULT($result);
1598                 }
1599
1600                 if ((!empty($tid)) && (!empty($fid))) {
1601                         // Sort menu
1602                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET `sort`=%s WHERE ".$AND." AND `id`=%s LIMIT 1",
1603                                 array(
1604                                         $type,
1605                                         bigintval(getRequestElement('tid')),
1606                                         bigintval($fid)
1607                                 ), __FUNCTION__, __LINE__);
1608                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET `sort`=%s WHERE ".$AND." AND `id`=%s LIMIT 1",
1609                                 array(
1610                                         $type,
1611                                         bigintval(getRequestElement('fid')),
1612                                         bigintval($tid)
1613                                 ), __FUNCTION__, __LINE__);
1614                 } // END - if
1615         } // END - if
1616 }
1617
1618 // [EOF]
1619 ?>