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