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