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