Fixed handling of float values, ext-surfbar continued:
[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         //* BUG: */ reportBug(__FUNCTION__, __LINE__, '<pre>'.print_r(postRequestArray(),true).'</pre>');
563         foreach ($postData as $id => $val) {
564                 // Process only formular field but not submit buttons ;)
565                 if ($id == 'ok') {
566                         // Skip this button
567                         continue;
568                 } // END - if
569
570                 // Do not save the ok value
571                 convertSelectionsToEpocheTime($postData, $tableData, $id, $skip);
572
573                 // Shall we process this id? It muss not be empty, of course
574                 if (($skip === FALSE) && (!empty($id)) && ((!isset($GLOBALS['skip_config'][$id]))) || ($tableName != '_config')) {
575                         // Translate the value? (comma to dot!)
576                         if ((is_array($translateComma)) && (in_array($id, $translateComma))) {
577                                 // Then do it here... :)
578                                 $val = convertCommaToDot($val);
579                         } // END - if
580
581                         // Test value on float
582                         $test = (float) $val;
583
584                         // Debug message
585                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'test=' . $test . ',val=' . $val . ',id=' . $id);
586
587                         // Shall we add numbers or strings?
588                         if ('' . $val . '' == '' . $test . '') {
589                                 // Add numbers
590                                 array_push($tableData, sprintf("`%s`=%s", $id, $test));
591                         } elseif (is_null($val)) {
592                                 // Add NULL
593                                 array_push($tableData, sprintf("`%s`=NULL", $id));
594                         } else {
595                                 // Add strings
596                                 array_push($tableData, sprintf("`%s`='%s'", $id, trim($val)));
597                         }
598
599                         // Do not add a config entry twice
600                         $GLOBALS['skip_config'][$id] = TRUE;
601
602                         // Update current configuration
603                         setConfigEntry($id, $val);
604                 } // END - if
605         } // END - foreach
606
607         // Check if entry does exist
608         $result = FALSE;
609         if ($alwaysAdd === FALSE) {
610                 if (!empty($whereStatement)) {
611                         $result = SQL_QUERY("SELECT * FROM `{?_MYSQL_PREFIX?}" . $tableName . "` WHERE " . $whereStatement . " LIMIT 1", __FUNCTION__, __LINE__);
612                 } else {
613                         $result = SQL_QUERY("SELECT * FROM `{?_MYSQL_PREFIX?}" . $tableName . "` LIMIT 1", __FUNCTION__, __LINE__);
614                 }
615         } // END - if
616
617         if (SQL_NUMROWS($result) == 1) {
618                 // "Implode" all data to single string
619                 $updatedData = implode(', ', $tableData);
620
621                 // Generate SQL string
622                 $sql = sprintf("UPDATE `{?_MYSQL_PREFIX?}%s` SET %s WHERE %s LIMIT 1",
623                         $tableName,
624                         $updatedData,
625                         $whereStatement
626                 );
627         } else {
628                 // Add Line (does only work with AUTO_INCREMENT!
629                 $keys = array(); $values = array();
630                 foreach ($tableData as $entry) {
631                         // Split up
632                         $line = explode('=', $entry);
633                         array_push($keys  , $line[0]);
634                         array_push($values, $line[1]);
635                 } // END - foreach
636
637                 // Add both in one line
638                 $keys   = implode('`, `', $keys);
639                 $values = implode(', '  , $values);
640
641                 // Generate SQL string
642                 $sql = sprintf("INSERT INTO `{?_MYSQL_PREFIX?}%s` (%s) VALUES (%s)",
643                         $tableName,
644                         $keys,
645                         $values
646                 );
647         }
648
649         // Free memory
650         SQL_FREERESULT($result);
651
652         // Simply run generated SQL string
653         SQL_QUERY($sql, __FUNCTION__, __LINE__);
654
655         // Remember affected rows
656         $affected = SQL_AFFECTEDROWS();
657
658         // Rebuild cache
659         rebuildCache('config', 'config');
660
661         // Settings saved, so display message?
662         if ($displayMessage === TRUE) {
663                 // Display a message
664                 displayMessage('{--SETTINGS_SAVED--}');
665         } // END - if
666
667         // Return affected rows
668         return $affected;
669 }
670
671 // Generate a selection box
672 function adminAddMenuSelectionBox ($menu, $type, $name, $default = '') {
673         // Open the requested menu directory
674         $menuArray = getArrayFromDirectory(sprintf("inc/modules/%s/", $menu), $type . '-', FALSE, FALSE);
675
676         // Init the selection box
677         $OUT = '<select name="' . $name . '" class="form_select" size="1"><option value="">{--ADMIN_IS_TOP_MENU--}</option>';
678
679         // Walk through all files
680         foreach ($menuArray as $file) {
681                 // Is this a PHP script?
682                 if ((!isDirectory($file)) && (isInString('' . $type . '-', $file)) && (isInString('.php', $file))) {
683                         // Then test if the file is readable
684                         $test = sprintf("inc/modules/%s/%s", $menu, $file);
685
686                         // Is the file there?
687                         if (isIncludeReadable($test)) {
688                                 // Extract the value for what=xxx
689                                 $part = substr($file, (strlen($type) + 1));
690                                 $part = substr($part, 0, -4);
691
692                                 // Is that part different from the overview?
693                                 if ($part != 'welcome') {
694                                         $OUT .= '<option value="' . $part . '"';
695                                         if ($part == $default) {
696                                                 $OUT .= ' selected="selected"';
697                                         } // END - if
698                                         $OUT .= '>' . $part . '</option>';
699                                 } // END - if
700                         } // END - if
701                 } // END - if
702         } // END - foreach
703
704         // Close selection box
705         $OUT .= '</select>';
706
707         // Return contents
708         return $OUT;
709 }
710
711 // Creates a user-profile link for the admin. This function can also be used for many other purposes
712 function generateUserProfileLink ($userid, $title = '', $what = '') {
713         // Is there cache?
714         if (!isset($GLOBALS[__FUNCTION__][$userid][$title . '_' . $what])) {
715                 // Is title empty and valid userid?
716                 if (($title == '') && (isValidUserId($userid))) {
717                         // Set userid as title
718                         $title = $userid;
719                 } elseif (!isValidUserId($userid)) {
720                         // User id zero is invalid
721                         return '<strong>' . convertNullToZero($userid) . '</strong>';
722                 }
723
724                 // Is what set?
725                 if (empty($what)) {
726                         // Then get it
727                         $what = getWhat();
728                 } // END - if
729
730                 if (($title == '0') && ($what == 'list_refs')) {
731                         // Return title again
732                         return $title;
733                 } elseif (!empty($title)) {
734                         // Not empty, so skip next one
735                 } elseif (isExtensionActive('nickname')) {
736                         // Get nickname
737                         $nick = getNickname($userid);
738
739                         // Is it not empty, use it as title else the userid
740                         if (!empty($nick)) {
741                                 $title = $nick . '(' . $userid . ')';
742                         } else {
743                                 $title = $userid;
744                         }
745                 }
746
747                 // Set it in cache
748                 $GLOBALS[__FUNCTION__][$userid][$title . '_' . $what] = '[<a href="{%url=modules.php?module=admin&amp;what=' . $what . '&amp;userid=' . $userid . '%}" title="{--ADMIN_USER_PROFILE_TITLE--}">' . $title . '</a>]';
749         } // END - if
750
751         // Return cache
752         return $GLOBALS[__FUNCTION__][$userid][$title . '_' . $what];
753 }
754
755 // Check "logical-area-mode"
756 function adminGetMenuMode () {
757         // Set the default menu mode as the mode for all admins
758         $mode = 'global';
759
760         // If ext-sql_patches is up-to-date enough, use the configuration
761         if (isExtensionInstalledAndNewer('sql_patches', '0.3.2')) {
762                 $mode = getAdminMenu();
763         } // END - if
764
765         // Backup it
766         $adminMode = $mode;
767
768         // Get admin id
769         $adminId = getCurrentAdminId();
770
771         // Check individual settings of current admin
772         if (isset($GLOBALS['cache_array']['admin']['la_mode'][$adminId])) {
773                 // Load from cache
774                 $adminMode = $GLOBALS['cache_array']['admin']['la_mode'][$adminId];
775                 incrementStatsEntry('cache_hits');
776         } elseif (isExtensionInstalledAndNewer('admins', '0.6.7')) {
777                 // Load from database when version of 'admins' is enough
778                 $result = SQL_QUERY_ESC("SELECT `la_mode` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
779                         array($adminId), __FUNCTION__, __LINE__);
780
781                 // Is there an entry?
782                 if (SQL_NUMROWS($result) == 1) {
783                         // Load data
784                         list($adminMode) = SQL_FETCHROW($result);
785                 } // END - if
786
787                 // Free memory
788                 SQL_FREERESULT($result);
789         }
790
791         // Check what the admin wants and set it when it's not the default mode
792         if ($adminMode != 'global') {
793                 $mode = $adminMode;
794         } // END - if
795
796         // Return admin-menu's mode
797         return $mode;
798 }
799
800 // Change activation status
801 function adminChangeActivationStatus ($IDs, $table, $row, $idRow = 'id') {
802         $count = '0';
803         if ((is_array($IDs)) && (count($IDs) > 0)) {
804                 // "Walk" all through and count them
805                 foreach ($IDs as $id => $selected) {
806                         // Secure the id number
807                         $id = bigintval($id);
808
809                         // Should always be set... ;-)
810                         if (!empty($selected)) {
811                                 // Determine new status
812                                 $result = SQL_QUERY_ESC("SELECT %s FROM `{?_MYSQL_PREFIX?}_%s` WHERE %s=%s LIMIT 1",
813                                         array(
814                                                 $row,
815                                                 $table,
816                                                 $idRow,
817                                                 $id
818                                         ), __FUNCTION__, __LINE__);
819
820                                 // Row found?
821                                 if (SQL_NUMROWS($result) == 1) {
822                                         // Load the status
823                                         list($currStatus) = SQL_FETCHROW($result);
824
825                                         // And switch it N<->Y
826                                         $newStatus = convertBooleanToYesNo(!($currStatus == 'Y'));
827
828                                         // Change this status
829                                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s` SET %s='%s' WHERE %s=%s LIMIT 1",
830                                                 array(
831                                                         $table,
832                                                         $row,
833                                                         $newStatus,
834                                                         $idRow,
835                                                         $id
836                                                 ), __FUNCTION__, __LINE__);
837
838                                         // Count up affected rows
839                                         $count += SQL_AFFECTEDROWS();
840                                 } // END - if
841
842                                 // Free the result
843                                 SQL_FREERESULT($result);
844                         } // END - if
845                 } // END - foreach
846
847                 // Output status
848                 displayMessage(sprintf(getMessage('ADMIN_STATUS_CHANGED'), $count, count($IDs)));
849         } else {
850                 // Nothing selected!
851                 displayMessage('{--ADMIN_NOTHING_SELECTED_CHANGE--}');
852         }
853 }
854
855 // Build a special template list
856 function adminListBuilder ($listType, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId = array('userid')) {
857         // Call inner (general) function
858         doGenericListBuilder('admin', $listType, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId);
859 }
860
861 // Change status of "build" list
862 function adminBuilderStatusHandler ($mode, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray, $rawUserId = array('userid'), $cacheFiles = array()) {
863         // $tableName must be an array
864         if ((!is_array($tableName)) || (count($tableName) != 1)) {
865                 // No tableName specified
866                 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
867         } elseif (!is_array($idColumn)) {
868                 // $idColumn is no array
869                 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
870         } elseif ((!is_array($userIdColumn)) || (count($userIdColumn) != 1)) {
871                 // $tableName is no array
872                 reportBug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array: userIdColumn=' . $userIdColumn);
873         } // END - if
874
875         // "Walk" through all entries
876         foreach (postRequestElement($idColumn[0]) as $id => $sel) {
877                 // Construct SQL query
878                 $sql = sprintf("UPDATE `{?_MYSQL_PREFIX?}_%s` SET", SQL_ESCAPE($tableName[0]));
879
880                 // Load data of entry
881                 $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`=%s LIMIT 1",
882                         array(
883                                 $tableName[0],
884                                 $idColumn[0],
885                                 $id
886                         ), __FUNCTION__, __LINE__);
887
888                 // Fetch the data
889                 $content = SQL_FETCHARRAY($result);
890
891                 // Free the result
892                 SQL_FREERESULT($result);
893
894                 // Add all status entries (e.g. status column last_updated or so)
895                 $newStatus = 'UNKNOWN';
896                 $oldStatus = 'UNKNOWN';
897                 $statusColumn = 'unknown';
898                 foreach ($statusArray as $column => $statusInfo) {
899                         // Does the entry exist?
900                         if ((isset($content[$column])) && (isset($statusInfo[$content[$column]]))) {
901                                 // Add these entries for update
902                                 $sql .= sprintf(" `%s`='%s',", SQL_ESCAPE($column), SQL_ESCAPE($statusInfo[$content[$column]]));
903
904                                 // Remember status
905                                 if ($statusColumn == 'unknown') {
906                                         // Always (!!!) change status column first!
907                                         $oldStatus = $content[$column];
908                                         $newStatus = $statusInfo[$oldStatus];
909                                         $statusColumn = $column;
910                                 } // END - if
911                         } elseif (isset($content[$column])) {
912                                 // Unfinished!
913                                 reportBug(__FUNCTION__, __LINE__, ':UNFINISHED: id=' . $id . ',column=' . $column . '[' . gettype($statusInfo) . '] = ' . $content[$column]);
914                         }
915                 } // END - foreach
916
917                 // Add other columns as well
918                 foreach (postRequestArray() as $key => $entries) {
919                         // Debug message
920                         logDebugMessage(__FUNCTION__, __LINE__, 'Found entry: ' . $key);
921
922                         // Skip id, raw userid and 'do_$mode'
923                         if (!in_array($key, array($idColumn[0], $rawUserId[0], ('do_' . $mode)))) {
924                                 // Are there brackets () at the end?
925                                 if (substr($entries[$id], -2, 2) == '()') {
926                                         // Direct SQL command found
927                                         $sql .= sprintf(" `%s`=%s,", SQL_ESCAPE($key), SQL_ESCAPE($entries[$id]));
928                                 } else {
929                                         // Add regular entry
930                                         $sql .= sprintf(" `%s`='%s',", SQL_ESCAPE($key), SQL_ESCAPE($entries[$id]));
931
932                                         // Add entry
933                                         $content[$key] = $entries[$id];
934                                 }
935                         } else {
936                                 // Skipped entry
937                                 logDebugMessage(__FUNCTION__, __LINE__, 'Skipped: ' . $key);
938                         }
939                 } // END - foreach
940
941                 // Finish SQL statement
942                 $sql = substr($sql, 0, -1) . sprintf(" WHERE `%s`=%s AND `%s`='%s' LIMIT 1",
943                         $idColumn[0],
944                         bigintval($id),
945                         $statusColumn,
946                         $oldStatus
947                 );
948
949                 // Run the SQL
950                 SQL_QUERY($sql, __FUNCTION__, __LINE__);
951
952                 // Send "build mails" out
953                 sendGenericBuildMails($mode, $tableName, $content, $id, $statusInfo[$content[$column]], $userIdColumn);
954         } // END - foreach
955 }
956
957 // Delete rows by given id numbers
958 function adminDeleteEntriesConfirm ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $deleteNow = array(FALSE), $idColumn = array('id'), $userIdColumn = array('userid'), $rawUserId = array('userid'), $cacheFiles = array()) {
959         // $tableName must be an array
960         if ((!is_array($tableName)) || (count($tableName) != 1)) {
961                 // No tableName specified
962                 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
963         } elseif (!is_array($idColumn)) {
964                 // $idColumn is no array
965                 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
966         } elseif (!is_array($userIdColumn)) {
967                 // $userIdColumn is no array
968                 reportBug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array: userIdColumn=' . $userIdColumn);
969         } elseif (!is_array($deleteNow)) {
970                 // $deleteNow is no array
971                 reportBug(__FUNCTION__, __LINE__, 'deleteNow[]=' . gettype($deleteNow) . '!=array: userIdColumn=' . $userIdColumn);
972         } // END - if
973
974         // Shall we delete here or list for deletion?
975         if ($deleteNow[0] === TRUE) {
976                 // Call generic function
977                 $affected = doGenericDeleteEntriesConfirm($tableName, $columns, $filterFunctions, $extraValues, $deleteNow, $idColumn, $userIdColumn, $rawUserId, $cacheFiles);
978
979                 // Was this fine?
980                 if ($affected == countPostSelection($idColumn[0])) {
981                         // All deleted
982                         displayMessage('{--ADMIN_ALL_ENTRIES_REMOVED--}');
983                 } else {
984                         // Some are still there :(
985                         displayMessage(sprintf(getMessage('ADMIN_SOME_ENTRIES_NOT_DELETED'), SQL_AFFECTEDROWS(), countPostSelection($idColumn[0])));
986                 }
987         } else {
988                 // List for deletion confirmation
989                 adminListBuilder('delete', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
990         }
991 }
992
993 // Edit rows by given id numbers
994 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()) {
995         // $tableName must be an array
996         if ((!is_array($tableName)) || (count($tableName) != 1)) {
997                 // No tableName specified
998                 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
999         } elseif (!is_array($idColumn)) {
1000                 // $idColumn is no array
1001                 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
1002         } elseif (!is_array($userIdColumn)) {
1003                 // $userIdColumn is no array
1004                 reportBug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array: userIdColumn=' . $userIdColumn);
1005         } elseif (!is_array($editNow)) {
1006                 // $editNow is no array
1007                 reportBug(__FUNCTION__, __LINE__, 'editNow[]=' . gettype($editNow) . '!=array: userIdColumn=' . $userIdColumn);
1008         } // END - if
1009
1010         // Shall we change here or list for editing?
1011         if ($editNow[0] === TRUE) {
1012                 // Call generic change method
1013                 $affected = doGenericEditEntriesConfirm($tableName, $columns, $filterFunctions, $extraValues, $timeColumns, $editNow, $idColumn, $userIdColumn, $rawUserId, $cacheFiles);
1014
1015                 // Was this fine?
1016                 if ($affected == countPostSelection($idColumn[0])) {
1017                         // All deleted
1018                         displayMessage('{--ADMIN_ALL_ENTRIES_EDITED--}');
1019                 } else {
1020                         // Some are still there :(
1021                         displayMessage(sprintf(getMessage('ADMIN_SOME_ENTRIES_NOT_EDITED'), $affected, countPostSelection($idColumn[0])));
1022                 }
1023         } else {
1024                 // List for editing
1025                 adminListBuilder('edit', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1026         }
1027 }
1028
1029 // Un-/lock rows by given id numbers
1030 function adminLockEntriesConfirm ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $statusArray = array(), $lockNow = array(FALSE), $idColumn = array('id'), $userIdColumn = array('userid')) {
1031         // $tableName must be an array
1032         if ((!is_array($tableName)) || (count($tableName) != 1)) {
1033                 // No tableName specified
1034                 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
1035         } elseif (!is_array($idColumn)) {
1036                 // $idColumn is no array
1037                 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
1038         } elseif (!is_array($lockNow)) {
1039                 // $lockNow is no array
1040                 reportBug(__FUNCTION__, __LINE__, 'lockNow[]=' . gettype($lockNow) . '!=array: userIdColumn=' . $userIdColumn);
1041         } // END - if
1042
1043         // Shall we un-/lock here or list for locking?
1044         if ($lockNow[0] === TRUE) {
1045                 // Un-/lock entries
1046                 adminBuilderStatusHandler('lock', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray);
1047         } else {
1048                 // List for editing
1049                 adminListBuilder('lock', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1050         }
1051 }
1052
1053 // Undelete rows by given id numbers
1054 function adminUndeleteEntriesConfirm ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $statusArray = array(), $undeleteNow = array(FALSE), $idColumn = array('id'), $userIdColumn = array('userid')) {
1055         // $tableName must be an array
1056         if ((!is_array($tableName)) || (count($tableName) != 1)) {
1057                 // No tableName specified
1058                 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
1059         } elseif (!is_array($idColumn)) {
1060                 // $idColumn is no array
1061                 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
1062         } elseif (!is_array($undeleteNow)) {
1063                 // $undeleteNow is no array
1064                 reportBug(__FUNCTION__, __LINE__, 'undeleteNow[]=' . gettype($undeleteNow) . '!=array: userIdColumn=' . $userIdColumn);
1065         } // END - if
1066
1067         // Shall we un-/lock here or list for locking?
1068         if ($undeleteNow[0] === TRUE) {
1069                 // Undelete entries
1070                 adminBuilderStatusHandler('undelete', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray);
1071         } else {
1072                 // List for editing
1073                 adminListBuilder('undelete', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1074         }
1075 }
1076
1077 // Adds a given entry to the database
1078 function adminAddEntries ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $timeColumns = array(), $columnIndex = NULL) {
1079         // Is the userid set?
1080         if (!isPostRequestElementSet('userid')) {
1081                 // Then set NULL here
1082                 setPostRequestElement('userid', NULL);
1083         } // END - if
1084
1085         // Call inner function
1086         doGenericAddEntries($tableName, $columns, $filterFunctions, $extraValues, $timeColumns, $columnIndex);
1087
1088         // Entry has been added?
1089         if ((!SQL_HASZEROAFFECTED()) && ($GLOBALS['__XML_PARSE_RESULT'] === TRUE)) {
1090                 // Display success message
1091                 displayMessage('{--ADMIN_ENTRY_ADDED--}');
1092         } else {
1093                 // Display failed message
1094                 displayMessage('{--ADMIN_ENTRY_NOT_ADDED--}');
1095         }
1096 }
1097
1098 // Checks proxy settins by fetching check-updates3.php from mxchange.org
1099 function adminTestProxySettings ($settingsArray) {
1100         // Set temporary the new settings
1101         mergeConfig($settingsArray);
1102
1103         // Now get the test URL
1104         $content = sendGetRequest('check-updates3.php');
1105
1106         // Is the first line with "200 OK"?
1107         $valid = isInString('200 OK', $content[0]);
1108
1109         // Return result
1110         return $valid;
1111 }
1112
1113 // Sends out a link to the given email adress so the admin can reset his/her password
1114 function sendAdminPasswordResetLink ($email) {
1115         // Init output
1116         $OUT = '';
1117
1118         // Look up administator login
1119         $result = SQL_QUERY_ESC("SELECT `id`, `login`, `password` FROM `{?_MYSQL_PREFIX?}_admins` WHERE '%s' REGEXP `email` LIMIT 1",
1120                 array($email), __FUNCTION__, __LINE__);
1121
1122         // Is there an account?
1123         if (SQL_HASZERONUMS($result)) {
1124                 // No account found
1125                 return '{--ADMIN_NO_LOGIN_WITH_EMAIL--}';
1126         } // END - if
1127
1128         // Load all data
1129         $content = SQL_FETCHARRAY($result);
1130
1131         // Free result
1132         SQL_FREERESULT($result);
1133
1134         // Generate hash for reset link
1135         $content['hash'] = generateHash(getUrl() . getEncryptSeparator() . $content['id'] . getEncryptSeparator() . $content['login'] . getEncryptSeparator() . $content['password'], substr($content['password'], getSaltLength()));
1136
1137         // Remove some data
1138         unset($content['id']);
1139         unset($content['password']);
1140
1141         // Prepare email
1142         $mailText = loadEmailTemplate('admin_reset_password', $content);
1143
1144         // Send it out
1145         sendEmail($email, '{--ADMIN_RESET_PASSWORD_LINK_SUBJECT--}', $mailText);
1146
1147         // Prepare output
1148         return '{--ADMIN_RESET_PASSWORD_LINK_SENT--}';
1149 }
1150
1151 // Validate hash and login for password reset
1152 function adminResetValidateHashLogin ($hash, $login) {
1153         // By default nothing validates... ;)
1154         $valid = FALSE;
1155
1156         // Then try to find that user
1157         $result = SQL_QUERY_ESC("SELECT `id`, `password`, `email` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
1158                 array($login), __FUNCTION__, __LINE__);
1159
1160         // Is an account here?
1161         if (SQL_NUMROWS($result) == 1) {
1162                 // Load all data
1163                 $content = SQL_FETCHARRAY($result);
1164
1165                 // Generate hash again
1166                 $hashFromData = generateHash(getUrl() . getEncryptSeparator() . $content['id'] . getEncryptSeparator() . $login . getEncryptSeparator() . $content['password'], substr($content['password'], getSaltLength()));
1167
1168                 // Does both match?
1169                 $valid = ($hash == $hashFromData);
1170         } // END - if
1171
1172         // Free result
1173         SQL_FREERESULT($result);
1174
1175         // Return result
1176         return $valid;
1177 }
1178
1179 // Reset the password for the login. Do NOT call this function without calling above function first!
1180 function doResetAdminPassword ($login, $password) {
1181         // Generate hash (we already check for ext-sql_patches in generateHash())
1182         $passHash = generateHash($password);
1183
1184         // Prepare fake POST data
1185         $postData = array(
1186                 'login'    => array(getAdminId($login) => $login),
1187                 'password' => array(getAdminId($login) => $passHash),
1188         );
1189
1190         // Update database
1191         $message = adminsChangeAdminAccount($postData, '', FALSE);
1192
1193         // Run filters
1194         runFilterChain('post_form_reset_pass', array('login' => $login, 'hash' => $passHash, 'message' => $message));
1195
1196         // Return output
1197         return '{--ADMIN_PASSWORD_RESET_DONE--}';
1198 }
1199
1200 // Solves a task by given id number
1201 function adminSolveTask ($id) {
1202         // Update the task data
1203         adminUpdateTaskData($id, 'status', 'SOLVED');
1204 }
1205
1206 // Marks a given task as deleted
1207 function adminDeleteTask ($id) {
1208         // Update the task data
1209         adminUpdateTaskData($id, 'status', 'DELETED');
1210 }
1211
1212 // Function to update task data
1213 function adminUpdateTaskData ($id, $row, $data) {
1214         // Should be admin and valid id
1215         if (!isAdmin()) {
1216                 // Not an admin so redirect better
1217                 reportBug(__FUNCTION__, __LINE__, 'id=' . $id . ',row=' . $row . ',data=' . $data . ' - isAdmin()=false');
1218         } elseif ($id <= 0) {
1219                 // Initiate backtrace
1220                 reportBug(__FUNCTION__, __LINE__, sprintf("id is invalid: %s. row=%s, data=%s",
1221                         $id,
1222                         $row,
1223                         $data
1224                 ));
1225         } // END - if
1226
1227         // Update the task
1228         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_task_system` SET `%s`='%s' WHERE `id`=%s LIMIT 1",
1229                 array(
1230                         $row,
1231                         $data,
1232                         bigintval($id)
1233                 ), __FUNCTION__, __LINE__);
1234 }
1235
1236 // Checks whether if the admin menu has entries
1237 function ifAdminMenuHasEntries ($action) {
1238         return (
1239                 ((
1240                         // Is the entry set?
1241                         isset($GLOBALS['admin_menu_has_entries'][$action])
1242                 ) && (
1243                         // And do we have a menu for this action?
1244                         $GLOBALS['admin_menu_has_entries'][$action] === TRUE
1245                 )) || (
1246                         // Login has always a menu
1247                         $action == 'login'
1248                 )
1249         );
1250 }
1251
1252 // Setter for 'admin_menu_has_entries'
1253 function setAdminMenuHasEntries ($action, $hasEntries) {
1254         $GLOBALS['admin_menu_has_entries'][$action] = (bool) $hasEntries;
1255 }
1256
1257 // Creates a link to the user's admin-profile
1258 function adminCreateUserLink ($userid) {
1259         // Is the userid set correctly?
1260         if (isValidUserId($userid)) {
1261                 // Create a link to that profile
1262                 return '{%url=modules.php?module=admin&amp;what=list_user&amp;userid=' . bigintval($userid) . '%}';
1263         } // END - if
1264
1265         // Return a link to the user list
1266         return '{%url=modules.php?module=admin&amp;what=list_user%}';
1267 }
1268
1269 // Generate a "link" for the given admin id (admin_id)
1270 function generateAdminLink ($adminId) {
1271         // No assigned admin is default
1272         $adminLink = '{--ADMIN_NO_ADMIN_ASSIGNED--}';
1273
1274         // Zero? = Not assigned
1275         if (isValidUserId($adminId)) {
1276                 // Load admin's login
1277                 $login = getAdminLogin($adminId);
1278
1279                 // Is the login valid?
1280                 if ($login != '***') {
1281                         // Is the extension there?
1282                         if (isExtensionActive('admins')) {
1283                                 // Admin found
1284                                 $adminLink = '<a href="' . generateEmailLink(getAdminEmail($adminId), 'admins') . '" title="{--ADMIN_CONTACT_LINK_TITLE--}">' . $login . '</a>';
1285                         } else {
1286                                 // Extension not found
1287                                 $adminLink = '{%message,ADMIN_TASK_ROW_EXTENSION_NOT_INSTALLED=admins%}';
1288                         }
1289                 } else {
1290                         // Maybe deleted?
1291                         $adminLink = '<div class="bad">{%message,ADMIN_ID_404=' . $adminId . '%}</div>';
1292                 }
1293         } // END - if
1294
1295         // Return result
1296         return $adminLink;
1297 }
1298
1299 // Verifies if the current admin has confirmed to alter expert settings
1300 //
1301 // Return values:
1302 // 'failed'    = Something goes wrong (default)
1303 // 'agreed'    = Has verified and and confirmed it to see them
1304 // 'forbidden' = Has not the proper right to alter them
1305 // 'update'    = Need to update extension 'admins'
1306 // 'ask'       = A form was send to the admin
1307 function doVerifyExpertSettings () {
1308         // Default return status is failed
1309         $return = 'failed';
1310
1311         // Is the extension installed and recent?
1312         if (isExtensionInstalledAndNewer('admins', '0.7.3')) {
1313                 // Okay, load the status
1314                 $expertSettings = getAminsExpertSettings();
1315
1316                 // Is he allowed?
1317                 if ($expertSettings == 'Y') {
1318                         // Okay, does he want to see them?
1319                         if (isAdminsExpertWarningEnabled()) {
1320                                 // Ask for them
1321                                 if (isFormSent()) {
1322                                         // Is the element set, then we need to change the admin
1323                                         if (isPostRequestElementSet('expert_settings')) {
1324                                                 // Get it and prepare final post data array
1325                                                 $postData['login'][getCurrentAdminId()] = getCurrentAdminLogin();
1326                                                 $postData['expert_warning'][getCurrentAdminId()] = 'N';
1327
1328                                                 // Change it in the admin
1329                                                 adminsChangeAdminAccount($postData, 'expert_warning');
1330                                         } // END - if
1331
1332                                         // All fine!
1333                                         $return = 'agreed';
1334                                 } else {
1335                                         // Send form
1336                                         loadTemplate('admin_expert_settings_form');
1337
1338                                         // Asked for it
1339                                         $return = 'ask';
1340                                 }
1341                         } else {
1342                                 // Do not display
1343                                 $return = 'agreed';
1344                         }
1345
1346                         // Is a form sent?
1347                         if ((isFormSent()) && (isPostRequestElementSet('expert_settings'))) {
1348                                 // Clear form
1349                                 unsetPostRequestElement('ok');
1350                                 unsetPostRequestElement('expert_settings');
1351                         } // END - if
1352                 } else {
1353                         // Forbidden
1354                         $return = 'forbidden';
1355                 }
1356         } else {
1357                 // Out-dated extension or not installed
1358                 $return = 'update';
1359         }
1360
1361         // Output message for other status than ask/agreed
1362         if (($return != 'ask') && ($return != 'agreed')) {
1363                 // Output message
1364                 displayMessage('{--ADMIN_EXPERT_SETTINGS_STATUS_' . strtoupper($return) . '--}');
1365         } // END - if
1366
1367         // Return status
1368         return $return;
1369 }
1370
1371 // Generate link to unconfirmed mails for admin
1372 function generateUnconfirmedAdminLink ($id, $unconfirmed, $type = 'bid') {
1373         // Init output
1374         $OUT = $unconfirmed;
1375
1376         // Is there unconfirmed mails?
1377         if ($unconfirmed > 0) {
1378                 // Add link to list_unconfirmed what-file
1379                 $OUT = '<a href="{%url=modules.php?module=admin&amp;what=list_unconfirmed&amp;' . $type . '=' . $id . '%}">{%pipe,translateComma=' . $unconfirmed . '%}</a>';
1380         } // END - if
1381
1382         // Return it
1383         return $OUT;
1384 }
1385
1386 // Generates a navigation row for listing emails
1387 function addEmailNavigation ($numPages, $offset, $show_form, $colspan, $return=false) {
1388         // Don't do anything if $numPages is 1
1389         if ($numPages == 1) {
1390                 // Abort here with empty content
1391                 return '';
1392         } // END - if
1393
1394         $TOP = '';
1395         if ($show_form === FALSE) {
1396                 $TOP = ' top';
1397         } // END - if
1398
1399         $NAV = '';
1400         for ($page = 1; $page <= $numPages; $page++) {
1401                 // Is the page currently selected or shall we generate a link to it?
1402                 if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
1403                         // Is currently selected, so only highlight it
1404                         $NAV .= '<strong>-';
1405                 } else {
1406                         // Open anchor tag and add base URL
1407                         $NAV .= '<a href="{%url=modules.php?module=admin&amp;what=' . getWhat() . '&amp;page=' . $page . '&amp;offset=' . $offset;
1408
1409                         // Add userid when we shall show all mails from a single member
1410                         if ((isGetRequestElementSet('userid')) && (isValidUserId(getRequestElement('userid')))) $NAV .= '&amp;userid=' . bigintval(getRequestElement('userid'));
1411
1412                         // Close open anchor tag
1413                         $NAV .= '%}">';
1414                 }
1415                 $NAV .= $page;
1416                 if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
1417                         // Is currently selected, so only highlight it
1418                         $NAV .= '-</strong>';
1419                 } else {
1420                         // Close anchor tag
1421                         $NAV .= '</a>';
1422                 }
1423
1424                 // Add separator if we have not yet reached total pages
1425                 if ($page < $numPages) {
1426                         // Add it
1427                         $NAV .= '|';
1428                 } // END - if
1429         } // END - for
1430
1431         // Define constants only once
1432         $content['nav']  = $NAV;
1433         $content['span'] = $colspan;
1434         $content['top']  = $TOP;
1435
1436         // Load navigation template
1437         $OUT = loadTemplate('admin_email_nav_row', TRUE, $content);
1438
1439         if ($return === TRUE) {
1440                 // Return generated HTML-Code
1441                 return $OUT;
1442         } else {
1443                 // Output HTML-Code
1444                 outputHtml($OUT);
1445         }
1446 }
1447
1448 // Process menu editing form
1449 function adminProcessMenuEditForm ($type, $subMenu) {
1450         // An action is done...
1451         foreach (postRequestElement('sel') as $sel => $menu) {
1452                 $AND = "(`what` = '' OR `what` IS NULL)";
1453
1454                 $sel = bigintval($sel);
1455
1456                 if (!empty($subMenu)) {
1457                         $AND = "`action`='" . $subMenu . "'";
1458                 } // END - if
1459
1460                 switch (postRequestElement('ok')) {
1461                         case 'edit': // Edit menu
1462                                 // Shall we update a menu or sub menu?
1463                                 if (!isGetRequestElementSet('sub')) {
1464                                         // Update with 'what'=null
1465                                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET `title`='%s',`action`='%s',`what`=NULL WHERE ".$AND." AND `id`=%s LIMIT 1",
1466                                                 array(
1467                                                         $type,
1468                                                         $menu,
1469                                                         postRequestElement('sel_action', $sel),
1470                                                         $sel
1471                                                 ), __FUNCTION__, __LINE__);
1472                                 } else {
1473                                         // Update with selected 'what'
1474                                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET `title`='%s',`action`='%s',`what`='%s' WHERE ".$AND." AND `id`=%s LIMIT 1",
1475                                                 array(
1476                                                         $type,
1477                                                         $menu,
1478                                                         postRequestElement('sel_action', $sel),
1479                                                         postRequestElement('sel_what', $sel),
1480                                                         $sel
1481                                                 ), __FUNCTION__, __LINE__);
1482                                 }
1483                                 break;
1484
1485                         case 'delete': // Delete menu
1486                                 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE ".$AND." AND `id`=%s LIMIT 1",
1487                                         array(
1488                                                 $type,
1489                                                 $sel
1490                                         ), __FUNCTION__, __LINE__);
1491                                 break;
1492
1493                         case 'status': // Change status of menus
1494                                 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET `visible`='%s',`locked`='%s' WHERE ".$AND." AND `id`=%s LIMIT 1",
1495                                         array(
1496                                                 $type,
1497                                                 postRequestElement('visible', $sel),
1498                                                 postRequestElement('locked', $sel),
1499                                                 $sel
1500                                         ), __FUNCTION__, __LINE__);
1501                                 break;
1502
1503                         default: // Unexpected action
1504                                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unsupported action %s detected.", postRequestElement('ok')));
1505                                 displayMessage('{%message,ADMIN_UNKNOWN_OKAY=' . postRequestElement('ok') . '%}');
1506                                 break;
1507                 } // END - switch
1508         } // END - foreach
1509
1510         // Load template
1511         displayMessage('{--SETTINGS_SAVED--}');
1512 }
1513
1514 // Handle weightning
1515 function doAdminProcessMenuWeightning ($type, $AND) {
1516         // Are there all required (generalized) GET parameter?
1517         if ((isGetRequestElementSet('act')) && (isGetRequestElementSet('tid')) && (isGetRequestElementSet('fid'))) {
1518                 // Init variables
1519                 $tid = ''; $fid = '';
1520
1521                 // Get ids
1522                 if (isGetRequestElementSet('w')) {
1523                         // Sub menus selected
1524                         $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `action`='%s' AND `sort`=%s LIMIT 1",
1525                                 array(
1526                                         $type,
1527                                         getRequestElement('act'),
1528                                         bigintval(getRequestElement('tid'))
1529                                 ), __FUNCTION__, __LINE__);
1530                         list($tid) = SQL_FETCHROW($result);
1531                         SQL_FREERESULT($result);
1532                         $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `action`='%s' AND `sort`=%s LIMIT 1",
1533                                 array(
1534                                         $type,
1535                                         getRequestElement('act'),
1536                                         bigintval(getRequestElement('fid'))
1537                                 ), __FUNCTION__, __LINE__);
1538                         list($fid) = SQL_FETCHROW($result);
1539                         SQL_FREERESULT($result);
1540                 } else {
1541                         // Main menu selected
1542                         $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE (`what`='' OR `what` IS NULL) AND `sort`=%s LIMIT 1",
1543                                 array(
1544                                         $type,
1545                                         bigintval(getRequestElement('tid'))
1546                                 ), __FUNCTION__, __LINE__);
1547                         list($tid) = SQL_FETCHROW($result);
1548                         SQL_FREERESULT($result);
1549                         $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE (`what`='' OR `what` IS NULL) AND `sort`=%s LIMIT 1",
1550                                 array(
1551                                         $type,
1552                                         bigintval(getRequestElement('fid'))
1553                                 ), __FUNCTION__, __LINE__);
1554                         list($fid) = SQL_FETCHROW($result);
1555                         SQL_FREERESULT($result);
1556                 }
1557
1558                 if ((!empty($tid)) && (!empty($fid))) {
1559                         // Sort menu
1560                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET `sort`=%s WHERE ".$AND." AND `id`=%s LIMIT 1",
1561                                 array(
1562                                         $type,
1563                                         bigintval(getRequestElement('tid')),
1564                                         bigintval($fid)
1565                                 ), __FUNCTION__, __LINE__);
1566                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET `sort`=%s WHERE ".$AND." AND `id`=%s LIMIT 1",
1567                                 array(
1568                                         $type,
1569                                         bigintval(getRequestElement('fid')),
1570                                         bigintval($tid)
1571                                 ), __FUNCTION__, __LINE__);
1572                 } // END - if
1573         } // END - if
1574 }
1575
1576 // [EOF]
1577 ?>