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