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