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, $return = false) {
257 $GLOBALS['menu']['description'] = array();
258 $GLOBALS['menu']['title'] = array();
261 $result_main = SQL_QUERY("SELECT
262 `action`,`title`,`descr`
264 `{?_MYSQL_PREFIX?}_admin_menu`
266 (`what`='' OR `what` IS NULL)
269 `id` DESC", __FUNCTION__, __LINE__);
271 // Do we have entries?
272 if (!SQL_HASZERONUMS($result_main)) {
273 $OUT .= '<ul class="admin_menu_main">';
274 // @TODO Rewrite this to $content = SQL_FETCHARRAY()
275 while (list($menu, $title, $descr) = SQL_FETCHROW($result_main)) {
277 $inc = sprintf("inc/modules/admin/action-%s.php", $menu);
279 // Is the file readable?
280 $readable = isIncludeReadable($inc);
282 // Is the current admin allowed to access this 'action' menu?
283 if (isAdminAllowedAccessMenu($menu)) {
284 if ($SUB === false) {
285 // Insert compiled menu title and description
286 $GLOBALS['menu']['title'][$menu] = $title;
287 $GLOBALS['menu']['description'][$menu] = $descr;
289 $OUT .= '<li class="admin_menu">
290 <div class="nobr"><strong>·</strong> ';
292 if ($readable === true) {
293 if (($menu == $action) && (empty($what))) {
296 $OUT .= '[<a href="{%url=modules.php?module=admin&action=' . $menu . '%}">';
299 $OUT .= '<em style="cursor:help" class="notice" title="{%message,ADMIN_MENU_ACTION_404_TITLE=' . $menu . '%}">';
304 if ($readable === true) {
305 if (($menu == $action) && (empty($what))) {
317 // Check for menu entries
318 $result_what = SQL_QUERY_ESC("SELECT
319 `what`,`title`,`descr`
321 `{?_MYSQL_PREFIX?}_admin_menu`
329 array($menu), __FUNCTION__, __LINE__);
331 // Remember the count for later checks
332 setAdminMenuHasEntries($menu, ((!SQL_HASZERONUMS($result_what)) && ($action == $menu)));
334 // Do we have entries?
335 if ((ifAdminMenuHasEntries($menu)) && (!SQL_HASZERONUMS($result_what))) {
336 $GLOBALS['menu']['description'] = array();
337 $GLOBALS['menu']['title'] = array();
339 $OUT .= '<li class="admin_menu_sub"><ul class="admin_menu_sub">';
340 // @TODO Rewrite this to $content = SQL_FETCHARRAY()
341 while (list($what_sub, $title_what, $desc_what) = SQL_FETCHROW($result_what)) {
343 $inc = sprintf("inc/modules/admin/what-%s.php", $what_sub);
345 // Is the file readable?
346 $readable = isIncludeReadable($inc);
348 // Is the current admin allowed to access this 'what' menu?
349 if (isAdminAllowedAccessMenu(null, $what_sub)) {
350 // Insert compiled title and description
351 $GLOBALS['menu']['title'][$what_sub] = $title_what;
352 $GLOBALS['menu']['description'][$what_sub] = $desc_what;
353 $OUT .= '<li class="admin_menu">
354 <div class="nobr"><strong>--></strong> ';
355 if ($readable === true) {
356 if ($what == $what_sub) {
359 $OUT .= '[<a href="{%url=modules.php?module=admin&what=' . $what_sub . '%}">';
362 $OUT .= '<em style="cursor:help" class="notice" title="{%message,ADMIN_MENU_WHAT_404_TITLE=' . $what_sub . '%}">';
367 if ($readable === true) {
368 if ($what == $what_sub) {
382 SQL_FREERESULT($result_what);
390 SQL_FREERESULT($result_main);
394 // Is there a cache instance again?
395 // Return or output content?
396 if ($return === true) {
403 // Create an admin selection box form
404 function addAdminSelectionBox ($adminId = NULL, $special = '') {
405 // Default is email as "special column"
406 $ADD = ',`email` AS `special`';
408 // Is a special column given?
409 if (!empty($special)) {
410 // Additional column for SQL query
411 $ADD = ',`' . $special . '` AS `special`';
415 $result = SQL_QUERY('SELECT
416 `id`,`login`' . $ADD . '
418 `{?_MYSQL_PREFIX?}_admins`
420 `login` ASC', __FUNCTION__, __LINE__);
426 while ($content = SQL_FETCHARRAY($result)) {
428 $OUT .= loadTemplate('select_admins_option', true, $content);
432 SQL_FREERESULT($result);
434 // Add form to content
435 $content['form_selection'] = $OUT;
438 loadTemplate('select_admins_box', false, $content);
441 // Create a member selection box
442 function addMemberSelectionBox ($userid = NULL, $add_all = false, $return = false, $none = false, $field = 'userid') {
443 // Output selection form with all confirmed user accounts listed
444 $result = SQL_QUERY('SELECT
445 `userid`,`surname`,`family`
447 `{?_MYSQL_PREFIX?}_user_data`
449 `userid` ASC', __FUNCTION__, __LINE__);
454 // USe this only for adding points (e.g. adding refs really makes no sence ;-) )
455 if ($add_all === true) {
456 $OUT = ' <option value="all">{--ALL_MEMBERS--}</option>';
457 } elseif ($none === true) {
458 $OUT = ' <option value="0">{--SELECT_NONE--}</option>';
462 while ($content = SQL_FETCHARRAY($result)) {
463 $OUT .= '<option value="' . bigintval($content['userid']) . '"';
464 if ($userid == $content['userid']) $OUT .= ' selected="selected"';
465 $OUT .= '>' . $content['surname'] . ' ' . $content['family'] . ' (' . bigintval($content['userid']) . ')</option>';
469 SQL_FREERESULT($result);
471 if ($return === false) {
472 // Remeber options in constant
473 $content['form_selection'] = $OUT;
474 $content['what'] = '{%pipe,getWhat%}';
477 loadTemplate('admin_form_selection_box', false, $content);
479 // Return content in selection frame
480 return '<select class="form_select" name="' . handleFieldWithBraces($field) . '" size="1">' . $OUT . '</select>';
484 // Create a menu selection box for given menu system
485 // @TODO Try to rewrite this to adminAddMenuSelectionBox()
487 function adminMenuSelectionBox_DEPRECATED ($mode, $default = '', $defid = '') {
488 $what = "`what` != '' AND `what` IS NOT NULL";
489 if ($mode == 'action') $what = "(`what`='' OR `what` IS NULL) AND `action` != 'login'";
491 $result = SQL_QUERY_ESC("SELECT `%s` AS `menu`,`title` FROM `{?_MYSQL_PREFIX?}_admin_menu` WHERE ".$what." ORDER BY `sort` ASC",
492 array($mode), __FUNCTION__, __LINE__);
493 if (!SQL_HASZERONUMS($result)) {
494 // Load menu as selection
495 $OUT = '<select name="' . $mode . '_menu';
496 if ((!empty($defid)) || ($defid == '0')) $OUT .= '[' . $defid . ']';
497 $OUT .= '" size="1" class="form_select">
498 <option value="">{--SELECT_NONE--}</option>';
500 while ($content = SQL_FETCHARRAY($result)) {
501 $OUT .= '<option value="' . $content['menu'] . '"';
502 if ((!empty($default)) && ($default == $content['menu'])) $OUT .= ' selected="selected"';
503 $OUT .= '>' . $content['title'] . '</option>';
507 SQL_FREERESULT($result);
509 // Add closing select-tag
513 $OUT = '{--ADMIN_PROBLEM_NO_MENU--}';
520 // Wrapper for $_POST and adminSaveSettings
521 function adminSaveSettingsFromPostData ($tableName = '_config', $whereStatement = '`config`=0', $translateComma = array(), $alwaysAdd = false, $displayMessage = true) {
523 $postData = postRequestArray();
525 // Call the lower function
526 adminSaveSettings($postData, $tableName, $whereStatement, $translateComma, $alwaysAdd, $displayMessage);
529 // Save settings to the database
530 function adminSaveSettings (&$postData, $tableName = '_config', $whereStatement = '`config`=0', $translateComma = array(), $alwaysAdd = false, $displayMessage = true) {
531 // Prepare all arrays, variables
532 $tableData = array();
535 // Now, walk through all entries and prepare them for saving
536 foreach ($postData as $id => $val) {
537 // Process only formular field but not submit buttons ;)
539 // Do not save the ok value
540 convertSelectionsToEpocheTime($postData, $tableData, $id, $skip);
542 // Shall we process this id? It muss not be empty, of course
543 if (($skip === false) && (!empty($id)) && ((!isset($GLOBALS['skip_config'][$id]))) || ($tableName != '_config')) {
544 // Translate the value? (comma to dot!)
545 if ((is_array($translateComma)) && (in_array($id, $translateComma))) {
546 // Then do it here... :)
547 $val = convertCommaToDot($val);
550 // Shall we add numbers or strings?
551 $test = (float) $val;
552 if ('' . $val . '' == '' . $test . '') {
554 $tableData[] = sprintf("`%s`=%s", $id, $test);
555 } elseif (is_null($val)) {
557 $tableData[] = sprintf("`%s`=NULL", $id);
560 $tableData[] = sprintf("`%s`='%s'", $id, trim($val));
563 // Do not add a config entry twice
564 $GLOBALS['skip_config'][$id] = true;
566 // Update current configuration
567 setConfigEntry($id, $val);
572 // Check if entry does exist
574 if ($alwaysAdd === false) {
575 if (!empty($whereStatement)) {
576 $result = SQL_QUERY("SELECT * FROM `{?_MYSQL_PREFIX?}" . $tableName . "` WHERE " . $whereStatement . " LIMIT 1", __FUNCTION__, __LINE__);
578 $result = SQL_QUERY("SELECT * FROM `{?_MYSQL_PREFIX?}" . $tableName . "` LIMIT 1", __FUNCTION__, __LINE__);
582 if (SQL_NUMROWS($result) == 1) {
583 // "Implode" all data to single string
584 $updatedData = implode(', ', $tableData);
586 // Generate SQL string
587 $sql = sprintf("UPDATE `{?_MYSQL_PREFIX?}%s` SET %s WHERE %s LIMIT 1",
593 // Add Line (does only work with AUTO_INCREMENT!
594 $keys = array(); $values = array();
595 foreach ($tableData as $entry) {
597 $line = explode('=', $entry);
599 $values[] = $line[1];
602 // Add both in one line
603 $keys = implode('`,`', $keys);
604 $values = implode(', ', $values);
606 // Generate SQL string
607 $sql = sprintf("INSERT INTO `{?_MYSQL_PREFIX?}%s` (%s) VALUES (%s)",
615 SQL_FREERESULT($result);
617 // Simply run generated SQL string
618 SQL_QUERY($sql, __FUNCTION__, __LINE__);
620 // Remember affected rows
621 $affected = SQL_AFFECTEDROWS();
624 rebuildCache('config', 'config');
626 // Settings saved, so display message?
627 if ($displayMessage === true) displayMessage('{--SETTINGS_SAVED--}');
629 // Return affected rows
633 // Generate a selection box
634 function adminAddMenuSelectionBox ($menu, $type, $name, $default = '') {
635 // Open the requested menu directory
636 $menuArray = getArrayFromDirectory(sprintf("inc/modules/%s/", $menu), $type . '-', false, false);
638 // Init the selection box
639 $OUT = '<select name="' . $name . '" class="form_select" size="1"><option value="">{--ADMIN_IS_TOP_MENU--}</option>';
641 // Walk through all files
642 foreach ($menuArray as $file) {
643 // Is this a PHP script?
644 if ((!isDirectory($file)) && (isInString('' . $type . '-', $file)) && (isInString('.php', $file))) {
645 // Then test if the file is readable
646 $test = sprintf("inc/modules/%s/%s", $menu, $file);
648 // Is the file there?
649 if (isIncludeReadable($test)) {
650 // Extract the value for what=xxx
651 $part = substr($file, (strlen($type) + 1));
652 $part = substr($part, 0, -4);
654 // Is that part different from the overview?
655 if ($part != 'overview') {
656 $OUT .= '<option value="' . $part . '"';
657 if ($part == $default) $OUT .= ' selected="selected"';
658 $OUT .= '>' . $part . '</option>';
664 // Close selection box
671 // Creates a user-profile link for the admin. This function can also be used for many other purposes
672 function generateUserProfileLink ($userid, $title = '', $what = 'list_user') {
673 if (($title == '') && (isValidUserId($userid))) {
674 // Set userid as title
676 } elseif (!isValidUserId($userid)) {
677 // User id zero is invalid
678 return '<strong>' . makeNullToZero($userid) . '</strong>';
681 if (($title == '0') && ($what == 'list_refs')) {
682 // Return title again
684 } elseif (isExtensionActive('nickname')) {
686 $nick = getNickname($userid);
688 // Is it not empty, use it as title else the userid
690 $title = $nick . '(' . $userid . ')';
697 return '[<a href="{%url=modules.php?module=admin&what=' . $what . '&userid=' . $userid . '%}" title="{--ADMIN_USER_PROFILE_TITLE--}">' . $title . '</a>]';
700 // Check "logical-area-mode"
701 function adminGetMenuMode () {
702 // Set the default menu mode as the mode for all admins
705 // If sql_patches is up-to-date enough, use the configuration
706 if (isExtensionInstalledAndNewer('sql_patches', '0.3.2')) {
707 $mode = getAdminMenu();
714 $adminId = getCurrentAdminId();
716 // Check individual settings of current admin
717 if (isset($GLOBALS['cache_array']['admin']['la_mode'][$adminId])) {
719 $adminMode = $GLOBALS['cache_array']['admin']['la_mode'][$adminId];
720 incrementStatsEntry('cache_hits');
721 } elseif (isExtensionInstalledAndNewer('admins', '0.6.7')) {
722 // Load from database when version of 'admins' is enough
723 $result = SQL_QUERY_ESC("SELECT `la_mode` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `id`=%s LIMIT 1",
724 array($adminId), __FUNCTION__, __LINE__);
726 // Do we have an entry?
727 if (SQL_NUMROWS($result) == 1) {
729 list($adminMode) = SQL_FETCHROW($result);
733 SQL_FREERESULT($result);
736 // Check what the admin wants and set it when it's not the default mode
737 if ($adminMode != 'global') {
741 // Return admin-menu's mode
745 // Change activation status
746 function adminChangeActivationStatus ($IDs, $table, $row, $idRow = 'id') {
748 if ((is_array($IDs)) && (count($IDs) > 0)) {
749 // "Walk" all through and count them
750 foreach ($IDs as $id => $selected) {
751 // Secure the id number
752 $id = bigintval($id);
754 // Should always be set... ;-)
755 if (!empty($selected)) {
756 // Determine new status
757 $result = SQL_QUERY_ESC("SELECT %s FROM `{?_MYSQL_PREFIX?}_%s` WHERE %s=%s LIMIT 1",
763 ), __FUNCTION__, __LINE__);
766 if (SQL_NUMROWS($result) == 1) {
768 list($currStatus) = SQL_FETCHROW($result);
770 // And switch it N<->Y
771 $newStatus = convertBooleanToYesNo(!($currStatus == 'Y'));
773 // Change this status
774 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s` SET %s='%s' WHERE %s=%s LIMIT 1",
781 ), __FUNCTION__, __LINE__);
783 // Count up affected rows
784 $count += SQL_AFFECTEDROWS();
788 SQL_FREERESULT($result);
793 displayMessage(sprintf(getMessage('ADMIN_STATUS_CHANGED'), $count, count($IDs)));
796 displayMessage('{--ADMIN_NOTHING_SELECTED_CHANGE--}');
800 // Send mails for del/edit/lock build modes
801 function sendAdminBuildMails ($mode, $tableName, $content, $id, $subjectPart = '', $userIdColumn = array('userid')) {
802 // $tableName must be an array
803 if ((!is_array($tableName)) || (count($tableName) != 1)) {
804 // $tableName is no array
805 debug_report_bug(__FUNCTION__, __LINE__, 'tableName[]=' . gettype($tableName) . '!=array');
806 } elseif ((!is_array($userIdColumn)) || (count($userIdColumn) != 1)) {
807 // $tableName is no array
808 debug_report_bug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array');
811 // Default subject is the subject part
812 $subject = $subjectPart;
814 // Is the subject part not set?
815 if (empty($subjectPart)) {
816 // Then use it from the mode
817 $subject = strtoupper($mode);
820 // Is the raw userid set?
821 if (postRequestElement($userIdColumn[0], $id) > 0) {
822 // Load email template
823 if (!empty($subjectPart)) {
824 $mail = loadEmailTemplate('member_' . $mode . '_' . strtolower($subjectPart) . '_' . $tableName[0], $content);
826 $mail = loadEmailTemplate('member_' . $mode . '_' . $tableName[0], $content);
830 sendEmail(postRequestElement($userIdColumn[0], $id), strtoupper('{--MEMBER_' . $subject . '_' . $tableName[0] . '_SUBJECT--}'), $mail);
834 $subject = strtoupper('{--ADMIN_' . $subject . '_' . $tableName[0] . '_SUBJECT--}');
836 // Send admin notification out
837 if (!empty($subjectPart)) {
838 sendAdminNotification($subject, 'admin_' . $mode . '_' . strtolower($subjectPart) . '_' . $tableName[0], $content, postRequestElement($userIdColumn[0], $id));
840 sendAdminNotification($subject, 'admin_' . $mode . '_' . $tableName[0], $content, postRequestElement($userIdColumn[0], $id));
844 // Build a special template list
845 function adminListBuilder ($listType, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId = array('userid')) {
846 // $tableName and $idColumn must bove be arrays!
847 if ((!is_array($tableName)) || (count($tableName) != 1)) {
848 // $tableName is no array
849 debug_report_bug(__FUNCTION__, __LINE__, 'tableName[]=' . gettype($tableName) . '!=array');
850 } elseif (!is_array($idColumn)) {
851 // $idColumn is no array
852 debug_report_bug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array');
853 } elseif ((!is_array($userIdColumn)) || (count($userIdColumn) != 1)) {
854 // $tableName is no array
855 debug_report_bug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array');
861 // "Walk"Â through all entries
862 //* 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>');
863 foreach (postRequestElement($idColumn[0]) as $id => $selected) {
865 $id = bigintval($id);
867 // Get result from a given column array and table name
868 $result = SQL_RESULT_FROM_ARRAY($tableName[0], $columns, $idColumn[0], $id, __FUNCTION__, __LINE__);
870 // Is there one entry?
871 if (SQL_NUMROWS($result) == 1) {
873 $content = SQL_FETCHARRAY($result);
876 foreach ($content as $key => $value) {
878 $idx = array_search($key, $columns, true);
880 //Â Do we have a userid?
881 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',userIdColumn=' . $userIdColumn[0]);
882 if ($key == $userIdColumn[0]) {
883 // Add it again as raw id
884 //* DEBUG: */ debug_report_bug(__FUNCTION__, __LINE__, 'key=' . $key . ',userIdColumn=' . $userIdColumn[0]);
885 $content[$userIdColumn[0]] = bigintval($value);
886 $content[$userIdColumn[0] . '_raw'] = $content[$userIdColumn[0]];
889 // If the key matches the idColumn variable, we need to temporary remember it
890 //* DEBUG: */ debugOutput('key=' . $key . ',idColumn=' . $idColumn[0] . ',value=' . $value);
891 if ($key == $idColumn[0]) {
892 // Found, so remember it
893 $GLOBALS['admin_list_builder_id_value'] = $value;
896 // Handle the call in external function
897 //* DEBUG: */ debugOutput('key=' . $key . ',fucntion=' . $filterFunctions[$idx] . ',value=' . $value);
898 $content[$key] = handleExtraValues(
899 $filterFunctions[$idx],
906 $OUT .= loadTemplate(sprintf("admin_%s_%s_row",
914 SQL_FREERESULT($result);
917 // Load master template
918 loadTemplate(sprintf("admin_%s_%s",
925 // Change status of "build" list
926 function adminBuilderStatusHandler ($mode, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray, $rawUserId = array('userid')) {
927 // $tableName must be an array
928 if ((!is_array($tableName)) || (count($tableName) != 1)) {
929 // No tableName specified
930 debug_report_bug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array');
931 } elseif (!is_array($idColumn)) {
932 // $idColumn is no array
933 debug_report_bug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array');
934 } elseif ((!is_array($userIdColumn)) || (count($userIdColumn) != 1)) {
935 // $tableName is no array
936 debug_report_bug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array');
939 // All valid entries? (We hope so here!)
940 if ((count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues)) && (count($statusArray) > 0)) {
941 // "Walk" through all entries
942 foreach (postRequestElement($idColumn[0]) as $id => $sel) {
943 // Construct SQL query
944 $sql = sprintf("UPDATE `{?_MYSQL_PREFIX?}_%s` SET", SQL_ESCAPE($tableName[0]));
946 // Load data of entry
947 $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`=%s LIMIT 1",
952 ), __FUNCTION__, __LINE__);
955 $content = SQL_FETCHARRAY($result);
958 SQL_FREERESULT($result);
960 // Add all status entries (e.g. status column last_updated or so)
961 $newStatus = 'UNKNOWN';
962 $oldStatus = 'UNKNOWN';
963 $statusColumn = 'unknown';
964 foreach ($statusArray as $column => $statusInfo) {
965 // Does the entry exist?
966 if ((isset($content[$column])) && (isset($statusInfo[$content[$column]]))) {
967 // Add these entries for update
968 $sql .= sprintf(" `%s`='%s',", SQL_ESCAPE($column), SQL_ESCAPE($statusInfo[$content[$column]]));
971 if ($statusColumn == 'unknown') {
972 // Always (!!!) change status column first!
973 $oldStatus = $content[$column];
974 $newStatus = $statusInfo[$oldStatus];
975 $statusColumn = $column;
977 } elseif (isset($content[$column])) {
979 debug_report_bug(__FUNCTION__, __LINE__, ':UNFINISHED: id=' . $id . ',column=' . $column . '[' . gettype($statusInfo) . '] = ' . $content[$column]);
983 // Add other columns as well
984 foreach (postRequestArray() as $key => $entries) {
986 logDebugMessage(__FUNCTION__, __LINE__, 'Found entry: ' . $key);
988 // Skip id, raw userid and 'do_$mode'
989 if (!in_array($key, array($idColumn[0], $rawUserId[0], ('do_' . $mode)))) {
990 // Are there brackets () at the end?
991 if (substr($entries[$id], -2, 2) == '()') {
992 // Direct SQL command found
993 $sql .= sprintf(" `%s`=%s,", SQL_ESCAPE($key), SQL_ESCAPE($entries[$id]));
996 $sql .= sprintf(" `%s`='%s',", SQL_ESCAPE($key), SQL_ESCAPE($entries[$id]));
999 $content[$key] = $entries[$id];
1003 logDebugMessage(__FUNCTION__, __LINE__, 'Skipped: ' . $key);
1007 // Finish SQL statement
1008 $sql = substr($sql, 0, -1) . sprintf(" WHERE `%s`=%s AND `%s`='%s' LIMIT 1",
1016 SQL_QUERY($sql, __FUNCTION__, __LINE__);
1018 // Do we have an URL?
1019 if (isset($content['url'])) {
1020 // Then add a framekiller test as well
1021 $content['frametester'] = generateFrametesterUrl($content['url']);
1024 // Send "build mails" out
1025 sendAdminBuildMails($mode, $tableName, $content, $id, $statusInfo[$content[$column]], $userIdColumn);
1030 // Delete rows by given id numbers
1031 function adminDeleteEntriesConfirm ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $deleteNow = array(false), $idColumn = array('id'), $userIdColumn = array('userid'), $rawUserId = array('userid')) {
1032 // $tableName must be an array
1033 if ((!is_array($tableName)) || (count($tableName) != 1)) {
1034 // No tableName specified
1035 debug_report_bug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array');
1036 } elseif (!is_array($idColumn)) {
1037 // $idColumn is no array
1038 debug_report_bug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array');
1039 } elseif (!is_array($userIdColumn)) {
1040 // $userIdColumn is no array
1041 debug_report_bug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array');
1042 } elseif (!is_array($deleteNow)) {
1043 // $deleteNow is no array
1044 debug_report_bug(__FUNCTION__, __LINE__, 'deleteNow[]=' . gettype($deleteNow) . '!=array');
1047 // All valid entries? (We hope so here!)
1048 if ((count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues))) {
1049 // Shall we delete here or list for deletion?
1050 if ($deleteNow[0] === true) {
1051 // The base SQL command:
1052 $sql = "DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s` IN (%s)";
1056 foreach (postRequestElement($idColumn[0]) as $id => $sel) {
1057 // Is there a userid?
1058 if (isPostRequestElementSet($rawUserId[0], $id)) {
1059 // Load all data from that id
1060 $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`=%s LIMIT 1",
1065 ), __FUNCTION__, __LINE__);
1068 $content = SQL_FETCHARRAY($result);
1071 SQL_FREERESULT($result);
1073 // Send "build mails" out
1074 sendAdminBuildMails('delete', $tableName, $content, $id, '', $userIdColumn);
1078 $idList .= $id . ',';
1082 SQL_QUERY_ESC($sql, array($tableName[0], $idColumn[0], substr($idList, 0, -1)), __FUNCTION__, __LINE__);
1085 if (SQL_AFFECTEDROWS() == count(postRequestElement($idColumn[0]))) {
1087 displayMessage('{--ADMIN_ALL_ENTRIES_REMOVED--}');
1089 // Some are still there :(
1090 displayMessage(sprintf(getMessage('ADMIN_SOME_ENTRIES_NOT_DELETED'), SQL_AFFECTEDROWS(), count(postRequestElement($idColumn[0]))));
1093 // List for deletion confirmation
1094 adminListBuilder('delete', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1099 // Edit rows by given id numbers
1100 function adminEditEntriesConfirm ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $editNow = array(false), $idColumn = array('id'), $userIdColumn = array('userid'), $rawUserId = array('userid')) {
1101 // $tableName must be an array
1102 if ((!is_array($tableName)) || (count($tableName) != 1)) {
1103 // No tableName specified
1104 debug_report_bug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array');
1105 } elseif (!is_array($idColumn)) {
1106 // $idColumn is no array
1107 debug_report_bug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array');
1108 } elseif (!is_array($userIdColumn)) {
1109 // $userIdColumn is no array
1110 debug_report_bug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array');
1111 } elseif (!is_array($editNow)) {
1112 // $editNow is no array
1113 debug_report_bug(__FUNCTION__, __LINE__, 'editNow[]=' . gettype($editNow) . '!=array');
1116 // All valid entries? (We hope so here!)
1117 //* 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>');
1118 if ((count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues))) {
1119 // Shall we change here or list for editing?
1120 if ($editNow[0] === true) {
1123 foreach (postRequestElement($idColumn[0]) as $id => $sel) {
1124 // Prepare content array (new values)
1127 // Prepare SQL for this row
1128 $sql = sprintf("UPDATE `{?_MYSQL_PREFIX?}_%s` SET",
1129 SQL_ESCAPE($tableName[0])
1131 foreach (postRequestArray() as $key => $entries) {
1132 // Skip raw userid which is always invalid
1133 if ($key == $rawUserId[0]) {
1134 // Continue with next field
1138 // Is entries an array?
1139 if (($key != $idColumn[0]) && (is_array($entries)) && (isset($entries[$id]))) {
1140 // Add this entry to content
1141 $content[$key] = $entries[$id];
1143 // Send data through the filter function if found
1144 if ((isset($filterFunctions[$key])) && (isset($extraValues[$key]))) {
1145 // Filter function set!
1146 $entries[$id] = handleExtraValues($filterFunctions[$key], $entries[$id], $extraValues[$key]);
1149 // Then add this value
1150 $sql .= sprintf(" `%s`='%s',",
1152 SQL_ESCAPE($entries[$id])
1154 } elseif (($key != $idColumn[0]) && (!is_array($entries))) {
1155 // Add normal entries as well!
1156 $content[$key] = $entries;
1159 // Do we have an URL?
1160 if ($key == 'url') {
1161 // Then add a framekiller test as well
1162 $content['frametester'] = generateFrametesterUrl($content[$key]);
1166 // Finish SQL command
1167 $sql = substr($sql, 0, -1) . " WHERE `" . $idColumn[0] . "`=" . bigintval($id) . " LIMIT 1";
1170 SQL_QUERY($sql, __FUNCTION__, __LINE__);
1172 // Add affected rows
1173 $affected += SQL_AFFECTEDROWS();
1175 // Load all data from that id
1176 $result = SQL_QUERY_ESC("SELECT * FROM `{?_MYSQL_PREFIX?}_%s` WHERE `%s`=%s LIMIT 1",
1181 ), __FUNCTION__, __LINE__);
1183 // Fetch the data and merge it into $content
1184 $content = merge_array($content, SQL_FETCHARRAY($result));
1187 SQL_FREERESULT($result);
1189 // Send "build mails" out
1190 sendAdminBuildMails('edit', $tableName, $content, $id, '', $userIdColumn);
1194 if ($affected == count(postRequestElement($idColumn[0]))) {
1196 displayMessage('{--ADMIN_ALL_ENTRIES_EDITED--}');
1198 // Some are still there :(
1199 displayMessage(sprintf(getMessage('ADMIN_SOME_ENTRIES_NOT_EDITED'), $affected, count(postRequestElement($idColumn[0]))));
1203 adminListBuilder('edit', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1206 // Maybe some invalid parameters
1207 debug_report_bug(__FUNCTION__, __LINE__, 'tableName=' . $tableName[0] . ',columns[]=' . gettype($columns) . ',filterFunctions[]=' . gettype($filterFunctions) . ',extraValues[]=' . gettype($extraValues) . ',idColumn=' . $idColumn[0] . ',userIdColumn=' . $userIdColumn[0] . ' - INVALID!');
1211 // Un-/lock rows by given id numbers
1212 function adminLockEntriesConfirm ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $statusArray = array(), $lockNow = array(false), $idColumn = array('id'), $userIdColumn = array('userid')) {
1213 // $tableName must be an array
1214 if ((!is_array($tableName)) || (count($tableName) != 1)) {
1215 // No tableName specified
1216 debug_report_bug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array');
1217 } elseif (!is_array($idColumn)) {
1218 // $idColumn is no array
1219 debug_report_bug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array');
1220 } elseif (!is_array($lockNow)) {
1221 // $lockNow is no array
1222 debug_report_bug(__FUNCTION__, __LINE__, 'lockNow[]=' . gettype($lockNow) . '!=array');
1225 // All valid entries? (We hope so here!)
1226 if ((count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues)) && (($lockNow[0] === false) || (count($statusArray) == 1))) {
1227 // Shall we un-/lock here or list for locking?
1228 if ($lockNow[0] === true) {
1230 adminBuilderStatusHandler('lock', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray);
1233 adminListBuilder('lock', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1238 // Undelete rows by given id numbers
1239 function adminUndeleteEntriesConfirm ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $statusArray = array(), $undeleteNow = array(false), $idColumn = array('id'), $userIdColumn = array('userid')) {
1240 // $tableName must be an array
1241 if ((!is_array($tableName)) || (count($tableName) != 1)) {
1242 // No tableName specified
1243 debug_report_bug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array');
1244 } elseif (!is_array($idColumn)) {
1245 // $idColumn is no array
1246 debug_report_bug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array');
1247 } elseif (!is_array($undeleteNow)) {
1248 // $undeleteNow is no array
1249 debug_report_bug(__FUNCTION__, __LINE__, 'undeleteNow[]=' . gettype($undeleteNow) . '!=array');
1252 // All valid entries? (We hope so here!)
1253 if ((count($columns) == count($filterFunctions)) && (count($columns) == count($extraValues)) && (($undeleteNow[0] === false) || (count($statusArray) == 1))) {
1254 // Shall we un-/lock here or list for locking?
1255 if ($undeleteNow[0] === true) {
1257 adminBuilderStatusHandler('undelete', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $statusArray);
1260 adminListBuilder('undelete', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
1265 // Adds a given entry to the database
1266 function adminAddEntries ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array()) {
1267 //* 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>');
1268 // Verify that tableName and columns are not empty
1269 if ((!is_array($tableName)) || (count($tableName) != 1)) {
1270 // No tableName specified
1271 debug_report_bug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array');
1272 } elseif (count($columns) == 0) {
1273 // No columns specified
1274 debug_report_bug(__FUNCTION__, __LINE__, 'columns is not given. Please fix your XML.');
1277 // Init columns and value elements
1278 $sqlColumns = array();
1279 $sqlValues = array();
1281 // Add columns and values
1282 foreach ($columns as $key=>$columnName) {
1283 // Copy entry to final arrays
1284 $sqlColumns[$key] = $columnName;
1285 $sqlValues[$key] = postRequestElement($columnName);
1286 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key='.$key.',columnName='.$columnName.',filterFunctions='.$filterFunctions[$key].',extraValues='.intval(isset($extraValues[$key])).',extraValuesName='.intval(isset($extraValues[$columnName . '_list'])).'<br />');
1288 // Send data through the filter function if found
1289 if ((isset($filterFunctions[$key])) && (isset($extraValues[$key . '_list']))) {
1290 // Filter function set!
1291 $sqlValues[$key] = call_user_func_array($filterFunctions[$key], merge_array(array($columnName), $extraValues[$key . '_list']));
1295 // Build the SQL query
1296 $SQL = 'INSERT INTO `{?_MYSQL_PREFIX?}_' . $tableName[0] . '` (`' . implode('`, `', $sqlColumns) . "`) VALUES ('" . implode("','", $sqlValues) . "')";
1298 // Run the SQL query
1299 SQL_QUERY($SQL, __FUNCTION__, __LINE__);
1301 // Entry has been added?
1302 if (!SQL_HASZEROAFFECTED()) {
1303 // Display success message
1304 displayMessage('{--ADMIN_ENTRY_ADDED--}');
1306 // Display failed message
1307 displayMessage('{--ADMIN_ENTRY_NOT_ADDED--}');
1311 // List all given rows (callback function from XML)
1312 function adminListEntries ($tableTemplate, $rowTemplate, $noEntryMessageId, $tableName, $columns, $whereColumns, $orderByColumns, $callbackColumns, $extraParameters = array()) {
1313 // Verify that tableName and columns are not empty
1314 if ((!is_array($tableName)) || (count($tableName) != 1)) {
1315 // No tableName specified
1316 debug_report_bug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array,tableTemplate=' . $tableTemplate . ',rowTemplate=' . $rowTemplate);
1317 } elseif (count($columns) == 0) {
1318 // No columns specified
1319 debug_report_bug(__FUNCTION__, __LINE__, 'columns is not given. Please fix your XML,tableTemplate=' . $tableTemplate . ',rowTemplate=' . $rowTemplate . ',tableName[0]=' . $tableName[0]);
1322 // This is the minimum query, so at least columns and tableName must have entries
1324 foreach ($columns as $columnArray) {
1327 // Do we have a table/alias
1328 if (!empty($columnArray['table'])) {
1330 $sqlPart .= $columnArray['table'] . '.';
1334 $sqlPart .= '`' . $columnArray['column'] . '`';
1336 // Is a function and alias set?
1337 if ((!empty($columnArray['function'])) && (!empty($columnArray['alias']))) {
1339 $sqlPart = $columnArray['function'] . '(' . $sqlPart . ') AS `' . $columnArray['alias'] . '`';
1342 // Add finished SQL part to the query
1343 $SQL .= $sqlPart . ',';
1346 // Remove last commata and add FROM statement
1347 $SQL = substr($SQL, 0, -1) . ' FROM `{?_MYSQL_PREFIX?}_' . $tableName[0] . '`';
1349 // Do we have entries from whereColumns to add?
1350 if (count($whereColumns) > 0) {
1351 // Then add these as well
1352 if (count($whereColumns) == 1) {
1356 // Table/alias included?
1357 if (!empty($whereColumns[0]['table'])) {
1359 $SQL .= $whereColumns[0]['table'] . '.';
1363 $SQL .= '`' . $whereColumns[0]['column'] . '`' . $whereColumns[0]['condition'] . "'" . $whereColumns[0]['look_for'] . "'";
1365 // More than one entry -> Unsupported
1366 debug_report_bug(__FUNCTION__, __LINE__, 'More than one WHERE statement found. This is currently not supported.');
1370 // Do we have entries from orderByColumns to add?
1371 if (count($orderByColumns) > 0) {
1373 $SQL .= ' ORDER BY ';
1374 foreach ($orderByColumns as $orderByColumn=>$array) {
1375 // Get keys (table/alias) and values (sorting itself)
1376 $table = trim(implode('', array_keys($array)));
1377 $sorting = trim(implode('', array_keys($array)));
1379 // table/alias can be omitted
1380 if (!empty($table)) {
1381 // table/alias is given
1382 $SQL .= $table . '.';
1385 // Add order-by column
1386 $SQL .= '`' . $orderByColumn . '` ' . $sorting . ',';
1389 // Remove last column
1390 $SQL = substr($SQL, 0, -1);
1393 // Now handle all over to the inner function which will execute the listing
1394 doAdminListEntries($SQL, $tableTemplate, $noEntryMessageId, $rowTemplate, $callbackColumns, $extraParameters);
1397 // Do the listing of entries
1398 function doAdminListEntries ($SQL, $tableTemplate, $noEntryMessageId, $rowTemplate, $callbackColumns, $extraParameters = array()) {
1399 // Run the SQL query
1400 $result = SQL_QUERY($SQL, __FUNCTION__, __LINE__);
1402 // Do we have some URLs left?
1403 if (!SQL_HASZERONUMS($result)) {
1406 while ($content = SQL_FETCHARRAY($result)) {
1407 // "Translate" content
1408 foreach ($callbackColumns as $columnName=>$callbackFunction) {
1409 // Fill the callback arguments
1410 $args = array($content[$columnName]);
1412 // Do we have more to add?
1413 if (isset($extraParameters[$columnName])) {
1415 $args = merge_array($args, $extraParameters[$columnName]);
1418 // Call the callback-function
1419 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'callbackFunction=' . $callbackFunction . ',args=<pre>'.print_r($args, true).'</pre>');
1420 // @TODO If we can rewrite the EL sub-system to support more than one parameter, this call_user_func_array() can be avoided
1421 $content[$columnName] = call_user_func_array($callbackFunction, $args);
1424 // Load row template
1425 $OUT .= loadTemplate(trim($rowTemplate[0]), true, $content);
1428 // Load main template
1429 loadTemplate(trim($tableTemplate[0]), false, $OUT);
1431 // No URLs in surfbar
1432 displayMessage('{--' .$noEntryMessageId[0] . '--}');
1436 SQL_FREERESULT($result);
1439 // Checks proxy settins by fetching check-updates3.php from mxchange.org
1440 function adminTestProxySettings ($settingsArray) {
1441 // Set temporary the new settings
1442 mergeConfig($settingsArray);
1444 // Now get the test URL
1445 $content = sendGetRequest('check-updates3.php');
1447 // Is the first line with "200 OK"?
1448 $valid = isInString('200 OK', $content[0]);
1454 // Sends out a link to the given email adress so the admin can reset his/her password
1455 function sendAdminPasswordResetLink ($email) {
1459 //Â Look up administator login
1460 $result = SQL_QUERY_ESC("SELECT `id`,`login`,`password` FROM `{?_MYSQL_PREFIX?}_admins` WHERE '%s' REGEXP `email` LIMIT 1",
1461 array($email), __FUNCTION__, __LINE__);
1463 // Is there an account?
1464 if (SQL_HASZERONUMS($result)) {
1466 return '{--ADMIN_NO_LOGIN_WITH_EMAIL--}';
1470 $content = SQL_FETCHARRAY($result);
1473 SQL_FREERESULT($result);
1475 // Generate hash for reset link
1476 $content['hash'] = generateHash(getUrl() . getEncryptSeperator() . $content['id'] . getEncryptSeperator() . $content['login'] . getEncryptSeperator() . $content['password'], substr($content['password'], getSaltLength()));
1479 unset($content['id']);
1480 unset($content['password']);
1483 $mailText = loadEmailTemplate('admin_reset_password', $content);
1486 sendEmail($email, '{--ADMIN_RESET_PASSWORD_LINK_SUBJECT--}', $mailText);
1489 return '{--ADMIN_RESET_PASSWORD_LINK_SENT--}';
1492 // Validate hash and login for password reset
1493 function adminResetValidateHashLogin ($hash, $login) {
1494 // By default nothing validates... ;)
1497 // Then try to find that user
1498 $result = SQL_QUERY_ESC("SELECT `id`,`password`,`email` FROM `{?_MYSQL_PREFIX?}_admins` WHERE `login`='%s' LIMIT 1",
1499 array($login), __FUNCTION__, __LINE__);
1501 // Is an account here?
1502 if (SQL_NUMROWS($result) == 1) {
1504 $content = SQL_FETCHARRAY($result);
1506 // Generate hash again
1507 $hashFromData = generateHash(getUrl() . getEncryptSeperator() . $content['id'] . getEncryptSeperator() . $login . getEncryptSeperator() . $content['password'], substr($content['password'], getSaltLength()));
1510 $valid = ($hash == $hashFromData);
1514 SQL_FREERESULT($result);
1520 // Reset the password for the login. Do NOT call this function without calling above function first!
1521 function doResetAdminPassword ($login, $password) {
1522 // Generate hash (we already check for sql_patches in generateHash())
1523 $passHash = generateHash($password);
1525 // Prepare fake POST data
1527 'login' => array(getAdminId($login) => $login),
1528 'password' => array(getAdminId($login) => $passHash),
1532 $message = adminsChangeAdminAccount($postData, '', false);
1535 runFilterChain('post_form_reset_pass', array('login' => $login, 'hash' => $passHash, 'message' => $message));
1538 return '{--ADMIN_PASSWORD_RESET_DONE--}';
1541 // Solves a task by given id number
1542 function adminSolveTask ($id) {
1543 // Update the task data
1544 adminUpdateTaskData($id, 'status', 'SOLVED');
1547 // Marks a given task as deleted
1548 function adminDeleteTask ($id) {
1549 // Update the task data
1550 adminUpdateTaskData($id, 'status', 'DELETED');
1553 // Function to update task data
1554 function adminUpdateTaskData ($id, $row, $data) {
1555 // Should be admin and valid id
1557 // Not an admin so redirect better
1558 debug_report_bug(__FUNCTION__, __LINE__, 'id=' . $id . ',row=' . $row . ',data=' . $data . ' - isAdmin()=false');
1559 } elseif ($id <= 0) {
1560 // Initiate backtrace
1561 debug_report_bug(__FUNCTION__, __LINE__, sprintf("id is invalid: %s. row=%s, data=%s",
1569 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_task_system` SET `%s`='%s' WHERE `id`=%s LIMIT 1",
1574 ), __FUNCTION__, __LINE__);
1577 // Checks wether if the admin menu has entries
1578 function ifAdminMenuHasEntries ($action) {
1581 // Is the entry set?
1582 isset($GLOBALS['admin_menu_has_entries'][$action])
1584 // And do we have a menu for this action?
1585 $GLOBALS['admin_menu_has_entries'][$action] === true
1587 // Login has always a menu
1593 // Setter for 'admin_menu_has_entries'
1594 function setAdminMenuHasEntries ($action, $hasEntries) {
1595 $GLOBALS['admin_menu_has_entries'][$action] = (bool) $hasEntries;
1598 // Creates a link to the user's admin-profile
1599 function adminCreateUserLink ($userid) {
1600 // Is the userid set correctly?
1601 if (isValidUserId($userid)) {
1602 // Create a link to that profile
1603 return '{%url=modules.php?module=admin&what=list_user&userid=' . bigintval($userid) . '%}';
1606 // Return a link to the user list
1607 return '{%url=modules.php?module=admin&what=list_user%}';
1610 // Generate a "link" for the given admin id (admin_id)
1611 function generateAdminLink ($adminId) {
1612 // No assigned admin is default
1613 $adminLink = '<span class="notice">{--ADMIN_NO_ADMIN_ASSIGNED--}</span>';
1615 // Zero? = Not assigned
1616 if (bigintval($adminId) > 0) {
1617 // Load admin's login
1618 $login = getAdminLogin($adminId);
1620 // Is the login valid?
1621 if ($login != '***') {
1622 // Is the extension there?
1623 if (isExtensionActive('admins')) {
1625 $adminLink = '<a href="' . generateEmailLink(getAdminEmail($adminId), 'admins') . '" title="{--ADMIN_CONTACT_LINK_TITLE--}">' . $login . '</a>';
1627 // Extension not found
1628 $adminLink = '{%message,ADMIN_TASK_ROW_EXTENSION_NOT_INSTALLED=admins%}';
1632 $adminLink = '<div class="notice">{%message,ADMIN_ID_404=' . $adminId . '%}</div>';
1640 // Verifies if the current admin has confirmed to alter expert settings
1643 // 'failed' = Something goes wrong (default)
1644 // 'agreed' = Has verified and and confirmed it to see them
1645 // 'forbidden' = Has not the proper right to alter them
1646 // 'update' = Need to update extension 'admins'
1647 // 'ask' = A form was send to the admin
1648 function doVerifyExpertSettings () {
1649 // Default return status is failed
1652 // Is the extension installed and recent?
1653 if (isExtensionInstalledAndNewer('admins', '0.7.3')) {
1654 // Okay, load the status
1655 $expertSettings = getAminsExpertSettings();
1658 if ($expertSettings == 'Y') {
1659 // Okay, does he want to see them?
1660 if (isAdminsExpertWarningEnabled()) {
1663 // Is the element set, then we need to change the admin
1664 if (isPostRequestElementSet('expert_settings')) {
1665 // Get it and prepare final post data array
1666 $postData['login'][getCurrentAdminId()] = getCurrentAdminLogin();
1667 $postData['expert_warning'][getCurrentAdminId()] = 'N';
1669 // Change it in the admin
1670 adminsChangeAdminAccount($postData, 'expert_warning');
1673 unsetPostRequestElement('ok');
1680 loadTemplate('admin_expert_settings_form');
1691 $return = 'forbidden';
1694 // Out-dated extension or not installed
1698 // Output message for other status than ask/agreed
1699 if (($return != 'ask') && ($return != 'agreed')) {
1701 displayMessage('{--ADMIN_EXPERT_SETTINGS_STATUS_' . strtoupper($return) . '--}');
1708 // Generate link to unconfirmed mails for admin
1709 function generateUnconfirmedAdminLink ($id, $unconfirmed, $type = 'bid') {
1711 $OUT = $unconfirmed;
1713 // Do we have unconfirmed mails?
1714 if ($unconfirmed > 0) {
1715 // Add link to list_unconfirmed what-file
1716 $OUT = '<a href="{%url=modules.php?module=admin&what=list_unconfirmed&' . $type . '=' . $id . '%}">{%pipe,translateComma=' . $unconfirmed . '%}</a>';
1723 // Generates a navigation row for listing emails
1724 function addEmailNavigation ($numPages, $offset, $show_form, $colspan, $return=false) {
1725 // Don't do anything if $numPages is 1
1726 if ($numPages == 1) {
1727 // Abort here with empty content
1732 if ($show_form === false) {
1737 for ($page = 1; $page <= $numPages; $page++) {
1738 // Is the page currently selected or shall we generate a link to it?
1739 if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
1740 // Is currently selected, so only highlight it
1741 $NAV .= '<strong>-';
1743 // Open anchor tag and add base URL
1744 $NAV .= '<a href="{%url=modules.php?module=admin&what=' . getWhat() . '&page=' . $page . '&offset=' . $offset;
1746 // Add userid when we shall show all mails from a single member
1747 if ((isGetRequestElementSet('userid')) && (isValidUserId(getRequestElement('userid')))) $NAV .= '&userid=' . bigintval(getRequestElement('userid'));
1749 // Close open anchor tag
1753 if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
1754 // Is currently selected, so only highlight it
1755 $NAV .= '-</strong>';
1761 // Add seperator if we have not yet reached total pages
1762 if ($page < $numPages) {
1768 // Define constants only once
1769 $content['nav'] = $NAV;
1770 $content['span'] = $colspan;
1771 $content['top'] = $TOP;
1773 // Load navigation template
1774 $OUT = loadTemplate('admin_email_nav_row', true, $content);
1776 if ($return === true) {
1777 // Return generated HTML-Code
1785 // Process menu editing form
1786 function adminProcessMenuEditForm ($type, $subMenu) {
1787 // An action is done...
1788 foreach (postRequestElement('sel') as $sel => $menu) {
1789 $AND = "(`what` = '' OR `what` IS NULL)";
1791 $sel = bigintval($sel);
1793 if (!empty($subMenu)) {
1794 $AND = "`action`='" . $subMenu . "'";
1797 switch (postRequestElement('ok')) {
1798 case 'edit': // Edit menu
1799 if (postRequestElement('sel_what', $sel) == '') {
1800 // Update with 'what'=null
1801 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET `title`='%s', `action`='%s', `what`=NULL WHERE ".$AND." AND `id`=%s LIMIT 1",
1805 postRequestElement('sel_action', $sel),
1807 ), __FILE__, __LINE__);
1809 // Update with selected 'what'
1810 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET `title`='%s', `action`='%s', `what`='%s' WHERE ".$AND." AND `id`=%s LIMIT 1",
1814 postRequestElement('sel_action', $sel),
1815 postRequestElement('sel_what', $sel),
1817 ), __FILE__, __LINE__);
1821 case 'delete': // Delete menu
1822 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE ".$AND." AND `id`=%s LIMIT 1",
1823 array($type, $sel), __FILE__, __LINE__);
1826 case 'status': // Change status of menus
1827 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET `visible`='%s', `locked`='%s' WHERE ".$AND." AND `id`=%s LIMIT 1",
1828 array($type, postRequestElement('visible', $sel), postRequestElement('locked', $sel), $sel), __FILE__, __LINE__);
1831 default: // Unexpected action
1832 logDebugMessage(__FILE__, __LINE__, sprintf("Unsupported action %s detected.", postRequestElement('ok')));
1833 displayMessage('{%message,ADMIN_UNKNOWN_OKAY=' . postRequestElement('ok') . '%}');
1839 displayMessage('{--SETTINGS_SAVED--}');
1842 // Handle weightning
1843 function doAdminProcessMenuWeightning ($type, $AND) {
1844 // Are there all required (generalized) GET parameter?
1845 if ((isGetRequestElementSet('act')) && (isGetRequestElementSet('tid')) && (isGetRequestElementSet('fid'))) {
1847 $tid = ''; $fid = '';
1850 if (isGetRequestElementSet('w')) {
1851 // Sub menus selected
1852 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `action`='%s' AND `sort`=%s LIMIT 1",
1855 getRequestElement('act'),
1856 bigintval(getRequestElement('tid'))
1857 ), __FILE__, __LINE__);
1858 list($tid) = SQL_FETCHROW($result);
1859 SQL_FREERESULT($result);
1860 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE `action`='%s' AND `sort`=%s LIMIT 1",
1863 getRequestElement('act'),
1864 bigintval(getRequestElement('fid'))
1865 ), __FILE__, __LINE__);
1866 list($fid) = SQL_FETCHROW($result);
1867 SQL_FREERESULT($result);
1869 // Main menu selected
1870 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE (`what`='' OR `what` IS NULL) AND `sort`=%s LIMIT 1",
1873 bigintval(getRequestElement('tid'))
1874 ), __FILE__, __LINE__);
1875 list($tid) = SQL_FETCHROW($result);
1876 SQL_FREERESULT($result);
1877 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_%s_menu` WHERE (`what`='' OR `what` IS NULL) AND `sort`=%s LIMIT 1",
1880 bigintval(getRequestElement('fid'))
1881 ), __FILE__, __LINE__);
1882 list($fid) = SQL_FETCHROW($result);
1883 SQL_FREERESULT($result);
1886 if ((!empty($tid)) && (!empty($fid))) {
1888 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET `sort`=%s WHERE ".$AND." AND `id`=%s LIMIT 1",
1891 bigintval(getRequestElement('tid')),
1893 ), __FILE__, __LINE__);
1894 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_%s_menu` SET `sort`=%s WHERE ".$AND." AND `id`=%s LIMIT 1",
1897 bigintval(getRequestElement('fid')),
1899 ), __FILE__, __LINE__);