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