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