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