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