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