New wrapper functions introduced
[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  * Copyright (c) 2009, 2010 by Mailer Developer Team                    *
22  * For more information visit: http://www.mxchange.org                  *
23  *                                                                      *
24  * This program is free software; you can redistribute it and/or modify *
25  * it under the terms of the GNU General Public License as published by *
26  * the Free Software Foundation; either version 2 of the License, or    *
27  * (at your option) any later version.                                  *
28  *                                                                      *
29  * This program is distributed in the hope that it will be useful,      *
30  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
31  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
32  * GNU General Public License for more details.                         *
33  *                                                                      *
34  * You should have received a copy of the GNU General Public License    *
35  * along with this program; if not, write to the Free Software          *
36  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
37  * MA  02110-1301  USA                                                  *
38  ************************************************************************/
39
40 // Some security stuff...
41 if (!defined('__SECURITY')) {
42         die();
43 } // END - if
44
45 // Register an administrator account
46 function addAdminAccount ($adminLogin, $passHash, $adminEmail) {
47         // Login does already exist
48         $ret = 'already';
49
50         // Lookup the admin
51         $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
52                 array($adminLogin), __FUNCTION__, __LINE__);
53
54         // Is the entry there?
55         if (SQL_HASZERONUMS($result)) {
56                 // Ok, let's create the admin login
57                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_admins` (`login`, `password`, `email`) VALUES ('%s', '%s', '%s')",
58                         array(
59                                 $adminLogin,
60                                 $passHash,
61                                 $adminEmail
62                         ), __FUNCTION__, __LINE__);
63
64                 // All done
65                 $ret = 'done';
66         } // END - if
67
68         // Free memory
69         SQL_FREERESULT($result);
70
71         // Return result
72         return $ret;
73 }
74
75 // This function will be executed when the admin is not logged in and has submitted his login data
76 function ifAdminLoginDataIsValid ($adminLogin, $adminPassword) {
77         // First of all, no admin login is found
78         $ret = '404';
79
80         // Get admin id from login
81         $adminId = getAdminId($adminLogin);
82
83         // Continue only with found admin ids
84         if ($adminId > 0) {
85                 // Then we need to lookup the login name by getting the admin hash
86                 $adminHash = getAdminHash($adminId);
87
88                 // If this is fine, we can continue
89                 if ($adminHash != '-1') {
90                         // Get admin id and set it as current
91                         setCurrentAdminId($adminId);
92
93                         // Now, we need to encode the password in the same way the one is encoded in database
94                         $testHash = generateHash($adminPassword, $adminHash);
95
96                         // If they both match, the login data is valid
97                         if ($testHash == $adminHash) {
98                                 // All fine
99                                 $ret = 'done';
100                         } else {
101                                 // Set status
102                                 $ret = 'pass';
103                         }
104                 } // END - if
105         } // END - if
106
107         // Prepare data array
108         $data = array(
109                 'id'         => $adminId,
110                 'login'      => $adminLogin,
111                 'plain_pass' => $adminPassword,
112                 'pass_hash'  => $adminHash
113         );
114
115         // Run a special filter
116         runFilterChain('do_admin_login_' . $ret, $data);
117
118         // Return status
119         return $ret;
120 }
121
122 // Only be executed on cookie checking
123 function ifAdminCookiesAreValid ($adminLogin, $passHash) {
124         // First of all, no admin login is found
125         $ret = '404';
126
127         // Then we need to lookup the login name by getting the admin hash
128         $adminHash = getAdminHash($adminLogin);
129
130         // If this is fine, we can continue
131         if ($adminHash != '-1') {
132                 // Now, we need to encode the password in the same way the one is encoded in database
133                 $testHash = encodeHashForCookie($adminHash);
134                 //* DEBUG: */ debugOutput('adminLogin=' . $adminLogin . ',passHash='.$passHash.',adminHash='.$adminHash.',testHash='.$testHash);
135
136                 // If they both match, the login data is valid
137                 if ($testHash == $passHash) {
138                         // All fine
139                         $ret = 'done';
140                 } else {
141                         // Set status
142                         $ret = 'pass';
143                 }
144         } // END - if
145
146         // Return status
147         //* DEBUG: */ debugOutput('ret='.$ret);
148         return $ret;
149 }
150
151 // Do an admin action
152 function doAdminAction () {
153         // Get default what
154         $what = getWhat();
155
156         //* DEBUG: */ debugOutput(__LINE__.'*'.$what.'/'.getModule().'/'.getAction().'/'.getWhat().'*');
157
158         // Remove any spaces from variable
159         if (empty($what)) {
160                 // Default admin action is the overview page
161                 $what = 'overview';
162         } else {
163                 // Secure it
164                 $what = secureString($what);
165         }
166
167         // Get action value
168         $action = getActionFromModuleWhat(getModule(), $what);
169
170         // Define admin login name and id number
171         $content['login'] = getAdminLogin(getSession('admin_id'));
172         $content['id']    = getCurrentAdminId();
173
174         // Preload templates
175         if (isExtensionActive('admins')) {
176                 $content['welcome'] = loadTemplate('admin_welcome_admins', true, $content);
177         } else {
178                 $content['welcome'] = loadTemplate('admin_welcome', true, $content);
179         }
180         $content['footer'] = loadTemplate('admin_footer' , true, $content);
181         $content['menu']   = addAdminMenu($action, $what, true);
182
183         // Tableset header
184         loadTemplate('admin_main_header', false, $content);
185
186         // Check if action/what pair is valid
187         $result_action = SQL_QUERY_ESC("SELECT
188         `id`
189 FROM
190         `{?_MYSQL_PREFIX?}_admin_menu`
191 WHERE
192         `action`='%s' AND
193         (
194                 (
195                         `what`='%s' AND `what` != 'overview'
196                 ) OR (
197                         (
198                                 `what`='' OR `what` IS NULL
199                         ) AND (
200                                 '%s'='overview'
201                         )
202                 )
203         )
204 LIMIT 1",
205                 array(
206                         $action,
207                         $what,
208                         $what
209                 ), __FUNCTION__, __LINE__);
210
211         // Do we have an entry?
212         if (SQL_NUMROWS($result_action) == 1) {
213                 // Is valid but does the inlcude file exists?
214                 $inc = sprintf("inc/modules/admin/action-%s.php", $action);
215                 if ((isIncludeReadable($inc)) && (isMenuActionValid('admin', $action, $what)) && ($GLOBALS['acl_allow'] === true)) {
216                         // Ok, we finally load the admin action module
217                         loadInclude($inc);
218                 } elseif ($GLOBALS['acl_allow'] === false) {
219                         // Access denied
220                         loadTemplate('admin_menu_failed', false, getMaskedMessage('ADMIN_ACCESS_DENIED', $what));
221                 } else {
222                         // Include file not found! :-(
223                         loadTemplate('admin_menu_failed', false, getMaskedMessage('ADMIN_ACTION_404', $action));
224                 }
225         } else {
226                 // Invalid action/what pair found!
227                 loadTemplate('admin_menu_failed', false, getMaskedMessage('ADMIN_ACTION_INVALID', $action . '/' . $what));
228         }
229
230         // Free memory
231         SQL_FREERESULT($result_action);
232
233         // Tableset footer
234         loadTemplate('admin_main_footer', false, $content);
235 }
236
237 // Adds an admin menu
238 function addAdminMenu ($action, $what, $return=false) {
239         // Init variables
240         $SUB = false;
241         $OUT = '';
242
243         // Menu descriptions
244         $GLOBALS['menu']['description'] = array();
245         $GLOBALS['menu']['title'] = array();
246
247         // Build main menu
248         $result_main = SQL_QUERY("SELECT
249         `action`, `title`, `descr`
250 FROM
251         `{?_MYSQL_PREFIX?}_admin_menu`
252 WHERE
253         (`what`='' OR `what` IS NULL)
254 ORDER BY
255         `sort` ASC,
256         `id` DESC", __FUNCTION__, __LINE__);
257
258         // Do we have entries?
259         if (!SQL_HASZERONUMS($result_main)) {
260                 $OUT .= '<ul class="admin_menu_main">';
261                 // @TODO Rewrite this to $content = SQL_FETCHARRAY()
262                 while (list($menu, $title, $descr) = SQL_FETCHROW($result_main)) {
263                         if (isExtensionInstalledAndNewer('admins', '0.2.0')) {
264                                 $ACL = adminsCheckAdminAcl($menu, '');
265                         } else {
266                                 // @TODO ACL is 'allow'... hmmm
267                                 $ACL = true;
268                         }
269
270                         // Filename
271                         $inc = sprintf("inc/modules/admin/action-%s.php", $menu);
272
273                         // Is the file readable?
274                         $readable = isIncludeReadable($inc);
275
276                         if ($ACL === true) {
277                                 if ($SUB === false) {
278                                         // Insert compiled menu title and description
279                                         $GLOBALS['menu']['title'][$menu]      = $title;
280                                         $GLOBALS['menu']['description'][$menu] = $descr;
281                                 }
282                                 $OUT .= '<li class="admin_menu">
283 <div class="nobr"><strong>&middot;</strong>&nbsp;';
284
285                                 if ($readable === true) {
286                                         if (($menu == $action) && (empty($what))) {
287                                                 $OUT .= '<strong>';
288                                         } else {
289                                                 $OUT .= '[<a href="{%url=modules.php?module=admin&amp;action=' . $menu . '%}">';
290                                         }
291                                 } else {
292                                         $OUT .= '<em style="cursor:help" class="admin_note" title="{%message,MENU_ACTION_404=' . $menu . '}">';
293                                 }
294
295                                 $OUT .= $title;
296
297                                 if ($readable === true) {
298                                         if (($menu == $action) && (empty($what))) {
299                                                 $OUT .= '</strong>';
300                                         } else {
301                                                 $OUT .= '</a>]';
302                                         }
303                                 } else {
304                                         $OUT .= '</em>';
305                                 }
306
307                                 $OUT .= '</div>
308 </li>';
309
310                                 // Check for menu entries
311                                 $result_what = SQL_QUERY_ESC("SELECT
312         `what`, `title`, `descr`
313 FROM
314         `{?_MYSQL_PREFIX?}_admin_menu`
315 WHERE
316         `action`='%s' AND
317         `what` != '' AND
318         `what` IS NOT NULL
319 ORDER BY
320         `sort` ASC,
321         `id` DESC",
322                                         array($menu), __FUNCTION__, __LINE__);
323
324                                 // Remember the count for later checks
325                                 setAdminMenuHasEntries($menu, ((!SQL_HASZERONUMS($result_what)) && ($action == $menu)));
326
327                                 // Do we have entries?
328                                 if ((ifAdminMenuHasEntries($menu)) && (!SQL_HASZERONUMS($result_what))) {
329                                         $GLOBALS['menu']['description'] = array();
330                                         $GLOBALS['menu']['title'] = array(); $SUB = true;
331                                         $OUT .= '<li class="admin_menu_sub"><ul class="admin_menu_sub">';
332                                         // @TODO Rewrite this to $content = SQL_FETCHARRAY()
333                                         while (list($what_sub, $title_what, $desc_what) = SQL_FETCHROW($result_what)) {
334                                                 // Check for access level
335                                                 if (isExtensionInstalledAndNewer('admins', '0.2.0')) {
336                                                         $ACL = adminsCheckAdminAcl('', $what_sub);
337                                                 } else {
338                                                         // @TODO ACL is 'allow'... hmmm
339                                                         $ACL = true;
340                                                 }
341
342                                                 // Filename
343                                                 $inc = sprintf("inc/modules/admin/what-%s.php", $what_sub);
344
345                                                 // Is the file readable?
346                                                 $readable = isIncludeReadable($inc);
347
348                                                 // Access allowed?
349                                                 if ($ACL === true) {
350                                                         // Insert compiled title and description
351                                                         $GLOBALS['menu']['title'][$what_sub]      = $title_what;
352                                                         $GLOBALS['menu']['description'][$what_sub] = $desc_what;
353                                                         $OUT .= '<li class="admin_menu">
354 <div class="nobr"><strong>--&gt;</strong>&nbsp;';
355                                                         if ($readable === true) {
356                                                                 if ($what == $what_sub) {
357                                                                         $OUT .= '<strong>';
358                                                                 } else {
359                                                                         $OUT .= '[<a href="{%url=modules.php?module=admin&amp;what=' . $what_sub . '%}">';
360                                                                 }
361                                                         } else {
362                                                                 $OUT .= '<em style="cursor:help" class="admin_note" title="{%message,MENU_WHAT_404=' . $what_sub . '%}">';
363                                                         }
364
365                                                         $OUT .= $title_what;
366
367                                                         if ($readable === true) {
368                                                                 if ($what == $what_sub) {
369                                                                         $OUT .= '</strong>';
370                                                                 } else {
371                                                                         $OUT .= '</a>]';
372                                                                 }
373                                                         } else {
374                                                                 $OUT .= '</em>';
375                                                         }
376                                                         $OUT .= '</div>
377 </li>';
378                                                 } // END - if
379                                         } // END - while
380
381                                         // Free memory
382                                         SQL_FREERESULT($result_what);
383                                         $OUT .= '</ul>
384 </li>';
385                                 } // END - if
386                         } // END - if
387                 } // END - while
388
389                 // Free memory
390                 SQL_FREERESULT($result_main);
391                 $OUT .= '</ul>';
392         }
393
394         // Is there a cache instance again?
395         // Return or output content?
396         if ($return === true) {
397                 return $OUT;
398         } else {
399                 outputHtml($OUT);
400         }
401 }
402
403 // Create member selection box
404 function addMemberSelectionBox ($def = 0, $add_all = false, $return = false, $none = false, $field = 'userid') {
405         // Output selection form with all confirmed user accounts listed
406         $result = SQL_QUERY("SELECT `userid`, `surname`, `family` FROM `{?_MYSQL_PREFIX?}_user_data` ORDER BY `userid` ASC", __FUNCTION__, __LINE__);
407
408         // Default output
409         $OUT = '';
410
411         // USe this only for adding points (e.g. adding refs really makes no sence ;-) )
412         if ($add_all === true)   $OUT = '      <option value="all">{--ALL_MEMBERS--}</option>';
413          elseif ($none === true) $OUT = '      <option value="0">{--SELECT_NONE--}</option>';
414
415         while ($content = SQL_FETCHARRAY($result)) {
416                 $OUT .= '<option value="' . bigintval($content['userid']) . '"';
417                 if ($def == $content['userid']) $OUT .= ' selected="selected"';
418                 $OUT .= '>' . $content['surname'] . ' ' . $content['family'] . ' (' . bigintval($content['userid']) . ')</option>';
419         } // END - while
420
421         // Free memory
422         SQL_FREERESULT($result);
423
424         if ($return === false) {
425                 // Remeber options in constant
426                 $content['member_selection'] = $OUT;
427                 $content['what']             = getWhat();
428
429                 // Load template
430                 loadTemplate('admin_member_selection_box', false, $content);
431         } else {
432                 // Return content in selection frame
433                 return '<select class="admin_select" name="' . handleFieldWithBraces($field) . '" size="1">' . $OUT . '</select>';
434         }
435 }
436
437 // Create a menu selection box for given menu system
438 // @TODO Try to rewrite this to adminAddMenuSelectionBox()
439 // @DEPRECATED
440 function adminMenuSelectionBox_DEPRECATED ($mode, $default = '', $defid = '') {
441         $what = "`what` != ''";
442         if ($mode == 'action') $what = "(`what`='' OR `what` IS NULL) AND `action` !='login'";
443
444         $result = SQL_QUERY_ESC("SELECT `%s` AS `menu`, `title` FROM `{?_MYSQL_PREFIX?}_admin_menu` WHERE ".$what." ORDER BY `sort` ASC",
445                 array($mode), __FUNCTION__, __LINE__);
446         if (!SQL_HASZERONUMS($result)) {
447                 // Load menu as selection
448                 $OUT = '<select name="' . $mode . '_menu';
449                 if ((!empty($defid)) || ($defid == '0')) $OUT .= '[' . $defid . ']';
450                 $OUT .= '" size="1" class="admin_select">
451         <option value="">{--SELECT_NONE--}</option>';
452                 // Load all entries
453                 while ($content = SQL_FETCHARRAY($result)) {
454                         $OUT .= '<option value="' . $content['menu'] . '"';
455                         if ((!empty($default)) && ($default == $content['menu'])) $OUT .= ' selected="selected"';
456                         $OUT .= '>' . $content['title'] . '</option>';
457                 } // END - while
458
459                 // Free memory
460                 SQL_FREERESULT($result);
461
462                 // Add closing select-tag
463                 $OUT .= '</select>';
464         } else {
465                 // No menus???
466                 $OUT = '{--ADMIN_PROBLEM_NO_MENU--}';
467         }
468
469         // Return output
470         return $OUT;
471 }
472
473 // Wrapper for $_POST and adminSaveSettings
474 function adminSaveSettingsFromPostData ($tableName = '_config', $whereStatement = '`config`=0', $translateComma = array(), $alwaysAdd = false, $displayMessage = true) {
475         // Get the array
476         $postData = postRequestArray();
477
478         // Call the lower function
479         adminSaveSettings($postData, $tableName, $whereStatement, $translateComma, $alwaysAdd, $displayMessage);
480 }
481
482 // Save settings to the database
483 function adminSaveSettings (&$postData, $tableName = '_config', $whereStatement = '`config`=0', $translateComma = array(), $alwaysAdd = false, $displayMessage = true) {
484         // Prepare all arrays, variables
485         $tableData = array();
486         $skip = false;
487
488         // Now, walk through all entries and prepare them for saving
489         foreach ($postData as $id => $val) {
490                 // Process only formular field but not submit buttons ;)
491                 if ($id != 'ok') {
492                         // Do not save the ok value
493                         convertSelectionsToTimestamp($postData, $tableData, $id, $skip);
494
495                         // Shall we process this id? It muss not be empty, of course
496                         if (($skip === false) && (!empty($id)) && ((!isset($GLOBALS['skip_config'][$id]))) || ($tableName != '_config')) {
497                                 // Translate the value? (comma to dot!)
498                                 if ((is_array($translateComma)) && (in_array($id, $translateComma))) {
499                                         // Then do it here... :)
500                                         $val = convertCommaToDot($val);
501                                 } // END - if
502
503                                 // Shall we add numbers or strings?
504                                 $test = (float)$val;
505                                 if ('' . $val . '' == '' . $test . '') {
506                                         // Add numbers
507                                         $tableData[] = sprintf("`%s`=%s", $id, $test);
508                                 } elseif (is_null($val)) {
509                                         // Add NULL
510                                         $tableData[] = sprintf("`%s`=NULL", $id);
511                                 } else {
512                                         // Add strings
513                                         $tableData[] = sprintf("`%s`='%s'", $id, trim($val));
514                                 }
515
516                                 // Do not add a config entry twice
517                                 $GLOBALS['skip_config'][$id] = true;
518
519                                 // Update current configuration
520                                 setConfigEntry($id, $val);
521                         } // END - if
522                 } // END - if
523         } // END - foreach
524
525         // Check if entry does exist
526         $result = false;
527         if ($alwaysAdd === false) {
528                 if (!empty($whereStatement)) {
529                         $result = SQL_QUERY("SELECT * FROM `{?_MYSQL_PREFIX?}" . $tableName . "` WHERE " . $whereStatement . " LIMIT 1", __FUNCTION__, __LINE__);
530                 } else {
531                         $result = SQL_QUERY("SELECT * FROM `{?_MYSQL_PREFIX?}" . $tableName . "` LIMIT 1", __FUNCTION__, __LINE__);
532                 }
533         } // END - if
534
535         if (SQL_NUMROWS($result) == 1) {
536                 // "Implode" all data to single string
537                 $updatedData = implode(', ', $tableData);
538
539                 // Generate SQL string
540                 $sql = sprintf("UPDATE `{?_MYSQL_PREFIX?}%s` SET %s WHERE %s LIMIT 1",
541                         $tableName,
542                         $updatedData,
543                         $whereStatement
544                 );
545         } else {
546                 // Add Line (does only work with auto_increment!
547                 $keys = array(); $values = array();
548                 foreach ($tableData as $entry) {
549                         // Split up
550                         $line = explode('=', $entry);
551                         $keys[] = $line[0];
552                         $values[] = $line[1];
553                 } // END - foreach
554
555                 // Add both in one line
556                 $keys = implode('`, `', $keys);
557                 $values = implode(', ', $values);
558
559                 // Generate SQL string
560                 $sql = sprintf("INSERT INTO `{?_MYSQL_PREFIX?}%s` (%s) VALUES (%s)",
561                         $tableName,
562                         $keys,
563                         $values
564                 );
565         }
566
567         // Free memory
568         SQL_FREERESULT($result);
569
570         // Simply run generated SQL string
571         SQL_QUERY($sql, __FUNCTION__, __LINE__);
572
573         // Remember affected rows
574         $affected = SQL_AFFECTEDROWS();
575
576         // Rebuild cache
577         rebuildCache('config', 'config');
578
579         // Settings saved, so display message?
580         if ($displayMessage === true) loadTemplate('admin_settings_saved', false, '{--SETTINGS_SAVED--}');
581
582         // Return affected rows
583         return $affected;
584 }
585
586 // Generate a selection box
587 function adminAddMenuSelectionBox ($menu, $type, $name, $default = '') {
588         // Open the requested menu directory
589         $menuArray = getArrayFromDirectory(sprintf("inc/modules/%s/", $menu), '', false, false);
590
591         // Init the selection box
592         $OUT = '<select name="' . $name . '" class="admin_select" size="1"><option value="">{--IS_TOP_MENU--}</option>';
593
594         // Walk through all files
595         foreach ($menuArray as $file) {
596                 // Is this a PHP script?
597                 if ((!isDirectory($file)) && (strpos($file, '' . $type . '-') > -1) && (strpos($file, '.php') > 0)) {
598                         // Then test if the file is readable
599                         $test = sprintf("inc/modules/%s/%s", $menu, $file);
600
601                         // Is the file there?
602                         if (isIncludeReadable($test)) {
603                                 // Extract the value for what=xxx
604                                 $part = substr($file, (strlen($type) + 1));
605                                 $part = substr($part, 0, -4);
606
607                                 // Is that part different from the overview?
608                                 if ($part != 'overview') {
609                                         $OUT .= '<option value="' . $part . '"';
610                                         if ($part == $default) $OUT .= ' selected="selected"';
611                                         $OUT .= '>' . $part . '</option>';
612                                 } // END - if
613                         } // END - if
614                 } // END - if
615         } // END - foreach
616
617         // Close selection box
618         $OUT .= '</select>';
619
620         // Return contents
621         return $OUT;
622 }
623
624 // Creates a user-profile link for the admin. This function can also be used for many other purposes
625 function generateUserProfileLink ($userid, $title = '', $what = 'list_user') {
626         if (($title == '') && ($userid > 0)) {
627                 // Set userid as title
628                 $title = $userid;
629         } elseif ($userid == 0) {
630                 // User id zero is invalid
631                 return '<strong>' . $userid . '</strong>';
632         }
633
634         if (($title == '0') && ($what == 'list_refs')) {
635                 // Return title again
636                 return $title;
637         } elseif (isExtensionActive('nickname')) {
638                 // Get nickname
639                 $nick = getNickname($userid);
640
641                 // Is it not empty, use it as title else the userid
642                 if (!empty($nick)) $title = $nick . '(' . $userid . ')'; else $title = $userid;
643         }
644
645         // Return link
646         return '[<a href="{%url=modules.php?module=admin&amp;what=' . $what . '&amp;userid=' . $userid . '%}" title="{--ADMIN_USER_PROFILE_TITLE--}">' . $title . '</a>]';
647 }
648
649 // Check "logical-area-mode"
650 function adminGetMenuMode () {
651         // Set the default menu mode as the mode for all admins
652         $mode = getConfig('admin_menu');
653         $adminMode = $mode;
654
655         // Get admin id
656         $adminId = getCurrentAdminId();
657
658         // Check individual settings of current admin
659         if (isset($GLOBALS['cache_array']['admin']['la_mode'][$adminId])) {
660                 // Load from cache
661                 $adminMode = $GLOBALS['cache_array']['admin']['la_mode'][$adminId];
662                 incrementStatsEntry('cache_hits');
663         } elseif (isExtensionInstalledAndNewer('admins', '0.6.7')) {
664                 // Load from database when version of 'admins' is enough
665                 $result = SQL_QUERY_ESC("SELECT `la_mode` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
666                         array($adminId), __FUNCTION__, __LINE__);
667
668                 // Do we have an entry?
669                 if (SQL_NUMROWS($result) == 1) {
670                         // Load data
671                         list($adminMode) = SQL_FETCHROW($result);
672                 } // END - if
673
674                 // Free memory
675                 SQL_FREERESULT($result);
676         }
677
678         // Check what the admin wants and set it when it's not the default mode
679         if ($adminMode != 'global') $mode = $adminMode;
680
681         // Return admin-menu's mode
682         return $mode;
683 }
684
685 // Change activation status
686 function adminChangeActivationStatus ($IDs, $table, $row, $idRow = 'id') {
687         $cnt = '0'; $newStatus = 'Y';
688         if ((is_array($IDs)) && (count($IDs) > 0)) {
689                 // "Walk" all through and count them
690                 foreach ($IDs as $id => $selected) {
691                         // Secure the id number
692                         $id = bigintval($id);
693
694                         // Should always be set... ;-)
695                         if (!empty($selected)) {
696                                 // Determine new status
697                                 $result = SQL_QUERY_ESC("SELECT %s FROM `{?_MYSQL_PREFIX?}_%s` WHERE %s=%s LIMIT 1",
698                                 array($row, $table, $idRow, $id), __FUNCTION__, __LINE__);
699
700                                 // Row found?
701                                 if (SQL_NUMROWS($result) == 1) {
702                                         // Load the status
703                                         list($currStatus) = SQL_FETCHROW($result);
704
705                                         // And switch it N<->Y
706                                         if ($currStatus == 'Y') $newStatus = 'N'; else $newStatus = 'Y';
707
708                                         // Change this status
709                                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s` SET %s='%s' WHERE %s=%s LIMIT 1",
710                                         array($table, $row, $newStatus, $idRow, $id), __FUNCTION__, __LINE__);
711
712                                         // Count up affected rows
713                                         $cnt += SQL_AFFECTEDROWS();
714                                 } // END - if
715
716                                 // Free the result
717                                 SQL_FREERESULT($result);
718                         } // END - if
719                 } // END - foreach
720
721                 // Output status
722                 loadTemplate('admin_settings_saved', false, sprintf(getMessage('ADMIN_STATUS_CHANGED'), $cnt, count($IDs)));
723         } else {
724                 // Nothing selected!
725                 loadTemplate('admin_settings_saved', false, '{--ADMIN_NOTHING_SELECTED_CHANGE--}');
726         }
727 }
728
729 // Send mails for del/edit/lock build modes
730 function sendAdminBuildMails ($mode, $table, $content, $id, $subjectPart = '', $userid = 'userid') {
731         // Default subject is the subject part
732         $subject = $subjectPart;
733
734         // Is the subject part not set?
735         if (empty($subjectPart)) {
736                 // Then use it from the mode
737                 $subject = strtoupper($mode);
738         } // END - if
739
740         // Is the raw userid set?
741         if (postRequestParameter($userid, $id) > 0) {
742                 // Generate subject
743                 $subject = '{--MEMBER_' . strtoupper($subject) . '_' . strtoupper($table) . '_SUBJECT--}';
744
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), $subject, $mail);
754         } // END - if
755
756         // Generate subject
757         $subject = '{--ADMIN_' . strtoupper($subject) . '_' . strtoupper($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('del', $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('del', $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('admin_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_admin_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 ($userid > 0) {
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="admin_note">{--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('EXTENSION_PROBLEM_EXTENSION_NOT_INSTALLED', 'admins');
1278                         }
1279                 } else {
1280                         // Maybe deleted?
1281                         $adminLink = '<div class="admin_note">' . 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 . '%}">' . 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 // [EOF]
1435 ?>