Functions imported, some dev-scripts added
[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_failures'] = $cacheArray['admins']['login_failures'][$aid];
87                         $data['last_failure']   = $cacheArray['admins']['last_failure'][$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 failures if available
137                 if (GET_EXT_VERSION("admins") >= "0.7.2") {
138                         // Store it in session
139                         set_session('mxchange_admin_failures', $data['login_failures']);
140                         set_session('mxchange_admin_last_fail', $data['last_failure']);
141
142                         // Update password and reset login failures
143                         SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_admins` SET password='%s',login_failures=0,last_failure='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 failure 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_failures=login_failures+1,last_failure=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 failure 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_failures=0,last_failure='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("inc/modules/admin/action-%s.php", $act);
353                 if ((INCLUDE_READABLE($INC)) && (VALIDATE_MENU_ACTION("admin", $act, $wht)) && (__ACL_ALLOW == true)) {
354                         // Ok, we finally load the admin action module
355                         LOAD_INC($INC);
356                 } elseif (__ACL_ALLOW == false) {
357                         // Access denied
358                         LOAD_TEMPLATE("admin_menu_failed", false, getMessage('ADMIN_ACCESS_DENIED'));
359                         addFatalMessage(getMessage('ADMIN_ACCESS_DENIED'));
360                 } else {
361                         // Include file not found! :-(
362                         LOAD_TEMPLATE("admin_menu_failed", false, sprintf(getMessage('ADMIN_ACTION_404'), $act));
363                         addFatalMessage(getMessage('ADMIN_ACTION_404'), $act);
364                 }
365         } else {
366                 // Invalid action/what pair found!
367                 LOAD_TEMPLATE("admin_menu_failed", false, sprintf(getMessage('ADMIN_ACTION_INVALID'), $act."/".$wht));
368                 addFatalMessage(getMessage('ADMIN_ACTION_INVALID'), $act."/".$wht);
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                 $OUT = "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_menu_main\">
417 <tr><td colspan=\"2\" height=\"7\" class=\"seperator\">&nbsp;</td></tr>\n";
418                 while (list($menu, $title, $descr) = SQL_FETCHROW($result_main)) {
419                         if ((EXT_IS_ACTIVE("admins")) && (GET_EXT_VERSION("admins") > "0.2")) {
420                                 $ACL = ADMINS_CHECK_ACL($menu, "");
421                         } else {
422                                 // ACL is "allow"... hmmm
423                                 $ACL = true;
424                         }
425
426                         if ($ACL === true) {
427                                 if (!$SUB) {
428                                         // Insert compiled menu title and description
429                                         $menuTitle[$menu]      = $title;
430                                         $menuDesription[$menu] = $descr;
431                                 }
432                                 $OUT .= "<tr>
433         <td class=\"admin_menu\" colspan=\"2\">
434                 <NOBR>&nbsp;<strong>&middot;</strong>&nbsp;";
435                                 if (($menu == $act) && (empty($wht)))
436                                 {
437                                         $OUT .= "<strong>";
438                                 }
439                                  else
440                                 {
441                                         $OUT .= "[<a href=\"{!URL!}/modules.php?module=admin&amp;action=".$menu."\">";
442                                 }
443                                 $OUT .= $title;
444                                 if (($menu == $act) && (empty($wht)))
445                                 {
446                                         $OUT .= "</strong>";
447                                 }
448                                  else
449                                 {
450                                         $OUT .= "</a>]";
451                                 }
452                                 $OUT .= "</NOBR></td>
453 </tr>\n";
454                                 $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",
455                                         array($menu), __FILE__, __LINE__);
456                                 if ((SQL_NUMROWS($result_what) > 0) && ($act == $menu))
457                                 {
458                                         $menuDesription = array();
459                                         $menuTitle = array(); $SUB = true;
460                                         $OUT .= "<tr>
461         <td width=\"10\" class=\"seperator\">&nbsp;</td>
462         <td class=\"admin_menu\">
463                 <table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_menu_sub\">\n";
464                                         while (list($wht_sub, $title_what, $desc_what) = SQL_FETCHROW($result_what)) {
465                                                 // Filename
466                                                 $INC = sprintf("%sinc/modules/admin/what-%s.php", constant('PATH'), $wht_sub);
467                                                 if ((EXT_IS_ACTIVE("admins")) && (GET_EXT_VERSION("admins") > "0.2")) {
468                                                         $ACL = ADMINS_CHECK_ACL("", $wht_sub);
469                                                 } else {
470                                                         // ACL is "allow"... hmmm
471                                                         $ACL = true;
472                                                 }
473                                                 $readable = INCLUDE_READABLE($INC);
474                                                 if ($ACL === true) {
475                                                         // Insert compiled title and description
476                                                         $menuTitle[$wht_sub]      = $title_what;
477                                                         $menuDesription[$wht_sub] = $desc_what;
478                                                         $OUT .= "<tr>
479         <td class=\"admin_menu\" colspan=\"2\">
480                 <NOBR>&nbsp;<strong>--&gt;</strong>&nbsp;";
481                                                         if ($readable === true)
482                                                         {
483                                                                 if ($wht == $wht_sub)
484                                                                 {
485                                                                         $OUT .= "<strong>";
486                                                                 }
487                                                                  else
488                                                                 {
489                                                                         $OUT .= "[<a href=\"{!URL!}/modules.php?module=admin&amp;what=".$wht_sub."\">";
490                                                                 }
491                                                         }
492                                                          else
493                                                         {
494                                                                 $OUT .= "<i class=\"admin_note\">";
495                                                         }
496                                                         $OUT .= $title_what;
497                                                         if ($readable === true)
498                                                         {
499                                                                 if ($wht == $wht_sub)
500                                                                 {
501                                                                         $OUT .= "</strong>";
502                                                                 }
503                                                                  else
504                                                                 {
505                                                                         $OUT .= "</a>]";
506                                                                 }
507                                                         }
508                                                          else
509                                                         {
510                                                                 $OUT .= "</em>";
511                                                         }
512                                                         $OUT .= "</NOBR></td>
513 </tr>\n";
514                                                 }
515                                         }
516
517                                         // Free memory
518                                         SQL_FREERESULT($result_what);
519                                         $OUT .= "    </table>
520         </td>
521 </tr>\n";
522                                 }
523                                 $OUT .= "<tr><td height=\"7\" colspan=\"2\"></td></tr>\n";
524                         }
525                 }
526
527                 // Free memory
528                 SQL_FREERESULT($result_main);
529                 $OUT .= "</table>\n";
530         }
531
532         // Compile and run the code here. This inserts all constants into the
533         // HTML output. Costs me some time to figure this out... *sigh* Quix0r
534         $eval = "\$OUT = \"".COMPILE_CODE(SQL_ESCAPE($OUT))."\";";
535         eval($eval);
536
537         // Is there a cache instance again?
538         if ((is_object($cacheInstance)) && (getConfig('cache_admin_menu') == "Y")) {
539                 // Init cache
540                 $cacheInstance->init($cacheName);
541
542                 // Prepare cache data
543                 $data = array(
544                         'output' => base64_encode($OUT),
545                         'title'  => $menuTitle,
546                         'descr'  => $menuDesription
547                 );
548
549                 // Write the data away
550                 $cacheInstance->addRow($data);
551
552                 // Close cache
553                 $cacheInstance->finalize();
554         } // END - if
555
556         // Return or output content?
557         if ($return) {
558                 return $OUT;
559         } else {
560                 OUTPUT_HTML($OUT);
561         }
562 }
563 //
564 function ADD_MEMBER_SELECTION_BOX ($def="0", $add_all=false, $return=false, $none=false, $field="userid")
565 {
566         // Output selection form with all confirmed user accounts listed
567         $result = SQL_QUERY("SELECT userid, surname, family FROM `{!_MYSQL_PREFIX!}_user_data` ORDER BY userid", __FILE__, __LINE__);
568         $OUT = "";
569
570         // USe this only for adding points (e.g. adding refs really makes no sence ;-) )
571         if ($add_all) $OUT = "      <option value=\"all\">".ALL_MEMBERS."</option>\n";
572          elseif ($none) $OUT = "      <option value=\"0\">".SELECT_NONE."</option>\n";
573         while (list($id, $sname, $fname) = SQL_FETCHROW($result))
574         {
575                 $OUT .= "      <option value=\"".bigintval($id)."\"";
576                 if ($def == $id) $OUT .= " selected=\"selected\"";
577                 $OUT .= ">".$sname." ".$fname." (".bigintval($id).")</option>\n";
578         }
579
580         // Free memory
581         SQL_FREERESULT($result);
582
583         if (!$return) {
584                 // Remeber options in constant
585                 define('_MEMBER_SELECTION', $OUT);
586
587                 // Display selection box
588                 define('__LANG_VALUE', GET_LANGUAGE());
589
590                 // Load template
591                 LOAD_TEMPLATE("admin_member_selection_box", false, $GLOBALS['what']);
592         } else {
593                 // Return content in selection frame
594                 return "<select class=\"admin_select\" name=\"".$field."\" size=\"1\">\n".$OUT."</select>\n";
595         }
596 }
597 //
598 function ADMIN_MENU_SELECTION($MODE, $default="", $defid="") {
599         $wht = "`what` != ''";
600         if ($MODE == "action") $wht = "(what='' OR `what` IS NULL) AND action !='login'";
601         $result = SQL_QUERY_ESC("SELECT %s, title FROM `{!_MYSQL_PREFIX!}_admin_menu` WHERE ".$wht." ORDER BY `sort`",
602          array($MODE), __FILE__, __LINE__);
603         if (SQL_NUMROWS($result) > 0) {
604                 // Load menu as selection
605                 $OUT = "<select name=\"".$MODE."_menu";
606                 if ((!empty($defid)) || ($defid == "0")) $OUT .= "[".$defid."]";
607                 $OUT .= "\" size=\"1\" class=\"admin_select\">
608         <option value=\"\">".SELECT_NONE."</option>\n";
609                 while (list($menu, $title) = SQL_FETCHROW($result)) {
610                         $OUT .= "  <option value=\"".$menu."\"";
611                         if ((!empty($default)) && ($default == $menu)) $OUT .= " selected=\"selected\"";
612                         $OUT .= ">".$title."</option>\n";
613                 } // END - while
614
615                 // Free memory
616                 SQL_FREERESULT($result);
617                 $OUT .= "</select>\n";
618         } else {
619                 // No menus???
620                 $OUT = ADMIN_PROBLEM_NO_MENU;
621         }
622
623         // Return output
624         return $OUT;
625 }
626
627 // Save settings to the database
628 function ADMIN_SAVE_SETTINGS (&$POST, $tableName="_config", $whereStatement="config=0", $translateComma=array(), $alwaysAdd=false) {
629         global $cacheArray, $cacheInstance;
630
631         // Prepare all arrays, variables
632         $DATA = array();
633         $skip = false;
634
635         // Now, walk through all entries and prepare them for saving
636         foreach ($POST as $id => $val) {
637                 // Process only formular field but not submit buttons ;)
638                 if ($id != "ok") {
639                         // Do not save the ok value
640                         CONVERT_SELECTIONS_TO_TIMESTAMP($POST, $DATA, $id, $skip);
641
642                         // Shall we process this ID? It muss not be empty, of course
643                         if ((!$skip) && (!empty($id))) {
644                                 // Save this entry
645                                 $val = COMPILE_CODE($val);
646
647                                 // Translate the value? (comma to dot!)
648                                 if ((is_array($translateComma)) && (in_array($id, $translateComma))) {
649                                         // Then do it here... :)
650                                         $val = REVERT_COMMA($val);
651                                 } // END - if
652
653                                 // Shall we add numbers or strings?
654                                 $test = (float)$val;
655                                 if ("".$val."" == "".$test."") {
656                                         // Add numbers
657                                         $DATA[] = sprintf("`%s`=%s", $id, $test);
658                                 } else {
659                                         // Add strings
660                                         $DATA[] = sprintf("`%s`='%s'", $id, trim($val));
661                                 }
662
663                                 // Update current configuration
664                                 setConfigEntry($id, $val);
665                         } // END - if
666                 } // END - if
667         } // END - foreach
668
669         // Check if entry does exist
670         $result = false;
671         if (!$alwaysAdd) {
672                 if (!empty($whereStatement)) {
673                         $result = SQL_QUERY("SELECT * FROM `{!_MYSQL_PREFIX!}".$tableName."` WHERE ".$whereStatement." LIMIT 1", __FILE__, __LINE__);
674                 } else {
675                         $result = SQL_QUERY("SELECT * FROM `{!_MYSQL_PREFIX!}".$tableName."` LIMIT 1", __FILE__, __LINE__);
676                 }
677         } // END - if
678
679         if (SQL_NUMROWS($result) == 1) {
680                 // "Implode" all data to single string
681                 $DATA_UPDATE = implode(", ", $DATA);
682
683                 // Generate SQL string
684                 $SQL = sprintf("UPDATE `{!_MYSQL_PREFIX!}%s` SET %s WHERE %s LIMIT 1",
685                         $tableName,
686                         $DATA_UPDATE,
687                         $whereStatement
688                 );
689         } else {
690                 // Add Line (does only work with auto_increment!
691                 $KEYs = array(); $VALUEs = array();
692                 foreach ($DATA as $entry) {
693                         // Split up
694                         $line = explode("=", $entry);
695                         $KEYs[] = $line[0]; $VALUEs[] = $line[1];
696                 } // END - foreach
697
698                 // Add both in one line
699                 $KEYs = implode(", ", $KEYs);
700                 $VALUEs = implode(", ", $VALUEs);
701
702                 // Generate SQL string
703                 $SQL = sprintf("INSERT INTO {!_MYSQL_PREFIX!}%s (%s) VALUES (%s)",
704                         $tableName,
705                         $KEYs,
706                         $VALUEs
707                 );
708         }
709
710         // Free memory
711         SQL_FREERESULT($result);
712
713         // Simply run generated SQL string
714         SQL_QUERY($SQL, __FILE__, __LINE__);
715
716         // Rebuild cache
717         REBUILD_CACHE("config", "config");
718
719         // Settings saved
720         LOAD_TEMPLATE("admin_settings_saved", false, getMessage('SETTINGS_SAVED'));
721 }
722
723 // Generate a selection box
724 function ADMIN_MAKE_MENU_SELECTION ($menu, $type, $name, $default="") {
725         // Open the requested menu directory
726         $handle = opendir(sprintf("%sinc/modules/%s/", constant('PATH'), $menu)) or mxchange_die("Cannot load menu ".$menu."!");
727
728         // Init the selection box
729         $OUT = "<select name=\"".$name."\" class=\"admin_select\" size=\"1\">\n <option value=\"\">".IS_TOP_MENU."</option>\n";
730
731         // Walk through all files
732         while ($file = readdir($handle)) {
733                 // Is this a PHP script?
734                 if (($file != ".") && ($file != "..") && ($file != "lost+found") && (strpos($file, "".$type."-") > -1) && (strpos($file, ".php") > 0)) {
735                         // Then test if the file is readable
736                         $test = sprintf("%sinc/modules/%s/%s", constant('PATH'), $menu, $file);
737
738                         // Is the file there?
739                         if (FILE_READABLE($test)) {
740                                 // Extract the value for what=xxx
741                                 $part = substr($file, (strlen($type) + 1));
742                                 $part = substr($part, 0, -4);
743
744                                 // Is that part different from the overview?
745                                 if ($part != "overview") {
746                                         $OUT .= "       <option value=\"".$part."\"";
747                                         if ($part == $default) $OUT .= " selected=\"selected\"";
748                                         $OUT .= ">".$part."</option>\n";
749                                 } // END - if
750                         } // END - if
751                 } // END - if
752         } // END - while
753
754         // Close dir and selection box
755         closedir($handle);
756         $OUT .= "</select>\n";
757         
758         // Return contents
759         return $OUT;
760 }
761 //
762 function ADMIN_USER_PROFILE_LINK ($uid, $title="", $wht="list_user") {
763         if (($title == "") && ($title != "0")) {
764                 // Set userid as title
765                 $title = $uid;
766         } // END - if
767
768         if (($title == "0") && ($wht == "list_refs")) {
769                 // Return title again
770                 return $title;
771         } // END - if
772
773         //* DEBUG: */ echo "a:".$title."<br />";
774         // Return link
775         return "<a href=\"{!URL!}/modules.php?module=admin&amp;what=".$wht."&amp;u_id=".$uid."\" title=\"{--ADMIN_USER_PROFILE_TITLE--}\">".$title."</a>";
776 }
777
778 // Check "logical-area-mode"
779 function ADMIN_CHECK_MENU_MODE () {
780         global $cacheArray;
781
782         // Set the global mode as the mode for all admins
783         $MODE = getConfig('admin_menu');
784         $ADMIN = $MODE;
785
786         // Get admin id
787         $aid = GET_CURRENT_ADMIN_ID();
788
789         // Check individual settings of current admin
790         if (isset($cacheArray['admins']['la_mode'][$aid])) {
791                 // Load from cache
792                 $ADMIN = $cacheArray['admins']['la_mode'][$aid];
793                 incrementConfigEntry('cache_hits');
794         } elseif (GET_EXT_VERSION("admins") >= "0.6.7") {
795                 // Load from database when version of "admins" is enough
796                 $result = SQL_QUERY_ESC("SELECT la_mode FROM `{!_MYSQL_PREFIX!}_admins` WHERE id=%s LIMIT 1",
797                         array($aid), __FILE__, __LINE__);
798                 if (SQL_NUMROWS($result) == 1) {
799                         // Load data
800                         list($ADMIN) = SQL_FETCHROW($result);
801                 }
802
803                 // Free memory
804                 SQL_FREERESULT($result);
805         }
806
807         // Check what the admin wants and set it when it's not the global mode
808         if ($ADMIN != "global") $MODE = $ADMIN;
809
810         // Return admin-menu's mode
811         return $MODE;
812 }
813
814 // Change activation status
815 function ADMIN_CHANGE_ACTIVATION_STATUS ($IDs, $table, $row, $idRow = "id") {
816         $cnt = 0; $newStatus = "Y";
817         if ((is_array($IDs)) && (count($IDs) > 0)) {
818                 // "Walk" all through and count them
819                 foreach ($IDs as $id => $selected) {
820                         // Secure the ID number
821                         $id = bigintval($id);
822
823                         // Should always be set... ;-)
824                         if (!empty($selected)) {
825                                 // Determine new status
826                                 $result = SQL_QUERY_ESC("SELECT %s FROM `{!_MYSQL_PREFIX!}_%s` WHERE %s=%s LIMIT 1",
827                                         array($row, $table, $idRow, $id), __FILE__, __LINE__);
828
829                                 // Row found?
830                                 if (SQL_NUMROWS($result) == 1) {
831                                         // Load the status
832                                         list($currStatus) = SQL_FETCHROW($result);
833
834                                         // And switch it N<->Y
835                                         if ($currStatus == "Y") $newStatus = "N"; else $newStatus = "Y";
836
837                                         // Change this status
838                                         SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_%s` SET %s='%s' WHERE %s=%s LIMIT 1",
839                                                 array($table, $row, $newStatus, $idRow, $id), __FILE__, __LINE__);
840
841                                         // Count up affected rows
842                                         $cnt += SQL_AFFECTEDROWS();
843                                 } // END - if
844
845                                 // Free the result
846                                 SQL_FREERESULT($result);
847                         } // END - if
848                 } // END - foreach
849
850                 // Output status
851                 LOAD_TEMPLATE("admin_settings_saved", false, ADMIN_STATUS_CHANGED_1.$cnt.ADMIN_STATUS_CHANGED_2.count($IDs).ADMIN_STATUS_CHANGED_3);
852         } else {
853                 // Nothing selected!
854                 LOAD_TEMPLATE("admin_settings_saved", false, getMessage('ADMIN_NOTHING_SELECTED_CHANGE'));
855         }
856 }
857
858 // Send mails for del/edit/lock build modes
859 function ADMIN_SEND_BUILD_MAILS ($mode, $table, $content, $id, $subjectPart="") {
860         // Default subject is the subject part
861         $subject = $subjectPart;
862
863         // Is the subject part not set?
864         if (empty($subjectPart)) {
865                 // Then use it from the mode
866                 $subject = strtoupper($mode);
867         } // END - if
868
869         // Is the raw userid set?
870         if ($_POST['uid_raw'][$id] > 0) {
871                 // Generate subject
872                 $subjectLine = constant('MEMBER_'.strtoupper($subject).'_'.strtoupper($table).'_SUBJECT');
873
874                 // Load email template
875                 if (!empty($subjectPart)) {
876                         $mail = LOAD_EMAIL_TEMPLATE("member_".$mode."_".strtolower($subjectPart)."_".$table, $content);
877                 } else {
878                         $mail = LOAD_EMAIL_TEMPLATE("member_".$mode."_".$table, $content);
879                 }
880
881                 // Send email out
882                 SEND_EMAIL($_POST['uid_raw'][$id], $subjectLine, $mail);
883         } // END - if
884
885         // Generate subject
886         $subjectLine = constant('ADMIN_'.strtoupper($subject).'_'.strtoupper($table).'_SUBJECT');
887
888         // Send admin notification out
889         if (!empty($subjectPart)) {
890                 SEND_ADMIN_NOTIFICATION($subjectLine, "admin_".$mode."_".strtolower($subjectPart)."_".$table, $content, $_POST['uid_raw'][$id]);
891         } else {
892                 SEND_ADMIN_NOTIFICATION($subjectLine, "admin_".$mode."_".$table, $content, $_POST['uid_raw'][$id]);
893         }
894 }
895
896 // Build a special template list
897 function ADMIN_BUILD_LIST ($listType, $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn) {
898         $OUT = ""; $SW = 2;
899
900         // "Walk" through all entries
901         foreach ($IDs as $id => $selected) {
902                 // Secure ID number
903                 $id = bigintval($id);
904
905                 // Get result from a given column array and table name
906                 $result = SQL_RESULT_FROM_ARRAY($table, $columns, $idColumn, $id, __FILE__, __LINE__);
907
908                 // Is there one entry?
909                 if (SQL_NUMROWS($result) == 1) {
910                         // Load all data
911                         $content = SQL_FETCHARRAY($result);
912
913                         // Filter all data
914                         foreach ($content as $key => $value) {
915                                 // Search index
916                                 $idx = array_search($key, $columns, true);
917
918                                 // Do we have a userid?
919                                 if ($key == "userid") {
920                                         // Add it again as raw id
921                                         $content['uid'] = bigintval($value);
922                                 } // END - if
923
924                                 // Handle the call in external function
925                                 $content[$key] = HANDLE_EXTRA_VALUES($filterFunctions[$idx], $value, $extraValues[$idx]);
926                         } // END - foreach
927
928                         // Add color switching
929                         $content['sw'] = $SW;
930
931                         // Then list it
932                         $OUT .= LOAD_TEMPLATE(sprintf("admin_%s_%s_row",
933                                         $listType,
934                                         $table
935                                 ), true, $content
936                         );
937
938                         // Switch color
939                         $SW = 3 - $SW;
940                 } // END - if
941
942                 // Free the result
943                 SQL_FREERESULT($result);
944         } // END - foreach
945
946         // Load master template
947         LOAD_TEMPLATE(sprintf("admin_%s_%s",
948                         $listType,
949                         $table
950                 ), false, $OUT
951         );
952 }
953
954 // Change status of "build" list
955 function ADMIN_BUILD_STATUS_HANDLER ($mode, $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray) {
956         // All valid entries? (We hope so here!)
957         if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues)) && (count($statusArray) > 0)) {
958                 // "Walk" through all entries
959                 foreach ($IDs as $id => $sel) {
960                         // Construct SQL query
961                         $SQL = sprintf("UPDATE `{!_MYSQL_PREFIX!}_%s` SET",
962                                 SQL_ESCAPE($table)
963                         );
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
1039 // Delete rows by given ID numbers
1040 function ADMIN_DELETE_ENTRIES_CONFIRM ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $deleteNow=false, $idColumn="id", $userIdColumn="userid") {
1041         // All valid entries? (We hope so here!)
1042         if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues))) {
1043                 // Shall we delete here or list for deletion?
1044                 if ($deleteNow) {
1045                         // The base SQL command:
1046                         $SQL = "DELETE LOW_PRIORITY FROM `{!_MYSQL_PREFIX!}_%s` WHERE %s IN (%s)";
1047
1048                         // Delete them all
1049                         $idList = "";
1050                         foreach ($IDs as $id => $sel) {
1051                                 // Is there a userid?
1052                                 if (isset($_POST['uid_raw'][$id])) {
1053                                         // Load all data from that id
1054                                         $result = SQL_QUERY_ESC("SELECT * FROM `{!_MYSQL_PREFIX!}_%s` WHERE %s=%s LIMIT 1",
1055                                                 array($table, $idColumn, $id), __FILE__, __LINE__);
1056
1057                                         // Fetch the data
1058                                         $content = SQL_FETCHARRAY($result);
1059
1060                                         // Free the result
1061                                         SQL_FREERESULT($result);
1062
1063                                         // Send "build mails" out
1064                                         ADMIN_SEND_BUILD_MAILS("del", $table, $content, $id);
1065                                 } // END - if
1066
1067                                 // Add id number
1068                                 $idList .= $id.",";
1069                         } // END - foreach
1070
1071                         // Run the query
1072                         SQL_QUERY($SQL, array($table, $idColumn, substr($idList, 0, -1)), __FILE__, __LINE__);
1073
1074                         // Was this fine?
1075                         if (SQL_AFFECTEDROWS() == count($IDs)) {
1076                                 // All deleted
1077                                 LOAD_TEMPLATE("admin_settings_saved", false, getMessage('ADMIN_ALL_ENTRIES_REMOVED'));
1078                         } else {
1079                                 // Some are still there :(
1080                                 LOAD_TEMPLATE("admin_settings_saved", false, sprintf(ADMIN_SOME_ENTRIES_NOT_DELETED, SQL_AFFECTEDROWS(), count($IDs)));
1081                         }
1082                 } else {
1083                         // List for deletion confirmation
1084                         ADMIN_BUILD_LIST("del", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1085                 }
1086         } // END - if
1087 }
1088
1089 // Edit rows by given ID numbers
1090 function ADMIN_EDIT_ENTRIES_CONFIRM ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $editNow=false, $idColumn="id", $userIdColumn="userid") {
1091         // All valid entries? (We hope so here!)
1092         if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues))) {
1093                 // Shall we change here or list for editing?
1094                 if ($editNow) {
1095                         // Change them all
1096                         $affected = 0;
1097                         foreach ($IDs as $id => $sel) {
1098                                 // Prepare content array (new values)
1099                                 $content = array();
1100
1101                                 // Prepare SQL for this row
1102                                 $SQL = sprintf("UPDATE `{!_MYSQL_PREFIX!}_ SET",
1103                                         SQL_ESCAPE($table)
1104                                 );
1105                                 foreach ($_POST as $key => $entries) {
1106                                         // Skip raw userid which is always invalid
1107                                         if ($key == "uid_raw") {
1108                                                 // Continue with next field
1109                                                 continue;
1110                                         } // END - if
1111
1112                                         // Is entries an array?
1113                                         if (($key != $idColumn) && (is_array($entries)) && (isset($entries[$id]))) {
1114                                                 // Add this entry to content
1115                                                 $content[$key] = $entries[$id];
1116
1117                                                 // Send data through the filter function if found
1118                                                 if ((isset($filterFunctions[$key])) && (isset($extraValues[$key]))) {
1119                                                         // Filter function set!
1120                                                         $entries[$id] = HANDLE_EXTRA_VALUES($filterFunctions[$key], $entries[$id], $extraValues[$key]);
1121                                                 } // END - if
1122
1123                                                 // Then add this value
1124                                                 $SQL .= sprintf(" %s='%s',",
1125                                                         SQL_ESCAPE($key),
1126                                                         SQL_ESCAPE($entries[$id])
1127                                                 );
1128                                         } elseif (($key != $idColumn) && (!is_array($entries))) {
1129                                                 // Add normal entries as well!
1130                                                 $content[$key] =  $entries;
1131                                         }
1132
1133                                         // Do we have an URL?
1134                                         if ($key == "url") {
1135                                                 // Then add a framekiller test as well
1136                                                 $content['frametester'] = FRAMETESTER($content[$key]);
1137                                         } // END - if
1138                                 } // END - foreach
1139
1140                                 // Finish SQL command
1141                                 $SQL = substr($SQL, 0, -1) . " WHERE ".$idColumn."=".bigintval($id)." LIMIT 1";
1142
1143                                 // Run this query
1144                                 SQL_QUERY($SQL, __FILE__, __LINE__);
1145
1146                                 // Add affected rows
1147                                 $affected += SQL_AFFECTEDROWS();
1148
1149                                 // Load all data from that id
1150                                 $result = SQL_QUERY_ESC("SELECT * FROM `{!_MYSQL_PREFIX!}_%s` WHERE %s=%s LIMIT 1",
1151                                         array($table, $idColumn, $id), __FILE__, __LINE__);
1152
1153                                 // Fetch the data
1154                                 global $DATA;
1155                                 $DATA = SQL_FETCHARRAY($result);
1156
1157                                 // Free the result
1158                                 SQL_FREERESULT($result);
1159
1160                                 // Send "build mails" out
1161                                 ADMIN_SEND_BUILD_MAILS("edit", $table, $content, $id);
1162                         } // END - foreach
1163
1164                         // Was this fine?
1165                         if ($affected == count($IDs)) {
1166                                 // All deleted
1167                                 LOAD_TEMPLATE("admin_settings_saved", false, getMessage('ADMIN_ALL_ENTRIES_EDITED'));
1168                         } else {
1169                                 // Some are still there :(
1170                                 LOAD_TEMPLATE("admin_settings_saved", false, sprintf(ADMIN_SOME_ENTRIES_NOT_EDITED, $affected, count($IDs)));
1171                         }
1172                 } else {
1173                         // List for editing
1174                         ADMIN_BUILD_LIST("edit", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1175                 }
1176         } // END - if
1177 }
1178
1179 // Un-/lock rows by given ID numbers
1180 function ADMIN_LOCK_ENTRIES_CONFIRM ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $statusArray=array(), $lockNow=false, $idColumn="id", $userIdColumn="userid") {
1181         // All valid entries? (We hope so here!)
1182         if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues)) && ((!$lockNow) || (count($statusArray) == 1))) {
1183                 // Shall we un-/lock here or list for locking?
1184                 if ($lockNow) {
1185                         // Un-/lock entries
1186                         ADMIN_BUILD_STATUS_HANDLER("lock", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray);
1187                 } else {
1188                         // List for editing
1189                         ADMIN_BUILD_LIST("lock", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1190                 }
1191         } // END - if
1192 }
1193
1194 // Undelete rows by given ID numbers
1195 function ADMIN_UNDELETE_ENTRIES_CONFIRM ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $statusArray=array(), $lockNow=false, $idColumn="id", $userIdColumn="userid") {
1196         // All valid entries? (We hope so here!)
1197         if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues)) && ((!$lockNow) || (count($statusArray) == 1))) {
1198                 // Shall we un-/lock here or list for locking?
1199                 if ($lockNow) {
1200                         // Undelete entries
1201                         ADMIN_BUILD_STATUS_HANDLER("undelete", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray);
1202                 } else {
1203                         // List for editing
1204                         ADMIN_BUILD_LIST("undelete", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1205                 }
1206         } // END - if
1207 }
1208
1209 // Checks proxy settins by fetching check-updates3.php from www.mxchange.org
1210 function ADMIN_TEST_PROXY_SETTINGS ($settingsArray) {
1211         // Set temporary the new settings
1212         mergeConfig($settingsArray);
1213
1214         // Now get the test URL
1215         $content = GET_URL("check-updates3.php");
1216
1217         // Is the first line with "200 OK"?
1218         $valid = eregi("200 OK", $content[0]);
1219
1220         // Return result
1221         return $valid;
1222 }
1223
1224 // Sends out a link to the given email adress so the admin can reset his/her password
1225 function ADMIN_SEND_PASSWORD_RESET_LINK ($email) {
1226         // Init output
1227         $OUT = "";
1228
1229         // Compile out security characters (must be for looking up!)
1230         $email = COMPILE_CODE($email);
1231
1232         // Look up administator login
1233         $result = SQL_QUERY_ESC("SELECT id, login, password FROM `{!_MYSQL_PREFIX!}_admins` WHERE email='%s' LIMIT 1",
1234                 array($email), __FILE__, __LINE__);
1235
1236         // Is there an account?
1237         if (SQL_NUMROWS($result) == 0) {
1238                 // No account found!
1239                 return getMessage('ADMIN_NO_LOGIN_WITH_EMAIL');
1240         } // END - if
1241
1242         // Load all data
1243         $content = SQL_FETCHARRAY($result);
1244
1245         // Free result
1246         SQL_FREERESULT($result);
1247
1248         // Generate hash for reset link
1249         $content['hash'] = generateHash(URL.":".$content['id'].":".$content['login'].":".$content['password'], substr($content['password'], 10));
1250
1251         // Remove some data
1252         unset($content['id']);
1253         unset($content['password']);
1254
1255         // Prepare email
1256         $mailText = LOAD_EMAIL_TEMPLATE("admin_reset_password", $content);
1257
1258         // Send it out
1259         SEND_EMAIL($email, getMessage('ADMIN_RESET_PASS_LINK_SUBJ'), $mailText);
1260
1261         // Prepare output
1262         return getMessage('ADMIN_RESET_LINK_SENT');
1263 }
1264
1265 // Validate hash and login for password reset
1266 function ADMIN_VALIDATE_RESET_LINK_HASH_LOGIN ($hash, $login) {
1267         // By default nothing validates... ;)
1268         $valid = false;
1269
1270         // Compile the login for lookup
1271         $login = COMPILE_CODE($login);
1272
1273         // Then try to find that user
1274         $result = SQL_QUERY_ESC("SELECT id, password, email FROM `{!_MYSQL_PREFIX!}_admins` WHERE login='%s' LIMIT 1",
1275                 array($login), __FILE__, __LINE__);
1276
1277         // Is an account here?
1278         if (SQL_NUMROWS($result) == 1) {
1279                 // Load all data
1280                 $content = SQL_FETCHARRAY($result);
1281
1282                 // Generate hash again
1283                 $hashFromData = generateHash(URL.":".$content['id'].":".$login.":".$content['password'], substr($content['password'], 10));
1284
1285                 // Does both match?
1286                 $valid = ($hash == $hashFromData);
1287         } // END - if
1288
1289         // Free result
1290         SQL_FREERESULT($result);
1291
1292         // Return result
1293         return $valid;
1294 }
1295 // Reset the password for the login. Do NOT call this function without calling above function first!
1296 function ADMIN_RESET_PASSWORD ($login, $password) {
1297         // Init hash
1298         $passHash = "";
1299
1300         // Now check if we have sql_patches installed
1301         if (GET_EXT_VERSION("sql_patches") >= "0.3.6") {
1302                 // Use new way of hashing
1303                 $passHash = generateHash($password);
1304         } else {
1305                 // Old MD5 method
1306                 $passHash = md5($password);
1307         }
1308
1309         // Update database
1310         SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_admins` SET password='%s' WHERE login='%s' LIMIT 1",
1311                 array($passHash, $login), __FILE__, __LINE__);
1312
1313         // Run filters
1314         RUN_FILTER('post_admin_reset_pass', array('login' => $login, 'hash' => $passHash));
1315
1316         // Return output
1317         return ADMIN_PASSWORD_RESET_DONE;
1318 }
1319 // Solves a task by given id number
1320 function ADMIN_SOLVE_TASK ($id) {
1321         // Update the task data
1322         ADMIN_UPDATE_TASK_DATA($id, "status", "SOLVED");
1323 }
1324 // Marks a given task as deleted
1325 function ADMIN_DELETE_TASK ($id) {
1326         // Update the task data
1327         ADMIN_UPDATE_TASK_DATA($id, "status", "DELETED");
1328 }
1329 // Function to update task data
1330 function ADMIN_UPDATE_TASK_DATA ($id, $row, $data) {
1331         // Update the task
1332         SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_task_system` SET %s='%s' WHERE id=%s LIMIT 1",
1333                 array($row, $data, bigintval($id)), __FILE__, __LINE__);
1334 }
1335 //
1336 ?>