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