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