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