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