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