0a5b93e134e771de3ff7a5fef891bdc4b539b293
[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         $ret = "404"; $pass = "";
66         if (!empty($cacheArray['admins']['aid'][$admin_login])) {
67                 // Get password from cache
68                 $pass = $cacheArray['admins']['password'][$admin_login];
69                 $ret = "pass";
70                 $_CONFIG['cache_hits']++;
71         } else {
72                 // Get password from DB
73                 $result = SQL_QUERY_ESC("SELECT password FROM "._MYSQL_PREFIX."_admins WHERE login='%s' LIMIT 1",
74                  array($admin_login), __FILE__, __LINE__);
75                 if (SQL_NUMROWS($result) == 1) {
76                         $ret = "pass";
77                         list($pass) = SQL_FETCHROW($result);
78                         SQL_FREERESULT($result);
79                 }
80         }
81
82         //* DEBUG: */ echo "*".$pass."/".md5($password)."/".$ret."<br />";
83         if ((strlen($pass) == 32) && ($pass == md5($password))) {
84                 // Generate new hash
85                 $pass = generateHash($password);
86
87                 // Is the sql_patches not installed, than we cannot have a valid hashed password here!
88                 if (($ret == "pass") && ((GET_EXT_VERSION("sql_patches") < "0.3.6") || (GET_EXT_VERSION("sql_patches") == ""))) $ret = "done";
89         } elseif ((GET_EXT_VERSION("sql_patches") < "0.3.6") || (GET_EXT_VERSION("sql_patches") == "")) {
90                 // Old hashing way
91                 return $ret;
92         }
93
94         // Generate salt of password
95         define('__SALT', substr($pass, 0, -40));
96         $salt = __SALT;
97
98         // Check if password is same
99         //* DEBUG: */ echo "*".$ret.",".$pass.",".$password.",".$salt."*<br >\n";
100         if (($ret == "pass") && ($pass == generateHash($password, $salt)) && (!empty($salt)))   {
101                 // Change the passord hash here
102                 $pass = generateHash($password);
103
104                 // Update password
105                 $result = SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_admins SET password='%s' WHERE login='%s' LIMIT 1",
106                  array($pass, $admin_login), __FILE__, __LINE__);
107
108                 // Shall I remove the cache file?
109                 if ((EXT_IS_ACTIVE("cache")) && ($cacheInstance != false)) {
110                         if ($cacheInstance->cache_file("admins", true)) $cacheInstance->cache_destroy();
111                 }
112
113                 // Login has failed by default... ;-)
114                 $ret = "failed";
115
116                 // Password matches so login here
117                 if (LOGIN_ADMIN($admin_login, $pass)) {
118                         // All done now
119                         $ret = "done";
120                 }
121         } elseif ((empty($salt)) && ($ret == "pass")) {
122                 // Something bad went wrong
123                 $ret = "failed";
124         } elseif ($ret == "done") {
125                 // Try to login here if we have the old hashing way (sql_patches not installed?)
126                 if (!LOGIN_ADMIN($admin_login, $pass)) {
127                         // Something went wrong
128                         $ret = "failed";
129                 }
130         }
131
132         // Return the result
133         //* DEBUG: */ die("RETURN=".$ret);
134         return $ret;
135 }
136
137 // Try to login the admin by setting some session/cookie variables
138 function LOGIN_ADMIN ($adminLogin, $passHash) {
139         // Now set all session variables and return the result
140         return (
141                 (
142                         set_session("admin_md5", generatePassString($passHash))
143                 ) && (
144                         set_session("admin_login", $adminLogin)
145                 ) && (
146                         set_session("admin_last", time())
147                 ) && (
148                         set_session("admin_to", $_POST['timeout'])
149                 )
150         );
151 }
152
153 // Only be executed on cookie checking
154 function CHECK_ADMIN_COOKIES ($admin_login, $password) {
155         global $cacheArray, $_CONFIG;
156         $ret = "404"; $pass = "";
157         if (!empty($cacheArray['admins']['aid'][$admin_login])) {
158                 // Get password from cache
159                 $pass = $cacheArray['admins']['password'][$admin_login];
160                 $ret = "pass";
161                 $_CONFIG['cache_hits']++;
162         } else {
163                 // Get password from DB
164                 $result = SQL_QUERY_ESC("SELECT password FROM "._MYSQL_PREFIX."_admins WHERE login='%s' LIMIT 1",
165                  array($admin_login), __FILE__, __LINE__);
166                 if (SQL_NUMROWS($result) == 1) {
167                         // Entry found
168                         $ret = "pass";
169
170                         // Fetch password
171                         list($pass) = SQL_FETCHROW($result);
172                 }
173
174                 // Free result
175                 SQL_FREERESULT($result);
176         }
177
178         //* DEBUG: */ echo __FUNCTION__.":".$pass."(".strlen($pass).")/".$password."(".strlen($password).")<br />\n";
179
180         // Check if password matches
181         if (($ret == "pass") && ((generatePassString($pass) == $password) || ($pass == $password) || ((strlen($pass) == 32) && (md5($password) == $pass)))) {
182                 // Passwords matches!
183                 $ret = "done";
184         }
185
186         // Return result
187         return $ret;
188 }
189 //
190 function admin_WriteData ($file, $comment, $prefix, $suffix, $DATA, $seek=0) {
191         // Initialize some variables
192         $done = false;
193         $seek++;
194         $found = false;
195
196         // Is the file there and read-/write-able?
197         if ((file_exists($file)) && (is_readable($file)) && (is_writeable($file))) {
198                 $search = "CFG: ".$comment;
199                 $tmp = $file.".tmp";
200
201                 // Open the source file
202                 $fp = @fopen($file, 'r') or OUTPUT_HTML("<STRONG>READ:</STRONG> ".$file."<br />");
203
204                 // Is the resource valid?
205                 if (is_resource($fp)) {
206                         // Open temporary file
207                         $fp_tmp = @fopen($tmp, 'w') or OUTPUT_HTML("<STRONG>WRITE:</STRONG> ".$tmp."<br />");
208
209                         // Is the resource again valid?
210                         if (is_resource($fp_tmp)) {
211                                 while (!feof($fp)) {
212                                         // Read from source file
213                                         $line = fgets ($fp, 1024);
214
215                                         if (strpos($line, $search) > -1) { $next = 0; $found = true; }
216
217                                         if ($next > -1) {
218                                                 if ($next == $seek) {
219                                                         $next = -1;
220                                                         $line = $prefix . $DATA . $suffix."\n";
221                                                 } else {
222                                                         $next++;
223                                                 }
224                                         }
225
226                                         // Write to temp file
227                                         fputs($fp_tmp, $line);
228                                 }
229
230                                 // Close temp file
231                                 fclose($fp_tmp);
232
233                                 // Finished writing tmp file
234                                 $done = true;
235                         }
236
237                         // Close source file
238                         fclose($fp);
239
240                         if (($done) && ($found)) {
241                                 // Copy back tmp file and delete tmp :-)
242                                 @copy($tmp, $file);
243                                 @unlink($tmp);
244                                 define('_FATAL', false);
245                         } elseif (!$found) {
246                                 OUTPUT_HTML("<STRONG>CHANGE:</STRONG> 404!");
247                                 define('_FATAL', true);
248                         } else {
249                                 OUTPUT_HTML("<STRONG>TMP:</STRONG> UNDONE!");
250                                 define('_FATAL', true);
251                         }
252                 }
253         } else {
254                 // File not found, not readable or writeable
255                 OUTPUT_HTML("<STRONG>404:</STRONG> ".$file."<br />");
256         }
257 }
258
259 //
260 function ADMIN_DO_ACTION($wht)
261 {
262         global $menuDesription, $menuTitle, $_CONFIG, $cacheArray, $link, $DATA, $DEPTH;
263         //* DEBUG: */ echo __LINE__."*".$wht."/".$GLOBALS['module']."/".$GLOBALS['action']."/".$GLOBALS['what']."*<br />\n";
264         if (EXT_IS_ACTIVE("cache"))
265         {
266                 // Include cache instance
267                 global $cacheInstance;
268         }
269
270         // Remove any spaces from variable
271         if (empty($wht))
272         {
273                 // Default admin action is the overview page
274                 $wht = "overview";
275         }
276          else
277         {
278                 // Compile out some chars
279                 $wht = COMPILE_CODE($wht, false, false, false);
280         }
281
282         // Get action value
283         $act = GET_ACTION($GLOBALS['module'], $wht);
284
285         // Define admin login name and ID number
286         define('__ADMIN_LOGIN', SQL_ESCAPE(get_session('admin_login')));
287         define('__ADMIN_ID'   , GET_ADMIN_ID(get_session('admin_login')));
288
289         // Preload templates
290         if (EXT_IS_ACTIVE("admins")) {
291                 define('__ADMIN_WELCOME', LOAD_TEMPLATE("admin_welcome_admins", true));
292         } else {
293                 define('__ADMIN_WELCOME', LOAD_TEMPLATE("admin_welcome", true));
294         }
295         define('__ADMIN_FOOTER' , LOAD_TEMPLATE("admin_footer" , true));
296         define('__ADMIN_MENU'   , ADD_ADMIN_MENU($act, $wht, true));
297
298         // Tableset header
299         LOAD_TEMPLATE("admin_main_header");
300
301         // Check if action/what pair is valid
302         $result = SQL_QUERY_ESC("SELECT id FROM "._MYSQL_PREFIX."_admin_menu
303 WHERE action='%s' AND ((what='%s' AND what != 'overview') OR ((what='' OR what IS NULL) AND '%s'='overview'))
304 LIMIT 1", array($act, $wht, $wht), __FILE__, __LINE__);
305         if (SQL_NUMROWS($result) == 1)
306         {
307                 // Free memory
308                 SQL_FREERESULT($result);
309
310                 // Is valid but does the inlcude file exists?
311                 $INC = sprintf("%sinc/modules/admin/action-%s.php", PATH, $act);
312                 if ((file_exists($INC)) && (is_readable($INC)) && (VALIDATE_MENU_ACTION("admin", $act, $wht)) && (__ACL_ALLOW == true))
313                 {
314                         // Ok, we finally load the admin action module
315                         include($INC);
316                 }
317                  elseif (__ACL_ALLOW == false)
318                 {
319                         // Access denied
320                         LOAD_TEMPLATE("admin_menu_failed", false, ADMINS_ACCESS_DENIED);
321                         ADD_FATAL(ADMINS_ACCESS_DENIED);
322                 }
323                  else
324                 {
325                         // Include file not found! :-(
326                         LOAD_TEMPLATE("admin_menu_failed", false, ADMIN_404_ACTION);
327                         ADD_FATAL(ADMIN_404_ACTION_1.$act.ADMIN_404_ACTION_2);
328                 }
329         } else {
330                 // Invalid action/what pair found!
331                 LOAD_TEMPLATE("admin_menu_failed", false, ADMIN_INVALID_ACTION);
332                 ADD_FATAL(ADMIN_INVALID_ACTION_1.$act."/".$wht.ADMIN_INVALID_ACTION_2);
333         }
334
335         // Tableset footer
336         LOAD_TEMPLATE("admin_main_footer");
337 }
338 //
339 function ADD_ADMIN_MENU($act, $wht,$return=false)
340 {
341         global $menuDesription, $menuTitle, $link;
342         $SUB = false;
343
344         // Menu descriptions
345         $menuDesription = array();
346         $menuTitle = array();
347
348         // Build main menu
349         $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__);
350         $OUT = "";
351         if (SQL_NUMROWS($result_main) > 0)
352         {
353                 $OUT = "<TABLE border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_menu_main\">
354 <TR><TD colspan=\"2\" height=\"7\" class=\"seperator\">&nbsp;</TD></TR>\n";
355                 while (list($menu, $title, $descr) = SQL_FETCHROW($result_main))
356                 {
357                         if ((EXT_IS_ACTIVE("admins")) && (GET_EXT_VERSION("admins") > "0.2"))
358                         {
359                                 $ACL = ADMINS_CHECK_ACL($menu, "");
360                         }
361                          else
362                         {
363                                 // ACL is "allow"... hmmm
364                                 $ACL = true;
365                         }
366                         if ($ACL)
367                         {
368                                 if (!$SUB)
369                                 {
370                                         // Insert compiled menu title and description
371                                         $menuTitle[$menu]        = $title;
372                                         $menuDesription[$menu] = $descr;
373                                 }
374                                 $OUT .= "<TR>
375         <TD class=\"admin_menu\" colspan=\"2\">
376                 <NOBR>&nbsp;<STRONG>&middot;</STRONG>&nbsp;";
377                                         if (($menu == $act) && (empty($wht)))
378                                 {
379                                         $OUT .= "<STRONG>";
380                                 }
381                                  else
382                                 {
383                                         $OUT .= "[<A href=\"".URL."/modules.php?module=admin&amp;action=".$menu."\">";
384                                 }
385                                 $OUT .= $title;
386                                         if (($menu == $act) && (empty($wht)))
387                                 {
388                                         $OUT .= "</STRONG>";
389                                 }
390                                  else
391                                 {
392                                         $OUT .= "</A>]";
393                                 }
394                                 $OUT .= "</NOBR></TD>
395 </TR>\n";
396                                 $result_what = SQL_QUERY_ESC("SELECT what, title, descr FROM "._MYSQL_PREFIX."_admin_menu WHERE action='%s' AND what != '' ORDER BY sort, id DESC",
397                                  array($menu), __FILE__, __LINE__);
398                                 if ((SQL_NUMROWS($result_what) > 0) && ($act == $menu))
399                                 {
400                                         $menuDesription = array();
401                                         $menuTitle = array(); $SUB = true;
402                                         $OUT .= "<TR>
403         <TD width=\"10\" class=\"seperator\">&nbsp;</TD>
404         <TD class=\"admin_menu\">
405                 <TABLE border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_menu_sub\">\n";
406                                                 while (list($wht_sub, $title_what, $desc_what) = SQL_FETCHROW($result_what))
407                                         {
408                                                 // Filename
409                                                 $INC = sprintf("%sinc/modules/admin/what-%s.php", PATH, $wht_sub);
410                                                 if ((EXT_IS_ACTIVE("admins")) && (GET_EXT_VERSION("admins") > "0.2"))
411                                                 {
412                                                         $ACL = ADMINS_CHECK_ACL("", $wht_sub);
413                                                 }
414                                                  else
415                                                 {
416                                                         // ACL is "allow"... hmmm
417                                                         $ACL = true;
418                                                 }
419                                                 $readable = ((file_exists($INC)) && (is_readable($INC)));
420                                                 if ($ACL)
421                                                 {
422                                                         // Insert compiled title and description
423                                                         $menuTitle[$wht_sub]        = $title_what;
424                                                         $menuDesription[$wht_sub] = $desc_what;
425                                                         $OUT .= "<TR>
426         <TD class=\"admin_menu\" colspan=\"2\">
427                 <NOBR>&nbsp;<STRONG>--&gt;</STRONG>&nbsp;";
428                                                         if ($readable)
429                                                         {
430                                                                 if ($wht == $wht_sub)
431                                                                 {
432                                                                         $OUT .= "<STRONG>";
433                                                                 }
434                                                                  else
435                                                                 {
436                                                                         $OUT .= "[<A href=\"".URL."/modules.php?module=admin&amp;what=".$wht_sub."\">";
437                                                                 }
438                                                         }
439                                                          else
440                                                         {
441                                                                 $OUT .= "<I class=\"admin_note\">";
442                                                         }
443                                                         $OUT .= $title_what;
444                                                         if ($readable)
445                                                         {
446                                                                 if ($wht == $wht_sub)
447                                                                 {
448                                                                         $OUT .= "</STRONG>";
449                                                                 }
450                                                                  else
451                                                                 {
452                                                                         $OUT .= "</A>]";
453                                                                 }
454                                                         }
455                                                          else
456                                                         {
457                                                                 $OUT .= "</I>";
458                                                         }
459                                                         $OUT .= "</NOBR></TD>
460 </TR>\n";
461                                                 }
462                                         }
463
464                                         // Free memory
465                                         SQL_FREERESULT($result_what);
466                                         $OUT .= "    </TABLE>
467         </TD>
468 </TR>\n";
469                                 }
470                                 $OUT .= "<TR><TD height=\"7\" colspan=\"2\"></TD></TR>\n";
471                         }
472                 }
473
474                 // Free memory
475                 SQL_FREERESULT($result_main);
476                 $OUT .= "</TABLE>\n";
477         }
478
479         // Compile and run the code here. This inserts all constants into the
480         // HTML output. Costs me some time to figure this out... *sigh* Quix0r
481         $eval = "\$OUT = \"".COMPILE_CODE(addslashes($OUT))."\";";
482         eval($eval);
483
484         // Return or output content?
485         if ($return) {
486                 return $OUT;
487         } else {
488                 OUTPUT_HTML($OUT);
489         }
490 }
491 //
492 function ADD_MEMBER_SELECTION_BOX($add_all = false, $return = false, $none = false, $def = "0")
493 {
494         // Output selection form with all confirmed user accounts listed
495         $result = SQL_QUERY("SELECT userid, surname, family FROM "._MYSQL_PREFIX."_user_data ORDER BY userid", __FILE__, __LINE__);
496         $OUT = "";
497
498         // USe this only for adding points (e.g. adding refs really makes no sence ;-) )
499         if ($add_all) $OUT = "      <OPTION value=\"all\">".ALL_MEMBERS."</OPTION>\n";
500          elseif ($none) $OUT = "      <OPTION value=\"0\">".SELECT_NONE."</OPTION>\n";
501         while (list($id, $sname, $fname) = SQL_FETCHROW($result))
502         {
503                 $OUT .= "      <OPTION value=\"".$id."\"";
504                 if ($def == $id) $OUT .= " selected=\"selected\"";
505                 $OUT .= ">".$sname." ".$fname." (".$id.")</OPTION>\n";
506         }
507
508         // Free memory
509         SQL_FREERESULT($result);
510
511         // Remeber options in constant
512         define('_MEMBER_SELECTION', $OUT);
513
514         if (!$return) {
515                 // Display selection box
516                 define('__LANG_VALUE', GET_LANGUAGE());
517
518                 // Load template
519                 LOAD_TEMPLATE("admin_member_selection_box", false, $GLOBALS['what']);
520         }
521 }
522 //
523 function ADMIN_MENU_SELECTION($MODE, $default="", $defid="") {
524         $wht = "what != ''";
525         if ($MODE == "action") $wht = "(what='' OR what IS NULL) AND action !='login'";
526         $result = SQL_QUERY_ESC("SELECT %s, title FROM "._MYSQL_PREFIX."_admin_menu WHERE ".$wht." ORDER BY sort",
527          array($MODE), __FILE__, __LINE__);
528         if (SQL_NUMROWS($result) > 0)
529         {
530                 // Load menu as selection
531                 $OUT = "<SELECT name=\"".$MODE."_menu";
532                 if ((!empty($defid)) || ($defid == "0")) $OUT .= "[".$defid."]";
533                 $OUT .= "\" size=\"1\" class=\"admin_select\">
534         <OPTION value=\"\">".SELECT_NONE."</OPTION>\n";
535                 while (list($menu, $title) = SQL_FETCHROW($result))
536                 {
537                         $OUT .= "  <OPTION value=\"".$menu."\"";
538                         if ((!empty($default)) && ($default == $menu)) $OUT .= " selected=\"selected\"";
539                         $OUT .= ">".$title."</OPTION>\n";
540                 }
541
542                 // Free memory
543                 SQL_FREERESULT($result);
544                 $OUT .= "</SELECT>\n";
545         }
546          else
547         {
548                 // No menus???
549                 $OUT = ADMIN_PROBLEM_NO_MENU;
550         }
551
552         // Return output
553         return $OUT;
554 }
555 //
556 function ADMIN_SAVE_SETTINGS (&$POST, $tableName="_config", $whereStatement="config=0", $translateComma = array(), $alwaysAdd=false)
557 {
558         global $_CONFIG, $cacheArray, $cacheInstance;
559         $DATA = array();
560         $skip = false; $TEST2 = "";
561         foreach ($POST as $id=>$val) {
562                 // Process only formular field but not submit buttons ;)
563                 if ($id != "ok") {
564                         // Do not save the ok value
565                         $TEST = substr($id, -3);
566                         if ((($TEST == "_ye") || ($TEST == "_mo") || ($TEST == "_we") || ($TEST == "_da") || ($TEST == "_ho") || ($TEST == "_mi") || ($TEST == "_se")) && (isset($val))) {
567                                 // Found a multi-selection for timings?
568                                 $TEST = substr($id, 0, -3);
569                                 if ((isset($POST[$TEST."_ye"])) && (isset($POST[$TEST."_mo"])) && (isset($POST[$TEST."_we"])) && (isset($POST[$TEST."_da"])) && (isset($POST[$TEST."_ho"])) && (isset($POST[$TEST."_mi"])) && (isset($POST[$TEST."_se"])) && ($TEST != $TEST2)) {
570                                         // Generate timestamp
571                                         $POST[$TEST] = CREATE_TIMESTAMP_FROM_SELECTIONS($TEST, $POST);
572                                         $DATA[] = "$TEST='".$POST[$TEST]."'";
573
574                                         // Remove data from array
575                                         unset($POST[$TEST."_ye"]);
576                                         unset($POST[$TEST."_mo"]);
577                                         unset($POST[$TEST."_we"]);
578                                         unset($POST[$TEST."_da"]);
579                                         unset($POST[$TEST."_ho"]);
580                                         unset($POST[$TEST."_mi"]);
581                                         unset($POST[$TEST."_se"]);
582
583                                         // Skip adding
584                                         unset($id); $skip = true; $TEST2 = $TEST;
585                                 }
586                         } else {
587                                 // Process this entry
588                                 $skip = false; $TEST2 = "";
589                         }
590
591                         // Shall we process this ID? It muss not be empty, of course
592                         if ((!$skip) && (!empty($id))) {
593                                 // Save this entry
594                                 $val = COMPILE_CODE($val);
595
596                                 // Translate the value? (comma to dot!)
597                                 if ((is_array($translateComma)) && (in_array($id, $translateComma))) {
598                                         // Then do it here... :)
599                                         $val = str_replace(",", ".", $val);
600                                 }
601
602                                 // Shall we add numbers or strings?
603                                 $test = (float)$val;
604                                 if ("".$val."" == "".$test."") {
605                                         // Add numbers
606                                         $DATA[] = $id."=".$val."";
607                                 } else {
608                                         // Add strings
609                                         $DATA[] = $id."='".trim($val)."'";
610                                 }
611
612                                 // Update current configuration
613                                 $_CONFIG[$id] = $val;
614                         }
615                 }
616         }
617
618         // Check if entry does exist
619         $result = false;
620         if (!$alwaysAdd) {
621                 if (!empty($whereStatement)) {
622                         $result = SQL_QUERY("SELECT * FROM "._MYSQL_PREFIX.$tableName." WHERE ".$whereStatement." LIMIT 1", __FILE__, __LINE__);
623                 } else {
624                         $result = SQL_QUERY("SELECT * FROM "._MYSQL_PREFIX.$tableName." LIMIT 1", __FILE__, __LINE__);
625                 }
626         }
627
628         if (SQL_NUMROWS($result) == 1) {
629                 // "Implode" all data to single string
630                 $DATA_UPDATE = implode(", ", $DATA);
631
632                 // Generate SQL string
633                 $SQL = "UPDATE "._MYSQL_PREFIX.$tableName." SET ".$DATA_UPDATE." WHERE ".$whereStatement." LIMIT 1";
634         } else {
635                 // Add Line (does only work with auto_increment!
636                 $KEYs = array(); $VALUEs = array();
637                 foreach ($DATA as $entry) {
638                         // Split up
639                         $line = explode("=", $entry);
640                         $KEYs[] = $line[0]; $VALUEs[] = $line[1];
641                 }
642
643                 // Add both in one line
644                 $KEYs = implode(", ", $KEYs);
645                 $VALUEs = implode(", ", $VALUEs);
646
647                 // Generate SQL string
648                 $SQL = "INSERT INTO "._MYSQL_PREFIX.$tableName." (".$KEYs.") VALUES(".$VALUEs.")";
649         }
650
651         // Free memory
652         SQL_FREERESULT($result);
653
654         // Simply run generated SQL string
655         $result = SQL_QUERY($SQL, __FILE__, __LINE__);
656
657         // Is the config table updated and the cache extension installed?
658         if ((GET_EXT_VERSION("cache") >= "0.1.2") && ($tableName == "_config")) {
659                 // Remove it here...
660                 if ($cacheInstance->cache_file("config", true)) $cacheInstance->cache_destroy();
661                 unset($cacheArray);
662         }
663
664         // Settings saved
665         LOAD_TEMPLATE("admin_settings_saved", false, "<STRONG class=\"admin_done\">".SETTINGS_SAVED."</STRONG>");
666 }
667 //
668 function ADMIN_MAKE_MENU_SELECTION($menu, $type, $name, $default="") {
669         // Init the selection box
670         $OUT = "<SELECT name=\"".$name."\" class=\"admin_select\" size=\"1\">\n <OPTION value=\"\">".IS_TOP_MENU."</OPTION>\n";
671
672         // Open the requested menu directory
673         $handle = opendir(PATH."inc/modules/".$menu."/") or mxchange_die("Cannot load menu ".$menu."!");
674         while ($file = readdir($handle)) {
675                 // Is this a PHP script?
676                 if (($file != ".") && ($file != "..") && ($file != "lost+found") && (strpos($file, "".$type."-") > -1) && (strpos($file, ".php") > 0)) {
677                         // Then test if the file is readable
678                         $test = PATH."inc/modules/".$menu."/".$file;
679                         if (is_readable($test)) {
680                                 // Extract the value for what=xxx
681                                 $part = substr($file, (strlen($type) + 1)); $part = substr($part, 0, strpos($part, ".php"));
682
683                                 // Is that part different from the overview?
684                                 if ($part != "overview") {
685                                         $OUT .= "       <OPTION value=\"".$part."\"";
686                                         if ($part == $default) $OUT .= "selected";
687                                         $OUT .= ">".$part."</OPTION>\n";
688                                 }
689                         }
690                 }
691         }
692         closedir($handle);
693         $OUT .= "</SELECT>\n";
694         return $OUT;
695 }
696 //
697 function ADMIN_USER_PROFILE_LINK($uid, $title="", $wht="list_user")
698 {
699         if (($title == "") && ($title != "0")) { $title = $uid; }
700         if (($title == "0") && ($wht == "list_refs"))
701         {
702                 // Return title again
703                 return $title;
704         }
705
706         //* DEBUG: */ echo "A:".$title."<br />";
707         // Return link
708         return "<A href=\"".URL."/modules.php?module=admin&amp;what=".$wht."&amp;u_id=".$uid."\" title=\"".ADMIN_USER_PROFILE_TITLE."\">".$title."</A>";
709 }
710 //
711 function ADMIN_CHECK_MENU_MODE()
712 {
713         global $_CONFIG, $cacheArray;
714
715         // Set the global mode as the mode for all admins
716         $MODE = $_CONFIG['admin_menu']; $ADMIN = $MODE;
717
718         // Check individual settings of current admin
719         if (isset($cacheArray['admins']['la_mode'][get_session('admin_login')]))
720         {
721                 // Load from cache
722                 $ADMIN = $cacheArray['admins']['la_mode'][get_session('admin_login')];
723                 $_CONFIG['cache_hits']++;
724         }
725          elseif (GET_EXT_VERSION("admins") >= "0.6.7")
726         {
727                 // Load from database when version of "admins" is enough
728                 $result = SQL_QUERY_ESC("SELECT la_mode FROM "._MYSQL_PREFIX."_admins WHERE login='%s' LIMIT 1",
729                  array(get_session('admin_login')), __FILE__, __LINE__);
730                 if (SQL_NUMROWS($result) == 1)
731                 {
732                         // Load data
733                         list($ADMIN) = SQL_FETCHROW($result);
734                 }
735
736                 // Free memory
737                 SQL_FREERESULT($result);
738         }
739
740         // Check what the admin wants and set it when it's not the global mode
741         if ($ADMIN != "global") $MODE = $ADMIN;
742
743         // Return admin-menu's mode
744         return $MODE;
745 }
746 // Change activation status
747 function ADMIN_CHANGE_ACTIVATION_STATUS ($IDs, $table, $row, $idRow = "id") {
748         global $_CONFIG;
749         $cnt = 0; $newStatus = "Y";
750         if ((is_array($IDs)) && (count($IDs) > 0)) {
751                 // "Walk" all through and count them
752                 foreach ($IDs as $id=>$selected) {
753                         // Secure the ID number
754                         $id = bigintval($id);
755
756                         // Should always be 1 ;-)
757                         if ($selected == 1) {
758                                 // Determine new status
759                                 $result = SQL_QUERY_ESC("SELECT %s FROM "._MYSQL_PREFIX."_%s WHERE %s=%d LIMIT 1",
760                                         array($row, $table, $idRow, $id), __FILE__, __LINE__);
761
762                                 // Row found?
763                                 if (SQL_NUMROWS($result) == 1) {
764                                         // Load the status
765                                         list($currStatus) = SQL_FETCHROW($result);
766                                         if ($currStatus == "Y") $newStatus='N'; else $newStatus = "Y";
767
768                                         // Change this status
769                                         SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_%s SET %s='%s' WHERE %s=%d LIMIT 1",
770                                                 array($table, $row, $newStatus, $idRow, $id), __FILE__, __LINE__);
771
772                                         // Count up affected rows
773                                         $cnt += SQL_AFFECTEDROWS();
774                                 }
775
776                                 // Free the result
777                                 SQL_FREERESULT($result);
778                         }
779                 }
780
781                 // Output status
782                 LOAD_TEMPLATE("admin_settings_saved", false, ADMIN_STATUS_CHANGED_1.$cnt.ADMIN_STATUS_CHANGED_2.count($IDs).ADMIN_STATUS_CHANGED_3);
783         } else {
784                 // Nothing selected!
785                 LOAD_TEMPLATE("admin_settings_saved", false, ADMIN_NOTHING_SELECTED_CHANGE);
786         }
787 }
788 // Delete rows by given ID numbers
789 function ADMIN_DELETE_ENTRIES_CONFIRM ($IDs, $table, $row, $columns = array(), $filterFunctions = array(), $deleteNow=false, $idRow="id") {
790         global $_CONFIG;
791         $OUT = ""; $SW = 2;
792         if ((is_array($IDs)) && (count($IDs) > 0)) {
793                 // "Walk" through all entries and count them
794                 if ($deleteNow) {
795                         // Delete them
796                         die("DELETE!");
797                 } else {
798                         // List for confirmation
799                         foreach ($IDs as $id => $selected) {
800                                 // Secure ID number
801                                 $id = bigintval($id);
802
803                                 // Will always be 1 ;-)
804                                 if ($selected == 1) {
805                                         // Get result from a given column array and table name
806                                         $result = SQL_RESULT_FROM_ARRAY($table, $columns, $idRow, $id);
807
808                                         // Is there one entry?
809                                         if (SQL_NUMROWS($result) == 1) {
810                                                 // Load all data
811                                                 $content = SQL_FETCHARRAY($result);
812
813                                                 // Filter all data
814                                                 foreach ($content as $key=>$value) {
815                                                         // Is a filter function set?
816                                                         $idx = array_search($key, $columns, true);
817                                                         if (!empty($filterFunctions[$idx])) {
818                                                                 // Then call it!
819                                                                 $content[$key] = call_user_func($filterFunctions[$idx], $value);
820                                                         }
821                                                 }
822
823                                                 // Add color switching
824                                                 $content['sw'] = $SW;
825
826                                                 // Then list it again...
827                                                 $OUT .= LOAD_TEMPLATE("admin_del_".$table."_row", true, $content);
828                                                 $SW = 3 - $SW;
829                                         }
830
831                                         // Free the result
832                                         SQL_FREERESULT($result);
833                                 }
834                         }
835
836                         // Load master template
837                         LOAD_TEMPLATE("admin_del_".$table."", false, $OUT);
838                 }
839         }
840 }
841 // Edit rows by given ID numbers
842 function ADMIN_EDIT_ENTRIES_CONFIRM ($IDs, $table, $row, $columns = array(), $filterFunctions = array(), $editNow=false, $idRow="id") {
843         global $_CONFIG;
844         $OUT = ""; $SW = 2;
845         if ((is_array($IDs)) && (count($IDs) > 0)) {
846                 // "Walk" through all entries and count them
847                 if ($editNow) {
848                         // Delete them
849                         die("EDIT!");
850                 } else {
851                         // List for confirmation
852                         foreach ($IDs as $id => $selected) {
853                                 // Secure ID number
854                                 $id = bigintval($id);
855
856                                 // Will always be 1 ;-)
857                                 if ($selected == 1) {
858                                         // Get result from a given column array and table name
859                                         $result = SQL_RESULT_FROM_ARRAY($table, $columns, $idRow, $id);
860
861                                         // Is there one entry?
862                                         if (SQL_NUMROWS($result) == 1) {
863                                                 // Load all data
864                                                 $content = SQL_FETCHARRAY($result);
865
866                                                 // Filter all data
867                                                 foreach ($content as $key=>$value) {
868                                                         // Is a filter function set?
869                                                         $idx = array_search($key, $columns, true);
870                                                         if (!empty($filterFunctions[$idx])) {
871                                                                 // Then call it!
872                                                                 $content[$key] = call_user_func($filterFunctions[$idx], $value);
873                                                         }
874                                                 }
875
876                                                 // Add color switching
877                                                 $content['sw'] = $SW;
878
879                                                 // Then list it again...
880                                                 $OUT .= LOAD_TEMPLATE("admin_edit_".$table."_row", true, $content);
881                                                 $SW = 3 - $SW;
882                                         }
883
884                                         // Free the result
885                                         SQL_FREERESULT($result);
886                                 }
887                         }
888
889                         // Load master template
890                         LOAD_TEMPLATE("admin_edit_".$table."", false, $OUT);
891                 }
892         }
893 }
894 // Checks proxy settins by fetching check-updates2.php from www.mxchange.org
895 function ADMIN_TEST_PROXY_SETTINGS ($settingsArray) {
896         global $_CONFIG;
897         // By default they are invalid
898         $valid = false;
899
900         // Set temporary the new settings
901         $_CONFIG = array_merge($_CONFIG, $settingsArray);
902
903         // Now get the test URL
904         $content = MXCHANGE_OPEN("check-updates2.php");
905
906         // Is the first line with "200 OK"?
907         $valid = eregi("200 OK", $content[0]);
908
909         // Return result
910         return $valid;
911 }
912 // Sends out a link to the given email adress so the admin can reset his/her password
913 function ADMIN_SEND_PASSWORD_RESET_LINK ($email) {
914         global $_CONFIG;
915         // Init output
916         $OUT = "";
917
918         // Compile out security characters (must be for looking up!)
919         $email = COMPILE_CODE($email);
920
921         // Look up administator login
922         $result = SQL_QUERY_ESC("SELECT id, login, password FROM "._MYSQL_PREFIX."_admins WHERE email='%s' LIMIT 1",
923                 array($email), __FILE__, __LINE__);
924
925         // Is there an account?
926         if (SQL_NUMROWS($result) == 0) {
927                 // No account found!
928                 return ADMIN_NO_LOGIN_WITH_EMAIL;
929         } // END - if
930
931         // Load all data
932         $content = SQL_FETCHARRAY($result);
933
934         // Free result
935         SQL_FREERESULT($result);
936
937         // Generate hash for reset link
938         $content['hash'] = generateHash(URL.":".$content['id'].":".$content['login'].":".$content['password'], substr($content['password'], 10));
939
940         // Remove some data
941         unset($content['id']);
942         unset($content['password']);
943
944         // Prepare email
945         $mailText = LOAD_EMAIL_TEMPLATE("admin_reset_password", $content);
946
947         // Send it out
948         SEND_EMAIL($email, ADMIN_RESET_PASS_LINK_SUBJ, $mailText);
949
950         // Prepare output
951         return ADMIN_RESET_LINK_SENT;
952 }
953 // Validate hash and login for password reset
954 function ADMIN_VALIDATE_RESET_LINK_HASH_LOGIN ($hash, $login) {
955         // By default nothing validates... ;)
956         $valid = false;
957
958         // Compile the login for lookup
959         $login = COMPILE_CODE($login);
960
961         // Then try to find that user
962         $result = SQL_QUERY_ESC("SELECT id, password, email FROM "._MYSQL_PREFIX."_admins WHERE login='%s' LIMIT 1",
963                 array($login), __FILE__, __LINE__);
964
965         // Is an account here?
966         if (SQL_NUMROWS($result) == 1) {
967                 // Load all data
968                 $content = SQL_FETCHARRAY($result);
969
970                 // Generate hash again
971                 $hashFromData = generateHash(URL.":".$content['id'].":".$login.":".$content['password'], substr($content['password'], 10));
972
973                 // Does both match?
974                 $valid = ($hash == $hashFromData);
975         } // END - if
976
977         // Free result
978         SQL_FREERESULT($result);
979
980         // Return result
981         return $valid;
982 }
983 // Reset the password for the login. Do NOT call this function without calling above function first!
984 function ADMIN_RESET_PASSWORD ($login, $password) {
985         // Init hash
986         $passHash = "";
987
988         // Now check if we have sql_patches installed
989         if (GET_EXT_VERSION("sql_patches") >= "0.3.6") {
990                 // Use new way of hashing
991                 $passHash = generateHash($password);
992         } else {
993                 // Old MD5 method
994                 $passHash = md5($password);
995         }
996
997         // Update database
998         SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_admins SET password='%s' WHERE login='%s' LIMIT 1",
999                 array($passHash, $login), __FILE__, __LINE__);
1000
1001         // Return output
1002         return ADMIN_PASSWORD_RESET_DONE;
1003 }
1004 //
1005 ?>