2 /************************************************************************
3 * Mailer v0.2.1-FINAL Start: 08/31/2003 *
4 * =================== Last change: 11/23/2004 *
6 * -------------------------------------------------------------------- *
7 * File : admin-inc.php *
8 * -------------------------------------------------------------------- *
9 * Short description : Administrative related functions *
10 * -------------------------------------------------------------------- *
11 * Kurzbeschreibung : Fuer die Administration benoetigte Funktionen *
12 * -------------------------------------------------------------------- *
15 * $Tag:: 0.2.1-FINAL $ *
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 *
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. *
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. *
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, *
37 ************************************************************************/
39 // Some security stuff...
40 if (!defined('__SECURITY')) {
44 // Register an administrator account
45 function addAdminAccount ($adminLogin, $passHash, $adminEmail) {
46 // Login does already exist
50 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
51 array($adminLogin), __FUNCTION__, __LINE__);
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')",
61 ), __FUNCTION__, __LINE__);
68 SQL_FREERESULT($result);
74 // This function will be executed when the admin is not logged in and has submitted his login data
75 function ifAdminLoginDataIsValid ($adminLogin, $adminPassword) {
76 // First of all, no admin login is found
79 // Then we need to lookup the login name by getting the admin hash
80 $adminHash = getAdminHash($adminLogin);
82 // If this is fine, we can continue
83 if ($adminHash != '-1') {
84 // Get admin id and set it as current
85 setCurrentAdminId(getAdminId($adminLogin));
87 // Now, we need to encode the password in the same way the one is encoded in database
88 $testHash = generateHash($adminPassword, $adminHash);
90 // If they both match, the login data is valid
91 if ($testHash == $adminHash) {
100 // Prepare data array
102 'login' => $adminLogin,
103 'pass_hash' => $adminHash
106 // Run a special filter
107 runFilterChain('do_admin_login_' . $ret, $data);
113 // Only be executed on cookie checking
114 function ifAdminCookiesAreValid ($adminLogin, $passHash) {
115 // First of all, no admin login is found
118 // Then we need to lookup the login name by getting the admin hash
119 $adminHash = getAdminHash($adminLogin);
121 // If this is fine, we can continue
122 if ($adminHash != '-1') {
123 // Now, we need to encode the password in the same way the one is encoded in database
124 $testHash = encodeHashForCookie($adminHash);
126 // If they both match, the login data is valid
127 if ($testHash == $passHash) {
141 // Do an admin action
142 function doAdminAction () {
146 //* DEBUG: */ outputHtml(__LINE__."*".$what.'/'.getModule().'/'.getAction().'/'.getWhat()."*<br />");
148 // Remove any spaces from variable
150 // Default admin action is the overview page
154 $what = secureString($what);
158 $action = getActionFromModuleWhat(getModule(), $what);
160 // Define admin login name and id number
161 $content['login'] = getSession('admin_login');
162 $content['id'] = getCurrentAdminId();
165 if (isExtensionActive('admins')) {
166 $content['welcome'] = loadTemplate('admin_welcome_admins', true, $content);
168 $content['welcome'] = loadTemplate('admin_welcome', true, $content);
170 $content['footer'] = loadTemplate('admin_footer' , true, $content);
171 $content['menu'] = addAdminMenu($action, $what, true);
174 loadTemplate('admin_main_header', false, $content);
176 // Check if action/what pair is valid
177 $result_action = SQL_QUERY_ESC("SELECT
180 `{?_MYSQL_PREFIX?}_admin_menu`
185 `what`='%s' AND `what` != 'overview'
188 `what`='' OR `what` IS NULL
199 ), __FUNCTION__, __LINE__);
201 // Do we have an entry?
202 if (SQL_NUMROWS($result_action) == 1) {
203 // Is valid but does the inlcude file exists?
204 $inc = sprintf("inc/modules/admin/action-%s.php", $action);
205 if ((isIncludeReadable($inc)) && (isMenuActionValid('admin', $action, $what)) && ($GLOBALS['acl_allow'] === true)) {
206 // Ok, we finally load the admin action module
208 } elseif ($GLOBALS['acl_allow'] === false) {
210 loadTemplate('admin_menu_failed', false, getMaskedMessage('ADMIN_ACCESS_DENIED', $what));
212 // Include file not found! :-(
213 loadTemplate('admin_menu_failed', false, getMaskedMessage('ADMIN_ACTION_404', $action));
216 // Invalid action/what pair found!
217 loadTemplate('admin_menu_failed', false, getMaskedMessage('ADMIN_ACTION_INVALID', $action . '/' . $what));
221 SQL_FREERESULT($result_action);
224 loadTemplate('admin_main_footer', false, $content);
227 // Adds an admin menu
228 function addAdminMenu ($action, $what, $return=false) {
234 $GLOBALS['menu']['description'] = array();
235 $GLOBALS['menu']['title'] = array();
238 $result_main = SQL_QUERY("SELECT
239 `action`, `title`, `descr`
241 `{?_MYSQL_PREFIX?}_admin_menu`
243 (`what`='' OR `what` IS NULL)
246 `id` DESC", __FUNCTION__, __LINE__);
248 // Do we have entries?
249 if (SQL_NUMROWS($result_main) > 0) {
250 $OUT .= '<ul class="admin_menu_main">';
251 // @TODO Rewrite this to $content = SQL_FETCHARRAY()
252 while (list($menu, $title, $descr) = SQL_FETCHROW($result_main)) {
253 if ((isExtensionActive('admins')) && (getExtensionVersion('admins') > '0.2.0')) {
254 $ACL = adminsCheckAdminAcl($menu, '');
256 // @TODO ACL is 'allow'... hmmm
261 $inc = sprintf("inc/modules/admin/action-%s.php", $menu);
263 // Is the file readable?
264 $readable = isIncludeReadable($inc);
267 if ($SUB === false) {
268 // Insert compiled menu title and description
269 $GLOBALS['menu']['title'][$menu] = $title;
270 $GLOBALS['menu']['description'][$menu] = $descr;
272 $OUT .= '<li class="admin_menu">
273 <div class="nobr"><strong>·</strong> ';
275 if ($readable === true) {
276 if (($menu == $action) && (empty($what))) {
279 $OUT .= '[<a href="{%url=modules.php?module=admin&action=' . $menu . '%}">';
282 $OUT .= '<em style="cursor:help" class="admin_note" title="{--MENU_ACTION_404--}">';
287 if ($readable === true) {
288 if (($menu == $action) && (empty($what))) {
300 // Check for menu entries
301 $result_what = SQL_QUERY_ESC("SELECT
302 `what`, `title`, `descr`
304 `{?_MYSQL_PREFIX?}_admin_menu`
312 array($menu), __FUNCTION__, __LINE__);
314 // Remember the count for later checks
315 setAdminMenuHasEntries($menu, ((SQL_NUMROWS($result_what) > 0) && ($action == $menu)));
317 // Do we have entries?
318 if ((ifAdminMenuHasEntries($menu)) && (SQL_NUMROWS($result_what) > 0)) {
319 $GLOBALS['menu']['description'] = array();
320 $GLOBALS['menu']['title'] = array(); $SUB = true;
321 $OUT .= '<li class="admin_menu_sub"><ul class="admin_menu_sub">';
322 // @TODO Rewrite this to $content = SQL_FETCHARRAY()
323 while (list($what_sub, $title_what, $desc_what) = SQL_FETCHROW($result_what)) {
324 // Check for access level
325 if ((isExtensionActive('admins')) && (getExtensionVersion('admins') > '0.2.0')) {
326 $ACL = adminsCheckAdminAcl('', $what_sub);
328 // @TODO ACL is 'allow'... hmmm
333 $inc = sprintf("inc/modules/admin/what-%s.php", $what_sub);
335 // Is the file readable?
336 $readable = isIncludeReadable($inc);
340 // Insert compiled title and description
341 $GLOBALS['menu']['title'][$what_sub] = $title_what;
342 $GLOBALS['menu']['description'][$what_sub] = $desc_what;
343 $OUT .= '<li class="admin_menu">
344 <div class="nobr"><strong>--></strong> ';
345 if ($readable === true) {
346 if ($what == $what_sub) {
349 $OUT .= '[<a href="{%url=modules.php?module=admin&what=' . $what_sub . '%}">';
352 $OUT .= '<em style="cursor:help" class="admin_note" title="{--MENU_WHAT_404--}">';
357 if ($readable === true) {
358 if ($what == $what_sub) {
372 SQL_FREERESULT($result_what);
380 SQL_FREERESULT($result_main);
384 // Is there a cache instance again?
385 // Return or output content?
386 if ($return === true) {
393 // Create member selection box
394 function addMemberSelectionBox ($def=0, $add_all=false, $return=false, $none=false, $field='userid') {
395 // Output selection form with all confirmed user accounts listed
396 $result = SQL_QUERY("SELECT `userid`, `surname`, `family` FROM `{?_MYSQL_PREFIX?}_user_data` ORDER BY `userid` ASC", __FUNCTION__, __LINE__);
401 // USe this only for adding points (e.g. adding refs really makes no sence ;-) )
402 if ($add_all === true) $OUT = ' <option value="all">{--ALL_MEMBERS--}</option>';
403 elseif ($none === true) $OUT = ' <option value="0">{--SELECT_NONE--}</option>';
405 while ($content = SQL_FETCHARRAY($result)) {
406 $OUT .= ' <option value="' . bigintval($content['userid']) . '"';
407 if ($def == $content['userid']) $OUT .= ' selected="selected"';
408 $OUT .= '>' . $content['surname'] . ' ' . $content['family'] . ' (' . bigintval($content['userid']) . ')</option>';
412 SQL_FREERESULT($result);
414 if ($return === false) {
415 // Remeber options in constant
416 $content['member_selection'] = $OUT;
417 $content['what'] = getWhat();
420 loadTemplate('admin_member_selection_box', false, $content);
422 // Return content in selection frame
423 return '<select class="admin_select" name="' . $field . '" size="1">' . $OUT . '</select>';
427 // Create a menu selection box for given menu system
428 // @TODO Try to rewrite this to adminAddMenuSelectionBox()
430 function adminMenuSelectionBox_DEPRECATED ($mode, $default = '', $defid = '') {
431 $what = "`what` != ''";
432 if ($mode == 'action') $what = "(`what`='' OR `what` IS NULL) AND `action` !='login'";
434 $result = SQL_QUERY_ESC("SELECT %s, `title` FROM `{?_MYSQL_PREFIX?}_admin_menu` WHERE ".$what." ORDER BY `sort` ASC",
435 array($mode), __FUNCTION__, __LINE__);
436 if (SQL_NUMROWS($result) > 0) {
437 // Load menu as selection
438 $OUT = "<select name=\"".$mode."_menu";
439 if ((!empty($defid)) || ($defid == '0')) $OUT .= "[".$defid."]";
440 $OUT .= "\" size=\"1\" class=\"admin_select\">
441 <option value=\"\">{--SELECT_NONE--}</option>\n";
442 // @TODO Try to rewrite this to $content = SQL_FETCHARRAY(). Please look some lines above for the dynamic query
443 while (list($menu, $title) = SQL_FETCHROW($result)) {
444 $OUT .= " <option value=\"".$menu."\"";
445 if ((!empty($default)) && ($default == $menu)) $OUT .= ' selected="selected"';
446 $OUT .= ">".$title."</option>\n";
450 SQL_FREERESULT($result);
451 $OUT .= "</select>\n";
454 $OUT = getMessage('ADMIN_PROBLEM_NO_MENU');
461 // Wrapper for $_POST and adminSaveSettings
462 function adminSaveSettingsFromPostData ($tableName = '_config', $whereStatement = '`config`=0', $translateComma = array(), $alwaysAdd = false, $displayMessage = true) {
464 $postData = postRequestArray();
466 // Call the lower function
467 adminSaveSettings($postData, $tableName, $whereStatement, $translateComma, $alwaysAdd, $displayMessage);
470 // Save settings to the database
471 function adminSaveSettings (&$postData, $tableName = '_config', $whereStatement = '`config`=0', $translateComma = array(), $alwaysAdd = false, $displayMessage = true) {
472 // Prepare all arrays, variables
473 $tableData = array();
476 // Now, walk through all entries and prepare them for saving
477 foreach ($postData as $id => $val) {
478 // Process only formular field but not submit buttons ;)
480 // Do not save the ok value
481 convertSelectionsToTimestamp($postData, $tableData, $id, $skip);
483 // Shall we process this id? It muss not be empty, of course
484 if (($skip === false) && (!empty($id)) && ((!isset($GLOBALS['skip_config'][$id]))) || ($tableName != '_config')) {
485 // Translate the value? (comma to dot!)
486 if ((is_array($translateComma)) && (in_array($id, $translateComma))) {
487 // Then do it here... :)
488 $val = convertCommaToDot($val);
491 // Shall we add numbers or strings?
493 if ('' . $val . '' == '' . $test . '') {
495 $tableData[] = sprintf("`%s`=%s", $id, $test);
498 $tableData[] = sprintf("`%s`='%s'", $id, trim($val));
501 // Do not add a config entry twice
502 $GLOBALS['skip_config'][$id] = true;
504 // Update current configuration
505 setConfigEntry($id, $val);
510 // Check if entry does exist
512 if ($alwaysAdd === false) {
513 if (!empty($whereStatement)) {
514 $result = SQL_QUERY("SELECT * FROM `{?_MYSQL_PREFIX?}" . $tableName . "` WHERE " . $whereStatement . " LIMIT 1", __FUNCTION__, __LINE__);
516 $result = SQL_QUERY("SELECT * FROM `{?_MYSQL_PREFIX?}" . $tableName . "` LIMIT 1", __FUNCTION__, __LINE__);
520 if (SQL_NUMROWS($result) == 1) {
521 // "Implode" all data to single string
522 $updatedData = implode(', ', $tableData);
524 // Generate SQL string
525 $sql = sprintf("UPDATE `{?_MYSQL_PREFIX?}%s` SET %s WHERE %s LIMIT 1",
531 // Add Line (does only work with auto_increment!
532 $keys = array(); $values = array();
533 foreach ($tableData as $entry) {
535 $line = explode('=', $entry);
537 $values[] = $line[1];
540 // Add both in one line
541 $keys = implode('`, `', $keys);
542 $values = implode(', ', $values);
544 // Generate SQL string
545 $sql = sprintf("INSERT INTO `{?_MYSQL_PREFIX?}%s` (%s) VALUES (%s)",
553 SQL_FREERESULT($result);
555 // Simply run generated SQL string
556 SQL_QUERY($sql, __FUNCTION__, __LINE__);
558 // Remember affected rows
559 $affected = SQL_AFFECTEDROWS();
562 rebuildCacheFile('config', 'config');
564 // Settings saved, so display message?
565 if ($displayMessage === true) loadTemplate('admin_settings_saved', false, getMessage('SETTINGS_SAVED'));
567 // Return affected rows
571 // Generate a selection box
572 function adminAddMenuSelectionBox ($menu, $type, $name, $default = '') {
573 // Open the requested menu directory
574 $menuArray = getArrayFromDirectory(sprintf("inc/modules/%s/", $menu), '', false, false);
576 // Init the selection box
577 $OUT = "<select name=\"".$name."\" class=\"admin_select\" size=\"1\">
578 <option value=\"\">{--IS_TOP_MENU--}</option>\n";
580 // Walk through all files
581 foreach ($menuArray as $file) {
582 // Is this a PHP script?
583 if ((!isDirectory($file)) && (strpos($file, "".$type.'-') > -1) && (strpos($file, '.php') > 0)) {
584 // Then test if the file is readable
585 $test = sprintf("inc/modules/%s/%s", $menu, $file);
587 // Is the file there?
588 if (isIncludeReadable($test)) {
589 // Extract the value for what=xxx
590 $part = substr($file, (strlen($type) + 1));
591 $part = substr($part, 0, -4);
593 // Is that part different from the overview?
594 if ($part != 'overview') {
595 $OUT .= " <option value=\"".$part."\"";
596 if ($part == $default) $OUT .= ' selected="selected"';
597 $OUT .= ">".$part."</option>\n";
603 // Close selection box
604 $OUT .= "</select>\n";
610 // Creates a user-profile link for the admin. This function can also be used for many other purposes
611 function generateUserProfileLink ($userid, $title = '', $what = 'list_user') {
612 if (($title == '') && ($userid > 0)) {
613 // Set userid as title
615 } elseif ($userid == 0) {
616 // User id zero is invalid
617 return '<strong>' . $userid . '</strong>';
620 if (($title == '0') && ($what == 'list_refs')) {
621 // Return title again
623 } elseif (isExtensionActive('nickname')) {
625 $nick = getNickname($userid);
627 // Is it not empty, use it as title else the userid
628 if (!empty($nick)) $title = $nick . '(' . $userid . ')'; else $title = $userid;
632 return '[<a href="{%url=modules.php?module=admin&what=' . $what . '&userid=' . $userid . '%}" title="{--ADMIN_USER_PROFILE_TITLE--}">' . $title . '</a>]';
635 // Check "logical-area-mode"
636 function adminGetMenuMode () {
637 // Set the default menu mode as the mode for all admins
638 $mode = getConfig('admin_menu');
642 $adminId = getCurrentAdminId();
644 // Check individual settings of current admin
645 if (isset($GLOBALS['cache_array']['admin']['la_mode'][$adminId])) {
647 $adminMode = $GLOBALS['cache_array']['admin']['la_mode'][$adminId];
648 incrementStatsEntry('cache_hits');
649 } elseif (isExtensionInstalledAndNewer('admins', '0.6.7')) {
650 // Load from database when version of 'admins' is enough
651 $result = SQL_QUERY_ESC("SELECT la_mode FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
652 array($adminId), __FUNCTION__, __LINE__);
654 // Do we have an entry?
655 if (SQL_NUMROWS($result) == 1) {
657 list($adminMode) = SQL_FETCHROW($result);
661 SQL_FREERESULT($result);
664 // Check what the admin wants and set it when it's not the default mode
665 if ($adminMode != 'global') $mode = $adminMode;
667 // Return admin-menu's mode
671 // Change activation status
672 function adminChangeActivationStatus ($IDs, $table, $row, $idRow = 'id') {
673 $cnt = '0'; $newStatus = 'Y';
674 if ((is_array($IDs)) && (count($IDs) > 0)) {
675 // "Walk" all through and count them
676 foreach ($IDs as $id => $selected) {
677 // Secure the id number
678 $id = bigintval($id);
680 // Should always be set... ;-)
681 if (!empty($selected)) {
682 // Determine new status
683 $result = SQL_QUERY_ESC("SELECT %s FROM `{?_MYSQL_PREFIX?}_%s` WHERE %s=%s LIMIT 1",
684 array($row, $table, $idRow, $id), __FUNCTION__, __LINE__);
687 if (SQL_NUMROWS($result) == 1) {
689 list($currStatus) = SQL_FETCHROW($result);
691 // And switch it N<->Y
692 if ($currStatus == 'Y') $newStatus = 'N'; else $newStatus = 'Y';
694 // Change this status
695 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s` SET %s='%s' WHERE %s=%s LIMIT 1",
696 array($table, $row, $newStatus, $idRow, $id), __FUNCTION__, __LINE__);
698 // Count up affected rows
699 $cnt += SQL_AFFECTEDROWS();
703 SQL_FREERESULT($result);
708 loadTemplate('admin_settings_saved', false, sprintf(getMessage('ADMIN_STATUS_CHANGED'), $cnt, count($IDs)));
711 loadTemplate('admin_settings_saved', false, getMessage('ADMIN_NOTHING_SELECTED_CHANGE'));
715 // Send mails for del/edit/lock build modes
716 function sendAdminBuildMails ($mode, $table, $content, $id, $subjectPart = '') {
717 // Default subject is the subject part
718 $subject = $subjectPart;
720 // Is the subject part not set?
721 if (empty($subjectPart)) {
722 // Then use it from the mode
723 $subject = strtoupper($mode);
726 // Is the raw userid set?
727 if (postRequestParameter('userid_raw', $id) > 0) {
729 $subjectLine = getMessage('MEMBER_'.strtoupper($subject).'_'.strtoupper($table).'_SUBJECT');
731 // Load email template
732 if (!empty($subjectPart)) {
733 $mail = loadEmailTemplate('member_' . $mode . '_' . strtolower($subjectPart) . '_' . $table, $content);
735 $mail = loadEmailTemplate('member_' . $mode . '_' . $table, $content);
739 sendEmail(postRequestParameter('userid_raw', $id), $subjectLine, $mail);
743 $subjectLine = getMessage('ADMIN_'.strtoupper($subject).'_'.strtoupper($table).'_SUBJECT');
745 // Send admin notification out
746 if (!empty($subjectPart)) {
747 sendAdminNotification($subjectLine, 'admin_' . $mode . '_' . strtolower($subjectPart) . '_' . $table, $content, postRequestParameter('userid_raw', $id));
749 sendAdminNotification($subjectLine, 'admin_' . $mode . '_' . $table, $content, postRequestParameter('userid_raw', $id));
753 // Build a special template list
754 function adminListBuilder ($listType, $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn) {
757 // "Walk"Â through all entries
758 foreach ($IDs as $id => $selected) {
760 $id = bigintval($id);
762 // Get result from a given column array and table name
763 $result = SQL_RESULT_FROM_ARRAY($table, $columns, $idColumn, $id, __FUNCTION__, __LINE__);
765 // Is there one entry?
766 if (SQL_NUMROWS($result) == 1) {
768 $content = SQL_FETCHARRAY($result);
771 foreach ($content as $key => $value) {
773 $idx = array_search($key, $columns, true);
775 //Â Do we have a userid?
776 if ($key == 'userid') {
777 // Add it again as raw id
778 $content['userid'] = bigintval($value);
781 // Handle the call in external function
782 $content[$key] = handleExtraValues($filterFunctions[$idx], $value, $extraValues[$idx]);
785 // Add color switching
786 $content['sw'] = $SW;
789 $OUT .= loadTemplate(sprintf("admin_%s_%s_row",
800 SQL_FREERESULT($result);
803 // Load master template
804 loadTemplate(sprintf("admin_%s_%s",
811 // Change status of "build" list
812 function adminBuilderStatusHandler ($mode, $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray) {
813 // All valid entries? (We hope so here!)
814 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues)) && (count($statusArray) > 0)) {
815 // "Walk" through all entries
816 foreach ($IDs as $id => $sel) {
817 // Construct SQL query
818 $sql = sprintf("UPDATE `{?_MYSQL_PREFIX?}_%s` SET", SQL_ESCAPE($table));
820 // Load data of entry
821 $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_%s` WHERE %s=%s LIMIT 1",
822 array($table, $idColumn, $id), __FUNCTION__, __LINE__);
825 $content = SQL_FETCHARRAY($result);
828 SQL_FREERESULT($result);
830 // Add all status entries (e.g. status column last_updated or so)
831 $newStatus = 'UNKNOWN';
832 $oldStatus = 'UNKNOWN';
833 $statusColumn = 'unknown';
834 foreach ($statusArray as $column => $statusInfo) {
835 // Does the entry exist?
836 if ((isset($content[$column])) && (isset($statusInfo[$content[$column]]))) {
837 // Add these entries for update
838 $sql .= sprintf(" %s='%s',", SQL_ESCAPE($column), SQL_ESCAPE($statusInfo[$content[$column]]));
841 if ($statusColumn == 'unknown') {
842 // Always (!!!) change status column first!
843 $oldStatus = $content[$column];
844 $newStatus = $statusInfo[$oldStatus];
845 $statusColumn = $column;
847 } elseif (isset($content[$column])) {
849 app_die(__FUNCTION__, __LINE__, ":UNFINISHED: id={$id}/{$column}[".gettype($statusInfo)."] = {$content[$column]}");
853 // Add other columns as well
854 foreach (postRequestArray() as $key => $entries) {
855 // Skip id, raw userid and 'do_$mode'
856 if (!in_array($key, array($idColumn, 'userid_raw', ('do_'.$mode)))) {
857 // Are there brackets () at the end?
858 if (substr($entries[$id], -2, 2) == "()") {
859 // Direct SQL command found
860 $sql .= sprintf(" %s=%s,", SQL_ESCAPE($key), SQL_ESCAPE($entries[$id]));
863 $sql .= sprintf(" %s='%s',", SQL_ESCAPE($key), SQL_ESCAPE($entries[$id]));
866 $content[$key] = $entries[$id];
871 // Finish SQL statement
872 $sql = substr($sql, 0, -1) . sprintf(" WHERE `%s`=%s AND `%s`='%s' LIMIT 1",
880 SQL_QUERY($sql, __FUNCTION__, __LINE__);
882 // Do we have an URL?
883 if (isset($content['url'])) {
884 // Then add a framekiller test as well
885 $content['frametester'] = generateFrametesterUrl($content['url']);
888 // Send "build mails" out
889 sendAdminBuildMails($mode, $table, $content, $id, $statusInfo[$content[$column]]);
894 // Delete rows by given id numbers
895 function adminDeleteEntriesConfirm ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $deleteNow=false, $idColumn='id', $userIdColumn='userid') {
896 // All valid entries? (We hope so here!)
897 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues))) {
898 // Shall we delete here or list for deletion?
899 if ($deleteNow === true) {
900 // The base SQL command:
901 $sql = "DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_%s` WHERE %s IN (%s)";
905 foreach ($IDs as $id => $sel) {
906 // Is there a userid?
907 if (isPostRequestParameterSet('userid_raw', $id)) {
908 // Load all data from that id
909 $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_%s` WHERE %s=%s LIMIT 1",
910 array($table, $idColumn, $id), __FUNCTION__, __LINE__);
913 $content = SQL_FETCHARRAY($result);
916 SQL_FREERESULT($result);
918 // Send "build mails" out
919 sendAdminBuildMails('del', $table, $content, $id);
923 $idList .= $id . ',';
927 SQL_QUERY($sql, array($table, $idColumn, substr($idList, 0, -1)), __FUNCTION__, __LINE__);
930 if (SQL_AFFECTEDROWS() == count($IDs)) {
932 loadTemplate('admin_settings_saved', false, getMessage('ADMIN_ALL_ENTRIES_REMOVED'));
934 // Some are still there :(
935 loadTemplate('admin_settings_saved', false, sprintf(getMessage('ADMIN_SOME_ENTRIES_NOT_DELETED'), SQL_AFFECTEDROWS(), count($IDs)));
938 // List for deletion confirmation
939 adminListBuilder('del', $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
944 // Edit rows by given id numbers
945 function adminEditEntriesConfirm ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $editNow=false, $idColumn='id', $userIdColumn='userid') {
946 // All valid entries? (We hope so here!)
947 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues))) {
948 // Shall we change here or list for editing?
949 if ($editNow === true) {
952 foreach ($IDs as $id => $sel) {
953 // Prepare content array (new values)
956 // Prepare SQL for this row
957 $sql = sprintf("UPDATE `{?_MYSQL_PREFIX?}_%s` SET",
960 foreach (postRequestArray() as $key => $entries) {
961 // Skip raw userid which is always invalid
962 if ($key == 'userid_raw') {
963 // Continue with next field
967 // Is entries an array?
968 if (($key != $idColumn) && (is_array($entries)) && (isset($entries[$id]))) {
969 // Add this entry to content
970 $content[$key] = $entries[$id];
972 // Send data through the filter function if found
973 if ((isset($filterFunctions[$key])) && (isset($extraValues[$key]))) {
974 // Filter function set!
975 $entries[$id] = handleExtraValues($filterFunctions[$key], $entries[$id], $extraValues[$key]);
978 // Then add this value
979 $sql .= sprintf(" `%s`='%s',",
981 SQL_ESCAPE($entries[$id])
983 } elseif (($key != $idColumn) && (!is_array($entries))) {
984 // Add normal entries as well!
985 $content[$key] = $entries;
988 // Do we have an URL?
990 // Then add a framekiller test as well
991 $content['frametester'] = generateFrametesterUrl($content[$key]);
995 // Finish SQL command
996 $sql = substr($sql, 0, -1) . " WHERE `" . $idColumn . "`=" . bigintval($id) . " LIMIT 1";
999 SQL_QUERY($sql, __FUNCTION__, __LINE__);
1001 // Add affected rows
1002 $affected += SQL_AFFECTEDROWS();
1004 // Load all data from that id
1005 $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`=%s LIMIT 1",
1006 array($table, $idColumn, $id), __FUNCTION__, __LINE__);
1008 // Fetch the data and merge it into $content
1009 $content = merge_array($content, SQL_FETCHARRAY($result));
1012 SQL_FREERESULT($result);
1014 // Send "build mails" out
1015 sendAdminBuildMails('edit', $table, $content, $id);
1019 if ($affected == count($IDs)) {
1021 loadTemplate('admin_settings_saved', false, getMessage('ADMIN_ALL_ENTRIES_EDITED'));
1023 // Some are still there :(
1024 loadTemplate('admin_settings_saved', false, sprintf(getMessage('ADMIN_SOME_ENTRIES_NOT_EDITED'), $affected, count($IDs)));
1028 adminListBuilder('edit', $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1033 // Un-/lock rows by given id numbers
1034 function adminLockEntriesConfirm ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $statusArray=array(), $lockNow=false, $idColumn='id', $userIdColumn='userid') {
1035 // All valid entries? (We hope so here!)
1036 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues)) && (($lockNow === false) || (count($statusArray) == 1))) {
1037 // Shall we un-/lock here or list for locking?
1038 if ($lockNow === true) {
1040 adminBuilderStatusHandler('lock', $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray);
1043 adminListBuilder('lock', $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1048 // Undelete rows by given id numbers
1049 function adminUndeleteEntriesConfirm ($IDs, $table, $columns=array(), $filterFunctions=array(), $extraValues=array(), $statusArray=array(), $undeleteNow=false, $idColumn='id', $userIdColumn='userid') {
1050 // All valid entries? (We hope so here!)
1051 if ((is_array($IDs)) && (count($IDs) > 0) && (count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues)) && (($undeleteNow === false) || (count($statusArray) == 1))) {
1052 // Shall we un-/lock here or list for locking?
1053 if ($undeleteNow === true) {
1055 adminBuilderStatusHandler('undelete', $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray);
1058 adminListBuilder('undelete', $IDs, $table, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1063 // Checks proxy settins by fetching check-updates3.php from www.mxchange.org
1064 function adminTestProxySettings ($settingsArray) {
1065 // Set temporary the new settings
1066 mergeConfig($settingsArray);
1068 // Now get the test URL
1069 $content = sendGetRequest('check-updates3.php');
1071 // Is the first line with "200 OK"?
1072 $valid = (strpos($content[0], '200 OK') !== false);
1078 // Sends out a link to the given email adress so the admin can reset his/her password
1079 function sendAdminPasswordResetLink ($email) {
1083 //Â Look up administator login
1084 $result = SQL_QUERY_ESC("SELECT `id`, `login`, `password` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `email`='%s' LIMIT 1",
1085 array($email), __FUNCTION__, __LINE__);
1087 // Is there an account?
1088 if (SQL_NUMROWS($result) == '0') {
1089 // No account found!
1090 return getMessage('ADMIN_NO_LOGIN_WITH_EMAIL');
1094 $content = SQL_FETCHARRAY($result);
1097 SQL_FREERESULT($result);
1099 // Generate hash for reset link
1100 $content['hash'] = generateHash(getConfig('URL') . ':' . $content['id'] . ':' . $content['login'] . ':' . $content['password'], substr($content['password'], 10));
1103 unset($content['id']);
1104 unset($content['password']);
1107 $mailText = loadEmailTemplate('admin_reset_password', $content);
1110 sendEmail($email, getMessage('ADMIN_RESET_PASS_LINK_SUBJ'), $mailText);
1113 return getMessage('ADMIN_RESET_LINK_SENT');
1116 // Validate hash and login for password reset
1117 function adminResetValidateHashLogin ($hash, $login) {
1118 // By default nothing validates... ;)
1121 // Then try to find that user
1122 $result = SQL_QUERY_ESC("SELECT `id`, `password`, `email` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
1123 array($login), __FUNCTION__, __LINE__);
1125 // Is an account here?
1126 if (SQL_NUMROWS($result) == 1) {
1128 $content = SQL_FETCHARRAY($result);
1130 // Generate hash again
1131 $hashFromData = generateHash(getConfig('URL') . ':' . $content['id'] . ':' . $login . ':' . $content['password'], substr($content['password'], 10));
1134 $valid = ($hash == $hashFromData);
1138 SQL_FREERESULT($result);
1144 // Reset the password for the login. Do NOT call this function without calling above function first!
1145 function doResetAdminPassword ($login, $password) {
1146 // Generate hash (we already check for sql_patches in generateHash())
1147 $passHash = generateHash($password);
1150 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_admins` SET `password`='%s' WHERE `login`='%s' LIMIT 1",
1151 array($passHash, $login), __FUNCTION__, __LINE__);
1154 runFilterChain('post_admin_reset_pass', array('login' => $login, 'hash' => $passHash));
1157 return getMessage('ADMIN_PASSWORD_RESET_DONE');
1160 // Solves a task by given id number
1161 function adminSolveTask ($id) {
1162 // Update the task data
1163 adminUpdateTaskData($id, 'status', 'SOLVED');
1166 // Marks a given task as deleted
1167 function adminDeleteTask ($id) {
1168 // Update the task data
1169 adminUpdateTaskData($id, 'status', 'DELETED');
1172 // Function to update task data
1173 function adminUpdateTaskData ($id, $row, $data) {
1176 // Not an admin so redirect better
1177 redirectToUrl('modules.php?module=index');
1180 // Is the id not set, then we need a backtrace here... :(
1182 // Initiate backtrace
1183 debug_report_bug(sprintf("id is invalid: %s. row=%s, data=%s",
1191 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_task_system` SET `%s`='%s' WHERE `id`=%s LIMIT 1",
1196 ), __FUNCTION__, __LINE__);
1199 // Checks wether if the admin menu has entries
1200 function ifAdminMenuHasEntries ($action) {
1203 // Is the entry set?
1204 isset($GLOBALS['admin_menu_has_entries'][$action])
1206 // And do we have a menu for this action?
1207 $GLOBALS['admin_menu_has_entries'][$action] === true
1209 // Login has always a menu
1215 // Setter for 'admin_menu_has_entries'
1216 function setAdminMenuHasEntries ($action, $hasEntries) {
1217 $GLOBALS['admin_menu_has_entries'][$action] = (bool) $hasEntries;
1220 // Creates a link to the user's admin-profile
1221 function adminCreateUserLink ($userid) {
1222 // Is the userid set correctly?
1224 // Create a link to that profile
1225 return '{%url=modules.php?module=admin&what=list_user&userid=' . bigintval($userid) . '%}';
1228 // Return a link to the user list
1229 return '{%url=modules.php?module=admin&what=list_user%}';
1232 // Generate a "link" for the given admin id (admin_id)
1233 function generateAdminLink ($adminId) {
1234 // No assigned admin is default
1235 $adminLink = '<span class="admin_note">{--ADMIN_NO_ADMIN_ASSIGNED--}</span>';
1237 // Zero? = Not assigned
1238 if (bigintval($adminId) > 0) {
1239 // Load admin's login
1240 $login = getAdminLogin($adminId);
1242 // Is the login valid?
1243 if ($login != '***') {
1244 // Is the extension there?
1245 if (isExtensionActive('admins')) {
1247 $adminLink = '<a href="' . generateEmailLink(getAdminEmail($adminId), 'admins') . '" title="{--ADMIN_CONTACT_LINK_TITLE--}">' . $login . '</a>';
1249 // Extension not found
1250 $adminLink = getMaskedMessage('EXTENSION_PROBLEM_NOT_INSTALLED', 'admins');
1254 $adminLink = '<div class="admin_note">' . getMaskedMessage('ADMIN_ID_404', $adminId) . '</div>';
1262 // Verifies if the current admin has confirmed to alter expert settings
1265 // 'failed' = Something goes wrong (default)
1266 // 'agreed' = Has verified and and confirmed it to see them
1267 // 'forbidden' = Has not the proper right to alter them
1268 // 'update' = Need to update extension 'admins'
1269 // 'ask' = A form was send to the admin
1270 function doVerifyExpertSettings () {
1271 // Default return status is failed
1274 // Is the extension installed and recent?
1275 if (isExtensionInstalledAndNewer('admins', '0.7.3')) {
1276 // Okay, load the status
1277 $expertSettings = getAminsExpertSettings();
1280 if ($expertSettings == 'Y') {
1281 // Okay, does he want to see them?
1282 if (getAminsExpertWarning() == 'Y') {
1285 // Is the element set, then we need to change the admin
1286 if (isPostRequestParameterSet('expert_settings')) {
1287 // Get it and prepare final post data array
1288 $postData['login'][getCurrentAdminId()] = getAdminLogin(getCurrentAdminId());
1289 $postData['expert_warning'][getCurrentAdminId()] = 'N';
1291 // Change it in the admin
1292 adminsChangeAdminAccount($postData, 'expert_warning');
1295 unsetPostRequestParameter('ok');
1302 loadTemplate('admin_expert_settings_form');
1313 $return = 'forbidden';
1316 // Out-dated extension or not installed
1320 // Output message for other status than ask/agreed
1321 if (($return != 'ask') && ($return != 'agreed')) {
1323 loadTemplate('admin_settings_saved', false, getMessage('ADMIN_EXPERT_SETTINGS_STATUS_' . strtoupper($return)));