More references to removed (still some left)
[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 ((FILE_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         {
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", constant('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 $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                                 setConfigEntry($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, getMessage('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/", constant('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", constant('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 // Check "logical-area-mode"
785 function ADMIN_CHECK_MENU_MODE () {
786         global $cacheArray;
787
788         // Set the global mode as the mode for all admins
789         $MODE = getConfig('admin_menu');
790         $ADMIN = $MODE;
791
792         // Get admin id
793         $aid = GET_CURRENT_ADMIN_ID();
794
795         // Check individual settings of current admin
796         if (isset($cacheArray['admins']['la_mode'][$aid])) {
797                 // Load from cache
798                 $ADMIN = $cacheArray['admins']['la_mode'][$aid];
799                 incrementConfigEntry('cache_hits');
800         } elseif (GET_EXT_VERSION("admins") >= "0.6.7") {
801                 // Load from database when version of "admins" is enough
802                 $result = SQL_QUERY_ESC("SELECT la_mode FROM `{!_MYSQL_PREFIX!}_admins` WHERE id=%s LIMIT 1",
803                         array($aid), __FILE__, __LINE__);
804                 if (SQL_NUMROWS($result) == 1) {
805                         // Load data
806                         list($ADMIN) = SQL_FETCHROW($result);
807                 }
808
809                 // Free memory
810                 SQL_FREERESULT($result);
811         }
812
813         // Check what the admin wants and set it when it's not the global mode
814         if ($ADMIN != "global") $MODE = $ADMIN;
815
816         // Return admin-menu's mode
817         return $MODE;
818 }
819
820 // Change activation status
821 function ADMIN_CHANGE_ACTIVATION_STATUS ($IDs, $table, $row, $idRow = "id") {
822         $cnt = 0; $newStatus = "Y";
823         if ((is_array($IDs)) && (count($IDs) > 0)) {
824                 // "Walk" all through and count them
825                 foreach ($IDs as $id => $selected) {
826                         // Secure the ID number
827                         $id = bigintval($id);
828
829                         // Should always be set... ;-)
830                         if (!empty($selected)) {
831                                 // Determine new status
832                                 $result = SQL_QUERY_ESC("SELECT %s FROM `{!_MYSQL_PREFIX!}_%s` WHERE %s=%s LIMIT 1",
833                                         array($row, $table, $idRow, $id), __FILE__, __LINE__);
834
835                                 // Row found?
836                                 if (SQL_NUMROWS($result) == 1) {
837                                         // Load the status
838                                         list($currStatus) = SQL_FETCHROW($result);
839
840                                         // And switch it N<->Y
841                                         if ($currStatus == "Y") $newStatus = "N"; else $newStatus = "Y";
842
843                                         // Change this status
844                                         SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_%s` SET %s='%s' WHERE %s=%s LIMIT 1",
845                                                 array($table, $row, $newStatus, $idRow, $id), __FILE__, __LINE__);
846
847                                         // Count up affected rows
848                                         $cnt += SQL_AFFECTEDROWS();
849                                 } // END - if
850
851                                 // Free the result
852                                 SQL_FREERESULT($result);
853                         } // END - if
854                 } // END - foreach
855
856                 // Output status
857                 LOAD_TEMPLATE("admin_settings_saved", false, ADMIN_STATUS_CHANGED_1.$cnt.ADMIN_STATUS_CHANGED_2.count($IDs).ADMIN_STATUS_CHANGED_3);
858         } else {
859                 // Nothing selected!
860                 LOAD_TEMPLATE("admin_settings_saved", false, getMessage('ADMIN_NOTHING_SELECTED_CHANGE'));
861         }
862 }
863
864 // Send mails for del/edit/lock build modes
865 function ADMIN_SEND_BUILD_MAILS ($mode, $table, $content, $id, $subjectPart="") {
866         // Default subject is the subject part
867         $subject = $subjectPart;
868
869         // Is the subject part not set?
870         if (empty($subjectPart)) {
871                 // Then use it from the mode
872                 $subject = strtoupper($mode);
873         } // END - if
874
875         // Is the raw userid set?
876         if ($_POST['uid_raw'][$id] > 0) {
877                 // Generate subject
878                 $subjectLine = constant('MEMBER_'.strtoupper($subject).'_'.strtoupper($table).'_SUBJECT');
879
880                 // Load email template
881                 if (!empty($subjectPart)) {
882                         $mail = LOAD_EMAIL_TEMPLATE("member_".$mode."_".strtolower($subjectPart)."_".$table, $content);
883                 } else {
884                         $mail = LOAD_EMAIL_TEMPLATE("member_".$mode."_".$table, $content);
885                 }
886
887                 // Send email out
888                 SEND_EMAIL($_POST['uid_raw'][$id], $subjectLine, $mail);
889         } // END - if
890
891         // Generate subject
892         $subjectLine = constant('ADMIN_'.strtoupper($subject).'_'.strtoupper($table).'_SUBJECT');
893
894         // Send admin notification out
895         if (!empty($subjectPart)) {
896                 SEND_ADMIN_NOTIFICATION($subjectLine, "admin_".$mode."_".strtolower($subjectPart)."_".$table, $content, $_POST['uid_raw'][$id]);
897         } else {
898                 SEND_ADMIN_NOTIFICATION($subjectLine, "admin_".$mode."_".$table, $content, $_POST['uid_raw'][$id]);
899         }
900 }
901
902 // Build a special template list
903 function ADMIN_BUILD_LIST ($listType, $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn) {
904         $OUT = ""; $SW = 2;
905
906         // "Walk" through all entries
907         foreach ($IDs as $id => $selected) {
908                 // Secure ID number
909                 $id = bigintval($id);
910
911                 // Get result from a given column array and table name
912                 $result = SQL_RESULT_FROM_ARRAY($table, $columns, $idColumn, $id, __FILE__, __LINE__);
913
914                 // Is there one entry?
915                 if (SQL_NUMROWS($result) == 1) {
916                         // Load all data
917                         $content = SQL_FETCHARRAY($result);
918
919                         // Filter all data
920                         foreach ($content as $key => $value) {
921                                 // Search index
922                                 $idx = array_search($key, $columns, true);
923
924                                 // Do we have a userid?
925                                 if ($key == "userid") {
926                                         // Add it again as raw id
927                                         $content['uid'] = bigintval($value);
928                                 } // END - if
929
930                                 // Handle the call in external function
931                                 $content[$key] = HANDLE_EXTRA_VALUES($filterFunctions[$idx], $value, $extraValues[$idx]);
932                         } // END - foreach
933
934                         // Add color switching
935                         $content['sw'] = $SW;
936
937                         // Then list it
938                         $OUT .= LOAD_TEMPLATE(sprintf("admin_%s_%s_row",
939                                         $listType,
940                                         $table
941                                 ), true, $content
942                         );
943
944                         // Switch color
945                         $SW = 3 - $SW;
946                 } // END - if
947
948                 // Free the result
949                 SQL_FREERESULT($result);
950         } // END - foreach
951
952         // Load master template
953         LOAD_TEMPLATE(sprintf("admin_%s_%s",
954                         $listType,
955                         $table
956                 ), false, $OUT
957         );
958 }
959
960 // Change status of "build" list
961 function ADMIN_BUILD_STATUS_HANDLER ($mode, $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray) {
962         // All valid entries? (We hope so here!)
963         if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues)) && (count($statusArray) > 0)) {
964                 // "Walk" through all entries
965                 foreach ($IDs as $id => $sel) {
966                         // Construct SQL query
967                         $SQL = sprintf("UPDATE `{!_MYSQL_PREFIX!}_%s` SET",
968                                 SQL_ESCAPE($table)
969                         );
970
971                         // Load data of entry
972                         $result = SQL_QUERY_ESC("SELECT * FROM `{!_MYSQL_PREFIX!}_%s` WHERE %s=%s LIMIT 1",
973                                 array($table, $idColumn, $id), __FILE__, __LINE__);
974
975                         // Fetch the data
976                         $content = SQL_FETCHARRAY($result);
977
978                         // Free the result
979                         SQL_FREERESULT($result);
980
981                         // Add all status entries (e.g. status column last_updated or so)
982                         $newStatus = "UNKNOWN";
983                         $oldStatus = "UNKNOWN";
984                         $statusColumn = "unknown";
985                         foreach ($statusArray as $column => $statusInfo) {
986                                 // Does the entry exist?
987                                 if ((isset($content[$column])) && (isset($statusInfo[$content[$column]]))) {
988                                         // Add these entries for update
989                                         $SQL .= sprintf(" %s='%s',", SQL_ESCAPE($column), SQL_ESCAPE($statusInfo[$content[$column]]));
990
991                                         // Remember status
992                                         if ($statusColumn == "unknown") {
993                                                 // Always (!!!) change status column first!
994                                                 $oldStatus = $content[$column];
995                                                 $newStatus = $statusInfo[$oldStatus];
996                                                 $statusColumn = $column;
997                                         } // END - if
998                                 } elseif (isset($content[$column])) {
999                                         // Unfinished!
1000                                         mxchange_die("{--".__FUNCTION__."--}:".__LINE__.":UNFINISHED: id={$id}/{$column}[".gettype($statusInfo)."] = {$content[$column]}");
1001                                 }
1002                         } // END - foreach
1003
1004                         // Add other columns as well
1005                         foreach ($_POST as $key => $entries) {
1006                                 // Skip id, raw userid and 'do_$mode'
1007                                 if (!in_array($key, array($idColumn, 'uid_raw', ('do_'.$mode)))) {
1008                                         // Are there brackets () at the end?
1009                                         if (substr($entries[$id], -2, 2) == "()") {
1010                                                 // Direct SQL command found
1011                                                 $SQL .= sprintf(" %s=%s,", SQL_ESCAPE($key), SQL_ESCAPE($entries[$id]));
1012                                         } else {
1013                                                 // Add regular entry
1014                                                 $SQL .= sprintf(" %s='%s',", SQL_ESCAPE($key), SQL_ESCAPE($entries[$id]));
1015
1016                                                 // Add entry
1017                                                 $content[$key] = $entries[$id];
1018                                         }
1019                                 } // END - if
1020                         } // END - foreach
1021
1022                         // Finish SQL statement
1023                         $SQL = substr($SQL, 0, -1) . sprintf(" WHERE %s=%s AND %s='%s' LIMIT 1",
1024                                 $idColumn,
1025                                 bigintval($id),
1026                                 $statusColumn,
1027                                 $oldStatus
1028                         );
1029
1030                         // Run the SQL
1031                         SQL_QUERY($SQL, __FILE__, __LINE__);
1032
1033                         // Do we have an URL?
1034                         if (isset($content['url'])) {
1035                                 // Then add a framekiller test as well
1036                                 $content['frametester'] = FRAMETESTER($content['url']);
1037                         } // END - if
1038
1039                         // Send "build mails" out
1040                         ADMIN_SEND_BUILD_MAILS($mode, $table, $content, $id, $statusInfo[$content[$column]]);
1041                 } // END - foreach
1042         } // END - if
1043 }
1044
1045 // Delete rows by given ID numbers
1046 function ADMIN_DELETE_ENTRIES_CONFIRM ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $deleteNow=false, $idColumn="id", $userIdColumn="userid") {
1047         // All valid entries? (We hope so here!)
1048         if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues))) {
1049                 // Shall we delete here or list for deletion?
1050                 if ($deleteNow) {
1051                         // The base SQL command:
1052                         $SQL = "DELETE LOW_PRIORITY FROM `{!_MYSQL_PREFIX!}_%s` WHERE %s IN (%s)";
1053
1054                         // Delete them all
1055                         $idList = "";
1056                         foreach ($IDs as $id => $sel) {
1057                                 // Is there a userid?
1058                                 if (isset($_POST['uid_raw'][$id])) {
1059                                         // Load all data from that id
1060                                         $result = SQL_QUERY_ESC("SELECT * FROM `{!_MYSQL_PREFIX!}_%s` WHERE %s=%s LIMIT 1",
1061                                                 array($table, $idColumn, $id), __FILE__, __LINE__);
1062
1063                                         // Fetch the data
1064                                         $content = SQL_FETCHARRAY($result);
1065
1066                                         // Free the result
1067                                         SQL_FREERESULT($result);
1068
1069                                         // Send "build mails" out
1070                                         ADMIN_SEND_BUILD_MAILS("del", $table, $content, $id);
1071                                 } // END - if
1072
1073                                 // Add id number
1074                                 $idList .= $id.",";
1075                         } // END - foreach
1076
1077                         // Run the query
1078                         SQL_QUERY($SQL, array($table, $idColumn, substr($idList, 0, -1)), __FILE__, __LINE__);
1079
1080                         // Was this fine?
1081                         if (SQL_AFFECTEDROWS() == count($IDs)) {
1082                                 // All deleted
1083                                 LOAD_TEMPLATE("admin_settings_saved", false, getMessage('ADMIN_ALL_ENTRIES_REMOVED'));
1084                         } else {
1085                                 // Some are still there :(
1086                                 LOAD_TEMPLATE("admin_settings_saved", false, sprintf(ADMIN_SOME_ENTRIES_NOT_DELETED, SQL_AFFECTEDROWS(), count($IDs)));
1087                         }
1088                 } else {
1089                         // List for deletion confirmation
1090                         ADMIN_BUILD_LIST("del", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1091                 }
1092         } // END - if
1093 }
1094
1095 // Edit rows by given ID numbers
1096 function ADMIN_EDIT_ENTRIES_CONFIRM ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $editNow=false, $idColumn="id", $userIdColumn="userid") {
1097         // All valid entries? (We hope so here!)
1098         if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues))) {
1099                 // Shall we change here or list for editing?
1100                 if ($editNow) {
1101                         // Change them all
1102                         $affected = 0;
1103                         foreach ($IDs as $id => $sel) {
1104                                 // Prepare content array (new values)
1105                                 $content = array();
1106
1107                                 // Prepare SQL for this row
1108                                 $SQL = sprintf("UPDATE `{!_MYSQL_PREFIX!}_ SET",
1109                                         SQL_ESCAPE($table)
1110                                 );
1111                                 foreach ($_POST as $key => $entries) {
1112                                         // Skip raw userid which is always invalid
1113                                         if ($key == "uid_raw") {
1114                                                 // Continue with next field
1115                                                 continue;
1116                                         } // END - if
1117
1118                                         // Is entries an array?
1119                                         if (($key != $idColumn) && (is_array($entries)) && (isset($entries[$id]))) {
1120                                                 // Add this entry to content
1121                                                 $content[$key] = $entries[$id];
1122
1123                                                 // Send data through the filter function if found
1124                                                 if ((isset($filterFunctions[$key])) && (isset($extraValues[$key]))) {
1125                                                         // Filter function set!
1126                                                         $entries[$id] = HANDLE_EXTRA_VALUES($filterFunctions[$key], $entries[$id], $extraValues[$key]);
1127                                                 } // END - if
1128
1129                                                 // Then add this value
1130                                                 $SQL .= sprintf(" %s='%s',",
1131                                                         SQL_ESCAPE($key),
1132                                                         SQL_ESCAPE($entries[$id])
1133                                                 );
1134                                         } elseif (($key != $idColumn) && (!is_array($entries))) {
1135                                                 // Add normal entries as well!
1136                                                 $content[$key] =  $entries;
1137                                         }
1138
1139                                         // Do we have an URL?
1140                                         if ($key == "url") {
1141                                                 // Then add a framekiller test as well
1142                                                 $content['frametester'] = FRAMETESTER($content[$key]);
1143                                         } // END - if
1144                                 } // END - foreach
1145
1146                                 // Finish SQL command
1147                                 $SQL = substr($SQL, 0, -1) . " WHERE ".$idColumn."=".bigintval($id)." LIMIT 1";
1148
1149                                 // Run this query
1150                                 SQL_QUERY($SQL, __FILE__, __LINE__);
1151
1152                                 // Add affected rows
1153                                 $affected += SQL_AFFECTEDROWS();
1154
1155                                 // Load all data from that id
1156                                 $result = SQL_QUERY_ESC("SELECT * FROM `{!_MYSQL_PREFIX!}_%s` WHERE %s=%s LIMIT 1",
1157                                         array($table, $idColumn, $id), __FILE__, __LINE__);
1158
1159                                 // Fetch the data
1160                                 global $DATA;
1161                                 $DATA = SQL_FETCHARRAY($result);
1162
1163                                 // Free the result
1164                                 SQL_FREERESULT($result);
1165
1166                                 // Send "build mails" out
1167                                 ADMIN_SEND_BUILD_MAILS("edit", $table, $content, $id);
1168                         } // END - foreach
1169
1170                         // Was this fine?
1171                         if ($affected == count($IDs)) {
1172                                 // All deleted
1173                                 LOAD_TEMPLATE("admin_settings_saved", false, getMessage('ADMIN_ALL_ENTRIES_EDITED'));
1174                         } else {
1175                                 // Some are still there :(
1176                                 LOAD_TEMPLATE("admin_settings_saved", false, sprintf(ADMIN_SOME_ENTRIES_NOT_EDITED, $affected, count($IDs)));
1177                         }
1178                 } else {
1179                         // List for editing
1180                         ADMIN_BUILD_LIST("edit", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1181                 }
1182         } // END - if
1183 }
1184
1185 // Un-/lock rows by given ID numbers
1186 function ADMIN_LOCK_ENTRIES_CONFIRM ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $statusArray=array(), $lockNow=false, $idColumn="id", $userIdColumn="userid") {
1187         // All valid entries? (We hope so here!)
1188         if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues)) && ((!$lockNow) || (count($statusArray) == 1))) {
1189                 // Shall we un-/lock here or list for locking?
1190                 if ($lockNow) {
1191                         // Un-/lock entries
1192                         ADMIN_BUILD_STATUS_HANDLER("lock", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray);
1193                 } else {
1194                         // List for editing
1195                         ADMIN_BUILD_LIST("lock", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1196                 }
1197         } // END - if
1198 }
1199
1200 // Undelete rows by given ID numbers
1201 function ADMIN_UNDELETE_ENTRIES_CONFIRM ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $statusArray=array(), $lockNow=false, $idColumn="id", $userIdColumn="userid") {
1202         // All valid entries? (We hope so here!)
1203         if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues)) && ((!$lockNow) || (count($statusArray) == 1))) {
1204                 // Shall we un-/lock here or list for locking?
1205                 if ($lockNow) {
1206                         // Undelete entries
1207                         ADMIN_BUILD_STATUS_HANDLER("undelete", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray);
1208                 } else {
1209                         // List for editing
1210                         ADMIN_BUILD_LIST("undelete", $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1211                 }
1212         } // END - if
1213 }
1214
1215 // Checks proxy settins by fetching check-updates3.php from www.mxchange.org
1216 function ADMIN_TEST_PROXY_SETTINGS ($settingsArray) {
1217         global $_CONFIG;
1218
1219         // Set temporary the new settings
1220         $_CONFIG = merge_array($_CONFIG, $settingsArray);
1221
1222         // Now get the test URL
1223         $content = GET_URL("check-updates3.php");
1224
1225         // Is the first line with "200 OK"?
1226         $valid = eregi("200 OK", $content[0]);
1227
1228         // Return result
1229         return $valid;
1230 }
1231
1232 // Sends out a link to the given email adress so the admin can reset his/her password
1233 function ADMIN_SEND_PASSWORD_RESET_LINK ($email) {
1234         // Init output
1235         $OUT = "";
1236
1237         // Compile out security characters (must be for looking up!)
1238         $email = COMPILE_CODE($email);
1239
1240         // Look up administator login
1241         $result = SQL_QUERY_ESC("SELECT id, login, password FROM `{!_MYSQL_PREFIX!}_admins` WHERE email='%s' LIMIT 1",
1242                 array($email), __FILE__, __LINE__);
1243
1244         // Is there an account?
1245         if (SQL_NUMROWS($result) == 0) {
1246                 // No account found!
1247                 return getMessage('ADMIN_NO_LOGIN_WITH_EMAIL');
1248         } // END - if
1249
1250         // Load all data
1251         $content = SQL_FETCHARRAY($result);
1252
1253         // Free result
1254         SQL_FREERESULT($result);
1255
1256         // Generate hash for reset link
1257         $content['hash'] = generateHash(URL.":".$content['id'].":".$content['login'].":".$content['password'], substr($content['password'], 10));
1258
1259         // Remove some data
1260         unset($content['id']);
1261         unset($content['password']);
1262
1263         // Prepare email
1264         $mailText = LOAD_EMAIL_TEMPLATE("admin_reset_password", $content);
1265
1266         // Send it out
1267         SEND_EMAIL($email, getMessage('ADMIN_RESET_PASS_LINK_SUBJ'), $mailText);
1268
1269         // Prepare output
1270         return getMessage('ADMIN_RESET_LINK_SENT');
1271 }
1272
1273 // Validate hash and login for password reset
1274 function ADMIN_VALIDATE_RESET_LINK_HASH_LOGIN ($hash, $login) {
1275         // By default nothing validates... ;)
1276         $valid = false;
1277
1278         // Compile the login for lookup
1279         $login = COMPILE_CODE($login);
1280
1281         // Then try to find that user
1282         $result = SQL_QUERY_ESC("SELECT id, password, email FROM `{!_MYSQL_PREFIX!}_admins` WHERE login='%s' LIMIT 1",
1283                 array($login), __FILE__, __LINE__);
1284
1285         // Is an account here?
1286         if (SQL_NUMROWS($result) == 1) {
1287                 // Load all data
1288                 $content = SQL_FETCHARRAY($result);
1289
1290                 // Generate hash again
1291                 $hashFromData = generateHash(URL.":".$content['id'].":".$login.":".$content['password'], substr($content['password'], 10));
1292
1293                 // Does both match?
1294                 $valid = ($hash == $hashFromData);
1295         } // END - if
1296
1297         // Free result
1298         SQL_FREERESULT($result);
1299
1300         // Return result
1301         return $valid;
1302 }
1303 // Reset the password for the login. Do NOT call this function without calling above function first!
1304 function ADMIN_RESET_PASSWORD ($login, $password) {
1305         // Init hash
1306         $passHash = "";
1307
1308         // Now check if we have sql_patches installed
1309         if (GET_EXT_VERSION("sql_patches") >= "0.3.6") {
1310                 // Use new way of hashing
1311                 $passHash = generateHash($password);
1312         } else {
1313                 // Old MD5 method
1314                 $passHash = md5($password);
1315         }
1316
1317         // Update database
1318         SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_admins` SET password='%s' WHERE login='%s' LIMIT 1",
1319                 array($passHash, $login), __FILE__, __LINE__);
1320
1321         // Run filters
1322         RUN_FILTER('post_admin_reset_pass', array('login' => $login, 'hash' => $passHash));
1323
1324         // Return output
1325         return ADMIN_PASSWORD_RESET_DONE;
1326 }
1327 // Solves a task by given id number
1328 function ADMIN_SOLVE_TASK ($id) {
1329         // Update the task data
1330         ADMIN_UPDATE_TASK_DATA($id, "status", "SOLVED");
1331 }
1332 // Marks a given task as deleted
1333 function ADMIN_DELETE_TASK ($id) {
1334         // Update the task data
1335         ADMIN_UPDATE_TASK_DATA($id, "status", "DELETED");
1336 }
1337 // Function to update task data
1338 function ADMIN_UPDATE_TASK_DATA ($id, $row, $data) {
1339         // Update the task
1340         SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_task_system` SET %s='%s' WHERE id=%s LIMIT 1",
1341                 array($row, $data, bigintval($id)), __FILE__, __LINE__);
1342 }
1343 //
1344 ?>