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