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