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