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