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