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