e7b1acb6195185bad6baabc8fb6e00b097cabaea
[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($_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 $menuDesription, $menuTitle, $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         global $menuDesription, $menuTitle;
301
302         // Init variables
303         $SUB = false;
304         $OUT = "";
305
306         // Menu descriptions
307         $menuDesription = array();
308         $menuTitle = array();
309
310         // Is there a cache instance?
311         if ((is_object($GLOBALS['cache_instance'])) && (getConfig('cache_admin_menu') == "Y")) {
312                 // Create cache name
313                 $cacheName = "admin_".$act."_".$wht."_".GET_LANGUAGE()."_".strtolower(get_session('admin_login'));
314
315                 // Is that cache there?
316                 if ($GLOBALS['cache_instance']->loadCacheFile($cacheName)) {
317                         // Then load it
318                         $data = $GLOBALS['cache_instance']->getArrayFromCache();
319
320                         // Extract all parts
321                         $OUT = base64_decode($data['output'][0]);
322                         $menuTitle = unserialize(base64_decode($data['title'][0]));
323                         $menuDescription = unserialize(base64_decode($data['descr'][0]));
324
325                         // Return or output content?
326                         if ($return) {
327                                 return $OUT;
328                         } else {
329                                 OUTPUT_HTML($OUT);
330                         }
331                 } // END - if
332         } // END - if
333
334         // Build main menu
335         $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__);
336         if (SQL_NUMROWS($result_main) > 0) {
337                 $OUT = "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_menu_main\">
338 <tr><td colspan=\"2\" height=\"7\" class=\"seperator\">&nbsp;</td></tr>\n";
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                                         $menuTitle[$menu]      = $title;
351                                         $menuDesription[$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                                 {
358                                         $OUT .= "<strong>";
359                                 }
360                                  else
361                                 {
362                                         $OUT .= "[<a href=\"{!URL!}/modules.php?module=admin&amp;action=".$menu."\">";
363                                 }
364                                 $OUT .= $title;
365                                 if (($menu == $act) && (empty($wht)))
366                                 {
367                                         $OUT .= "</strong>";
368                                 }
369                                  else
370                                 {
371                                         $OUT .= "</a>]";
372                                 }
373                                 $OUT .= "</NOBR></td>
374 </tr>\n";
375                                 $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",
376                                         array($menu), __FILE__, __LINE__);
377                                 if ((SQL_NUMROWS($result_what) > 0) && ($act == $menu))
378                                 {
379                                         $menuDesription = array();
380                                         $menuTitle = array(); $SUB = true;
381                                         $OUT .= "<tr>
382         <td width=\"10\" class=\"seperator\">&nbsp;</td>
383         <td class=\"admin_menu\">
384                 <table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_menu_sub\">\n";
385                                         while (list($wht_sub, $title_what, $desc_what) = SQL_FETCHROW($result_what)) {
386                                                 // Filename
387                                                 $INC = sprintf("%sinc/modules/admin/what-%s.php", constant('PATH'), $wht_sub);
388                                                 if ((EXT_IS_ACTIVE("admins")) && (GET_EXT_VERSION("admins") > "0.2")) {
389                                                         $ACL = ADMINS_CHECK_ACL("", $wht_sub);
390                                                 } else {
391                                                         // ACL is "allow"... hmmm
392                                                         $ACL = true;
393                                                 }
394                                                 $readable = INCLUDE_READABLE($INC);
395                                                 if ($ACL === true) {
396                                                         // Insert compiled title and description
397                                                         $menuTitle[$wht_sub]      = $title_what;
398                                                         $menuDesription[$wht_sub] = $desc_what;
399                                                         $OUT .= "<tr>
400         <td class=\"admin_menu\" colspan=\"2\">
401                 <NOBR>&nbsp;<strong>--&gt;</strong>&nbsp;";
402                                                         if ($readable === true)
403                                                         {
404                                                                 if ($wht == $wht_sub)
405                                                                 {
406                                                                         $OUT .= "<strong>";
407                                                                 }
408                                                                  else
409                                                                 {
410                                                                         $OUT .= "[<a href=\"{!URL!}/modules.php?module=admin&amp;what=".$wht_sub."\">";
411                                                                 }
412                                                         }
413                                                          else
414                                                         {
415                                                                 $OUT .= "<i class=\"admin_note\">";
416                                                         }
417                                                         $OUT .= $title_what;
418                                                         if ($readable === true)
419                                                         {
420                                                                 if ($wht == $wht_sub)
421                                                                 {
422                                                                         $OUT .= "</strong>";
423                                                                 }
424                                                                  else
425                                                                 {
426                                                                         $OUT .= "</a>]";
427                                                                 }
428                                                         }
429                                                          else
430                                                         {
431                                                                 $OUT .= "</em>";
432                                                         }
433                                                         $OUT .= "</NOBR></td>
434 </tr>\n";
435                                                 }
436                                         }
437
438                                         // Free memory
439                                         SQL_FREERESULT($result_what);
440                                         $OUT .= "    </table>
441         </td>
442 </tr>\n";
443                                 }
444                                 $OUT .= "<tr><td height=\"7\" colspan=\"2\"></td></tr>\n";
445                         }
446                 }
447
448                 // Free memory
449                 SQL_FREERESULT($result_main);
450                 $OUT .= "</table>\n";
451         }
452
453         // Compile and run the code here. This inserts all constants into the
454         // HTML output. Costs me some time to figure this out... *sigh* Quix0r
455         $eval = "\$OUT = \"".COMPILE_CODE(SQL_ESCAPE($OUT))."\";";
456         eval($eval);
457
458         // Is there a cache instance again?
459         if ((is_object($GLOBALS['cache_instance'])) && (getConfig('cache_admin_menu') == "Y")) {
460                 // Init cache
461                 $GLOBALS['cache_instance']->init($cacheName);
462
463                 // Prepare cache data
464                 $data = array(
465                         'output' => base64_encode($OUT),
466                         'title'  => $menuTitle,
467                         'descr'  => $menuDesription
468                 );
469
470                 // Write the data away
471                 $GLOBALS['cache_instance']->addRow($data);
472
473                 // Close cache
474                 $GLOBALS['cache_instance']->finalize();
475         } // END - if
476
477         // Return or output content?
478         if ($return) {
479                 return $OUT;
480         } else {
481                 OUTPUT_HTML($OUT);
482         }
483 }
484 //
485 function ADD_MEMBER_SELECTION_BOX ($def="0", $add_all=false, $return=false, $none=false, $field="userid")
486 {
487         // Output selection form with all confirmed user accounts listed
488         $result = SQL_QUERY("SELECT userid, surname, family FROM `{!_MYSQL_PREFIX!}_user_data` ORDER BY userid", __FILE__, __LINE__);
489         $OUT = "";
490
491         // USe this only for adding points (e.g. adding refs really makes no sence ;-) )
492         if ($add_all) $OUT = "      <option value=\"all\">".ALL_MEMBERS."</option>\n";
493          elseif ($none) $OUT = "      <option value=\"0\">".SELECT_NONE."</option>\n";
494         while (list($id, $sname, $fname) = SQL_FETCHROW($result))
495         {
496                 $OUT .= "      <option value=\"".bigintval($id)."\"";
497                 if ($def == $id) $OUT .= " selected=\"selected\"";
498                 $OUT .= ">".$sname." ".$fname." (".bigintval($id).")</option>\n";
499         }
500
501         // Free memory
502         SQL_FREERESULT($result);
503
504         if (!$return) {
505                 // Remeber options in constant
506                 define('_MEMBER_SELECTION', $OUT);
507
508                 // Display selection box
509                 define('__LANG_VALUE', GET_LANGUAGE());
510
511                 // Load template
512                 LOAD_TEMPLATE("admin_member_selection_box", false, $GLOBALS['what']);
513         } else {
514                 // Return content in selection frame
515                 return "<select class=\"admin_select\" name=\"".$field."\" size=\"1\">\n".$OUT."</select>\n";
516         }
517 }
518 //
519 function ADMIN_MENU_SELECTION($MODE, $default="", $defid="") {
520         $wht = "`what` != ''";
521         if ($MODE == "action") $wht = "(what='' OR `what` IS NULL) AND action !='login'";
522         $result = SQL_QUERY_ESC("SELECT %s, title FROM `{!_MYSQL_PREFIX!}_admin_menu` WHERE ".$wht." ORDER BY `sort`",
523          array($MODE), __FILE__, __LINE__);
524         if (SQL_NUMROWS($result) > 0) {
525                 // Load menu as selection
526                 $OUT = "<select name=\"".$MODE."_menu";
527                 if ((!empty($defid)) || ($defid == "0")) $OUT .= "[".$defid."]";
528                 $OUT .= "\" size=\"1\" class=\"admin_select\">
529         <option value=\"\">".SELECT_NONE."</option>\n";
530                 while (list($menu, $title) = SQL_FETCHROW($result)) {
531                         $OUT .= "  <option value=\"".$menu."\"";
532                         if ((!empty($default)) && ($default == $menu)) $OUT .= " selected=\"selected\"";
533                         $OUT .= ">".$title."</option>\n";
534                 } // END - while
535
536                 // Free memory
537                 SQL_FREERESULT($result);
538                 $OUT .= "</select>\n";
539         } else {
540                 // No menus???
541                 $OUT = ADMIN_PROBLEM_NO_MENU;
542         }
543
544         // Return output
545         return $OUT;
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", __FILE__, __LINE__);
593                 } else {
594                         $result = SQL_QUERY("SELECT * FROM `{!_MYSQL_PREFIX!}".$tableName."` LIMIT 1", __FILE__, __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, __FILE__, __LINE__);
634
635         // Rebuild cache
636         REBUILD_CACHE("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\">\n <option value=\"\">".IS_TOP_MENU."</option>\n";
649
650         // Walk through all files
651         while ($file = readdir($handle)) {
652                 // Is this a PHP script?
653                 if (($file != ".") && ($file != "..") && ($file != "lost+found") && (strpos($file, "".$type."-") > -1) && (strpos($file, ".php") > 0)) {
654                         // Then test if the file is readable
655                         $test = sprintf("%sinc/modules/%s/%s", constant('PATH'), $menu, $file);
656
657                         // Is the file there?
658                         if (FILE_READABLE($test)) {
659                                 // Extract the value for what=xxx
660                                 $part = substr($file, (strlen($type) + 1));
661                                 $part = substr($part, 0, -4);
662
663                                 // Is that part different from the overview?
664                                 if ($part != "overview") {
665                                         $OUT .= "       <option value=\"".$part."\"";
666                                         if ($part == $default) $OUT .= " selected=\"selected\"";
667                                         $OUT .= ">".$part."</option>\n";
668                                 } // END - if
669                         } // END - if
670                 } // END - if
671         } // END - while
672
673         // Close dir and selection box
674         closedir($handle);
675         $OUT .= "</select>\n";
676         
677         // Return contents
678         return $OUT;
679 }
680 //
681 function ADMIN_USER_PROFILE_LINK ($uid, $title="", $wht="list_user") {
682         if (($title == "") && ($title != "0")) {
683                 // Set userid as title
684                 $title = $uid;
685         } // END - if
686
687         if (($title == "0") && ($wht == "list_refs")) {
688                 // Return title again
689                 return $title;
690         } // END - if
691
692         //* DEBUG: */ echo "a:".$title."<br />";
693         // Return link
694         return "<a href=\"{!URL!}/modules.php?module=admin&amp;what=".$wht."&amp;u_id=".$uid."\" title=\"{--ADMIN_USER_PROFILE_TITLE--}\">".$title."</a>";
695 }
696
697 // Check "logical-area-mode"
698 function ADMIN_CHECK_MENU_MODE () {
699         // Set the global mode as the mode for all admins
700         $MODE = getConfig('admin_menu');
701         $ADMIN = $MODE;
702
703         // Get admin id
704         $aid = GET_CURRENT_ADMIN_ID();
705
706         // Check individual settings of current admin
707         if (isset($GLOBALS['cache_array']['admins']['la_mode'][$aid])) {
708                 // Load from cache
709                 $ADMIN = $GLOBALS['cache_array']['admins']['la_mode'][$aid];
710                 incrementConfigEntry('cache_hits');
711         } elseif (GET_EXT_VERSION("admins") >= "0.6.7") {
712                 // Load from database when version of "admins" is enough
713                 $result = SQL_QUERY_ESC("SELECT la_mode FROM `{!_MYSQL_PREFIX!}_admins` WHERE id=%s LIMIT 1",
714                         array($aid), __FILE__, __LINE__);
715                 if (SQL_NUMROWS($result) == 1) {
716                         // Load data
717                         list($ADMIN) = SQL_FETCHROW($result);
718                 }
719
720                 // Free memory
721                 SQL_FREERESULT($result);
722         }
723
724         // Check what the admin wants and set it when it's not the global mode
725         if ($ADMIN != "global") $MODE = $ADMIN;
726
727         // Return admin-menu's mode
728         return $MODE;
729 }
730
731 // Change activation status
732 function ADMIN_CHANGE_ACTIVATION_STATUS ($IDs, $table, $row, $idRow = "id") {
733         $cnt = 0; $newStatus = "Y";
734         if ((is_array($IDs)) && (count($IDs) > 0)) {
735                 // "Walk" all through and count them
736                 foreach ($IDs as $id => $selected) {
737                         // Secure the ID number
738                         $id = bigintval($id);
739
740                         // Should always be set... ;-)
741                         if (!empty($selected)) {
742                                 // Determine new status
743                                 $result = SQL_QUERY_ESC("SELECT %s FROM `{!_MYSQL_PREFIX!}_%s` WHERE %s=%s LIMIT 1",
744                                         array($row, $table, $idRow, $id), __FILE__, __LINE__);
745
746                                 // Row found?
747                                 if (SQL_NUMROWS($result) == 1) {
748                                         // Load the status
749                                         list($currStatus) = SQL_FETCHROW($result);
750
751                                         // And switch it N<->Y
752                                         if ($currStatus == "Y") $newStatus = "N"; else $newStatus = "Y";
753
754                                         // Change this status
755                                         SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_%s` SET %s='%s' WHERE %s=%s LIMIT 1",
756                                                 array($table, $row, $newStatus, $idRow, $id), __FILE__, __LINE__);
757
758                                         // Count up affected rows
759                                         $cnt += SQL_AFFECTEDROWS();
760                                 } // END - if
761
762                                 // Free the result
763                                 SQL_FREERESULT($result);
764                         } // END - if
765                 } // END - foreach
766
767                 // Output status
768                 LOAD_TEMPLATE("admin_settings_saved", false, ADMIN_STATUS_CHANGED_1.$cnt.ADMIN_STATUS_CHANGED_2.count($IDs).ADMIN_STATUS_CHANGED_3);
769         } else {
770                 // Nothing selected!
771                 LOAD_TEMPLATE("admin_settings_saved", false, getMessage('ADMIN_NOTHING_SELECTED_CHANGE'));
772         }
773 }
774
775 // Send mails for del/edit/lock build modes
776 function ADMIN_SEND_BUILD_MAILS ($mode, $table, $content, $id, $subjectPart="") {
777         // Default subject is the subject part
778         $subject = $subjectPart;
779
780         // Is the subject part not set?
781         if (empty($subjectPart)) {
782                 // Then use it from the mode
783                 $subject = strtoupper($mode);
784         } // END - if
785
786         // Is the raw userid set?
787         if ($_POST['uid_raw'][$id] > 0) {
788                 // Generate subject
789                 $subjectLine = constant('MEMBER_'.strtoupper($subject).'_'.strtoupper($table).'_SUBJECT');
790
791                 // Load email template
792                 if (!empty($subjectPart)) {
793                         $mail = LOAD_EMAIL_TEMPLATE("member_".$mode."_".strtolower($subjectPart)."_".$table, $content);
794                 } else {
795                         $mail = LOAD_EMAIL_TEMPLATE("member_".$mode."_".$table, $content);
796                 }
797
798                 // Send email out
799                 SEND_EMAIL($_POST['uid_raw'][$id], $subjectLine, $mail);
800         } // END - if
801
802         // Generate subject
803         $subjectLine = constant('ADMIN_'.strtoupper($subject).'_'.strtoupper($table).'_SUBJECT');
804
805         // Send admin notification out
806         if (!empty($subjectPart)) {
807                 SEND_ADMIN_NOTIFICATION($subjectLine, "admin_".$mode."_".strtolower($subjectPart)."_".$table, $content, $_POST['uid_raw'][$id]);
808         } else {
809                 SEND_ADMIN_NOTIFICATION($subjectLine, "admin_".$mode."_".$table, $content, $_POST['uid_raw'][$id]);
810         }
811 }
812
813 // Build a special template list
814 function ADMIN_BUILD_LIST ($listType, $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn) {
815         $OUT = ""; $SW = 2;
816
817         // "Walk" through all entries
818         foreach ($IDs as $id => $selected) {
819                 // Secure ID number
820                 $id = bigintval($id);
821
822                 // Get result from a given column array and table name
823                 $result = SQL_RESULT_FROM_ARRAY($table, $columns, $idColumn, $id, __FILE__, __LINE__);
824
825                 // Is there one entry?
826                 if (SQL_NUMROWS($result) == 1) {
827                         // Load all data
828                         $content = SQL_FETCHARRAY($result);
829
830                         // Filter all data
831                         foreach ($content as $key => $value) {
832                                 // Search index
833                                 $idx = array_search($key, $columns, true);
834
835                                 // Do we have a userid?
836                                 if ($key == "userid") {
837                                         // Add it again as raw id
838                                         $content['uid'] = bigintval($value);
839                                 } // END - if
840
841                                 // Handle the call in external function
842                                 $content[$key] = HANDLE_EXTRA_VALUES($filterFunctions[$idx], $value, $extraValues[$idx]);
843                         } // END - foreach
844
845                         // Add color switching
846                         $content['sw'] = $SW;
847
848                         // Then list it
849                         $OUT .= LOAD_TEMPLATE(sprintf("admin_%s_%s_row",
850                                         $listType,
851                                         $table
852                                 ), true, $content
853                         );
854
855                         // Switch color
856                         $SW = 3 - $SW;
857                 } // END - if
858
859                 // Free the result
860                 SQL_FREERESULT($result);
861         } // END - foreach
862
863         // Load master template
864         LOAD_TEMPLATE(sprintf("admin_%s_%s",
865                         $listType,
866                         $table
867                 ), false, $OUT
868         );
869 }
870
871 // Change status of "build" list
872 function ADMIN_BUILD_STATUS_HANDLER ($mode, $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray) {
873         // All valid entries? (We hope so here!)
874         if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues)) && (count($statusArray) > 0)) {
875                 // "Walk" through all entries
876                 foreach ($IDs as $id => $sel) {
877                         // Construct SQL query
878                         $SQL = sprintf("UPDATE `{!_MYSQL_PREFIX!}_%s` SET",
879                                 SQL_ESCAPE($table)
880                         );
881
882                         // Load data of entry
883                         $result = SQL_QUERY_ESC("SELECT * FROM `{!_MYSQL_PREFIX!}_%s` WHERE %s=%s LIMIT 1",
884                                 array($table, $idColumn, $id), __FILE__, __LINE__);
885
886                         // Fetch the data
887                         $content = SQL_FETCHARRAY($result);
888
889                         // Free the result
890                         SQL_FREERESULT($result);
891
892                         // Add all status entries (e.g. status column last_updated or so)
893                         $newStatus = "UNKNOWN";
894                         $oldStatus = "UNKNOWN";
895                         $statusColumn = "unknown";
896                         foreach ($statusArray as $column => $statusInfo) {
897                                 // Does the entry exist?
898                                 if ((isset($content[$column])) && (isset($statusInfo[$content[$column]]))) {
899                                         // Add these entries for update
900                                         $SQL .= sprintf(" %s='%s',", SQL_ESCAPE($column), SQL_ESCAPE($statusInfo[$content[$column]]));
901
902                                         // Remember status
903                                         if ($statusColumn == "unknown") {
904                                                 // Always (!!!) change status column first!
905                                                 $oldStatus = $content[$column];
906                                                 $newStatus = $statusInfo[$oldStatus];
907                                                 $statusColumn = $column;
908                                         } // END - if
909                                 } elseif (isset($content[$column])) {
910                                         // Unfinished!
911                                         mxchange_die("{--".__FUNCTION__."--}:".__LINE__.":UNFINISHED: id={$id}/{$column}[".gettype($statusInfo)."] = {$content[$column]}");
912                                 }
913                         } // END - foreach
914
915                         // Add other columns as well
916                         foreach ($_POST as $key => $entries) {
917                                 // Skip id, raw userid and 'do_$mode'
918                                 if (!in_array($key, array($idColumn, 'uid_raw', ('do_'.$mode)))) {
919                                         // Are there brackets () at the end?
920                                         if (substr($entries[$id], -2, 2) == "()") {
921                                                 // Direct SQL command found
922                                                 $SQL .= sprintf(" %s=%s,", SQL_ESCAPE($key), SQL_ESCAPE($entries[$id]));
923                                         } else {
924                                                 // Add regular entry
925                                                 $SQL .= sprintf(" %s='%s',", SQL_ESCAPE($key), SQL_ESCAPE($entries[$id]));
926
927                                                 // Add entry
928                                                 $content[$key] = $entries[$id];
929                                         }
930                                 } // END - if
931                         } // END - foreach
932
933                         // Finish SQL statement
934                         $SQL = substr($SQL, 0, -1) . sprintf(" WHERE %s=%s AND %s='%s' LIMIT 1",
935                                 $idColumn,
936                                 bigintval($id),
937                                 $statusColumn,
938                                 $oldStatus
939                         );
940
941                         // Run the SQL
942                         SQL_QUERY($SQL, __FILE__, __LINE__);
943
944                         // Do we have an URL?
945                         if (isset($content['url'])) {
946                                 // Then add a framekiller test as well
947                                 $content['frametester'] = FRAMETESTER($content['url']);
948                         } // END - if
949
950                         // Send "build mails" out
951                         ADMIN_SEND_BUILD_MAILS($mode, $table, $content, $id, $statusInfo[$content[$column]]);
952                 } // END - foreach
953         } // END - if
954 }
955
956 // Delete rows by given ID numbers
957 function ADMIN_DELETE_ENTRIES_CONFIRM ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $deleteNow=false, $idColumn="id", $userIdColumn="userid") {
958         // All valid entries? (We hope so here!)
959         if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues))) {
960                 // Shall we delete here or list for deletion?
961                 if ($deleteNow) {
962                         // The base SQL command:
963                         $SQL = "DELETE LOW_PRIORITY FROM `{!_MYSQL_PREFIX!}_%s` WHERE %s IN (%s)";
964
965                         // Delete them all
966                         $idList = "";
967                         foreach ($IDs as $id => $sel) {
968                                 // Is there a userid?
969                                 if (isset($_POST['uid_raw'][$id])) {
970                                         // Load all data from that id
971                                         $result = SQL_QUERY_ESC("SELECT * FROM `{!_MYSQL_PREFIX!}_%s` WHERE %s=%s LIMIT 1",
972                                                 array($table, $idColumn, $id), __FILE__, __LINE__);
973
974                                         // Fetch the data
975                                         $content = SQL_FETCHARRAY($result);
976
977                                         // Free the result
978                                         SQL_FREERESULT($result);
979
980                                         // Send "build mails" out
981                                         ADMIN_SEND_BUILD_MAILS("del", $table, $content, $id);
982                                 } // END - if
983
984                                 // Add id number
985                                 $idList .= $id.",";
986                         } // END - foreach
987
988                         // Run the query
989                         SQL_QUERY($SQL, array($table, $idColumn, substr($idList, 0, -1)), __FILE__, __LINE__);
990
991                         // Was this fine?
992                         if (SQL_AFFECTEDROWS() == count($IDs)) {
993                                 // All deleted
994                                 LOAD_TEMPLATE("admin_settings_saved", false, getMessage('ADMIN_ALL_ENTRIES_REMOVED'));
995                         } else {
996                                 // Some are still there :(
997                                 LOAD_TEMPLATE("admin_settings_saved", false, sprintf(ADMIN_SOME_ENTRIES_NOT_DELETED, SQL_AFFECTEDROWS(), count($IDs)));
998                         }
999                 } else {
1000                         // List for deletion confirmation
1001                         ADMIN_BUILD_LIST("del", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1002                 }
1003         } // END - if
1004 }
1005
1006 // Edit rows by given ID numbers
1007 function ADMIN_EDIT_ENTRIES_CONFIRM ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $editNow=false, $idColumn="id", $userIdColumn="userid") {
1008         // All valid entries? (We hope so here!)
1009         if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues))) {
1010                 // Shall we change here or list for editing?
1011                 if ($editNow) {
1012                         // Change them all
1013                         $affected = 0;
1014                         foreach ($IDs as $id => $sel) {
1015                                 // Prepare content array (new values)
1016                                 $content = array();
1017
1018                                 // Prepare SQL for this row
1019                                 $SQL = sprintf("UPDATE `{!_MYSQL_PREFIX!}_ SET",
1020                                         SQL_ESCAPE($table)
1021                                 );
1022                                 foreach ($_POST as $key => $entries) {
1023                                         // Skip raw userid which is always invalid
1024                                         if ($key == "uid_raw") {
1025                                                 // Continue with next field
1026                                                 continue;
1027                                         } // END - if
1028
1029                                         // Is entries an array?
1030                                         if (($key != $idColumn) && (is_array($entries)) && (isset($entries[$id]))) {
1031                                                 // Add this entry to content
1032                                                 $content[$key] = $entries[$id];
1033
1034                                                 // Send data through the filter function if found
1035                                                 if ((isset($filterFunctions[$key])) && (isset($extraValues[$key]))) {
1036                                                         // Filter function set!
1037                                                         $entries[$id] = HANDLE_EXTRA_VALUES($filterFunctions[$key], $entries[$id], $extraValues[$key]);
1038                                                 } // END - if
1039
1040                                                 // Then add this value
1041                                                 $SQL .= sprintf(" %s='%s',",
1042                                                         SQL_ESCAPE($key),
1043                                                         SQL_ESCAPE($entries[$id])
1044                                                 );
1045                                         } elseif (($key != $idColumn) && (!is_array($entries))) {
1046                                                 // Add normal entries as well!
1047                                                 $content[$key] =  $entries;
1048                                         }
1049
1050                                         // Do we have an URL?
1051                                         if ($key == "url") {
1052                                                 // Then add a framekiller test as well
1053                                                 $content['frametester'] = FRAMETESTER($content[$key]);
1054                                         } // END - if
1055                                 } // END - foreach
1056
1057                                 // Finish SQL command
1058                                 $SQL = substr($SQL, 0, -1) . " WHERE ".$idColumn."=".bigintval($id)." LIMIT 1";
1059
1060                                 // Run this query
1061                                 SQL_QUERY($SQL, __FILE__, __LINE__);
1062
1063                                 // Add affected rows
1064                                 $affected += SQL_AFFECTEDROWS();
1065
1066                                 // Load all data from that id
1067                                 $result = SQL_QUERY_ESC("SELECT * FROM `{!_MYSQL_PREFIX!}_%s` WHERE %s=%s LIMIT 1",
1068                                         array($table, $idColumn, $id), __FILE__, __LINE__);
1069
1070                                 // Fetch the data
1071                                 global $DATA;
1072                                 $DATA = SQL_FETCHARRAY($result);
1073
1074                                 // Free the result
1075                                 SQL_FREERESULT($result);
1076
1077                                 // Send "build mails" out
1078                                 ADMIN_SEND_BUILD_MAILS("edit", $table, $content, $id);
1079                         } // END - foreach
1080
1081                         // Was this fine?
1082                         if ($affected == count($IDs)) {
1083                                 // All deleted
1084                                 LOAD_TEMPLATE("admin_settings_saved", false, getMessage('ADMIN_ALL_ENTRIES_EDITED'));
1085                         } else {
1086                                 // Some are still there :(
1087                                 LOAD_TEMPLATE("admin_settings_saved", false, sprintf(ADMIN_SOME_ENTRIES_NOT_EDITED, $affected, count($IDs)));
1088                         }
1089                 } else {
1090                         // List for editing
1091                         ADMIN_BUILD_LIST("edit", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1092                 }
1093         } // END - if
1094 }
1095
1096 // Un-/lock rows by given ID numbers
1097 function ADMIN_LOCK_ENTRIES_CONFIRM ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $statusArray=array(), $lockNow=false, $idColumn="id", $userIdColumn="userid") {
1098         // All valid entries? (We hope so here!)
1099         if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues)) && ((!$lockNow) || (count($statusArray) == 1))) {
1100                 // Shall we un-/lock here or list for locking?
1101                 if ($lockNow) {
1102                         // Un-/lock entries
1103                         ADMIN_BUILD_STATUS_HANDLER("lock", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray);
1104                 } else {
1105                         // List for editing
1106                         ADMIN_BUILD_LIST("lock", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1107                 }
1108         } // END - if
1109 }
1110
1111 // Undelete rows by given ID numbers
1112 function ADMIN_UNDELETE_ENTRIES_CONFIRM ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $statusArray=array(), $lockNow=false, $idColumn="id", $userIdColumn="userid") {
1113         // All valid entries? (We hope so here!)
1114         if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues)) && ((!$lockNow) || (count($statusArray) == 1))) {
1115                 // Shall we un-/lock here or list for locking?
1116                 if ($lockNow) {
1117                         // Undelete entries
1118                         ADMIN_BUILD_STATUS_HANDLER("undelete", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray);
1119                 } else {
1120                         // List for editing
1121                         ADMIN_BUILD_LIST("undelete", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1122                 }
1123         } // END - if
1124 }
1125
1126 // Checks proxy settins by fetching check-updates3.php from www.mxchange.org
1127 function ADMIN_TEST_PROXY_SETTINGS ($settingsArray) {
1128         // Set temporary the new settings
1129         mergeConfig($settingsArray);
1130
1131         // Now get the test URL
1132         $content = GET_URL("check-updates3.php");
1133
1134         // Is the first line with "200 OK"?
1135         $valid = eregi("200 OK", $content[0]);
1136
1137         // Return result
1138         return $valid;
1139 }
1140
1141 // Sends out a link to the given email adress so the admin can reset his/her password
1142 function ADMIN_SEND_PASSWORD_RESET_LINK ($email) {
1143         // Init output
1144         $OUT = "";
1145
1146         // Compile out security characters (must be for looking up!)
1147         $email = COMPILE_CODE($email);
1148
1149         // Look up administator login
1150         $result = SQL_QUERY_ESC("SELECT id, login, password FROM `{!_MYSQL_PREFIX!}_admins` WHERE email='%s' LIMIT 1",
1151                 array($email), __FILE__, __LINE__);
1152
1153         // Is there an account?
1154         if (SQL_NUMROWS($result) == 0) {
1155                 // No account found!
1156                 return getMessage('ADMIN_NO_LOGIN_WITH_EMAIL');
1157         } // END - if
1158
1159         // Load all data
1160         $content = SQL_FETCHARRAY($result);
1161
1162         // Free result
1163         SQL_FREERESULT($result);
1164
1165         // Generate hash for reset link
1166         $content['hash'] = generateHash(URL.":".$content['id'].":".$content['login'].":".$content['password'], substr($content['password'], 10));
1167
1168         // Remove some data
1169         unset($content['id']);
1170         unset($content['password']);
1171
1172         // Prepare email
1173         $mailText = LOAD_EMAIL_TEMPLATE("admin_reset_password", $content);
1174
1175         // Send it out
1176         SEND_EMAIL($email, getMessage('ADMIN_RESET_PASS_LINK_SUBJ'), $mailText);
1177
1178         // Prepare output
1179         return getMessage('ADMIN_RESET_LINK_SENT');
1180 }
1181
1182 // Validate hash and login for password reset
1183 function ADMIN_VALIDATE_RESET_LINK_HASH_LOGIN ($hash, $login) {
1184         // By default nothing validates... ;)
1185         $valid = false;
1186
1187         // Compile the login for lookup
1188         $login = COMPILE_CODE($login);
1189
1190         // Then try to find that user
1191         $result = SQL_QUERY_ESC("SELECT id, password, email FROM `{!_MYSQL_PREFIX!}_admins` WHERE login='%s' LIMIT 1",
1192                 array($login), __FILE__, __LINE__);
1193
1194         // Is an account here?
1195         if (SQL_NUMROWS($result) == 1) {
1196                 // Load all data
1197                 $content = SQL_FETCHARRAY($result);
1198
1199                 // Generate hash again
1200                 $hashFromData = generateHash(URL.":".$content['id'].":".$login.":".$content['password'], substr($content['password'], 10));
1201
1202                 // Does both match?
1203                 $valid = ($hash == $hashFromData);
1204         } // END - if
1205
1206         // Free result
1207         SQL_FREERESULT($result);
1208
1209         // Return result
1210         return $valid;
1211 }
1212 // Reset the password for the login. Do NOT call this function without calling above function first!
1213 function ADMIN_RESET_PASSWORD ($login, $password) {
1214         // Init hash
1215         $passHash = "";
1216
1217         // Now check if we have sql_patches installed
1218         if (GET_EXT_VERSION("sql_patches") >= "0.3.6") {
1219                 // Use new way of hashing
1220                 $passHash = generateHash($password);
1221         } else {
1222                 // Old MD5 method
1223                 $passHash = md5($password);
1224         }
1225
1226         // Update database
1227         SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_admins` SET password='%s' WHERE login='%s' LIMIT 1",
1228                 array($passHash, $login), __FILE__, __LINE__);
1229
1230         // Run filters
1231         RUN_FILTER('post_admin_reset_pass', array('login' => $login, 'hash' => $passHash));
1232
1233         // Return output
1234         return ADMIN_PASSWORD_RESET_DONE;
1235 }
1236 // Solves a task by given id number
1237 function ADMIN_SOLVE_TASK ($id) {
1238         // Update the task data
1239         ADMIN_UPDATE_TASK_DATA($id, "status", "SOLVED");
1240 }
1241 // Marks a given task as deleted
1242 function ADMIN_DELETE_TASK ($id) {
1243         // Update the task data
1244         ADMIN_UPDATE_TASK_DATA($id, "status", "DELETED");
1245 }
1246 // Function to update task data
1247 function ADMIN_UPDATE_TASK_DATA ($id, $row, $data) {
1248         // Update the task
1249         SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_task_system` SET %s='%s' WHERE id=%s LIMIT 1",
1250                 array($row, $data, bigintval($id)), __FILE__, __LINE__);
1251 }
1252 //
1253 ?>