9476cb086367fa14ce4fa9b21d26db7ee2f56874
[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                         // Passwords don't match
138                         $ret = 'password';
139                 } elseif (!isAdmin()) {
140                         // Is not valid session
141                         $ret = 'session';
142                 } else {
143                         // All fine
144                         $ret = 'done';
145                 }
146         } // END - if
147
148         // Return status
149         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ret='.$ret);
150         return $ret;
151 }
152
153 // Do an admin action
154 function doAdminAction () {
155         // Determine correct 'what' value
156         $what = determineWhat();
157
158         // Get action value
159         $action = getActionFromModuleWhat(getModule(), $what);
160
161         // Load welcome template
162         if (isExtensionActive('admins')) {
163                 // @TODO This and the next getCurrentAdminId() call might be moved into the templates?
164                 $content['welcome'] = loadTemplate('admin_welcome_admins', TRUE, getCurrentAdminId());
165         } else {
166                 $content['welcome'] = loadTemplate('admin_welcome', TRUE, getCurrentAdminId());
167         }
168
169         // Load header, footer, render menu
170         $content['header'] = loadTemplate('admin_header' , TRUE, $content);
171         $content['footer'] = loadTemplate('admin_footer' , TRUE, $content);
172         $content['menu']   = addAdminMenu($action, $what);
173
174         // Load main template
175         loadTemplate('admin_main', FALSE, $content);
176
177         // Check if action/what pair is valid
178         $result_action = SQL_QUERY_ESC("SELECT
179         `id`
180 FROM
181         `{?_MYSQL_PREFIX?}_admin_menu`
182 WHERE
183         `action`='%s' AND
184         (
185                 (
186                         `what`='%s' AND `what` != 'welcome'
187                 ) OR (
188                         (
189                                 `what`='' OR `what` IS NULL
190                         ) AND (
191                                 '%s'='welcome'
192                         )
193                 )
194         )
195 LIMIT 1",
196                 array(
197                         $action,
198                         $what,
199                         $what
200                 ), __FUNCTION__, __LINE__);
201
202         // Is there an entry?
203         if (SQL_NUMROWS($result_action) == 1) {
204                 // Is valid but does the inlcude file exists?
205                 $inc = sprintf("inc/modules/admin/action-%s.php", $action);
206                 if ((isIncludeReadable($inc)) && (isMenuActionValid('admin', $action, $what)) && ($GLOBALS['acl_allow'] === TRUE)) {
207                         // Ok, we finally load the admin action module
208                         loadInclude($inc);
209                 } elseif ($GLOBALS['acl_allow'] === FALSE) {
210                         // Access denied
211                         loadTemplate('admin_menu_failed', FALSE, '{%message,ADMIN_ACCESS_DENIED=' . $what . '%}');
212                 } else {
213                         // Include file not found :-(
214                         loadTemplate('admin_menu_failed', FALSE, '{%message,ADMIN_ACTION_404=' . $action . '%}');
215                 }
216         } else {
217                 // Invalid action/what pair found
218                 loadTemplate('admin_menu_failed', FALSE, '{%message,ADMIN_ACTION_INVALID=' . $action . '/' . $what . '%}');
219         }
220
221         // Free memory
222         SQL_FREERESULT($result_action);
223
224         // Tableset footer
225         loadTemplate('admin_main_footer', FALSE, $content);
226 }
227
228 /**
229  * Checks whether current admin is allowed to access given action/what
230  * combination (only one is allowed to be null!).
231  */
232 function isAdminAllowedAccessMenu ($action, $what = NULL) {
233         // Is there cache?
234         if (!isset($GLOBALS[__FUNCTION__][$action][$what])) {
235                 // ACL is always 'allow' when no ext-admins is installed
236                 // @TODO This can be rewritten into a filter
237                 $GLOBALS[__FUNCTION__][$action][$what] = ((!isExtensionInstalledAndNewer('admins', '0.2.0')) || ((isExtensionActive('admins')) && (isAdminsAllowedByAcl($action, $what))));
238         } // END - if
239
240         // Return the cached value
241         return $GLOBALS[__FUNCTION__][$action][$what];
242 }
243
244 // Adds an admin menu
245 function addAdminMenu ($action, $what) {
246         // Init variables
247         $SUB = FALSE;
248         $OUT = '';
249
250         // Menu descriptions
251         $GLOBALS['menu']['description'] = array();
252         $GLOBALS['menu']['title']       = array();
253
254         // Build main menu
255         $result_main = SQL_QUERY("SELECT
256         `action` AS `main_action`,
257         `title` AS `main_title`,
258         `descr` AS `main_descr`
259 FROM
260         `{?_MYSQL_PREFIX?}_admin_menu`
261 WHERE
262         (`what`='' OR `what` IS NULL)
263 ORDER BY
264         `sort` ASC,
265         `id` DESC", __FUNCTION__, __LINE__);
266
267         // Are there entries?
268         if (!SQL_HASZERONUMS($result_main)) {
269                 $OUT .= '<ul class="admin_menu_main">';
270
271                 // Load all 'action' menus
272                 while ($mainContent = SQL_FETCHARRAY($result_main)) {
273                         // Filename
274                         $inc = sprintf("inc/modules/admin/action-%s.php", $mainContent['main_action']);
275
276                         // Is the current admin allowed to access this 'action' menu?
277                         if (isAdminAllowedAccessMenu($mainContent['main_action'])) {
278                                 if ($SUB === FALSE) {
279                                         // Insert compiled menu title and description
280                                         $GLOBALS['menu']['title'][$mainContent['main_action']]       = $mainContent['main_title'];
281                                         $GLOBALS['menu']['description'][$mainContent['main_action']] = $mainContent['main_descr'];
282                                 } // END - if
283                                 $OUT .= '<li class="admin_menu"' . addJavaScriptMenuContent('admin', $mainContent['main_action'], $action, $what) . '>
284 <div class="nobr"><strong>&middot;</strong>&nbsp;';
285
286                                 // Is the file readable?
287                                 if (isIncludeReadable($inc)) {
288                                         if (($mainContent['main_action'] == $action) && (empty($what))) {
289                                                 $OUT .= '<strong>';
290                                         } else {
291                                                 $OUT .= '[<a href="{%url=modules.php?module=admin&amp;action=' . $mainContent['main_action'] . '%}">';
292                                         }
293                                 } else {
294                                         $OUT .= '<span class="bad" style="cursor:help" title="{%message,ADMIN_MENU_ACTION_404_TITLE=' . $mainContent['main_action'] . '%}">';
295                                 }
296
297                                 $OUT .= $mainContent['main_title'];
298
299                                 // Is the file readable?
300                                 if (isIncludeReadable($inc)) {
301                                         if (($mainContent['main_action'] == $action) && (empty($what))) {
302                                                 $OUT .= '</strong>';
303                                         } else {
304                                                 $OUT .= '</a>]';
305                                         }
306                                 } else {
307                                         $OUT .= '</span>';
308                                 }
309
310                                 $OUT .= '</div>
311 </li>';
312
313                                 // Add sub menu
314                                 $OUT .= addAdminSubMenu($mainContent, $action, $what);
315                         } // END - if
316                 } // END - while
317
318                 // Close ul-tag
319                 $OUT .= '</ul>';
320
321                 // Free memory
322                 SQL_FREERESULT($result_main);
323         } // END - if
324
325         // Return content
326         return $OUT;
327 }
328
329 // Add admin sub menu
330 function addAdminSubMenu ($mainContent, $action, $what) {
331         // Init content
332         $OUT = '';
333
334         // Check for menu entries
335         $result_what = SQL_QUERY_ESC("SELECT
336         `what` AS `sub_what`,
337         `title` AS `sub_title`,
338         `descr` AS `sub_descr`
339 FROM
340         `{?_MYSQL_PREFIX?}_admin_menu`
341 WHERE
342         `action`='%s' AND
343         `what` != '' AND
344         `what` IS NOT NULL
345 ORDER BY
346         `sort` ASC,
347         `id` DESC",
348                 array($mainContent['main_action']), __FUNCTION__, __LINE__);
349
350         // Remember the count for later checks
351         setAdminMenuHasEntries($mainContent['main_action'], ((!SQL_HASZERONUMS($result_what)) && (($action == $mainContent['main_action']) || (isAdminMenuJavascriptEnabled()))));
352
353         // Start li-tag for sub menu content
354         $OUT .= '<li class="admin_menu_sub" id="action_menu_' . $mainContent['main_action'] . '"' . addStyleMenuContent('admin', $mainContent['main_action'], $action) . '>';
355
356         // Are there entries?
357         if (ifAdminMenuHasEntries($mainContent['main_action'])) {
358                 // Sub menu has been called
359                 $SUB = TRUE;
360
361                 // Are there entries?
362                 if (!SQL_HASZERONUMS($result_what)) {
363                         // Start HTML code
364                         $OUT .= '<ul class="admin_menu_sub">';
365
366                         // Load all entries
367                         while ($subContent = SQL_FETCHARRAY($result_what)) {
368                                 // Filename
369                                 $inc = sprintf("inc/modules/admin/what-%s.php", $subContent['sub_what']);
370
371                                 // Is the current admin allowed to access this 'what' menu?
372                                 if (isAdminAllowedAccessMenu(NULL, $subContent['sub_what'])) {
373                                         // Insert compiled title and description
374                                         $GLOBALS['menu']['title'][$subContent['sub_what']]       = $subContent['sub_title'];
375                                         $GLOBALS['menu']['description'][$subContent['sub_what']] = $subContent['sub_descr'];
376                                         $OUT .= '<li class="admin_menu">
377 <div class="nobr"><strong>--&gt;</strong>&nbsp;';
378
379                                         // Is the file readable?
380                                         if (isIncludeReadable($inc)) {
381                                                 if ($what == $subContent['sub_what']) {
382                                                         $OUT .= '<strong>';
383                                                 } else {
384                                                         $OUT .= '[<a href="{%url=modules.php?module=admin&amp;what=' . $subContent['sub_what'] . '%}">';
385                                                 }
386                                         } else {
387                                                 $OUT .= '<span class="bad" style="cursor:help" title="{%message,ADMIN_MENU_WHAT_404_TITLE=' . $subContent['sub_what'] . '%}">';
388                                         }
389
390                                         $OUT .= $subContent['sub_title'];
391
392                                         // Is the file readable?
393                                         if (isIncludeReadable($inc)) {
394                                                 if ($what == $subContent['sub_what']) {
395                                                         $OUT .= '</strong>';
396                                                 } else {
397                                                         $OUT .= '</a>]';
398                                                 }
399                                         } else {
400                                                 $OUT .= '</span>';
401                                         }
402                                         $OUT .= '</div>
403 </li>';
404                                 } // END - if
405                         } // END - while
406
407                         // Finish HTML output
408                         $OUT .= '</ul>';
409                 } // END - if
410
411                 // Free memory
412                 SQL_FREERESULT($result_what);
413         } // END - if
414
415         // Close li-tag
416         $OUT .= '</li>';
417
418         // Return content
419         return $OUT;
420 }
421
422 // Create an admin selection box form
423 function addAdminSelectionBox ($adminId = NULL, $special = '') {
424         // Default is email as "special column"
425         $ADD = ',`email` AS `special`';
426
427         // Is a special column given?
428         if (!empty($special)) {
429                 // Additional column for SQL query
430                 $ADD = ',`' . $special . '` AS `special`';
431         } // END - if
432
433         // Query all entries
434         $result = SQL_QUERY('SELECT
435         `id`,
436         `login`
437         ' . $ADD . '
438 FROM
439         `{?_MYSQL_PREFIX?}_admins`
440 ORDER BY
441         `login` ASC', __FUNCTION__, __LINE__);
442
443         // Init output
444         $OUT = '';
445
446         // Load all entries
447         while ($content = SQL_FETCHARRAY($result)) {
448                 // Default is none
449                 $content['default'] = '';
450
451                 // Is the id the same?
452                 if ($content['id'] == $adminId) {
453                         // Set this as default
454                         $content['default'] = ' selected="selected"';
455                 } // END - if
456
457                 // Add the entry
458                 $OUT .= loadTemplate('select_admins_option', TRUE, $content);
459         } // END - if
460
461         // Free memory
462         SQL_FREERESULT($result);
463
464         // Add form to content
465         $content['form_selection'] = $OUT;
466
467         // Output form
468         loadTemplate('select_admins_box', FALSE, $content);
469 }
470
471 // Create a member selection box
472 function addMemberSelectionBox ($userid = NULL, $add_all = FALSE, $return = FALSE, $none = FALSE, $field = 'userid', $whereStatement = " WHERE `surname` NOT LIKE '{?tester_user_surname_prefix?}%'") {
473         // Output selection form with all confirmed user accounts listed
474         $result = SQL_QUERY('SELECT
475         `userid`,
476         `surname`,
477         `family`
478 FROM
479         `{?_MYSQL_PREFIX?}_user_data`
480 ' . $whereStatement . '
481 ORDER BY
482         `userid` ASC', __FUNCTION__, __LINE__);
483
484         // Default output
485         $OUT = '';
486
487         // USe this only for adding points (e.g. adding refs really makes no sence ;-) )
488         if ($add_all === TRUE) {
489                 $OUT = '      <option value="all">{--ALL_MEMBERS--}</option>';
490         } elseif ($none === TRUE) {
491                 $OUT = '      <option value="0">{--SELECT_NONE--}</option>';
492         }
493
494         // Load all entries
495         while ($content = SQL_FETCHARRAY($result)) {
496                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . intval($userid) . '/' . $content['userid']);
497                 $OUT .= '<option value="' . bigintval($content['userid']) . '"';
498                 if (bigintval($userid) === bigintval($content['userid'])) {
499                         $OUT .= ' selected="selected"';
500                 } // END - if
501                 $OUT .= '>' . $content['surname'] . ' ' . $content['family'] . ' (' . bigintval($content['userid']) . ')</option>';
502         } // END - while
503
504         // Free memory
505         SQL_FREERESULT($result);
506
507         if ($return === FALSE) {
508                 // Remeber options in constant
509                 $content['form_selection'] = $OUT;
510                 $content['what']           = '{%pipe,getWhat%}';
511
512                 // Load template
513                 loadTemplate('admin_form_selection_box', FALSE, $content);
514         } else {
515                 // Return content in selection frame
516                 return '<select class="form_select" name="' . handleFieldWithBraces($field) . '" size="1">' . $OUT . '</select>';
517         }
518 }
519
520 // Create a menu selection box for given menu system
521 // @TODO Try to rewrite this to adminAddMenuSelectionBox()
522 // @DEPRECATED
523 function adminMenuSelectionBox_DEPRECATED ($mode, $default = '', $defid = '') {
524         $what = "`what` != '' AND `what` IS NOT NULL";
525         if ($mode == 'action') $what = "(`what`='' OR `what` IS NULL) AND `action` != 'login'";
526
527         $result = SQL_QUERY_ESC("SELECT `%s` AS `menu`, `title` FROM `{?_MYSQL_PREFIX?}_admin_menu` WHERE ".$what." ORDER BY `sort` ASC",
528                 array($mode), __FUNCTION__, __LINE__);
529         if (!SQL_HASZERONUMS($result)) {
530                 // Load menu as selection
531                 $OUT = '<select name="' . $mode . '_menu';
532                 if ((!empty($defid)) || ($defid == '0')) $OUT .= '[' . $defid . ']';
533                 $OUT .= '" size="1" class="form_select">
534         <option value="">{--SELECT_NONE--}</option>';
535                 // Load all entries
536                 while ($content = SQL_FETCHARRAY($result)) {
537                         $OUT .= '<option value="' . $content['menu'] . '"';
538                         if ((!empty($default)) && ($default == $content['menu'])) {
539                                 $OUT .= ' selected="selected"';
540                         } // END - if
541                         $OUT .= '>' . $content['title'] . '</option>';
542                 } // END - while
543
544                 // Free memory
545                 SQL_FREERESULT($result);
546
547                 // Add closing select-tag
548                 $OUT .= '</select>';
549         } else {
550                 // No menus???
551                 $OUT = '{--ADMIN_PROBLEM_NO_MENU--}';
552         }
553
554         // Return output
555         return $OUT;
556 }
557
558 // Wrapper for $_POST and adminSaveSettings
559 function adminSaveSettingsFromPostData ($tableName = '_config', $whereStatement = '`config`=0', $translateComma = array(), $alwaysAdd = FALSE, $displayMessage = TRUE) {
560         // Get the array
561         $postData = postRequestArray();
562
563         // Call the lower function
564         adminSaveSettings($postData, $tableName, $whereStatement, $translateComma, $alwaysAdd, $displayMessage);
565 }
566
567 // Save settings to the database
568 function adminSaveSettings (&$postData, $tableName = '_config', $whereStatement = '`config`=0', $translateComma = array(), $alwaysAdd = FALSE, $displayMessage = TRUE) {
569         // Prepare all arrays, variables
570         $tableData = array();
571         $skip = FALSE;
572
573         // Now, walk through all entries and prepare them for saving
574         //* BUG: */ reportBug(__FUNCTION__, __LINE__, '<pre>'.print_r(postRequestArray(), TRUE).'</pre>');
575         foreach ($postData as $id => $val) {
576                 // Process only formular field but not submit buttons ;)
577                 if ($id == 'ok') {
578                         // Skip this button
579                         continue;
580                 } // END - if
581
582                 // Do not save the ok value
583                 convertSelectionsToEpocheTime($postData, $tableData, $id, $skip);
584
585                 // Shall we process this id? It muss not be empty, of course
586                 if (($skip === FALSE) && (!empty($id)) && ((!isset($GLOBALS['skip_config'][$id]))) || ($tableName != '_config')) {
587                         // Translate the value? (comma to dot!)
588                         if ((is_array($translateComma)) && (in_array($id, $translateComma))) {
589                                 // Then do it here... :)
590                                 $val = convertCommaToDot($val);
591                         } // END - if
592
593                         // Test value on float
594                         $test = (float) $val;
595
596                         // Debug message
597                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'test=' . $test . ',val=' . $val . ',id=' . $id);
598
599                         // Shall we add numbers or strings?
600                         if ('' . $val . '' == '' . $test . '') {
601                                 // Add numbers
602                                 array_push($tableData, sprintf("`%s`=%s", $id, $test));
603                         } elseif (is_null($val)) {
604                                 // Add NULL
605                                 array_push($tableData, sprintf("`%s`=NULL", $id));
606                         } else {
607                                 // Add strings
608                                 array_push($tableData, sprintf("`%s`='%s'", $id, trim($val)));
609                         }
610
611                         // Do not add a config entry twice
612                         $GLOBALS['skip_config'][$id] = TRUE;
613
614                         // Update current configuration
615                         setConfigEntry($id, $val);
616                 } // END - if
617         } // END - foreach
618
619         // Check if entry does exist
620         $result = FALSE;
621         if ($alwaysAdd === FALSE) {
622                 if (!empty($whereStatement)) {
623                         $result = SQL_QUERY("SELECT * FROM `{?_MYSQL_PREFIX?}" . $tableName . "` WHERE " . $whereStatement . " LIMIT 1", __FUNCTION__, __LINE__);
624                 } else {
625                         $result = SQL_QUERY("SELECT * FROM `{?_MYSQL_PREFIX?}" . $tableName . "` LIMIT 1", __FUNCTION__, __LINE__);
626                 }
627         } // END - if
628
629         if (SQL_NUMROWS($result) == 1) {
630                 // "Implode" all data to single string
631                 $updatedData = implode(', ', $tableData);
632
633                 // Generate SQL string
634                 $sql = sprintf("UPDATE `{?_MYSQL_PREFIX?}%s` SET %s WHERE %s LIMIT 1",
635                         $tableName,
636                         $updatedData,
637                         $whereStatement
638                 );
639         } else {
640                 // Add Line (does only work with AUTO_INCREMENT!
641                 $keys = array(); $values = array();
642                 foreach ($tableData as $entry) {
643                         // Split up
644                         $line = explode('=', $entry);
645                         array_push($keys  , $line[0]);
646                         array_push($values, $line[1]);
647                 } // END - foreach
648
649                 // Add both in one line
650                 $keys   = implode('`, `', $keys);
651                 $values = implode(', '  , $values);
652
653                 // Generate SQL string
654                 $sql = sprintf("INSERT INTO `{?_MYSQL_PREFIX?}%s` (%s) VALUES (%s)",
655                         $tableName,
656                         $keys,
657                         $values
658                 );
659         }
660
661         // Free memory
662         SQL_FREERESULT($result);
663
664         // Simply run generated SQL string
665         SQL_QUERY($sql, __FUNCTION__, __LINE__);
666
667         // Remember affected rows
668         $affected = SQL_AFFECTEDROWS();
669
670         // Rebuild cache
671         rebuildCache('config', 'config');
672
673         // Settings saved, so display message?
674         if ($displayMessage === TRUE) {
675                 // Display a message
676                 displayMessage('{--SETTINGS_SAVED--}');
677         } // END - if
678
679         // Return affected rows
680         return $affected;
681 }
682
683 // Generate a selection box
684 function adminAddMenuSelectionBox ($menu, $type, $name, $default = '') {
685         // Open the requested menu directory
686         $menuArray = getArrayFromDirectory(sprintf("inc/modules/%s/", $menu), $type . '-', FALSE, FALSE);
687
688         // Init the selection box
689         $OUT = '<select name="' . $name . '" class="form_select" size="1"><option value="">{--ADMIN_IS_TOP_MENU--}</option>';
690
691         // Walk through all files
692         foreach ($menuArray as $file) {
693                 // Is this a PHP script?
694                 if ((!isDirectory($file)) && (isInString('' . $type . '-', $file)) && (isInString('.php', $file))) {
695                         // Then test if the file is readable
696                         $test = sprintf("inc/modules/%s/%s", $menu, $file);
697
698                         // Is the file there?
699                         if (isIncludeReadable($test)) {
700                                 // Extract the value for what=xxx
701                                 $part = substr($file, (strlen($type) + 1));
702                                 $part = substr($part, 0, -4);
703
704                                 // Is that part different from the overview?
705                                 if ($part != 'welcome') {
706                                         $OUT .= '<option value="' . $part . '"';
707                                         if ($part == $default) {
708                                                 $OUT .= ' selected="selected"';
709                                         } // END - if
710                                         $OUT .= '>' . $part . '</option>';
711                                 } // END - if
712                         } // END - if
713                 } // END - if
714         } // END - foreach
715
716         // Close selection box
717         $OUT .= '</select>';
718
719         // Return contents
720         return $OUT;
721 }
722
723 // Creates a user-profile link for the admin. This function can also be used for many other purposes
724 function generateUserProfileLink ($userid, $title = '', $what = '') {
725         // Is there cache?
726         if (!isset($GLOBALS[__FUNCTION__][$userid][$title . '_' . $what])) {
727                 // Is title empty and valid userid?
728                 if (($title == '') && (isValidUserId($userid))) {
729                         // Set userid as title
730                         $title = $userid;
731                 } elseif (!isValidUserId($userid)) {
732                         // User id zero is invalid
733                         return '<strong>' . convertNullToZero($userid) . '</strong>';
734                 }
735
736                 // Is what set?
737                 if (empty($what)) {
738                         // Then get it to 'list_user'
739                         $what = 'list_user';
740                 } // END - if
741
742                 if (($title == '0') && ($what == 'list_refs')) {
743                         // Return title again
744                         return $title;
745                 } elseif (!empty($title)) {
746                         // Not empty, so skip next one
747                 } elseif (isExtensionActive('nickname')) {
748                         // Get nickname
749                         $nick = getNickname($userid);
750
751                         // Is it not empty, use it as title else the userid
752                         if (!empty($nick)) {
753                                 $title = $nick . '(' . $userid . ')';
754                         } else {
755                                 $title = $userid;
756                         }
757                 }
758
759                 // Set it in cache
760                 $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>]';
761         } // END - if
762
763         // Return cache
764         return $GLOBALS[__FUNCTION__][$userid][$title . '_' . $what];
765 }
766
767 // Check "logical-area-mode"
768 function adminGetMenuMode () {
769         // Set the default menu mode as the mode for all admins
770         $mode = 'global';
771
772         // If ext-sql_patches is up-to-date enough, use the configuration
773         if (isExtensionInstalledAndNewer('sql_patches', '0.3.2')) {
774                 $mode = getAdminMenu();
775         } // END - if
776
777         // Backup it
778         $adminMode = $mode;
779
780         // Get admin id
781         $adminId = getCurrentAdminId();
782
783         // Check individual settings of current admin
784         if (isset($GLOBALS['cache_array']['admin']['la_mode'][$adminId])) {
785                 // Load from cache
786                 $adminMode = $GLOBALS['cache_array']['admin']['la_mode'][$adminId];
787                 incrementStatsEntry('cache_hits');
788         } elseif (isExtensionInstalledAndNewer('admins', '0.6.7')) {
789                 // Load from database when version of 'admins' is enough
790                 $result = SQL_QUERY_ESC("SELECT `la_mode` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
791                         array($adminId), __FUNCTION__, __LINE__);
792
793                 // Is there an entry?
794                 if (SQL_NUMROWS($result) == 1) {
795                         // Load data
796                         list($adminMode) = SQL_FETCHROW($result);
797                 } // END - if
798
799                 // Free memory
800                 SQL_FREERESULT($result);
801         }
802
803         // Check what the admin wants and set it when it's not the default mode
804         if ($adminMode != 'global') {
805                 $mode = $adminMode;
806         } // END - if
807
808         // Return admin-menu's mode
809         return $mode;
810 }
811
812 // Change activation status
813 function adminChangeActivationStatus ($IDs, $table, $row, $idRow = 'id') {
814         $count = '0';
815         if ((is_array($IDs)) && (count($IDs) > 0)) {
816                 // "Walk" all through and count them
817                 foreach ($IDs as $id => $selected) {
818                         // Secure the id number
819                         $id = bigintval($id);
820
821                         // Should always be set... ;-)
822                         if (!empty($selected)) {
823                                 // Determine new status
824                                 $result = SQL_QUERY_ESC("SELECT %s FROM `{?_MYSQL_PREFIX?}_%s` WHERE %s=%s LIMIT 1",
825                                         array(
826                                                 $row,
827                                                 $table,
828                                                 $idRow,
829                                                 $id
830                                         ), __FUNCTION__, __LINE__);
831
832                                 // Row found?
833                                 if (SQL_NUMROWS($result) == 1) {
834                                         // Load the status
835                                         list($currStatus) = SQL_FETCHROW($result);
836
837                                         // And switch it N<->Y
838                                         $newStatus = convertBooleanToYesNo(!($currStatus == 'Y'));
839
840                                         // Change this status
841                                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s` SET %s='%s' WHERE %s=%s LIMIT 1",
842                                                 array(
843                                                         $table,
844                                                         $row,
845                                                         $newStatus,
846                                                         $idRow,
847                                                         $id
848                                                 ), __FUNCTION__, __LINE__);
849
850                                         // Count up affected rows
851                                         $count += SQL_AFFECTEDROWS();
852                                 } // END - if
853
854                                 // Free the result
855                                 SQL_FREERESULT($result);
856                         } // END - if
857                 } // END - foreach
858
859                 // Output status
860                 displayMessage(sprintf(getMessage('ADMIN_STATUS_CHANGED'), $count, count($IDs)));
861         } else {
862                 // Nothing selected!
863                 displayMessage('{--ADMIN_NOTHING_SELECTED_CHANGE--}');
864         }
865 }
866
867 // Build a special template list
868 function adminListBuilder ($listType, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId = array('userid')) {
869         // Call inner (general) function
870         doGenericListBuilder('admin', $listType, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId);
871 }
872
873 // Change status of "build" list
874 function adminBuilderStatusHandler ($mode, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray, $rawUserId = array('userid'), $cacheFiles = array()) {
875         // $tableName must be an array
876         if ((!is_array($tableName)) || (count($tableName) != 1)) {
877                 // No tableName specified
878                 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
879         } elseif (!is_array($idColumn)) {
880                 // $idColumn is no array
881                 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
882         } elseif ((!is_array($userIdColumn)) || (count($userIdColumn) != 1)) {
883                 // $tableName is no array
884                 reportBug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array: userIdColumn=' . $userIdColumn);
885         } // END - if
886
887         // "Walk" through all entries
888         foreach (postRequestElement($idColumn[0]) as $id => $sel) {
889                 // Construct SQL query
890                 $sql = sprintf("UPDATE `{?_MYSQL_PREFIX?}_%s` SET", SQL_ESCAPE($tableName[0]));
891
892                 // Load data of entry
893                 $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`=%s LIMIT 1",
894                         array(
895                                 $tableName[0],
896                                 $idColumn[0],
897                                 $id
898                         ), __FUNCTION__, __LINE__);
899
900                 // Fetch the data
901                 $content = SQL_FETCHARRAY($result);
902
903                 // Free the result
904                 SQL_FREERESULT($result);
905
906                 // Add all status entries (e.g. status column last_updated or so)
907                 $newStatus = 'UNKNOWN';
908                 $oldStatus = 'UNKNOWN';
909                 $statusColumn = 'unknown';
910                 foreach ($statusArray as $column => $statusInfo) {
911                         // Does the entry exist?
912                         if ((isset($content[$column])) && (isset($statusInfo[$content[$column]]))) {
913                                 // Add these entries for update
914                                 $sql .= sprintf(" `%s`='%s',", SQL_ESCAPE($column), SQL_ESCAPE($statusInfo[$content[$column]]));
915
916                                 // Remember status
917                                 if ($statusColumn == 'unknown') {
918                                         // Always (!!!) change status column first!
919                                         $oldStatus = $content[$column];
920                                         $newStatus = $statusInfo[$oldStatus];
921                                         $statusColumn = $column;
922                                 } // END - if
923                         } elseif (isset($content[$column])) {
924                                 // Unfinished!
925                                 reportBug(__FUNCTION__, __LINE__, ':UNFINISHED: id=' . $id . ',column=' . $column . '[' . gettype($statusInfo) . '] = ' . $content[$column]);
926                         }
927                 } // END - foreach
928
929                 // Add other columns as well
930                 foreach (postRequestArray() as $key => $entries) {
931                         // Debug message
932                         logDebugMessage(__FUNCTION__, __LINE__, 'Found entry: ' . $key);
933
934                         // Skip id, raw userid and 'do_$mode'
935                         if (!in_array($key, array($idColumn[0], $rawUserId[0], ('do_' . $mode)))) {
936                                 // Are there brackets () at the end?
937                                 if (substr($entries[$id], -2, 2) == '()') {
938                                         // Direct SQL command found
939                                         $sql .= sprintf(" `%s`=%s,", SQL_ESCAPE($key), SQL_ESCAPE($entries[$id]));
940                                 } else {
941                                         // Add regular entry
942                                         $sql .= sprintf(" `%s`='%s',", SQL_ESCAPE($key), SQL_ESCAPE($entries[$id]));
943
944                                         // Add entry
945                                         $content[$key] = $entries[$id];
946                                 }
947                         } else {
948                                 // Skipped entry
949                                 logDebugMessage(__FUNCTION__, __LINE__, 'Skipped: ' . $key);
950                         }
951                 } // END - foreach
952
953                 // Finish SQL statement
954                 $sql = substr($sql, 0, -1) . sprintf(" WHERE `%s`=%s AND `%s`='%s' LIMIT 1",
955                         $idColumn[0],
956                         bigintval($id),
957                         $statusColumn,
958                         $oldStatus
959                 );
960
961                 // Run the SQL
962                 SQL_QUERY($sql, __FUNCTION__, __LINE__);
963
964                 // Send "build mails" out
965                 sendGenericBuildMails($mode, $tableName, $content, $id, $statusInfo[$content[$column]], $userIdColumn);
966         } // END - foreach
967 }
968
969 // Delete rows by given id numbers
970 function adminDeleteEntriesConfirm ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $deleteNow = array(FALSE), $idColumn = array('id'), $userIdColumn = array('userid'), $rawUserId = array('userid'), $cacheFiles = array()) {
971         // $tableName must be an array
972         if ((!is_array($tableName)) || (count($tableName) != 1)) {
973                 // No tableName specified
974                 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
975         } elseif (!is_array($idColumn)) {
976                 // $idColumn is no array
977                 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
978         } elseif (!is_array($userIdColumn)) {
979                 // $userIdColumn is no array
980                 reportBug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array: userIdColumn=' . $userIdColumn);
981         } elseif (!is_array($deleteNow)) {
982                 // $deleteNow is no array
983                 reportBug(__FUNCTION__, __LINE__, 'deleteNow[]=' . gettype($deleteNow) . '!=array: userIdColumn=' . $userIdColumn);
984         } // END - if
985
986         // Shall we delete here or list for deletion?
987         if ($deleteNow[0] === TRUE) {
988                 // Call generic function
989                 $affected = doGenericDeleteEntriesConfirm($tableName, $columns, $filterFunctions, $extraValues, $deleteNow, $idColumn, $userIdColumn, $rawUserId, $cacheFiles);
990
991                 // Was this fine?
992                 if ($affected == countPostSelection($idColumn[0])) {
993                         // All deleted
994                         displayMessage('{--ADMIN_ALL_ENTRIES_REMOVED--}');
995                 } else {
996                         // Some are still there :(
997                         displayMessage(sprintf(getMessage('ADMIN_SOME_ENTRIES_NOT_DELETED'), SQL_AFFECTEDROWS(), countPostSelection($idColumn[0])));
998                 }
999         } else {
1000                 // List for deletion confirmation
1001                 adminListBuilder('delete', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1002         }
1003 }
1004
1005 // Edit rows by given id numbers
1006 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()) {
1007         // $tableName must be an array
1008         if ((!is_array($tableName)) || (count($tableName) != 1)) {
1009                 // No tableName specified
1010                 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
1011         } elseif (!is_array($idColumn)) {
1012                 // $idColumn is no array
1013                 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
1014         } elseif (!is_array($userIdColumn)) {
1015                 // $userIdColumn is no array
1016                 reportBug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array: userIdColumn=' . $userIdColumn);
1017         } elseif (!is_array($editNow)) {
1018                 // $editNow is no array
1019                 reportBug(__FUNCTION__, __LINE__, 'editNow[]=' . gettype($editNow) . '!=array: userIdColumn=' . $userIdColumn);
1020         } // END - if
1021
1022         // Shall we change here or list for editing?
1023         if ($editNow[0] === TRUE) {
1024                 // Call generic change method
1025                 $affected = doGenericEditEntriesConfirm($tableName, $columns, $filterFunctions, $extraValues, $timeColumns, $editNow, $idColumn, $userIdColumn, $rawUserId, $cacheFiles);
1026
1027                 // Was this fine?
1028                 if ($affected == countPostSelection($idColumn[0])) {
1029                         // All deleted
1030                         displayMessage('{--ADMIN_ALL_ENTRIES_EDITED--}');
1031                 } else {
1032                         // Some are still there :(
1033                         displayMessage(sprintf(getMessage('ADMIN_SOME_ENTRIES_NOT_EDITED'), $affected, countPostSelection($idColumn[0])));
1034                 }
1035         } else {
1036                 // List for editing
1037                 adminListBuilder('edit', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1038         }
1039 }
1040
1041 // Un-/lock rows by given id numbers
1042 function adminLockEntriesConfirm ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $statusArray = array(), $lockNow = array(FALSE), $idColumn = array('id'), $userIdColumn = array('userid')) {
1043         // $tableName must be an array
1044         if ((!is_array($tableName)) || (count($tableName) != 1)) {
1045                 // No tableName specified
1046                 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
1047         } elseif (!is_array($idColumn)) {
1048                 // $idColumn is no array
1049                 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
1050         } elseif (!is_array($lockNow)) {
1051                 // $lockNow is no array
1052                 reportBug(__FUNCTION__, __LINE__, 'lockNow[]=' . gettype($lockNow) . '!=array: userIdColumn=' . $userIdColumn);
1053         } // END - if
1054
1055         // Shall we un-/lock here or list for locking?
1056         if ($lockNow[0] === TRUE) {
1057                 // Un-/lock entries
1058                 adminBuilderStatusHandler('lock', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray);
1059         } else {
1060                 // List for editing
1061                 adminListBuilder('lock', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1062         }
1063 }
1064
1065 // Undelete rows by given id numbers
1066 function adminUndeleteEntriesConfirm ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $statusArray = array(), $undeleteNow = array(FALSE), $idColumn = array('id'), $userIdColumn = array('userid')) {
1067         // $tableName must be an array
1068         if ((!is_array($tableName)) || (count($tableName) != 1)) {
1069                 // No tableName specified
1070                 reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
1071         } elseif (!is_array($idColumn)) {
1072                 // $idColumn is no array
1073                 reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
1074         } elseif (!is_array($undeleteNow)) {
1075                 // $undeleteNow is no array
1076                 reportBug(__FUNCTION__, __LINE__, 'undeleteNow[]=' . gettype($undeleteNow) . '!=array: userIdColumn=' . $userIdColumn);
1077         } // END - if
1078
1079         // Shall we un-/lock here or list for locking?
1080         if ($undeleteNow[0] === TRUE) {
1081                 // Undelete entries
1082                 adminBuilderStatusHandler('undelete', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray);
1083         } else {
1084                 // List for editing
1085                 adminListBuilder('undelete', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1086         }
1087 }
1088
1089 // Adds a given entry to the database
1090 function adminAddEntries ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $timeColumns = array(), $columnIndex = NULL) {
1091         // Is the userid set?
1092         if (!isPostRequestElementSet('userid')) {
1093                 // Then set NULL here
1094                 setPostRequestElement('userid', NULL);
1095         } // END - if
1096
1097         // Call inner function
1098         doGenericAddEntries($tableName, $columns, $filterFunctions, $extraValues, $timeColumns, $columnIndex);
1099
1100         // Entry has been added?
1101         if ((!SQL_HASZEROAFFECTED()) && ($GLOBALS['__XML_PARSE_RESULT'] === TRUE)) {
1102                 // Display success message
1103                 displayMessage('{--ADMIN_ENTRY_ADDED--}');
1104         } else {
1105                 // Display failed message
1106                 displayMessage('{--ADMIN_ENTRY_NOT_ADDED--}');
1107         }
1108 }
1109
1110 // Checks proxy settins by fetching check-updates3.php from mxchange.org
1111 function adminTestProxySettings ($settingsArray) {
1112         // Set temporary the new settings
1113         mergeConfig($settingsArray);
1114
1115         // Now get the test URL
1116         $content = sendGetRequest('check-updates3.php');
1117
1118         // Is the first line with "200 OK"?
1119         $valid = isInString('200 OK', $content[0]);
1120
1121         // Return result
1122         return $valid;
1123 }
1124
1125 // Sends out a link to the given email adress so the admin can reset his/her password
1126 function sendAdminPasswordResetLink ($email) {
1127         // Init output
1128         $OUT = '';
1129
1130         // Look up administator login
1131         $result = SQL_QUERY_ESC("SELECT `id`, `login`, `password` FROM `{?_MYSQL_PREFIX?}_admins` WHERE '%s' REGEXP `email` LIMIT 1",
1132                 array($email), __FUNCTION__, __LINE__);
1133
1134         // Is there an account?
1135         if (SQL_HASZERONUMS($result)) {
1136                 // No account found
1137                 return '{--ADMIN_NO_LOGIN_WITH_EMAIL--}';
1138         } // END - if
1139
1140         // Load all data
1141         $content = SQL_FETCHARRAY($result);
1142
1143         // Free result
1144         SQL_FREERESULT($result);
1145
1146         // Generate hash for reset link
1147         $content['hash'] = generateHash(getUrl() . getEncryptSeparator() . $content['id'] . getEncryptSeparator() . $content['login'] . getEncryptSeparator() . $content['password'], substr($content['password'], getSaltLength()));
1148
1149         // Remove some data
1150         unset($content['id']);
1151         unset($content['password']);
1152
1153         // Prepare email
1154         $mailText = loadEmailTemplate('admin_reset_password', $content);
1155
1156         // Send it out
1157         sendEmail($email, '{--ADMIN_RESET_PASSWORD_LINK_SUBJECT--}', $mailText);
1158
1159         // Prepare output
1160         return '{--ADMIN_RESET_PASSWORD_LINK_SENT--}';
1161 }
1162
1163 // Validate hash and login for password reset
1164 function adminResetValidateHashLogin ($hash, $login) {
1165         // By default nothing validates... ;)
1166         $valid = FALSE;
1167
1168         // Then try to find that user
1169         $result = SQL_QUERY_ESC("SELECT `id`, `password`, `email` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
1170                 array($login), __FUNCTION__, __LINE__);
1171
1172         // Is an account here?
1173         if (SQL_NUMROWS($result) == 1) {
1174                 // Load all data
1175                 $content = SQL_FETCHARRAY($result);
1176
1177                 // Generate hash again
1178                 $hashFromData = generateHash(getUrl() . getEncryptSeparator() . $content['id'] . getEncryptSeparator() . $login . getEncryptSeparator() . $content['password'], substr($content['password'], getSaltLength()));
1179
1180                 // Does both match?
1181                 $valid = ($hash == $hashFromData);
1182         } // END - if
1183
1184         // Free result
1185         SQL_FREERESULT($result);
1186
1187         // Return result
1188         return $valid;
1189 }
1190
1191 // Reset the password for the login. Do NOT call this function without calling above function first!
1192 function doResetAdminPassword ($login, $password) {
1193         // Generate hash (we already check for ext-sql_patches in generateHash())
1194         $passHash = generateHash($password);
1195
1196         // Prepare fake POST data
1197         $postData = array(
1198                 'login'    => array(getAdminId($login) => $login),
1199                 'password' => array(getAdminId($login) => $passHash),
1200         );
1201
1202         // Update database
1203         $message = adminsChangeAdminAccount($postData, '', FALSE);
1204
1205         // Run filters
1206         runFilterChain('post_form_reset_pass', array('login' => $login, 'hash' => $passHash, 'message' => $message));
1207
1208         // Return output
1209         return '{--ADMIN_PASSWORD_RESET_DONE--}';
1210 }
1211
1212 // Solves a task by given id number
1213 function adminSolveTask ($id) {
1214         // Update the task data
1215         adminUpdateTaskData($id, 'status', 'SOLVED');
1216 }
1217
1218 // Marks a given task as deleted
1219 function adminDeleteTask ($id) {
1220         // Update the task data
1221         adminUpdateTaskData($id, 'status', 'DELETED');
1222 }
1223
1224 // Function to update task data
1225 function adminUpdateTaskData ($id, $row, $data) {
1226         // Should be admin and valid id
1227         if (!isAdmin()) {
1228                 // Not an admin so redirect better
1229                 reportBug(__FUNCTION__, __LINE__, 'id=' . $id . ',row=' . $row . ',data=' . $data . ' - isAdmin()=false');
1230         } elseif ($id <= 0) {
1231                 // Initiate backtrace
1232                 reportBug(__FUNCTION__, __LINE__, sprintf("id is invalid: %s. row=%s, data=%s",
1233                         $id,
1234                         $row,
1235                         $data
1236                 ));
1237         } // END - if
1238
1239         // Update the task
1240         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_task_system` SET `%s`='%s' WHERE `id`=%s LIMIT 1",
1241                 array(
1242                         $row,
1243                         $data,
1244                         bigintval($id)
1245                 ), __FUNCTION__, __LINE__);
1246 }
1247
1248 // Checks whether if the admin menu has entries
1249 function ifAdminMenuHasEntries ($action) {
1250         return (
1251                 ((
1252                         // Is the entry set?
1253                         isset($GLOBALS['admin_menu_has_entries'][$action])
1254                 ) && (
1255                         // And do we have a menu for this action?
1256                         $GLOBALS['admin_menu_has_entries'][$action] === TRUE
1257                 )) || (
1258                         // Login has always a menu
1259                         $action == 'login'
1260                 )
1261         );
1262 }
1263
1264 // Setter for 'admin_menu_has_entries'
1265 function setAdminMenuHasEntries ($action, $hasEntries) {
1266         $GLOBALS['admin_menu_has_entries'][$action] = (bool) $hasEntries;
1267 }
1268
1269 // Creates a link to the user's admin-profile
1270 function adminCreateUserLink ($userid) {
1271         // Is the userid set correctly?
1272         if (isValidUserId($userid)) {
1273                 // Create a link to that profile
1274                 return '{%url=modules.php?module=admin&amp;what=list_user&amp;userid=' . bigintval($userid) . '%}';
1275         } // END - if
1276
1277         // Return a link to the user list
1278         return '{%url=modules.php?module=admin&amp;what=list_user%}';
1279 }
1280
1281 // Generate a "link" for the given admin id (admin_id)
1282 function generateAdminLink ($adminId) {
1283         // No assigned admin is default
1284         $adminLink = '{--ADMIN_NO_ADMIN_ASSIGNED--}';
1285
1286         // Zero? = Not assigned
1287         if (isValidUserId($adminId)) {
1288                 // Load admin's login
1289                 $login = getAdminLogin($adminId);
1290
1291                 // Is the login valid?
1292                 if ($login != '***') {
1293                         // Is the extension there?
1294                         if (isExtensionActive('admins')) {
1295                                 // Admin found
1296                                 $adminLink = '<a href="' . generateEmailLink(getAdminEmail($adminId), 'admins') . '" title="{--ADMIN_CONTACT_LINK_TITLE--}">' . $login . '</a>';
1297                         } else {
1298                                 // Extension not found
1299                                 $adminLink = '{%message,ADMIN_TASK_ROW_EXTENSION_NOT_INSTALLED=admins%}';
1300                         }
1301                 } else {
1302                         // Maybe deleted?
1303                         $adminLink = '<div class="bad">{%message,ADMIN_ID_404=' . $adminId . '%}</div>';
1304                 }
1305         } // END - if
1306
1307         // Return result
1308         return $adminLink;
1309 }
1310
1311 // Verifies if the current admin has confirmed to alter expert settings
1312 //
1313 // Return values:
1314 // 'failed'    = Something goes wrong (default)
1315 // 'agreed'    = Has verified and and confirmed it to see them
1316 // 'forbidden' = Has not the proper right to alter them
1317 // 'update'    = Need to update extension 'admins'
1318 // 'ask'       = A form was send to the admin
1319 function doVerifyExpertSettings () {
1320         // Default return status is failed
1321         $return = 'failed';
1322
1323         // Is the extension installed and recent?
1324         if (isExtensionInstalledAndNewer('admins', '0.7.3')) {
1325                 // Okay, load the status
1326                 $expertSettings = getAminsExpertSettings();
1327
1328                 // Is he allowed?
1329                 if ($expertSettings == 'Y') {
1330                         // Okay, does he want to see them?
1331                         if (isAdminsExpertWarningEnabled()) {
1332                                 // Ask for them
1333                                 if (isFormSent()) {
1334                                         // Is the element set, then we need to change the admin
1335                                         if (isPostRequestElementSet('expert_settings')) {
1336                                                 // Get it and prepare final post data array
1337                                                 $postData['login'][getCurrentAdminId()] = getCurrentAdminLogin();
1338                                                 $postData['expert_warning'][getCurrentAdminId()] = 'N';
1339
1340                                                 // Change it in the admin
1341                                                 adminsChangeAdminAccount($postData, 'expert_warning');
1342                                         } // END - if
1343
1344                                         // All fine!
1345                                         $return = 'agreed';
1346                                 } else {
1347                                         // Send form
1348                                         loadTemplate('admin_expert_settings_form');
1349
1350                                         // Asked for it
1351                                         $return = 'ask';
1352                                 }
1353                         } else {
1354                                 // Do not display
1355                                 $return = 'agreed';
1356                         }
1357
1358                         // Is a form sent?
1359                         if ((isFormSent()) && (isPostRequestElementSet('expert_settings'))) {
1360                                 // Clear form
1361                                 unsetPostRequestElement('ok');
1362                                 unsetPostRequestElement('expert_settings');
1363                         } // END - if
1364                 } else {
1365                         // Forbidden
1366                         $return = 'forbidden';
1367                 }
1368         } else {
1369                 // Out-dated extension or not installed
1370                 $return = 'update';
1371         }
1372
1373         // Output message for other status than ask/agreed
1374         if (($return != 'ask') && ($return != 'agreed')) {
1375                 // Output message
1376                 displayMessage('{--ADMIN_EXPERT_SETTINGS_STATUS_' . strtoupper($return) . '--}');
1377         } // END - if
1378
1379         // Return status
1380         return $return;
1381 }
1382
1383 // Generate link to unconfirmed mails for admin
1384 function generateUnconfirmedAdminLink ($id, $unconfirmed, $type = 'bid') {
1385         // Init output
1386         $OUT = $unconfirmed;
1387
1388         // Is there unconfirmed mails?
1389         if ($unconfirmed > 0) {
1390                 // Add link to list_unconfirmed what-file
1391                 $OUT = '<a href="{%url=modules.php?module=admin&amp;what=list_unconfirmed&amp;' . $type . '=' . $id . '%}">{%pipe,translateComma=' . $unconfirmed . '%}</a>';
1392         } // END - if
1393
1394         // Return it
1395         return $OUT;
1396 }
1397
1398 // Generates a navigation row for listing emails
1399 function addEmailNavigation ($numPages, $offset, $show_form, $colspan, $return=false) {
1400         // Don't do anything if $numPages is 1
1401         if ($numPages == 1) {
1402                 // Abort here with empty content
1403                 return '';
1404         } // END - if
1405
1406         $TOP = '';
1407         if ($show_form === FALSE) {
1408                 $TOP = ' top';
1409         } // END - if
1410
1411         $NAV = '';
1412         for ($page = 1; $page <= $numPages; $page++) {
1413                 // Is the page currently selected or shall we generate a link to it?
1414                 if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
1415                         // Is currently selected, so only highlight it
1416                         $NAV .= '<strong>-';
1417                 } else {
1418                         // Open anchor tag and add base URL
1419                         $NAV .= '<a href="{%url=modules.php?module=admin&amp;what=' . getWhat() . '&amp;page=' . $page . '&amp;offset=' . $offset;
1420
1421                         // Add userid when we shall show all mails from a single member
1422                         if ((isGetRequestElementSet('userid')) && (isValidUserId(getRequestElement('userid')))) $NAV .= '&amp;userid=' . bigintval(getRequestElement('userid'));
1423
1424                         // Close open anchor tag
1425                         $NAV .= '%}">';
1426                 }
1427                 $NAV .= $page;
1428                 if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
1429                         // Is currently selected, so only highlight it
1430                         $NAV .= '-</strong>';
1431                 } else {
1432                         // Close anchor tag
1433                         $NAV .= '</a>';
1434                 }
1435
1436                 // Add separator if we have not yet reached total pages
1437                 if ($page < $numPages) {
1438                         // Add it
1439                         $NAV .= '|';
1440                 } // END - if
1441         } // END - for
1442
1443         // Define constants only once
1444         $content['nav']  = $NAV;
1445         $content['span'] = $colspan;
1446         $content['top']  = $TOP;
1447
1448         // Load navigation template
1449         $OUT = loadTemplate('admin_email_nav_row', TRUE, $content);
1450
1451         if ($return === TRUE) {
1452                 // Return generated HTML-Code
1453                 return $OUT;
1454         } else {
1455                 // Output HTML-Code
1456                 outputHtml($OUT);
1457         }
1458 }
1459
1460 // Process menu editing form
1461 function adminProcessMenuEditForm ($type, $subMenu) {
1462         // An action is done...
1463         foreach (postRequestElement('sel') as $sel => $menu) {
1464                 $AND = "(`what` = '' OR `what` IS NULL)";
1465
1466                 $sel = bigintval($sel);
1467
1468                 if (!empty($subMenu)) {
1469                         $AND = "`action`='" . $subMenu . "'";
1470                 } // END - if
1471
1472                 switch (postRequestElement('ok')) {
1473                         case 'edit': // Edit menu
1474                                 // Shall we update a menu or sub menu?
1475                                 if (!isGetRequestElementSet('sub')) {
1476                                         // Update with 'what'=null
1477                                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET `title`='%s',`action`='%s',`what`=NULL WHERE ".$AND." AND `id`=%s LIMIT 1",
1478                                                 array(
1479                                                         $type,
1480                                                         $menu,
1481                                                         postRequestElement('sel_action', $sel),
1482                                                         $sel
1483                                                 ), __FUNCTION__, __LINE__);
1484                                 } else {
1485                                         // Update with selected 'what'
1486                                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET `title`='%s',`action`='%s',`what`='%s' WHERE ".$AND." AND `id`=%s LIMIT 1",
1487                                                 array(
1488                                                         $type,
1489                                                         $menu,
1490                                                         postRequestElement('sel_action', $sel),
1491                                                         postRequestElement('sel_what', $sel),
1492                                                         $sel
1493                                                 ), __FUNCTION__, __LINE__);
1494                                 }
1495                                 break;
1496
1497                         case 'delete': // Delete menu
1498                                 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE ".$AND." AND `id`=%s LIMIT 1",
1499                                         array(
1500                                                 $type,
1501                                                 $sel
1502                                         ), __FUNCTION__, __LINE__);
1503                                 break;
1504
1505                         case 'status': // Change status of menus
1506                                 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET `visible`='%s',`locked`='%s' WHERE ".$AND." AND `id`=%s LIMIT 1",
1507                                         array(
1508                                                 $type,
1509                                                 postRequestElement('visible', $sel),
1510                                                 postRequestElement('locked', $sel),
1511                                                 $sel
1512                                         ), __FUNCTION__, __LINE__);
1513                                 break;
1514
1515                         default: // Unexpected action
1516                                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unsupported action %s detected.", postRequestElement('ok')));
1517                                 displayMessage('{%message,ADMIN_UNKNOWN_OKAY=' . postRequestElement('ok') . '%}');
1518                                 break;
1519                 } // END - switch
1520         } // END - foreach
1521
1522         // Load template
1523         displayMessage('{--SETTINGS_SAVED--}');
1524 }
1525
1526 // Handle weightning
1527 function doAdminProcessMenuWeightning ($type, $AND) {
1528         // Are there all required (generalized) GET parameter?
1529         if ((isGetRequestElementSet('act')) && (isGetRequestElementSet('tid')) && (isGetRequestElementSet('fid'))) {
1530                 // Init variables
1531                 $tid = ''; $fid = '';
1532
1533                 // Get ids
1534                 if (isGetRequestElementSet('w')) {
1535                         // Sub menus selected
1536                         $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `action`='%s' AND `sort`=%s LIMIT 1",
1537                                 array(
1538                                         $type,
1539                                         getRequestElement('act'),
1540                                         bigintval(getRequestElement('tid'))
1541                                 ), __FUNCTION__, __LINE__);
1542                         list($tid) = SQL_FETCHROW($result);
1543                         SQL_FREERESULT($result);
1544                         $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `action`='%s' AND `sort`=%s LIMIT 1",
1545                                 array(
1546                                         $type,
1547                                         getRequestElement('act'),
1548                                         bigintval(getRequestElement('fid'))
1549                                 ), __FUNCTION__, __LINE__);
1550                         list($fid) = SQL_FETCHROW($result);
1551                         SQL_FREERESULT($result);
1552                 } else {
1553                         // Main menu selected
1554                         $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE (`what`='' OR `what` IS NULL) AND `sort`=%s LIMIT 1",
1555                                 array(
1556                                         $type,
1557                                         bigintval(getRequestElement('tid'))
1558                                 ), __FUNCTION__, __LINE__);
1559                         list($tid) = SQL_FETCHROW($result);
1560                         SQL_FREERESULT($result);
1561                         $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE (`what`='' OR `what` IS NULL) AND `sort`=%s LIMIT 1",
1562                                 array(
1563                                         $type,
1564                                         bigintval(getRequestElement('fid'))
1565                                 ), __FUNCTION__, __LINE__);
1566                         list($fid) = SQL_FETCHROW($result);
1567                         SQL_FREERESULT($result);
1568                 }
1569
1570                 if ((!empty($tid)) && (!empty($fid))) {
1571                         // Sort menu
1572                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET `sort`=%s WHERE ".$AND." AND `id`=%s LIMIT 1",
1573                                 array(
1574                                         $type,
1575                                         bigintval(getRequestElement('tid')),
1576                                         bigintval($fid)
1577                                 ), __FUNCTION__, __LINE__);
1578                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET `sort`=%s WHERE ".$AND." AND `id`=%s LIMIT 1",
1579                                 array(
1580                                         $type,
1581                                         bigintval(getRequestElement('fid')),
1582                                         bigintval($tid)
1583                                 ), __FUNCTION__, __LINE__);
1584                 } // END - if
1585         } // END - if
1586 }
1587
1588 // [EOF]
1589 ?>