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 * -------------------------------------------------------------------- *
18 * Copyright (c) 2003 - 2009 by Roland Haeder *
19 * Copyright (c) 2009 - 2011 by Mailer Developer Team *
20 * For more information visit: http://mxchange.org *
22 * This program is free software; you can redistribute it and/or modify *
23 * it under the terms of the GNU General Public License as published by *
24 * the Free Software Foundation; either version 2 of the License, or *
25 * (at your option) any later version. *
27 * This program is distributed in the hope that it will be useful, *
28 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
29 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
30 * GNU General Public License for more details. *
32 * You should have received a copy of the GNU General Public License *
33 * along with this program; if not, write to the Free Software *
34 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
36 ************************************************************************/
38 // Some security stuff...
39 if (!defined('__SECURITY')) {
43 // Register an administrator account
44 function addAdminAccount ($adminLogin, $passHash, $adminEmail) {
45 // Login does already exist
49 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
50 array($adminLogin), __FUNCTION__, __LINE__);
52 // Is the entry there?
53 if (SQL_HASZERONUMS($result)) {
54 // Ok, let's create the admin login
55 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_admins` (`login`,`password`,`email`) VALUES ('%s', '%s', '%s')",
60 ), __FUNCTION__, __LINE__);
67 SQL_FREERESULT($result);
73 // This function will be executed when the admin is not logged in and has submitted his login data
74 function ifAdminLoginDataIsValid ($adminLogin, $adminPassword) {
75 // First of all, no admin login is found, so the admin hash is null
79 // Get admin id from login
80 $adminId = getAdminId($adminLogin);
82 // Continue only with found admin ids
84 // Then we need to lookup the login name by getting the admin hash
85 $adminHash = getAdminHash($adminId);
87 // If this is fine, we can continue
88 if ($adminHash != '-1') {
89 // Get admin id and set it as current
90 setCurrentAdminId($adminId);
92 // Now, we need to encode the password in the same way the one is encoded in database
93 $testHash = generateHash($adminPassword, $adminHash);
95 // If they both match, the login data is valid
96 if ($testHash == $adminHash) {
106 // Prepare data array
109 'login' => $adminLogin,
110 'plain_pass' => $adminPassword,
111 'pass_hash' => $adminHash
114 // Run a special filter
115 runFilterChain('do_admin_login_' . $ret, $data);
121 // Only be executed on cookie checking
122 function ifAdminCookiesAreValid ($adminLogin, $passHash) {
123 // First of all, no admin login is found
126 // Then we need to lookup the login name by getting the admin hash
127 $adminHash = getAdminHash($adminLogin);
129 // If this is fine, we can continue
130 if ($adminHash != '-1') {
131 // Now, we need to encode the password in the same way the one is encoded in database
132 $testHash = encodeHashForCookie($adminHash);
133 //* DEBUG: */ debugOutput('adminLogin=' . $adminLogin . ',passHash='.$passHash.',adminHash='.$adminHash.',testHash='.$testHash);
135 // If they both match, the login data is valid
136 if ($testHash == $passHash) {
146 //* DEBUG: */ debugOutput('ret='.$ret);
150 // Do an admin action
151 function doAdminAction () {
155 //* DEBUG: */ debugOutput(__LINE__.'*'.$what.'/'.getModule().'/'.getAction().'/'.getWhat().'*');
157 // Remove any spaces from variable
159 // Default admin action is the overview page
163 $what = secureString($what);
167 $action = getActionFromModuleWhat(getModule(), $what);
169 // Load welcome template
170 if (isExtensionActive('admins')) {
171 // @TODO This and the next getCurrentAdminId() call might be moved into the templates?
172 $content['welcome'] = loadTemplate('admin_welcome_admins', true, getCurrentAdminId());
174 $content['welcome'] = loadTemplate('admin_welcome', true, getCurrentAdminId());
177 // Load header, footer, render menu
178 $content['header'] = loadTemplate('admin_header' , true, $content);
179 $content['footer'] = loadTemplate('admin_footer' , true, $content);
180 $content['menu'] = addAdminMenu($action, $what, true);
183 loadTemplate('admin_main_header', false, $content);
185 // Check if action/what pair is valid
186 $result_action = SQL_QUERY_ESC("SELECT
189 `{?_MYSQL_PREFIX?}_admin_menu`
194 `what`='%s' AND `what` != 'overview'
197 `what`='' OR `what` IS NULL
208 ), __FUNCTION__, __LINE__);
210 // Do we have an entry?
211 if (SQL_NUMROWS($result_action) == 1) {
212 // Is valid but does the inlcude file exists?
213 $inc = sprintf("inc/modules/admin/action-%s.php", $action);
214 if ((isIncludeReadable($inc)) && (isMenuActionValid('admin', $action, $what)) && ($GLOBALS['acl_allow'] === true)) {
215 // Ok, we finally load the admin action module
217 } elseif ($GLOBALS['acl_allow'] === false) {
219 loadTemplate('admin_menu_failed', false, '{%message,ADMIN_ACCESS_DENIED=' . $what . '%}');
221 // Include file not found :-(
222 loadTemplate('admin_menu_failed', false, '{%message,ADMIN_ACTION_404=' . $action . '%}');
225 // Invalid action/what pair found
226 loadTemplate('admin_menu_failed', false, '{%message,ADMIN_ACTION_INVALID=' . $action . '/' . $what . '%}');
230 SQL_FREERESULT($result_action);
233 loadTemplate('admin_main_footer', false, $content);
236 // Checks wether current admin is allowed to access given action/what combination
237 // (only one is allowed to be null!)
238 function isAdminAllowedAccessMenu ($action, $what = NULL) {
240 if (!isset($GLOBALS[__FUNCTION__][$action][$what])) {
241 // ACL is always 'allow' when no ext-admins is installed
242 // @TODO This can be rewritten into a filter
243 $GLOBALS[__FUNCTION__][$action][$what] = ((!isExtensionInstalledAndNewer('admins', '0.2.0')) || (isAdminsAllowedByAcl($action, $what)));
246 // Return the cached value
247 return $GLOBALS[__FUNCTION__][$action][$what];
250 // Adds an admin menu
251 function addAdminMenu ($action, $what) {
257 $GLOBALS['menu']['description'] = array();
258 $GLOBALS['menu']['title'] = array();
261 $result_main = SQL_QUERY("SELECT
262 `action` AS `main_action`,
263 `title` AS `main_title`,
264 `descr` AS `main_descr`
266 `{?_MYSQL_PREFIX?}_admin_menu`
268 (`what`='' OR `what` IS NULL)
271 `id` DESC", __FUNCTION__, __LINE__);
273 // Do we have entries?
274 if (!SQL_HASZERONUMS($result_main)) {
275 $OUT .= '<ul class="admin_menu_main">';
277 // Load all 'action' menus
278 while ($mainContent = SQL_FETCHARRAY($result_main)) {
280 $inc = sprintf("inc/modules/admin/action-%s.php", $mainContent['main_action']);
282 // Is the file readable?
283 $readable = isIncludeReadable($inc);
285 // Is the current admin allowed to access this 'action' menu?
286 if (isAdminAllowedAccessMenu($mainContent['main_action'])) {
287 if ($SUB === false) {
288 // Insert compiled menu title and description
289 $GLOBALS['menu']['title'][$mainContent['main_action']] = $mainContent['main_title'];
290 $GLOBALS['menu']['description'][$mainContent['main_action']] = $mainContent['main_descr'];
292 $OUT .= '<li class="admin_menu">
293 <div class="nobr"><strong>·</strong> ';
295 if ($readable === true) {
296 if (($mainContent['main_action'] == $action) && (empty($what))) {
299 $OUT .= '[<a href="{%url=modules.php?module=admin&action=' . $mainContent['main_action'] . '%}">';
302 $OUT .= '<span class="bad" style="cursor:help" title="{%message,ADMIN_MENU_ACTION_404_TITLE=' . $mainContent['main_action'] . '%}">';
305 $OUT .= $mainContent['main_title'];
307 if ($readable === true) {
308 if (($mainContent['main_action'] == $action) && (empty($what))) {
320 // Check for menu entries
321 $result_what = SQL_QUERY_ESC("SELECT
322 `what` AS `sub_what`,
323 `title` AS `sub_title`,
324 `descr` AS `sub_descr`
326 `{?_MYSQL_PREFIX?}_admin_menu`
334 array($mainContent['main_action']), __FUNCTION__, __LINE__);
336 // Remember the count for later checks
337 setAdminMenuHasEntries($mainContent['main_action'], ((!SQL_HASZERONUMS($result_what)) && ($action == $mainContent['main_action'])));
339 // Start li-tag for sub menu content
340 $OUT .= '<li class="admin_menu_sub" id="action_menu_' . $mainContent['main_action'] . '">';
342 // Do we have entries?
343 if (ifAdminMenuHasEntries($mainContent['main_action'])) {
344 // Sub menu has been called
346 $OUT .= '<ul class="admin_menu_sub">';
349 while ($subContent = SQL_FETCHARRAY($result_what)) {
351 $inc = sprintf("inc/modules/admin/what-%s.php", $subContent['sub_what']);
353 // Is the file readable?
354 $readable = isIncludeReadable($inc);
356 // Is the current admin allowed to access this 'what' menu?
357 if (isAdminAllowedAccessMenu(NULL, $subContent['sub_what'])) {
358 // Insert compiled title and description
359 $GLOBALS['menu']['title'][$subContent['sub_what']] = $subContent['sub_title'];
360 $GLOBALS['menu']['description'][$subContent['sub_what']] = $subContent['sub_descr'];
361 $OUT .= '<li class="admin_menu">
362 <div class="nobr"><strong>--></strong> ';
363 if ($readable === true) {
364 if ($what == $subContent['sub_what']) {
367 $OUT .= '[<a href="{%url=modules.php?module=admin&what=' . $subContent['sub_what'] . '%}">';
370 $OUT .= '<span class="bad" style="cursor:help" title="{%message,ADMIN_MENU_WHAT_404_TITLE=' . $subContent['sub_what'] . '%}">';
373 $OUT .= $subContent['sub_title'];
375 if ($readable === true) {
376 if ($what == $subContent['sub_what']) {
390 SQL_FREERESULT($result_what);
400 SQL_FREERESULT($result_main);
408 // Create an admin selection box form
409 function addAdminSelectionBox ($adminId = NULL, $special = '') {
410 // Default is email as "special column"
411 $ADD = ',`email` AS `special`';
413 // Is a special column given?
414 if (!empty($special)) {
415 // Additional column for SQL query
416 $ADD = ',`' . $special . '` AS `special`';
420 $result = SQL_QUERY('SELECT
421 `id`,`login`' . $ADD . '
423 `{?_MYSQL_PREFIX?}_admins`
425 `login` ASC', __FUNCTION__, __LINE__);
431 while ($content = SQL_FETCHARRAY($result)) {
433 $OUT .= loadTemplate('select_admins_option', true, $content);
437 SQL_FREERESULT($result);
439 // Add form to content
440 $content['form_selection'] = $OUT;
443 loadTemplate('select_admins_box', false, $content);
446 // Create a member selection box
447 function addMemberSelectionBox ($userid = NULL, $add_all = false, $return = false, $none = false, $field = 'userid') {
448 // Output selection form with all confirmed user accounts listed
449 $result = SQL_QUERY('SELECT
450 `userid`,`surname`,`family`
452 `{?_MYSQL_PREFIX?}_user_data`
454 `userid` ASC', __FUNCTION__, __LINE__);
459 // USe this only for adding points (e.g. adding refs really makes no sence ;-) )
460 if ($add_all === true) {
461 $OUT = ' <option value="all">{--ALL_MEMBERS--}</option>';
462 } elseif ($none === true) {
463 $OUT = ' <option value="0">{--SELECT_NONE--}</option>';
467 while ($content = SQL_FETCHARRAY($result)) {
468 $OUT .= '<option value="' . bigintval($content['userid']) . '"';
469 if ($userid == $content['userid']) $OUT .= ' selected="selected"';
470 $OUT .= '>' . $content['surname'] . ' ' . $content['family'] . ' (' . bigintval($content['userid']) . ')</option>';
474 SQL_FREERESULT($result);
476 if ($return === false) {
477 // Remeber options in constant
478 $content['form_selection'] = $OUT;
479 $content['what'] = '{%pipe,getWhat%}';
482 loadTemplate('admin_form_selection_box', false, $content);
484 // Return content in selection frame
485 return '<select class="form_select" name="' . handleFieldWithBraces($field) . '" size="1">' . $OUT . '</select>';
489 // Create a menu selection box for given menu system
490 // @TODO Try to rewrite this to adminAddMenuSelectionBox()
492 function adminMenuSelectionBox_DEPRECATED ($mode, $default = '', $defid = '') {
493 $what = "`what` != '' AND `what` IS NOT NULL";
494 if ($mode == 'action') $what = "(`what`='' OR `what` IS NULL) AND `action` != 'login'";
496 $result = SQL_QUERY_ESC("SELECT `%s` AS `menu`,`title` FROM `{?_MYSQL_PREFIX?}_admin_menu` WHERE ".$what." ORDER BY `sort` ASC",
497 array($mode), __FUNCTION__, __LINE__);
498 if (!SQL_HASZERONUMS($result)) {
499 // Load menu as selection
500 $OUT = '<select name="' . $mode . '_menu';
501 if ((!empty($defid)) || ($defid == '0')) $OUT .= '[' . $defid . ']';
502 $OUT .= '" size="1" class="form_select">
503 <option value="">{--SELECT_NONE--}</option>';
505 while ($content = SQL_FETCHARRAY($result)) {
506 $OUT .= '<option value="' . $content['menu'] . '"';
507 if ((!empty($default)) && ($default == $content['menu'])) $OUT .= ' selected="selected"';
508 $OUT .= '>' . $content['title'] . '</option>';
512 SQL_FREERESULT($result);
514 // Add closing select-tag
518 $OUT = '{--ADMIN_PROBLEM_NO_MENU--}';
525 // Wrapper for $_POST and adminSaveSettings
526 function adminSaveSettingsFromPostData ($tableName = '_config', $whereStatement = '`config`=0', $translateComma = array(), $alwaysAdd = false, $displayMessage = true) {
528 $postData = postRequestArray();
530 // Call the lower function
531 adminSaveSettings($postData, $tableName, $whereStatement, $translateComma, $alwaysAdd, $displayMessage);
534 // Save settings to the database
535 function adminSaveSettings (&$postData, $tableName = '_config', $whereStatement = '`config`=0', $translateComma = array(), $alwaysAdd = false, $displayMessage = true) {
536 // Prepare all arrays, variables
537 $tableData = array();
540 // Now, walk through all entries and prepare them for saving
541 foreach ($postData as $id => $val) {
542 // Process only formular field but not submit buttons ;)
544 // Do not save the ok value
545 convertSelectionsToEpocheTime($postData, $tableData, $id, $skip);
547 // Shall we process this id? It muss not be empty, of course
548 if (($skip === false) && (!empty($id)) && ((!isset($GLOBALS['skip_config'][$id]))) || ($tableName != '_config')) {
549 // Translate the value? (comma to dot!)
550 if ((is_array($translateComma)) && (in_array($id, $translateComma))) {
551 // Then do it here... :)
552 $val = convertCommaToDot($val);
555 // Shall we add numbers or strings?
556 $test = (float) $val;
557 if ('' . $val . '' == '' . $test . '') {
559 $tableData[] = sprintf("`%s`=%s", $id, $test);
560 } elseif (is_null($val)) {
562 $tableData[] = sprintf("`%s`=NULL", $id);
565 $tableData[] = sprintf("`%s`='%s'", $id, trim($val));
568 // Do not add a config entry twice
569 $GLOBALS['skip_config'][$id] = true;
571 // Update current configuration
572 setConfigEntry($id, $val);
577 // Check if entry does exist
579 if ($alwaysAdd === false) {
580 if (!empty($whereStatement)) {
581 $result = SQL_QUERY("SELECT * FROM `{?_MYSQL_PREFIX?}" . $tableName . "` WHERE " . $whereStatement . " LIMIT 1", __FUNCTION__, __LINE__);
583 $result = SQL_QUERY("SELECT * FROM `{?_MYSQL_PREFIX?}" . $tableName . "` LIMIT 1", __FUNCTION__, __LINE__);
587 if (SQL_NUMROWS($result) == 1) {
588 // "Implode" all data to single string
589 $updatedData = implode(', ', $tableData);
591 // Generate SQL string
592 $sql = sprintf("UPDATE `{?_MYSQL_PREFIX?}%s` SET %s WHERE %s LIMIT 1",
598 // Add Line (does only work with AUTO_INCREMENT!
599 $keys = array(); $values = array();
600 foreach ($tableData as $entry) {
602 $line = explode('=', $entry);
604 $values[] = $line[1];
607 // Add both in one line
608 $keys = implode('`,`', $keys);
609 $values = implode(', ', $values);
611 // Generate SQL string
612 $sql = sprintf("INSERT INTO `{?_MYSQL_PREFIX?}%s` (%s) VALUES (%s)",
620 SQL_FREERESULT($result);
622 // Simply run generated SQL string
623 SQL_QUERY($sql, __FUNCTION__, __LINE__);
625 // Remember affected rows
626 $affected = SQL_AFFECTEDROWS();
629 rebuildCache('config', 'config');
631 // Settings saved, so display message?
632 if ($displayMessage === true) displayMessage('{--SETTINGS_SAVED--}');
634 // Return affected rows
638 // Generate a selection box
639 function adminAddMenuSelectionBox ($menu, $type, $name, $default = '') {
640 // Open the requested menu directory
641 $menuArray = getArrayFromDirectory(sprintf("inc/modules/%s/", $menu), $type . '-', false, false);
643 // Init the selection box
644 $OUT = '<select name="' . $name . '" class="form_select" size="1"><option value="">{--ADMIN_IS_TOP_MENU--}</option>';
646 // Walk through all files
647 foreach ($menuArray as $file) {
648 // Is this a PHP script?
649 if ((!isDirectory($file)) && (isInString('' . $type . '-', $file)) && (isInString('.php', $file))) {
650 // Then test if the file is readable
651 $test = sprintf("inc/modules/%s/%s", $menu, $file);
653 // Is the file there?
654 if (isIncludeReadable($test)) {
655 // Extract the value for what=xxx
656 $part = substr($file, (strlen($type) + 1));
657 $part = substr($part, 0, -4);
659 // Is that part different from the overview?
660 if ($part != 'overview') {
661 $OUT .= '<option value="' . $part . '"';
662 if ($part == $default) $OUT .= ' selected="selected"';
663 $OUT .= '>' . $part . '</option>';
669 // Close selection box
676 // Creates a user-profile link for the admin. This function can also be used for many other purposes
677 function generateUserProfileLink ($userid, $title = '', $what = 'list_user') {
678 if (($title == '') && (isValidUserId($userid))) {
679 // Set userid as title
681 } elseif (!isValidUserId($userid)) {
682 // User id zero is invalid
683 return '<strong>' . makeNullToZero($userid) . '</strong>';
686 if (($title == '0') && ($what == 'list_refs')) {
687 // Return title again
689 } elseif (isExtensionActive('nickname')) {
691 $nick = getNickname($userid);
693 // Is it not empty, use it as title else the userid
695 $title = $nick . '(' . $userid . ')';
702 return '[<a href="{%url=modules.php?module=admin&what=' . $what . '&userid=' . $userid . '%}" title="{--ADMIN_USER_PROFILE_TITLE--}">' . $title . '</a>]';
705 // Check "logical-area-mode"
706 function adminGetMenuMode () {
707 // Set the default menu mode as the mode for all admins
710 // If sql_patches is up-to-date enough, use the configuration
711 if (isExtensionInstalledAndNewer('sql_patches', '0.3.2')) {
712 $mode = getAdminMenu();
719 $adminId = getCurrentAdminId();
721 // Check individual settings of current admin
722 if (isset($GLOBALS['cache_array']['admin']['la_mode'][$adminId])) {
724 $adminMode = $GLOBALS['cache_array']['admin']['la_mode'][$adminId];
725 incrementStatsEntry('cache_hits');
726 } elseif (isExtensionInstalledAndNewer('admins', '0.6.7')) {
727 // Load from database when version of 'admins' is enough
728 $result = SQL_QUERY_ESC("SELECT `la_mode` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
729 array($adminId), __FUNCTION__, __LINE__);
731 // Do we have an entry?
732 if (SQL_NUMROWS($result) == 1) {
734 list($adminMode) = SQL_FETCHROW($result);
738 SQL_FREERESULT($result);
741 // Check what the admin wants and set it when it's not the default mode
742 if ($adminMode != 'global') {
746 // Return admin-menu's mode
750 // Change activation status
751 function adminChangeActivationStatus ($IDs, $table, $row, $idRow = 'id') {
753 if ((is_array($IDs)) && (count($IDs) > 0)) {
754 // "Walk" all through and count them
755 foreach ($IDs as $id => $selected) {
756 // Secure the id number
757 $id = bigintval($id);
759 // Should always be set... ;-)
760 if (!empty($selected)) {
761 // Determine new status
762 $result = SQL_QUERY_ESC("SELECT %s FROM `{?_MYSQL_PREFIX?}_%s` WHERE %s=%s LIMIT 1",
768 ), __FUNCTION__, __LINE__);
771 if (SQL_NUMROWS($result) == 1) {
773 list($currStatus) = SQL_FETCHROW($result);
775 // And switch it N<->Y
776 $newStatus = convertBooleanToYesNo(!($currStatus == 'Y'));
778 // Change this status
779 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s` SET %s='%s' WHERE %s=%s LIMIT 1",
786 ), __FUNCTION__, __LINE__);
788 // Count up affected rows
789 $count += SQL_AFFECTEDROWS();
793 SQL_FREERESULT($result);
798 displayMessage(sprintf(getMessage('ADMIN_STATUS_CHANGED'), $count, count($IDs)));
801 displayMessage('{--ADMIN_NOTHING_SELECTED_CHANGE--}');
805 // Send mails for del/edit/lock build modes
806 function sendAdminBuildMails ($mode, $tableName, $content, $id, $subjectPart = '', $userIdColumn = array('userid')) {
807 // $tableName must be an array
808 if ((!is_array($tableName)) || (count($tableName) != 1)) {
809 // $tableName is no array
810 debug_report_bug(__FUNCTION__, __LINE__, 'tableName[]=' . gettype($tableName) . '!=array');
811 } elseif ((!is_array($userIdColumn)) || (count($userIdColumn) != 1)) {
812 // $tableName is no array
813 debug_report_bug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array');
816 // Default subject is the subject part
817 $subject = $subjectPart;
819 // Is the subject part not set?
820 if (empty($subjectPart)) {
821 // Then use it from the mode
822 $subject = strtoupper($mode);
825 // Is the raw userid set?
826 if (postRequestElement($userIdColumn[0], $id) > 0) {
827 // Load email template
828 if (!empty($subjectPart)) {
829 $mail = loadEmailTemplate('member_' . $mode . '_' . strtolower($subjectPart) . '_' . $tableName[0], $content);
831 $mail = loadEmailTemplate('member_' . $mode . '_' . $tableName[0], $content);
835 sendEmail(postRequestElement($userIdColumn[0], $id), strtoupper('{--MEMBER_' . $subject . '_' . $tableName[0] . '_SUBJECT--}'), $mail);
839 $subject = strtoupper('{--ADMIN_' . $subject . '_' . $tableName[0] . '_SUBJECT--}');
841 // Send admin notification out
842 if (!empty($subjectPart)) {
843 sendAdminNotification($subject, 'admin_' . $mode . '_' . strtolower($subjectPart) . '_' . $tableName[0], $content, postRequestElement($userIdColumn[0], $id));
845 sendAdminNotification($subject, 'admin_' . $mode . '_' . $tableName[0], $content, postRequestElement($userIdColumn[0], $id));
849 // Build a special template list
850 function adminListBuilder ($listType, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId = array('userid')) {
851 // $tableName and $idColumn must bove be arrays!
852 if ((!is_array($tableName)) || (count($tableName) != 1)) {
853 // $tableName is no array
854 debug_report_bug(__FUNCTION__, __LINE__, 'tableName[]=' . gettype($tableName) . '!=array');
855 } elseif (!is_array($idColumn)) {
856 // $idColumn is no array
857 debug_report_bug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array');
858 } elseif ((!is_array($userIdColumn)) || (count($userIdColumn) != 1)) {
859 // $tableName is no array
860 debug_report_bug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array');
866 // "Walk"Â through all entries
867 //* DEBUG: */ debug_report_bug(__FUNCTION__, __LINE__, 'listType=<pre>'.print_r($listType,true).'</pre>,tableName<pre>'.print_r($tableName,true).'</pre>,columns=<pre>'.print_r($columns,true).'</pre>,filterFunctions=<pre>'.print_r($filterFunctions,true).'</pre>,extraValues=<pre>'.print_r($extraValues,true).'</pre>,idColumn=<pre>'.print_r($idColumn,true).'</pre>,userIdColumn=<pre>'.print_r($userIdColumn,true).'</pre>,rawUserId=<pre>'.print_r($rawUserId,true).'</pre>');
868 foreach (postRequestElement($idColumn[0]) as $id => $selected) {
870 $id = bigintval($id);
872 // Get result from a given column array and table name
873 $result = SQL_RESULT_FROM_ARRAY($tableName[0], $columns, $idColumn[0], $id, __FUNCTION__, __LINE__);
875 // Is there one entry?
876 if (SQL_NUMROWS($result) == 1) {
878 $content = SQL_FETCHARRAY($result);
881 foreach ($content as $key => $value) {
883 $idx = searchXmlArray($key, $columns, 'column');
885 // Skip any missing entries
886 if ($idx === false) {
888 //* DEBUG: */ debug_report_bug(__FUNCTION__, __LINE__, 'key=' . $key . ' - SKIPPED!');
892 //Â Do we have a userid?
893 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',userIdColumn=' . $userIdColumn[0]);
894 if ($key == $userIdColumn[0]) {
895 // Add it again as raw id
896 //* DEBUG: */ debug_report_bug(__FUNCTION__, __LINE__, 'key=' . $key . ',userIdColumn=' . $userIdColumn[0]);
897 $content[$userIdColumn[0]] = makeZeroToNull($value);
898 $content[$userIdColumn[0] . '_raw'] = $content[$userIdColumn[0]];
901 // If the key matches the idColumn variable, we need to temporary remember it
902 //* DEBUG: */ debugOutput('key=' . $key . ',idColumn=' . $idColumn[0] . ',value=' . $value);
903 if ($key == $idColumn[0]) {
904 // Found, so remember it
905 $GLOBALS['admin_list_builder_id_value'] = $value;
908 // Do we have a call-back function and extra-value pair?
909 if ((isset($filterFunctions[$idx])) && (isset($extraValues[$idx]))) {
910 // Handle the call in external function
911 //* DEBUG: */ debugOutput('key=' . $key . ',fucntion=' . $filterFunctions[$idx] . ',value=' . $value);
912 $content[$key] = handleExtraValues(
913 $filterFunctions[$idx],
917 } elseif ((isset($columns[$idx]['name'])) && (isset($filterFunctions[$columns[$idx]['name']])) && (isset($extraValues[$columns[$idx]['name']]))) {
918 // Handle the call in external function
919 //* DEBUG: */ debugOutput('key=' . $key . ',fucntion=' . $filterFunctions[$columns[$idx]['name']] . ',value=' . $value);
920 $content[$key] = handleExtraValues(
921 $filterFunctions[$columns[$idx]['name']],
923 $extraValues[$columns[$idx]['name']]
929 $OUT .= loadTemplate(sprintf("admin_%s_%s_row",
937 SQL_FREERESULT($result);
940 // Load master template
941 loadTemplate(sprintf("admin_%s_%s",
948 // Change status of "build" list
949 function adminBuilderStatusHandler ($mode, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray, $rawUserId = array('userid')) {
950 // $tableName must be an array
951 if ((!is_array($tableName)) || (count($tableName) != 1)) {
952 // No tableName specified
953 debug_report_bug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array');
954 } elseif (!is_array($idColumn)) {
955 // $idColumn is no array
956 debug_report_bug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array');
957 } elseif ((!is_array($userIdColumn)) || (count($userIdColumn) != 1)) {
958 // $tableName is no array
959 debug_report_bug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array');
962 // All valid entries? (We hope so here!)
963 if ((count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues)) && (count($statusArray) > 0)) {
964 // "Walk" through all entries
965 foreach (postRequestElement($idColumn[0]) as $id => $sel) {
966 // Construct SQL query
967 $sql = sprintf("UPDATE `{?_MYSQL_PREFIX?}_%s` SET", SQL_ESCAPE($tableName[0]));
969 // Load data of entry
970 $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`=%s LIMIT 1",
975 ), __FUNCTION__, __LINE__);
978 $content = SQL_FETCHARRAY($result);
981 SQL_FREERESULT($result);
983 // Add all status entries (e.g. status column last_updated or so)
984 $newStatus = 'UNKNOWN';
985 $oldStatus = 'UNKNOWN';
986 $statusColumn = 'unknown';
987 foreach ($statusArray as $column => $statusInfo) {
988 // Does the entry exist?
989 if ((isset($content[$column])) && (isset($statusInfo[$content[$column]]))) {
990 // Add these entries for update
991 $sql .= sprintf(" `%s`='%s',", SQL_ESCAPE($column), SQL_ESCAPE($statusInfo[$content[$column]]));
994 if ($statusColumn == 'unknown') {
995 // Always (!!!) change status column first!
996 $oldStatus = $content[$column];
997 $newStatus = $statusInfo[$oldStatus];
998 $statusColumn = $column;
1000 } elseif (isset($content[$column])) {
1002 debug_report_bug(__FUNCTION__, __LINE__, ':UNFINISHED: id=' . $id . ',column=' . $column . '[' . gettype($statusInfo) . '] = ' . $content[$column]);
1006 // Add other columns as well
1007 foreach (postRequestArray() as $key => $entries) {
1009 logDebugMessage(__FUNCTION__, __LINE__, 'Found entry: ' . $key);
1011 // Skip id, raw userid and 'do_$mode'
1012 if (!in_array($key, array($idColumn[0], $rawUserId[0], ('do_' . $mode)))) {
1013 // Are there brackets () at the end?
1014 if (substr($entries[$id], -2, 2) == '()') {
1015 // Direct SQL command found
1016 $sql .= sprintf(" `%s`=%s,", SQL_ESCAPE($key), SQL_ESCAPE($entries[$id]));
1018 // Add regular entry
1019 $sql .= sprintf(" `%s`='%s',", SQL_ESCAPE($key), SQL_ESCAPE($entries[$id]));
1022 $content[$key] = $entries[$id];
1026 logDebugMessage(__FUNCTION__, __LINE__, 'Skipped: ' . $key);
1030 // Finish SQL statement
1031 $sql = substr($sql, 0, -1) . sprintf(" WHERE `%s`=%s AND `%s`='%s' LIMIT 1",
1039 SQL_QUERY($sql, __FUNCTION__, __LINE__);
1041 // Do we have an URL?
1042 if (isset($content['url'])) {
1043 // Then add a framekiller test as well
1044 $content['frametester'] = generateFrametesterUrl($content['url']);
1047 // Send "build mails" out
1048 sendAdminBuildMails($mode, $tableName, $content, $id, $statusInfo[$content[$column]], $userIdColumn);
1053 // Delete rows by given id numbers
1054 function adminDeleteEntriesConfirm ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $deleteNow = array(false), $idColumn = array('id'), $userIdColumn = array('userid'), $rawUserId = array('userid')) {
1055 // $tableName must be an array
1056 if ((!is_array($tableName)) || (count($tableName) != 1)) {
1057 // No tableName specified
1058 debug_report_bug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array');
1059 } elseif (!is_array($idColumn)) {
1060 // $idColumn is no array
1061 debug_report_bug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array');
1062 } elseif (!is_array($userIdColumn)) {
1063 // $userIdColumn is no array
1064 debug_report_bug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array');
1065 } elseif (!is_array($deleteNow)) {
1066 // $deleteNow is no array
1067 debug_report_bug(__FUNCTION__, __LINE__, 'deleteNow[]=' . gettype($deleteNow) . '!=array');
1070 // All valid entries? (We hope so here!)
1071 if ((count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues))) {
1072 // Shall we delete here or list for deletion?
1073 if ($deleteNow[0] === true) {
1074 // The base SQL command:
1075 $sql = "DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s` IN (%s)";
1079 foreach (postRequestElement($idColumn[0]) as $id => $sel) {
1080 // Is there a userid?
1081 if (isPostRequestElementSet($rawUserId[0], $id)) {
1082 // Load all data from that id
1083 $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`=%s LIMIT 1",
1088 ), __FUNCTION__, __LINE__);
1091 $content = SQL_FETCHARRAY($result);
1094 SQL_FREERESULT($result);
1096 // Send "build mails" out
1097 sendAdminBuildMails('delete', $tableName, $content, $id, '', $userIdColumn);
1101 $idList .= $id . ',';
1105 SQL_QUERY_ESC($sql, array($tableName[0], $idColumn[0], substr($idList, 0, -1)), __FUNCTION__, __LINE__);
1108 if (SQL_AFFECTEDROWS() == count(postRequestElement($idColumn[0]))) {
1110 displayMessage('{--ADMIN_ALL_ENTRIES_REMOVED--}');
1112 // Some are still there :(
1113 displayMessage(sprintf(getMessage('ADMIN_SOME_ENTRIES_NOT_DELETED'), SQL_AFFECTEDROWS(), count(postRequestElement($idColumn[0]))));
1116 // List for deletion confirmation
1117 adminListBuilder('delete', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1122 // Edit rows by given id numbers
1123 function adminEditEntriesConfirm ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $editNow = array(false), $idColumn = array('id'), $userIdColumn = array('userid'), $rawUserId = array('userid')) {
1124 // $tableName must be an array
1125 if ((!is_array($tableName)) || (count($tableName) != 1)) {
1126 // No tableName specified
1127 debug_report_bug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array');
1128 } elseif (!is_array($idColumn)) {
1129 // $idColumn is no array
1130 debug_report_bug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array');
1131 } elseif (!is_array($userIdColumn)) {
1132 // $userIdColumn is no array
1133 debug_report_bug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array');
1134 } elseif (!is_array($editNow)) {
1135 // $editNow is no array
1136 debug_report_bug(__FUNCTION__, __LINE__, 'editNow[]=' . gettype($editNow) . '!=array');
1139 // All valid entries? (We hope so here!)
1140 //* DEBUG: */ debug_report_bug(__FUNCTION__, __LINE__, 'idColumn=<pre>'.print_r($idColumn,true).'</pre>,tableName<pre>'.print_r($tableName,true).'</pre>,columns=<pre>'.print_r($columns,true).'</pre>,filterFunctions=<pre>'.print_r($filterFunctions,true).'</pre>,extraValues=<pre>'.print_r($extraValues,true).'</pre>,editNow=<pre>'.print_r($editNow,true).'</pre>,userIdColumn=<pre>'.print_r($userIdColumn,true).'</pre>,rawUserId=<pre>'.print_r($rawUserId,true).'</pre>');
1141 //if ((count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues))) {
1143 // Shall we change here or list for editing?
1144 if ($editNow[0] === true) {
1147 foreach (postRequestElement($idColumn[0]) as $id => $sel) {
1148 // Prepare content array (new values)
1151 // Prepare SQL for this row
1152 $sql = sprintf("UPDATE `{?_MYSQL_PREFIX?}_%s` SET",
1153 SQL_ESCAPE($tableName[0])
1155 foreach (postRequestArray() as $key => $entries) {
1156 // Skip raw userid which is always invalid
1157 if ($key == $rawUserId[0]) {
1158 // Continue with next field
1162 // Is entries an array?
1163 if (($key != $idColumn[0]) && (is_array($entries)) && (isset($entries[$id]))) {
1164 // Add this entry to content
1165 $content[$key] = $entries[$id];
1167 // Send data through the filter function if found
1168 if ((isset($filterFunctions[$key])) && (isset($extraValues[$key]))) {
1169 // Filter function set!
1170 $entries[$id] = handleExtraValues($filterFunctions[$key], $entries[$id], $extraValues[$key]);
1173 // Then add this value
1174 $sql .= sprintf(" `%s`='%s',",
1176 SQL_ESCAPE($entries[$id])
1178 } elseif (($key != $idColumn[0]) && (!is_array($entries))) {
1179 // Add normal entries as well!
1180 $content[$key] = $entries;
1183 // Do we have an URL?
1184 if ($key == 'url') {
1185 // Then add a framekiller test as well
1186 $content['frametester'] = generateFrametesterUrl($content[$key]);
1190 // Finish SQL command
1191 $sql = substr($sql, 0, -1) . " WHERE `" . $idColumn[0] . "`=" . bigintval($id) . " LIMIT 1";
1194 SQL_QUERY($sql, __FUNCTION__, __LINE__);
1196 // Add affected rows
1197 $affected += SQL_AFFECTEDROWS();
1199 // Load all data from that id
1200 $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`=%s LIMIT 1",
1205 ), __FUNCTION__, __LINE__);
1207 // Fetch the data and merge it into $content
1208 $content = merge_array($content, SQL_FETCHARRAY($result));
1211 SQL_FREERESULT($result);
1213 // Send "build mails" out
1214 sendAdminBuildMails('edit', $tableName, $content, $id, '', $userIdColumn);
1218 if ($affected == count(postRequestElement($idColumn[0]))) {
1220 displayMessage('{--ADMIN_ALL_ENTRIES_EDITED--}');
1222 // Some are still there :(
1223 displayMessage(sprintf(getMessage('ADMIN_SOME_ENTRIES_NOT_EDITED'), $affected, count(postRequestElement($idColumn[0]))));
1227 adminListBuilder('edit', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1230 // Maybe some invalid parameters
1231 debug_report_bug(__FUNCTION__, __LINE__, 'tableName=' . $tableName[0] . ',columns[]=' . gettype($columns) . ',filterFunctions[]=' . gettype($filterFunctions) . ',extraValues[]=' . gettype($extraValues) . ',idColumn=' . $idColumn[0] . ',userIdColumn=' . $userIdColumn[0] . ' - INVALID!');
1235 // Un-/lock rows by given id numbers
1236 function adminLockEntriesConfirm ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $statusArray = array(), $lockNow = array(false), $idColumn = array('id'), $userIdColumn = array('userid')) {
1237 // $tableName must be an array
1238 if ((!is_array($tableName)) || (count($tableName) != 1)) {
1239 // No tableName specified
1240 debug_report_bug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array');
1241 } elseif (!is_array($idColumn)) {
1242 // $idColumn is no array
1243 debug_report_bug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array');
1244 } elseif (!is_array($lockNow)) {
1245 // $lockNow is no array
1246 debug_report_bug(__FUNCTION__, __LINE__, 'lockNow[]=' . gettype($lockNow) . '!=array');
1249 // All valid entries? (We hope so here!)
1250 if ((count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues)) && (($lockNow[0] === false) || (count($statusArray) == 1))) {
1251 // Shall we un-/lock here or list for locking?
1252 if ($lockNow[0] === true) {
1254 adminBuilderStatusHandler('lock', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray);
1257 adminListBuilder('lock', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1262 // Undelete rows by given id numbers
1263 function adminUndeleteEntriesConfirm ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $statusArray = array(), $undeleteNow = array(false), $idColumn = array('id'), $userIdColumn = array('userid')) {
1264 // $tableName must be an array
1265 if ((!is_array($tableName)) || (count($tableName) != 1)) {
1266 // No tableName specified
1267 debug_report_bug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array');
1268 } elseif (!is_array($idColumn)) {
1269 // $idColumn is no array
1270 debug_report_bug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array');
1271 } elseif (!is_array($undeleteNow)) {
1272 // $undeleteNow is no array
1273 debug_report_bug(__FUNCTION__, __LINE__, 'undeleteNow[]=' . gettype($undeleteNow) . '!=array');
1276 // All valid entries? (We hope so here!)
1277 if ((count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues)) && (($undeleteNow[0] === false) || (count($statusArray) == 1))) {
1278 // Shall we un-/lock here or list for locking?
1279 if ($undeleteNow[0] === true) {
1281 adminBuilderStatusHandler('undelete', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray);
1284 adminListBuilder('undelete', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1289 // Adds a given entry to the database
1290 function adminAddEntries ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array()) {
1291 //* DEBUG: */ die('columns=<pre>'.print_r($columns,true).'</pre>,filterFunctions=<pre>'.print_r($filterFunctions,true).'</pre>,extraValues=<pre>'.print_r($extraValues,true).'</pre>,POST=<pre>'.print_r($_POST,true).'</pre>');
1292 // Verify that tableName and columns are not empty
1293 if ((!is_array($tableName)) || (count($tableName) != 1)) {
1294 // No tableName specified
1295 debug_report_bug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array');
1296 } elseif (count($columns) == 0) {
1297 // No columns specified
1298 debug_report_bug(__FUNCTION__, __LINE__, 'columns is not given. Please fix your XML.');
1301 // Init columns and value elements
1302 $sqlColumns = array();
1303 $sqlValues = array();
1305 // Add columns and values
1306 foreach ($columns as $key => $columnName) {
1307 // Copy entry to final arrays
1308 $sqlColumns[$key] = $columnName;
1309 $sqlValues[$key] = postRequestElement($columnName);
1310 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key='.$key.',columnName='.$columnName.',filterFunctions='.$filterFunctions[$key].',extraValues='.intval(isset($extraValues[$key])).',extraValuesName='.intval(isset($extraValues[$columnName . '_list'])).'<br />');
1312 // Send data through the filter function if found
1313 if ((isset($filterFunctions[$key])) && (isset($extraValues[$key . '_list']))) {
1314 // Filter function set!
1315 $sqlValues[$key] = call_user_func_array($filterFunctions[$key], merge_array(array($columnName), $extraValues[$key . '_list']));
1319 // Build the SQL query
1320 $SQL = 'INSERT INTO `{?_MYSQL_PREFIX?}_' . $tableName[0] . '` (`' . implode('`,`', $sqlColumns) . "`) VALUES ('" . implode("','", $sqlValues) . "')";
1322 // Run the SQL query
1323 SQL_QUERY($SQL, __FUNCTION__, __LINE__);
1325 // Entry has been added?
1326 if (!SQL_HASZEROAFFECTED()) {
1327 // Display success message
1328 displayMessage('{--ADMIN_ENTRY_ADDED--}');
1330 // Display failed message
1331 displayMessage('{--ADMIN_ENTRY_NOT_ADDED--}');
1335 // List all given rows (callback function from XML)
1336 function adminListEntries ($tableTemplate, $rowTemplate, $noEntryMessageId, $tableName, $columns, $whereColumns, $orderByColumns, $callbackColumns, $extraParameters = array()) {
1337 // Verify that tableName and columns are not empty
1338 if ((!is_array($tableName)) || (count($tableName) != 1)) {
1339 // No tableName specified
1340 debug_report_bug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array,tableTemplate=' . $tableTemplate . ',rowTemplate=' . $rowTemplate);
1341 } elseif (count($columns) == 0) {
1342 // No columns specified
1343 debug_report_bug(__FUNCTION__, __LINE__, 'columns is not given. Please fix your XML,tableTemplate=' . $tableTemplate . ',rowTemplate=' . $rowTemplate . ',tableName[0]=' . $tableName[0]);
1346 // This is the minimum query, so at least columns and tableName must have entries
1349 // Get the sql part back from given array
1350 $SQL .= getSqlPartFromXmlArray($columns);
1352 // Remove last commata and add FROM statement
1353 $SQL .= ' FROM `{?_MYSQL_PREFIX?}_' . $tableName[0] . '`';
1355 // Do we have entries from whereColumns to add?
1356 if (count($whereColumns) > 0) {
1357 // Then add these as well
1358 if (count($whereColumns) == 1) {
1362 // Table/alias included?
1363 if (!empty($whereColumns[0]['table'])) {
1365 $SQL .= $whereColumns[0]['table'] . '.';
1369 $SQL .= '`' . $whereColumns[0]['column'] . '`' . $whereColumns[0]['condition'] . "'" . $whereColumns[0]['look_for'] . "'";
1371 // More than one entry -> Unsupported
1372 debug_report_bug(__FUNCTION__, __LINE__, 'More than one WHERE statement found. This is currently not supported.');
1376 // Do we have entries from orderByColumns to add?
1377 if (count($orderByColumns) > 0) {
1379 $SQL .= ' ORDER BY ';
1380 foreach ($orderByColumns as $orderByColumn => $array) {
1381 // Get keys (table/alias) and values (sorting itself)
1382 $table = trim(implode('', array_keys($array)));
1383 $sorting = trim(implode('', array_keys($array)));
1385 // table/alias can be omitted
1386 if (!empty($table)) {
1387 // table/alias is given
1388 $SQL .= $table . '.';
1391 // Add order-by column
1392 $SQL .= '`' . $orderByColumn . '` ' . $sorting . ',';
1395 // Remove last column
1396 $SQL = substr($SQL, 0, -1);
1399 // Now handle all over to the inner function which will execute the listing
1400 doAdminListEntries($SQL, $tableTemplate, $noEntryMessageId, $rowTemplate, $callbackColumns, $extraParameters);
1403 // Do the listing of entries
1404 function doAdminListEntries ($SQL, $tableTemplate, $noEntryMessageId, $rowTemplate, $callbackColumns, $extraParameters = array()) {
1405 // Run the SQL query
1406 $result = SQL_QUERY($SQL, __FUNCTION__, __LINE__);
1408 // Do we have some URLs left?
1409 if (!SQL_HASZERONUMS($result)) {
1412 while ($content = SQL_FETCHARRAY($result)) {
1413 // "Translate" content
1414 foreach ($callbackColumns as $columnName => $callbackFunction) {
1415 // Fill the callback arguments
1416 $args = array($content[$columnName]);
1418 // Do we have more to add?
1419 if (isset($extraParameters[$columnName])) {
1421 $args = merge_array($args, $extraParameters[$columnName]);
1424 // Call the callback-function
1425 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'callbackFunction=' . $callbackFunction . ',args=<pre>'.print_r($args, true).'</pre>');
1426 // @TODO If we can rewrite the EL sub-system to support more than one parameter, this call_user_func_array() can be avoided
1427 $content[$columnName] = call_user_func_array($callbackFunction, $args);
1430 // Load row template
1431 $OUT .= loadTemplate(trim($rowTemplate[0]), true, $content);
1434 // Load main template
1435 loadTemplate(trim($tableTemplate[0]), false, $OUT);
1437 // No URLs in surfbar
1438 displayMessage('{--' .$noEntryMessageId[0] . '--}');
1442 SQL_FREERESULT($result);
1445 // Checks proxy settins by fetching check-updates3.php from mxchange.org
1446 function adminTestProxySettings ($settingsArray) {
1447 // Set temporary the new settings
1448 mergeConfig($settingsArray);
1450 // Now get the test URL
1451 $content = sendGetRequest('check-updates3.php');
1453 // Is the first line with "200 OK"?
1454 $valid = isInString('200 OK', $content[0]);
1460 // Sends out a link to the given email adress so the admin can reset his/her password
1461 function sendAdminPasswordResetLink ($email) {
1465 //Â Look up administator login
1466 $result = SQL_QUERY_ESC("SELECT `id`,`login`,`password` FROM `{?_MYSQL_PREFIX?}_admins` WHERE '%s' REGEXP `email` LIMIT 1",
1467 array($email), __FUNCTION__, __LINE__);
1469 // Is there an account?
1470 if (SQL_HASZERONUMS($result)) {
1472 return '{--ADMIN_NO_LOGIN_WITH_EMAIL--}';
1476 $content = SQL_FETCHARRAY($result);
1479 SQL_FREERESULT($result);
1481 // Generate hash for reset link
1482 $content['hash'] = generateHash(getUrl() . getEncryptSeparator() . $content['id'] . getEncryptSeparator() . $content['login'] . getEncryptSeparator() . $content['password'], substr($content['password'], getSaltLength()));
1485 unset($content['id']);
1486 unset($content['password']);
1489 $mailText = loadEmailTemplate('admin_reset_password', $content);
1492 sendEmail($email, '{--ADMIN_RESET_PASSWORD_LINK_SUBJECT--}', $mailText);
1495 return '{--ADMIN_RESET_PASSWORD_LINK_SENT--}';
1498 // Validate hash and login for password reset
1499 function adminResetValidateHashLogin ($hash, $login) {
1500 // By default nothing validates... ;)
1503 // Then try to find that user
1504 $result = SQL_QUERY_ESC("SELECT `id`,`password`,`email` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
1505 array($login), __FUNCTION__, __LINE__);
1507 // Is an account here?
1508 if (SQL_NUMROWS($result) == 1) {
1510 $content = SQL_FETCHARRAY($result);
1512 // Generate hash again
1513 $hashFromData = generateHash(getUrl() . getEncryptSeparator() . $content['id'] . getEncryptSeparator() . $login . getEncryptSeparator() . $content['password'], substr($content['password'], getSaltLength()));
1516 $valid = ($hash == $hashFromData);
1520 SQL_FREERESULT($result);
1526 // Reset the password for the login. Do NOT call this function without calling above function first!
1527 function doResetAdminPassword ($login, $password) {
1528 // Generate hash (we already check for sql_patches in generateHash())
1529 $passHash = generateHash($password);
1531 // Prepare fake POST data
1533 'login' => array(getAdminId($login) => $login),
1534 'password' => array(getAdminId($login) => $passHash),
1538 $message = adminsChangeAdminAccount($postData, '', false);
1541 runFilterChain('post_form_reset_pass', array('login' => $login, 'hash' => $passHash, 'message' => $message));
1544 return '{--ADMIN_PASSWORD_RESET_DONE--}';
1547 // Solves a task by given id number
1548 function adminSolveTask ($id) {
1549 // Update the task data
1550 adminUpdateTaskData($id, 'status', 'SOLVED');
1553 // Marks a given task as deleted
1554 function adminDeleteTask ($id) {
1555 // Update the task data
1556 adminUpdateTaskData($id, 'status', 'DELETED');
1559 // Function to update task data
1560 function adminUpdateTaskData ($id, $row, $data) {
1561 // Should be admin and valid id
1563 // Not an admin so redirect better
1564 debug_report_bug(__FUNCTION__, __LINE__, 'id=' . $id . ',row=' . $row . ',data=' . $data . ' - isAdmin()=false');
1565 } elseif ($id <= 0) {
1566 // Initiate backtrace
1567 debug_report_bug(__FUNCTION__, __LINE__, sprintf("id is invalid: %s. row=%s, data=%s",
1575 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_task_system` SET `%s`='%s' WHERE `id`=%s LIMIT 1",
1580 ), __FUNCTION__, __LINE__);
1583 // Checks wether if the admin menu has entries
1584 function ifAdminMenuHasEntries ($action) {
1587 // Is the entry set?
1588 isset($GLOBALS['admin_menu_has_entries'][$action])
1590 // And do we have a menu for this action?
1591 $GLOBALS['admin_menu_has_entries'][$action] === true
1593 // Login has always a menu
1599 // Setter for 'admin_menu_has_entries'
1600 function setAdminMenuHasEntries ($action, $hasEntries) {
1601 $GLOBALS['admin_menu_has_entries'][$action] = (bool) $hasEntries;
1604 // Creates a link to the user's admin-profile
1605 function adminCreateUserLink ($userid) {
1606 // Is the userid set correctly?
1607 if (isValidUserId($userid)) {
1608 // Create a link to that profile
1609 return '{%url=modules.php?module=admin&what=list_user&userid=' . bigintval($userid) . '%}';
1612 // Return a link to the user list
1613 return '{%url=modules.php?module=admin&what=list_user%}';
1616 // Generate a "link" for the given admin id (admin_id)
1617 function generateAdminLink ($adminId) {
1618 // No assigned admin is default
1619 $adminLink = '{--ADMIN_NO_ADMIN_ASSIGNED--}';
1621 // Zero? = Not assigned
1622 if (bigintval($adminId) > 0) {
1623 // Load admin's login
1624 $login = getAdminLogin($adminId);
1626 // Is the login valid?
1627 if ($login != '***') {
1628 // Is the extension there?
1629 if (isExtensionActive('admins')) {
1631 $adminLink = '<a href="' . generateEmailLink(getAdminEmail($adminId), 'admins') . '" title="{--ADMIN_CONTACT_LINK_TITLE--}">' . $login . '</a>';
1633 // Extension not found
1634 $adminLink = '{%message,ADMIN_TASK_ROW_EXTENSION_NOT_INSTALLED=admins%}';
1638 $adminLink = '<div class="bad">{%message,ADMIN_ID_404=' . $adminId . '%}</div>';
1646 // Verifies if the current admin has confirmed to alter expert settings
1649 // 'failed' = Something goes wrong (default)
1650 // 'agreed' = Has verified and and confirmed it to see them
1651 // 'forbidden' = Has not the proper right to alter them
1652 // 'update' = Need to update extension 'admins'
1653 // 'ask' = A form was send to the admin
1654 function doVerifyExpertSettings () {
1655 // Default return status is failed
1658 // Is the extension installed and recent?
1659 if (isExtensionInstalledAndNewer('admins', '0.7.3')) {
1660 // Okay, load the status
1661 $expertSettings = getAminsExpertSettings();
1664 if ($expertSettings == 'Y') {
1665 // Okay, does he want to see them?
1666 if (isAdminsExpertWarningEnabled()) {
1669 // Is the element set, then we need to change the admin
1670 if (isPostRequestElementSet('expert_settings')) {
1671 // Get it and prepare final post data array
1672 $postData['login'][getCurrentAdminId()] = getCurrentAdminLogin();
1673 $postData['expert_warning'][getCurrentAdminId()] = 'N';
1675 // Change it in the admin
1676 adminsChangeAdminAccount($postData, 'expert_warning');
1679 unsetPostRequestElement('ok');
1686 loadTemplate('admin_expert_settings_form');
1697 $return = 'forbidden';
1700 // Out-dated extension or not installed
1704 // Output message for other status than ask/agreed
1705 if (($return != 'ask') && ($return != 'agreed')) {
1707 displayMessage('{--ADMIN_EXPERT_SETTINGS_STATUS_' . strtoupper($return) . '--}');
1714 // Generate link to unconfirmed mails for admin
1715 function generateUnconfirmedAdminLink ($id, $unconfirmed, $type = 'bid') {
1717 $OUT = $unconfirmed;
1719 // Do we have unconfirmed mails?
1720 if ($unconfirmed > 0) {
1721 // Add link to list_unconfirmed what-file
1722 $OUT = '<a href="{%url=modules.php?module=admin&what=list_unconfirmed&' . $type . '=' . $id . '%}">{%pipe,translateComma=' . $unconfirmed . '%}</a>';
1729 // Generates a navigation row for listing emails
1730 function addEmailNavigation ($numPages, $offset, $show_form, $colspan, $return=false) {
1731 // Don't do anything if $numPages is 1
1732 if ($numPages == 1) {
1733 // Abort here with empty content
1738 if ($show_form === false) {
1743 for ($page = 1; $page <= $numPages; $page++) {
1744 // Is the page currently selected or shall we generate a link to it?
1745 if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
1746 // Is currently selected, so only highlight it
1747 $NAV .= '<strong>-';
1749 // Open anchor tag and add base URL
1750 $NAV .= '<a href="{%url=modules.php?module=admin&what=' . getWhat() . '&page=' . $page . '&offset=' . $offset;
1752 // Add userid when we shall show all mails from a single member
1753 if ((isGetRequestElementSet('userid')) && (isValidUserId(getRequestElement('userid')))) $NAV .= '&userid=' . bigintval(getRequestElement('userid'));
1755 // Close open anchor tag
1759 if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
1760 // Is currently selected, so only highlight it
1761 $NAV .= '-</strong>';
1767 // Add separator if we have not yet reached total pages
1768 if ($page < $numPages) {
1774 // Define constants only once
1775 $content['nav'] = $NAV;
1776 $content['span'] = $colspan;
1777 $content['top'] = $TOP;
1779 // Load navigation template
1780 $OUT = loadTemplate('admin_email_nav_row', true, $content);
1782 if ($return === true) {
1783 // Return generated HTML-Code
1791 // Process menu editing form
1792 function adminProcessMenuEditForm ($type, $subMenu) {
1793 // An action is done...
1794 foreach (postRequestElement('sel') as $sel => $menu) {
1795 $AND = "(`what` = '' OR `what` IS NULL)";
1797 $sel = bigintval($sel);
1799 if (!empty($subMenu)) {
1800 $AND = "`action`='" . $subMenu . "'";
1803 switch (postRequestElement('ok')) {
1804 case 'edit': // Edit menu
1805 // Shall we update a menu or sub menu?
1806 if (!isGetRequestElementSet('sub')) {
1807 // Update with 'what'=null
1808 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET `title`='%s',`action`='%s',`what`=NULL WHERE ".$AND." AND `id`=%s LIMIT 1",
1812 postRequestElement('sel_action', $sel),
1814 ), __FUNCTION__, __LINE__);
1816 // Update with selected 'what'
1817 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET `title`='%s',`action`='%s',`what`='%s' WHERE ".$AND." AND `id`=%s LIMIT 1",
1821 postRequestElement('sel_action', $sel),
1822 postRequestElement('sel_what', $sel),
1824 ), __FUNCTION__, __LINE__);
1828 case 'delete': // Delete menu
1829 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE ".$AND." AND `id`=%s LIMIT 1",
1833 ), __FUNCTION__, __LINE__);
1836 case 'status': // Change status of menus
1837 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET `visible`='%s',`locked`='%s' WHERE ".$AND." AND `id`=%s LIMIT 1",
1840 postRequestElement('visible', $sel),
1841 postRequestElement('locked', $sel),
1843 ), __FUNCTION__, __LINE__);
1846 default: // Unexpected action
1847 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unsupported action %s detected.", postRequestElement('ok')));
1848 displayMessage('{%message,ADMIN_UNKNOWN_OKAY=' . postRequestElement('ok') . '%}');
1854 displayMessage('{--SETTINGS_SAVED--}');
1857 // Handle weightning
1858 function doAdminProcessMenuWeightning ($type, $AND) {
1859 // Are there all required (generalized) GET parameter?
1860 if ((isGetRequestElementSet('act')) && (isGetRequestElementSet('tid')) && (isGetRequestElementSet('fid'))) {
1862 $tid = ''; $fid = '';
1865 if (isGetRequestElementSet('w')) {
1866 // Sub menus selected
1867 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `action`='%s' AND `sort`=%s LIMIT 1",
1870 getRequestElement('act'),
1871 bigintval(getRequestElement('tid'))
1872 ), __FUNCTION__, __LINE__);
1873 list($tid) = SQL_FETCHROW($result);
1874 SQL_FREERESULT($result);
1875 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `action`='%s' AND `sort`=%s LIMIT 1",
1878 getRequestElement('act'),
1879 bigintval(getRequestElement('fid'))
1880 ), __FUNCTION__, __LINE__);
1881 list($fid) = SQL_FETCHROW($result);
1882 SQL_FREERESULT($result);
1884 // Main menu selected
1885 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE (`what`='' OR `what` IS NULL) AND `sort`=%s LIMIT 1",
1888 bigintval(getRequestElement('tid'))
1889 ), __FUNCTION__, __LINE__);
1890 list($tid) = SQL_FETCHROW($result);
1891 SQL_FREERESULT($result);
1892 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE (`what`='' OR `what` IS NULL) AND `sort`=%s LIMIT 1",
1895 bigintval(getRequestElement('fid'))
1896 ), __FUNCTION__, __LINE__);
1897 list($fid) = SQL_FETCHROW($result);
1898 SQL_FREERESULT($result);
1901 if ((!empty($tid)) && (!empty($fid))) {
1903 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET `sort`=%s WHERE ".$AND." AND `id`=%s LIMIT 1",
1906 bigintval(getRequestElement('tid')),
1908 ), __FUNCTION__, __LINE__);
1909 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET `sort`=%s WHERE ".$AND." AND `id`=%s LIMIT 1",
1912 bigintval(getRequestElement('fid')),
1914 ), __FUNCTION__, __LINE__);