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