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