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