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