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