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