* @license GNU General Public License, version 2 (GPL-2.0) * * For full copyright and license information, please see * the docs/CREDITS.txt file. * */ /** * @ignore */ if (!defined('IN_PHPBB')) { exit; } /** * mcp_queue * Handling the moderation queue */ class mcp_queue { var $p_master; var $u_action; public function mcp_queue(&$p_master) { $this->p_master = &$p_master; } public function main($id, $mode) { global $auth, $db, $user, $template, $cache, $request; global $config, $phpbb_root_path, $phpEx, $action, $phpbb_container; global $phpbb_dispatcher; include_once($phpbb_root_path . 'includes/functions_posting.' . $phpEx); $forum_id = $request->variable('f', 0); $start = $request->variable('start', 0); $this->page_title = 'MCP_QUEUE'; switch ($action) { case 'approve': case 'restore': include_once($phpbb_root_path . 'includes/functions_messenger.' . $phpEx); $post_id_list = $request->variable('post_id_list', array(0)); $topic_id_list = $request->variable('topic_id_list', array(0)); if (!empty($post_id_list)) { self::approve_posts($action, $post_id_list, 'queue', $mode); } else if (!empty($topic_id_list)) { self::approve_topics($action, $topic_id_list, 'queue', $mode); } else { trigger_error('NO_POST_SELECTED'); } break; case 'delete': $post_id_list = $request->variable('post_id_list', array(0)); $topic_id_list = $request->variable('topic_id_list', array(0)); if (!empty($post_id_list)) { if (!function_exists('mcp_delete_post')) { global $phpbb_root_path, $phpEx; include($phpbb_root_path . 'includes/mcp/mcp_main.' . $phpEx); } mcp_delete_post($post_id_list, false, '', $action); } else if (!empty($topic_id_list)) { if (!function_exists('mcp_delete_topic')) { global $phpbb_root_path, $phpEx; include($phpbb_root_path . 'includes/mcp/mcp_main.' . $phpEx); } mcp_delete_topic($topic_id_list, false, '', $action); } else { trigger_error('NO_POST_SELECTED'); } break; case 'disapprove': $post_id_list = $request->variable('post_id_list', array(0)); $topic_id_list = $request->variable('topic_id_list', array(0)); if (!empty($topic_id_list) && $mode == 'deleted_topics') { if (!function_exists('mcp_delete_topics')) { global $phpbb_root_path, $phpEx; include($phpbb_root_path . 'includes/mcp/mcp_main.' . $phpEx); } mcp_delete_topic($topic_id_list, false, '', 'disapprove'); return; } if (!class_exists('messenger')) { include($phpbb_root_path . 'includes/functions_messenger.' . $phpEx); } if (!empty($topic_id_list)) { $post_visibility = ($mode == 'deleted_topics') ? ITEM_DELETED : array(ITEM_UNAPPROVED, ITEM_REAPPROVE); $sql = 'SELECT post_id FROM ' . POSTS_TABLE . ' WHERE ' . $db->sql_in_set('post_visibility', $post_visibility) . ' AND ' . $db->sql_in_set('topic_id', $topic_id_list); $result = $db->sql_query($sql); $post_id_list = array(); while ($row = $db->sql_fetchrow($result)) { $post_id_list[] = (int) $row['post_id']; } $db->sql_freeresult($result); } if (!empty($post_id_list)) { self::disapprove_posts($post_id_list, 'queue', $mode); } else { trigger_error('NO_POST_SELECTED'); } break; } switch ($mode) { case 'approve_details': $this->tpl_name = 'mcp_post'; $user->add_lang(array('posting', 'viewtopic')); $post_id = $request->variable('p', 0); $topic_id = $request->variable('t', 0); /* @var $phpbb_notifications \phpbb\notification\manager */ $phpbb_notifications = $phpbb_container->get('notification_manager'); if ($topic_id) { $topic_info = phpbb_get_topic_data(array($topic_id), 'm_approve'); if (isset($topic_info[$topic_id]['topic_first_post_id'])) { $post_id = (int) $topic_info[$topic_id]['topic_first_post_id']; $phpbb_notifications->mark_notifications_read('notification.type.topic_in_queue', $topic_id, $user->data['user_id']); } else { $topic_id = 0; } } $phpbb_notifications->mark_notifications_read('notification.type.post_in_queue', $post_id, $user->data['user_id']); $post_info = phpbb_get_post_data(array($post_id), 'm_approve', true); if (!sizeof($post_info)) { trigger_error('NO_POST_SELECTED'); } $post_info = $post_info[$post_id]; if ($post_info['topic_first_post_id'] != $post_id && topic_review($post_info['topic_id'], $post_info['forum_id'], 'topic_review', 0, false)) { $template->assign_vars(array( 'S_TOPIC_REVIEW' => true, 'S_BBCODE_ALLOWED' => $post_info['enable_bbcode'], 'TOPIC_TITLE' => $post_info['topic_title'], )); } $extensions = $attachments = $topic_tracking_info = array(); // Get topic tracking info if ($config['load_db_lastread']) { $tmp_topic_data = array($post_info['topic_id'] => $post_info); $topic_tracking_info = get_topic_tracking($post_info['forum_id'], $post_info['topic_id'], $tmp_topic_data, array($post_info['forum_id'] => $post_info['forum_mark_time'])); unset($tmp_topic_data); } else { $topic_tracking_info = get_complete_topic_tracking($post_info['forum_id'], $post_info['topic_id']); } $post_unread = (isset($topic_tracking_info[$post_info['topic_id']]) && $post_info['post_time'] > $topic_tracking_info[$post_info['topic_id']]) ? true : false; // Process message, leave it uncensored $parse_flags = ($post_info['bbcode_bitfield'] ? OPTION_FLAG_BBCODE : 0) | OPTION_FLAG_SMILIES; $message = generate_text_for_display($post_info['post_text'], $post_info['bbcode_uid'], $post_info['bbcode_bitfield'], $parse_flags, false); if ($post_info['post_attachment'] && $auth->acl_get('u_download') && $auth->acl_get('f_download', $post_info['forum_id'])) { $extensions = $cache->obtain_attach_extensions($post_info['forum_id']); $sql = 'SELECT * FROM ' . ATTACHMENTS_TABLE . ' WHERE post_msg_id = ' . $post_id . ' AND in_message = 0 ORDER BY filetime DESC, post_msg_id ASC'; $result = $db->sql_query($sql); while ($row = $db->sql_fetchrow($result)) { $attachments[] = $row; } $db->sql_freeresult($result); if (sizeof($attachments)) { $update_count = array(); parse_attachments($post_info['forum_id'], $message, $attachments, $update_count); } // Display not already displayed Attachments for this post, we already parsed them. ;) if (!empty($attachments)) { $template->assign_var('S_HAS_ATTACHMENTS', true); foreach ($attachments as $attachment) { $template->assign_block_vars('attachment', array( 'DISPLAY_ATTACHMENT' => $attachment, )); } } } // Deleting information if ($post_info['post_visibility'] == ITEM_DELETED && $post_info['post_delete_user']) { // User having deleted the post also being the post author? if (!$post_info['post_delete_user'] || $post_info['post_delete_user'] == $post_info['poster_id']) { $display_username = get_username_string('full', $post_info['poster_id'], $post_info['username'], $post_info['user_colour'], $post_info['post_username']); } else { $sql = 'SELECT u.user_id, u.username, u.user_colour FROM ' . POSTS_TABLE . ' p, ' . USERS_TABLE . ' u WHERE p.post_id = ' . $post_info['post_id'] . ' AND p.post_delete_user = u.user_id'; $result = $db->sql_query($sql); $post_delete_userinfo = $db->sql_fetchrow($result); $db->sql_freeresult($result); $display_username = get_username_string('full', $post_info['post_delete_user'], $post_delete_userinfo['username'], $post_delete_userinfo['user_colour']); } $l_deleted_by = $user->lang('DELETED_INFORMATION', $display_username, $user->format_date($post_info['post_delete_time'], false, true)); } else { $l_deleted_by = ''; } $post_url = append_sid("{$phpbb_root_path}viewtopic.$phpEx", 'f=' . $post_info['forum_id'] . '&p=' . $post_info['post_id'] . '#p' . $post_info['post_id']); $topic_url = append_sid("{$phpbb_root_path}viewtopic.$phpEx", 'f=' . $post_info['forum_id'] . '&t=' . $post_info['topic_id']); $template->assign_vars(array( 'S_MCP_QUEUE' => true, 'U_APPROVE_ACTION' => append_sid("{$phpbb_root_path}mcp.$phpEx", "i=queue&p=$post_id&f=$forum_id"), 'S_CAN_VIEWIP' => $auth->acl_get('m_info', $post_info['forum_id']), 'S_POST_REPORTED' => $post_info['post_reported'], 'S_POST_UNAPPROVED' => $post_info['post_visibility'] == ITEM_UNAPPROVED || $post_info['post_visibility'] == ITEM_REAPPROVE, 'S_POST_LOCKED' => $post_info['post_edit_locked'], 'S_USER_NOTES' => true, 'S_POST_DELETED' => ($post_info['post_visibility'] == ITEM_DELETED), 'DELETED_MESSAGE' => $l_deleted_by, 'DELETE_REASON' => $post_info['post_delete_reason'], 'U_EDIT' => ($auth->acl_get('m_edit', $post_info['forum_id'])) ? append_sid("{$phpbb_root_path}posting.$phpEx", "mode=edit&f={$post_info['forum_id']}&p={$post_info['post_id']}") : '', 'U_MCP_APPROVE' => append_sid("{$phpbb_root_path}mcp.$phpEx", 'i=queue&mode=approve_details&f=' . $post_info['forum_id'] . '&p=' . $post_id), 'U_MCP_REPORT' => append_sid("{$phpbb_root_path}mcp.$phpEx", 'i=reports&mode=report_details&f=' . $post_info['forum_id'] . '&p=' . $post_id), 'U_MCP_USER_NOTES' => append_sid("{$phpbb_root_path}mcp.$phpEx", 'i=notes&mode=user_notes&u=' . $post_info['user_id']), 'U_MCP_WARN_USER' => ($auth->acl_get('m_warn')) ? append_sid("{$phpbb_root_path}mcp.$phpEx", 'i=warn&mode=warn_user&u=' . $post_info['user_id']) : '', 'U_VIEW_POST' => $post_url, 'U_VIEW_TOPIC' => $topic_url, 'MINI_POST_IMG' => ($post_unread) ? $user->img('icon_post_target_unread', 'UNREAD_POST') : $user->img('icon_post_target', 'POST'), 'RETURN_QUEUE' => sprintf($user->lang['RETURN_QUEUE'], '', ''), 'RETURN_POST' => sprintf($user->lang['RETURN_POST'], '', ''), 'RETURN_TOPIC_SIMPLE' => sprintf($user->lang['RETURN_TOPIC_SIMPLE'], '', ''), 'REPORTED_IMG' => $user->img('icon_topic_reported', $user->lang['POST_REPORTED']), 'UNAPPROVED_IMG' => $user->img('icon_topic_unapproved', $user->lang['POST_UNAPPROVED']), 'EDIT_IMG' => $user->img('icon_post_edit', $user->lang['EDIT_POST']), 'POST_AUTHOR_FULL' => get_username_string('full', $post_info['user_id'], $post_info['username'], $post_info['user_colour'], $post_info['post_username']), 'POST_AUTHOR_COLOUR' => get_username_string('colour', $post_info['user_id'], $post_info['username'], $post_info['user_colour'], $post_info['post_username']), 'POST_AUTHOR' => get_username_string('username', $post_info['user_id'], $post_info['username'], $post_info['user_colour'], $post_info['post_username']), 'U_POST_AUTHOR' => get_username_string('profile', $post_info['user_id'], $post_info['username'], $post_info['user_colour'], $post_info['post_username']), 'POST_PREVIEW' => $message, 'POST_SUBJECT' => $post_info['post_subject'], 'POST_DATE' => $user->format_date($post_info['post_time']), 'POST_IP' => $post_info['poster_ip'], 'POST_IPADDR' => ($auth->acl_get('m_info', $post_info['forum_id']) && $request->variable('lookup', '')) ? @gethostbyaddr($post_info['poster_ip']) : '', 'POST_ID' => $post_info['post_id'], 'S_FIRST_POST' => ($post_info['topic_first_post_id'] == $post_id), 'U_LOOKUP_IP' => ($auth->acl_get('m_info', $post_info['forum_id'])) ? append_sid("{$phpbb_root_path}mcp.$phpEx", 'i=queue&mode=approve_details&f=' . $post_info['forum_id'] . '&p=' . $post_id . '&lookup=' . $post_info['poster_ip']) . '#ip' : '', )); break; case 'unapproved_topics': case 'unapproved_posts': case 'deleted_topics': case 'deleted_posts': $m_perm = 'm_approve'; $is_topics = ($mode == 'unapproved_topics' || $mode == 'deleted_topics') ? true : false; $is_restore = ($mode == 'deleted_posts' || $mode == 'deleted_topics') ? true : false; $visibility_const = (!$is_restore) ? array(ITEM_UNAPPROVED, ITEM_REAPPROVE) : ITEM_DELETED; $user->add_lang(array('viewtopic', 'viewforum')); $topic_id = $request->variable('t', 0); $forum_info = array(); /* @var $pagination \phpbb\pagination */ $pagination = $phpbb_container->get('pagination'); if ($topic_id) { $topic_info = phpbb_get_topic_data(array($topic_id)); if (!sizeof($topic_info)) { trigger_error('TOPIC_NOT_EXIST'); } $topic_info = $topic_info[$topic_id]; $forum_id = $topic_info['forum_id']; } $forum_list_approve = get_forum_list($m_perm, false, true); $forum_list_read = array_flip(get_forum_list('f_read', true, true)); // Flipped so we can isset() the forum IDs // Remove forums we cannot read foreach ($forum_list_approve as $k => $forum_data) { if (!isset($forum_list_read[$forum_data['forum_id']])) { unset($forum_list_approve[$k]); } } unset($forum_list_read); if (!$forum_id) { $forum_list = array(); foreach ($forum_list_approve as $row) { $forum_list[] = $row['forum_id']; } if (!sizeof($forum_list)) { trigger_error('NOT_MODERATOR'); } $sql = 'SELECT SUM(forum_topics_approved) as sum_forum_topics FROM ' . FORUMS_TABLE . ' WHERE ' . $db->sql_in_set('forum_id', $forum_list); $result = $db->sql_query($sql); $forum_info['forum_topics_approved'] = (int) $db->sql_fetchfield('sum_forum_topics'); $db->sql_freeresult($result); } else { $forum_info = phpbb_get_forum_data(array($forum_id), $m_perm); if (!sizeof($forum_info)) { trigger_error('NOT_MODERATOR'); } $forum_info = $forum_info[$forum_id]; $forum_list = $forum_id; } $forum_options = ''; foreach ($forum_list_approve as $row) { $forum_options .= ''; } $sort_days = $total = 0; $sort_key = $sort_dir = ''; $sort_by_sql = $sort_order_sql = array(); phpbb_mcp_sorting($mode, $sort_days, $sort_key, $sort_dir, $sort_by_sql, $sort_order_sql, $total, $forum_id, $topic_id); $forum_topics = ($total == -1) ? $forum_info['forum_topics_approved'] : $total; $limit_time_sql = ($sort_days) ? 'AND t.topic_last_post_time >= ' . (time() - ($sort_days * 86400)) : ''; $forum_names = array(); if (!$is_topics) { $sql = 'SELECT p.post_id FROM ' . POSTS_TABLE . ' p, ' . TOPICS_TABLE . ' t' . (($sort_order_sql[0] == 'u') ? ', ' . USERS_TABLE . ' u' : '') . ' WHERE ' . $db->sql_in_set('p.forum_id', $forum_list) . ' AND ' . $db->sql_in_set('p.post_visibility', $visibility_const) . ' ' . (($sort_order_sql[0] == 'u') ? 'AND u.user_id = p.poster_id' : '') . ' ' . (($topic_id) ? 'AND p.topic_id = ' . $topic_id : '') . " AND t.topic_id = p.topic_id AND (t.topic_visibility <> p.post_visibility OR t.topic_delete_user = 0) $limit_time_sql ORDER BY $sort_order_sql"; /** * Alter sql query to get posts in queue to be accepted * * @event core.mcp_queue_get_posts_query_before * @var string sql Associative array with the query to be executed * @var array forum_list List of forums that contain the posts * @var int visibility_const Integer with one of the possible ITEM_* constant values * @var int topic_id If topic_id not equal to 0, the topic id to filter the posts to display * @var string limit_time_sql String with the SQL code to limit the time interval of the post (Note: May be empty string) * @var string sort_order_sql String with the ORDER BY SQL code used in this query * @since 3.1.0-RC3 */ $vars = array( 'sql', 'forum_list', 'visibility_const', 'topic_id', 'limit_time_sql', 'sort_order_sql', ); extract($phpbb_dispatcher->trigger_event('core.mcp_queue_get_posts_query_before', compact($vars))); $result = $db->sql_query_limit($sql, $config['topics_per_page'], $start); $i = 0; $post_ids = array(); while ($row = $db->sql_fetchrow($result)) { $post_ids[] = $row['post_id']; $row_num[$row['post_id']] = $i++; } $db->sql_freeresult($result); if (sizeof($post_ids)) { $sql = 'SELECT t.topic_id, t.topic_title, t.forum_id, p.post_id, p.post_subject, p.post_username, p.poster_id, p.post_time, p.post_attachment, u.username, u.username_clean, u.user_colour FROM ' . POSTS_TABLE . ' p, ' . TOPICS_TABLE . ' t, ' . USERS_TABLE . ' u WHERE ' . $db->sql_in_set('p.post_id', $post_ids) . ' AND t.topic_id = p.topic_id AND u.user_id = p.poster_id ORDER BY ' . $sort_order_sql; $result = $db->sql_query($sql); $post_data = $rowset = array(); while ($row = $db->sql_fetchrow($result)) { $forum_names[] = $row['forum_id']; $post_data[$row['post_id']] = $row; } $db->sql_freeresult($result); foreach ($post_ids as $post_id) { $rowset[] = $post_data[$post_id]; } unset($post_data, $post_ids); } else { $rowset = array(); } } else { $sql = 'SELECT t.forum_id, t.topic_id, t.topic_title, t.topic_title AS post_subject, t.topic_time AS post_time, t.topic_poster AS poster_id, t.topic_first_post_id AS post_id, t.topic_attachment AS post_attachment, t.topic_first_poster_name AS username, t.topic_first_poster_colour AS user_colour FROM ' . TOPICS_TABLE . ' t WHERE ' . $db->sql_in_set('forum_id', $forum_list) . ' AND ' . $db->sql_in_set('topic_visibility', $visibility_const) . " AND topic_delete_user <> 0 $limit_time_sql ORDER BY $sort_order_sql"; /** * Alter sql query to get information on all topics in the list of forums provided. * * @event core.mcp_queue_get_posts_for_topics_query_before * @var string sql String with the query to be executed * @var array forum_list List of forums that contain the posts * @var int visibility_const Integer with one of the possible ITEM_* constant values * @var int topic_id topic_id in the page request * @var string limit_time_sql String with the SQL code to limit the time interval of the post (Note: May be empty string) * @var string sort_order_sql String with the ORDER BY SQL code used in this query * @since 3.1.0-RC3 */ $vars = array( 'sql', 'forum_list', 'visibility_const', 'topic_id', 'limit_time_sql', 'sort_order_sql', ); extract($phpbb_dispatcher->trigger_event('core.mcp_queue_get_posts_for_topics_query_before', compact($vars))); $result = $db->sql_query_limit($sql, $config['topics_per_page'], $start); $rowset = array(); while ($row = $db->sql_fetchrow($result)) { $forum_names[] = $row['forum_id']; $rowset[] = $row; } $db->sql_freeresult($result); } if (sizeof($forum_names)) { // Select the names for the forum_ids $sql = 'SELECT forum_id, forum_name FROM ' . FORUMS_TABLE . ' WHERE ' . $db->sql_in_set('forum_id', $forum_names); $result = $db->sql_query($sql, 3600); $forum_names = array(); while ($row = $db->sql_fetchrow($result)) { $forum_names[$row['forum_id']] = $row['forum_name']; } $db->sql_freeresult($result); } foreach ($rowset as $row) { if (empty($row['post_username'])) { $row['post_username'] = $row['username'] ?: $user->lang['GUEST']; } $template->assign_block_vars('postrow', array( 'U_TOPIC' => append_sid("{$phpbb_root_path}viewtopic.$phpEx", 'f=' . $row['forum_id'] . '&t=' . $row['topic_id']), 'U_VIEWFORUM' => append_sid("{$phpbb_root_path}viewforum.$phpEx", 'f=' . $row['forum_id']), 'U_VIEWPOST' => append_sid("{$phpbb_root_path}viewtopic.$phpEx", 'f=' . $row['forum_id'] . '&p=' . $row['post_id']) . (($mode == 'unapproved_posts') ? '#p' . $row['post_id'] : ''), 'U_VIEW_DETAILS' => append_sid("{$phpbb_root_path}mcp.$phpEx", "i=queue&start=$start&mode=approve_details&f={$row['forum_id']}&p={$row['post_id']}" . (($mode == 'unapproved_topics') ? "&t={$row['topic_id']}" : '')), 'POST_AUTHOR_FULL' => get_username_string('full', $row['poster_id'], $row['username'], $row['user_colour'], $row['post_username']), 'POST_AUTHOR_COLOUR' => get_username_string('colour', $row['poster_id'], $row['username'], $row['user_colour'], $row['post_username']), 'POST_AUTHOR' => get_username_string('username', $row['poster_id'], $row['username'], $row['user_colour'], $row['post_username']), 'U_POST_AUTHOR' => get_username_string('profile', $row['poster_id'], $row['username'], $row['user_colour'], $row['post_username']), 'POST_ID' => $row['post_id'], 'TOPIC_ID' => $row['topic_id'], 'FORUM_NAME' => $forum_names[$row['forum_id']], 'POST_SUBJECT' => ($row['post_subject'] != '') ? $row['post_subject'] : $user->lang['NO_SUBJECT'], 'TOPIC_TITLE' => $row['topic_title'], 'POST_TIME' => $user->format_date($row['post_time']), 'ATTACH_ICON_IMG' => ($auth->acl_get('u_download') && $auth->acl_get('f_download', $row['forum_id']) && $row['post_attachment']) ? $user->img('icon_topic_attach', $user->lang['TOTAL_ATTACHMENTS']) : '', )); } unset($rowset, $forum_names); $base_url = $this->u_action . "&f=$forum_id&st=$sort_days&sk=$sort_key&sd=$sort_dir"; $pagination->generate_template_pagination($base_url, 'pagination', 'start', $total, $config['topics_per_page'], $start); // Now display the page $template->assign_vars(array( 'L_DISPLAY_ITEMS' => (!$is_topics) ? $user->lang['DISPLAY_POSTS'] : $user->lang['DISPLAY_TOPICS'], 'L_EXPLAIN' => $user->lang['MCP_QUEUE_' . strtoupper($mode) . '_EXPLAIN'], 'L_TITLE' => $user->lang['MCP_QUEUE_' . strtoupper($mode)], 'L_ONLY_TOPIC' => ($topic_id) ? sprintf($user->lang['ONLY_TOPIC'], $topic_info['topic_title']) : '', 'S_FORUM_OPTIONS' => $forum_options, 'S_MCP_ACTION' => build_url(array('t', 'f', 'sd', 'st', 'sk')), 'S_TOPICS' => $is_topics, 'S_RESTORE' => $is_restore, 'TOPIC_ID' => $topic_id, 'TOTAL' => $user->lang(((!$is_topics) ? 'VIEW_TOPIC_POSTS' : 'VIEW_FORUM_TOPICS'), (int) $total), )); $this->tpl_name = 'mcp_queue'; break; } } /** * Approve/Restore posts * * @param $action string Action we perform on the posts ('approve' or 'restore') * @param $post_id_list array IDs of the posts to approve/restore * @param $id mixed Category of the current active module * @param $mode string Active module * @return null */ static public function approve_posts($action, $post_id_list, $id, $mode) { global $db, $template, $user, $config, $request, $phpbb_container, $phpbb_dispatcher; global $phpEx, $phpbb_root_path, $phpbb_log; if (!phpbb_check_ids($post_id_list, POSTS_TABLE, 'post_id', array('m_approve'))) { trigger_error('NOT_AUTHORISED'); } $redirect = $request->variable('redirect', build_url(array('quickmod'))); $redirect = reapply_sid($redirect); $success_msg = $post_url = ''; $approve_log = array(); $num_topics = 0; $s_hidden_fields = build_hidden_fields(array( 'i' => $id, 'mode' => $mode, 'post_id_list' => $post_id_list, 'action' => $action, 'redirect' => $redirect, )); $post_info = phpbb_get_post_data($post_id_list, 'm_approve'); if (confirm_box(true)) { $notify_poster = ($action == 'approve' && isset($_REQUEST['notify_poster'])); $topic_info = array(); // Group the posts by topic_id foreach ($post_info as $post_id => $post_data) { if ($post_data['post_visibility'] == ITEM_APPROVED) { continue; } $topic_id = (int) $post_data['topic_id']; $topic_info[$topic_id]['posts'][] = (int) $post_id; $topic_info[$topic_id]['forum_id'] = (int) $post_data['forum_id']; // Refresh the first post, if the time or id is older then the current one if ($post_id <= $post_data['topic_first_post_id'] || $post_data['post_time'] <= $post_data['topic_time']) { $topic_info[$topic_id]['first_post'] = true; } // Refresh the last post, if the time or id is newer then the current one if ($post_id >= $post_data['topic_last_post_id'] || $post_data['post_time'] >= $post_data['topic_last_post_time']) { $topic_info[$topic_id]['last_post'] = true; } $post_url = append_sid("{$phpbb_root_path}viewtopic.$phpEx", "f={$post_data['forum_id']}&t={$post_data['topic_id']}&p={$post_data['post_id']}") . '#p' . $post_data['post_id']; $approve_log[] = array( 'forum_id' => $post_data['forum_id'], 'topic_id' => $post_data['topic_id'], 'post_subject' => $post_data['post_subject'], ); } /* @var $phpbb_content_visibility \phpbb\content_visibility */ $phpbb_content_visibility = $phpbb_container->get('content.visibility'); foreach ($topic_info as $topic_id => $topic_data) { $phpbb_content_visibility->set_post_visibility(ITEM_APPROVED, $topic_data['posts'], $topic_id, $topic_data['forum_id'], $user->data['user_id'], time(), '', isset($topic_data['first_post']), isset($topic_data['last_post'])); } foreach ($approve_log as $log_data) { $phpbb_log->add('mod', $user->data['user_id'], $user->ip, 'LOG_POST_' . strtoupper($action) . 'D', false, array( 'forum_id' => $log_data['forum_id'], 'topic_id' => $log_data['topic_id'], $log_data['post_subject'] )); } // Only send out the mails, when the posts are being approved if ($action == 'approve') { /* @var $phpbb_notifications \phpbb\notification\manager */ $phpbb_notifications = $phpbb_container->get('notification_manager'); // Handle notifications foreach ($post_info as $post_id => $post_data) { // A single topic approval may also happen here, so handle deleting the respective notification. if (!$post_data['topic_posts_approved']) { $phpbb_notifications->delete_notifications('notification.type.topic_in_queue', $post_data['topic_id']); if ($post_data['post_visibility'] == ITEM_UNAPPROVED) { $phpbb_notifications->add_notifications(array('notification.type.topic'), $post_data); } if ($post_data['post_visibility'] != ITEM_APPROVED) { $num_topics++; } } else { // Only add notifications, if we are not reapproving post // When the topic was already approved, but was edited and // now needs re-approval, we don't want to notify the users // again. if ($post_data['post_visibility'] == ITEM_UNAPPROVED) { $phpbb_notifications->add_notifications(array( 'notification.type.bookmark', 'notification.type.post', ), $post_data); } } $phpbb_notifications->add_notifications(array('notification.type.quote'), $post_data); $phpbb_notifications->delete_notifications('notification.type.post_in_queue', $post_id); $phpbb_notifications->mark_notifications_read(array( 'notification.type.quote', 'notification.type.bookmark', 'notification.type.post', ), $post_data['post_id'], $user->data['user_id']); // Notify Poster? if ($notify_poster) { if ($post_data['poster_id'] == ANONYMOUS) { continue; } if (!$post_data['topic_posts_approved']) { $phpbb_notifications->add_notifications('notification.type.approve_topic', $post_data); } else { $phpbb_notifications->add_notifications('notification.type.approve_post', $post_data); } } } } if ($num_topics >= 1) { $success_msg = ($num_topics == 1) ? 'TOPIC_' . strtoupper($action) . 'D_SUCCESS' : 'TOPICS_' . strtoupper($action) . 'D_SUCCESS'; } else { $success_msg = (sizeof($post_info) == 1) ? 'POST_' . strtoupper($action) . 'D_SUCCESS' : 'POSTS_' . strtoupper($action) . 'D_SUCCESS'; } /** * Perform additional actions during post(s) approval * * @event core.approve_posts_after * @var string action Variable containing the action we perform on the posts ('approve' or 'restore') * @var array post_info Array containing info for all posts being approved * @var array topic_info Array containing info for all parent topics of the posts * @var int num_topics Variable containing number of topics * @var bool notify_poster Variable telling if the post should be notified or not * @var string success_msg Variable containing the language key for the success message * @var string redirect Variable containing the redirect url * @since 3.1.4-RC1 */ $vars = array( 'action', 'post_info', 'topic_info', 'num_topics', 'notify_poster', 'success_msg', 'redirect', ); extract($phpbb_dispatcher->trigger_event('core.approve_posts_after', compact($vars))); meta_refresh(3, $redirect); $message = $user->lang[$success_msg]; if ($request->is_ajax()) { $json_response = new \phpbb\json_response; $json_response->send(array( 'MESSAGE_TITLE' => $user->lang['INFORMATION'], 'MESSAGE_TEXT' => $message, 'REFRESH_DATA' => null, 'visible' => true, )); } $message .= '

' . $user->lang('RETURN_PAGE', '', ''); // If approving one post, also give links back to post... if (sizeof($post_info) == 1 && $post_url) { $message .= '

' . $user->lang('RETURN_POST', '', ''); } trigger_error($message); } else { $show_notify = false; if ($action == 'approve') { foreach ($post_info as $post_data) { if (!$post_data['topic_posts_approved']) { $num_topics++; } if (!$show_notify && $post_data['poster_id'] != ANONYMOUS) { $show_notify = true; } } } $template->assign_vars(array( 'S_NOTIFY_POSTER' => $show_notify, 'S_' . strtoupper($action) => true, )); // Create the confirm box message $action_msg = strtoupper($action); $num_posts = sizeof($post_id_list) - $num_topics; if ($num_topics > 0 && $num_posts <= 0) { $action_msg .= '_TOPIC' . (($num_topics == 1) ? '' : 'S'); } else { $action_msg .= '_POST' . ((sizeof($post_id_list) == 1) ? '' : 'S'); } confirm_box(false, $action_msg, $s_hidden_fields, 'mcp_approve.html'); } redirect($redirect); } /** * Approve/Restore topics * * @param $action string Action we perform on the posts ('approve' or 'restore') * @param $topic_id_list array IDs of the topics to approve/restore * @param $id mixed Category of the current active module * @param $mode string Active module * @return null */ static public function approve_topics($action, $topic_id_list, $id, $mode) { global $db, $template, $user, $config, $phpbb_log; global $phpEx, $phpbb_root_path, $request, $phpbb_container, $phpbb_dispatcher; if (!phpbb_check_ids($topic_id_list, TOPICS_TABLE, 'topic_id', array('m_approve'))) { trigger_error('NOT_AUTHORISED'); } $redirect = $request->variable('redirect', build_url(array('quickmod'))); $redirect = reapply_sid($redirect); $success_msg = $topic_url = ''; $approve_log = array(); $s_hidden_fields = build_hidden_fields(array( 'i' => $id, 'mode' => $mode, 'topic_id_list' => $topic_id_list, 'action' => $action, 'redirect' => $redirect, )); $topic_info = phpbb_get_topic_data($topic_id_list, 'm_approve'); if (confirm_box(true)) { $notify_poster = ($action == 'approve' && isset($_REQUEST['notify_poster'])) ? true : false; /* @var $phpbb_content_visibility \phpbb\content_visibility */ $phpbb_content_visibility = $phpbb_container->get('content.visibility'); $first_post_ids = array(); foreach ($topic_info as $topic_id => $topic_data) { $phpbb_content_visibility->set_topic_visibility(ITEM_APPROVED, $topic_id, $topic_data['forum_id'], $user->data['user_id'], time(), ''); $first_post_ids[$topic_id] = (int) $topic_data['topic_first_post_id']; $topic_url = append_sid("{$phpbb_root_path}viewtopic.$phpEx", "f={$topic_data['forum_id']}&t={$topic_id}"); $approve_log[] = array( 'forum_id' => $topic_data['forum_id'], 'topic_id' => $topic_data['topic_id'], 'topic_title' => $topic_data['topic_title'], ); } if (sizeof($topic_info) >= 1) { $success_msg = (sizeof($topic_info) == 1) ? 'TOPIC_' . strtoupper($action) . 'D_SUCCESS' : 'TOPICS_' . strtoupper($action) . 'D_SUCCESS'; } foreach ($approve_log as $log_data) { $phpbb_log->add('mod', $user->data['user_id'], $user->ip, 'LOG_TOPIC_' . strtoupper($action) . 'D', false, array( 'forum_id' => $log_data['forum_id'], 'topic_id' => $log_data['topic_id'], $log_data['topic_title'] )); } // Only send out the mails, when the posts are being approved if ($action == 'approve') { // Grab the first post text as it's needed for the quote notification. $sql = 'SELECT topic_id, post_text FROM ' . POSTS_TABLE . ' WHERE ' . $db->sql_in_set('post_id', $first_post_ids); $result = $db->sql_query($sql); while ($row = $db->sql_fetchrow($result)) { $topic_info[$row['topic_id']]['post_text'] = $row['post_text']; } $db->sql_freeresult($result); // Handle notifications /* @var $phpbb_notifications \phpbb\notification\manager */ $phpbb_notifications = $phpbb_container->get('notification_manager'); foreach ($topic_info as $topic_id => $topic_data) { $topic_data = array_merge($topic_data, array( 'post_id' => $topic_data['topic_first_post_id'], 'post_subject' => $topic_data['topic_title'], 'post_time' => $topic_data['topic_time'], 'poster_id' => $topic_data['topic_poster'], 'post_username' => $topic_data['topic_first_poster_name'], )); $phpbb_notifications->delete_notifications('notification.type.topic_in_queue', $topic_id); // Only add notifications, if we are not reapproving post // When the topic was already approved, but was edited and // now needs re-approval, we don't want to notify the users // again. if ($topic_data['topic_visibility'] == ITEM_UNAPPROVED) { $phpbb_notifications->add_notifications(array( 'notification.type.quote', 'notification.type.topic', ), $topic_data); } $phpbb_notifications->mark_notifications_read('notification.type.quote', $topic_data['post_id'], $user->data['user_id']); $phpbb_notifications->mark_notifications_read('notification.type.topic', $topic_id, $user->data['user_id']); if ($notify_poster) { $phpbb_notifications->add_notifications('notification.type.approve_topic', $topic_data); } } } /** * Perform additional actions during topics(s) approval * * @event core.approve_topics_after * @var string action Variable containing the action we perform on the posts ('approve' or 'restore') * @var mixed topic_info Array containing info for all topics being approved * @var array first_post_ids Array containing ids of all first posts * @var bool notify_poster Variable telling if the poster should be notified or not * @var string success_msg Variable containing the language key for the success message * @var string redirect Variable containing the redirect url * @since 3.1.4-RC1 */ $vars = array( 'action', 'topic_info', 'first_post_ids', 'notify_poster', 'success_msg', 'redirect', ); extract($phpbb_dispatcher->trigger_event('core.approve_topics_after', compact($vars))); meta_refresh(3, $redirect); $message = $user->lang[$success_msg]; if ($request->is_ajax()) { $json_response = new \phpbb\json_response; $json_response->send(array( 'MESSAGE_TITLE' => $user->lang['INFORMATION'], 'MESSAGE_TEXT' => $message, 'REFRESH_DATA' => null, 'visible' => true, )); } $message .= '

' . $user->lang('RETURN_PAGE', '', ''); // If approving one topic, also give links back to topic... if (sizeof($topic_info) == 1 && $topic_url) { $message .= '

' . $user->lang('RETURN_TOPIC', '', ''); } trigger_error($message); } else { $show_notify = false; if ($action == 'approve') { foreach ($topic_info as $topic_data) { if ($topic_data['topic_poster'] == ANONYMOUS) { continue; } else { $show_notify = true; break; } } } $template->assign_vars(array( 'S_NOTIFY_POSTER' => $show_notify, 'S_' . strtoupper($action) => true, )); confirm_box(false, strtoupper($action) . '_TOPIC' . ((sizeof($topic_id_list) == 1) ? '' : 'S'), $s_hidden_fields, 'mcp_approve.html'); } redirect($redirect); } /** * Disapprove Post * * @param $post_id_list array IDs of the posts to disapprove/delete * @param $id mixed Category of the current active module * @param $mode string Active module * @return null */ static public function disapprove_posts($post_id_list, $id, $mode) { global $db, $template, $user, $config, $phpbb_container, $phpbb_dispatcher; global $phpEx, $phpbb_root_path, $request, $phpbb_log; if (!phpbb_check_ids($post_id_list, POSTS_TABLE, 'post_id', array('m_approve'))) { trigger_error('NOT_AUTHORISED'); } $redirect = $request->variable('redirect', build_url(array('t', 'mode', 'quickmod')) . "&mode=$mode"); $redirect = reapply_sid($redirect); $reason = $request->variable('reason', '', true); $reason_id = $request->variable('reason_id', 0); $success_msg = $additional_msg = ''; $s_hidden_fields = build_hidden_fields(array( 'i' => $id, 'mode' => $mode, 'post_id_list' => $post_id_list, 'action' => 'disapprove', 'redirect' => $redirect, )); $notify_poster = $request->is_set('notify_poster'); $disapprove_reason = ''; if ($reason_id) { $sql = 'SELECT reason_title, reason_description FROM ' . REPORTS_REASONS_TABLE . " WHERE reason_id = $reason_id"; $result = $db->sql_query($sql); $row = $db->sql_fetchrow($result); $db->sql_freeresult($result); if (!$row || (!$reason && strtolower($row['reason_title']) == 'other')) { $additional_msg = $user->lang['NO_REASON_DISAPPROVAL']; $request->overwrite('confirm', null, \phpbb\request\request_interface::POST); $request->overwrite('confirm_key', null, \phpbb\request\request_interface::POST); $request->overwrite('confirm_key', null, \phpbb\request\request_interface::REQUEST); } else { // If the reason is defined within the language file, we will use the localized version, else just use the database entry... $disapprove_reason = (strtolower($row['reason_title']) != 'other') ? ((isset($user->lang['report_reasons']['DESCRIPTION'][strtoupper($row['reason_title'])])) ? $user->lang['report_reasons']['DESCRIPTION'][strtoupper($row['reason_title'])] : $row['reason_description']) : ''; $disapprove_reason .= ($reason) ? "\n\n" . $reason : ''; if (isset($user->lang['report_reasons']['DESCRIPTION'][strtoupper($row['reason_title'])])) { $disapprove_reason_lang = strtoupper($row['reason_title']); } } } $post_info = phpbb_get_post_data($post_id_list, 'm_approve'); $is_disapproving = false; foreach ($post_info as $post_id => $post_data) { if ($post_data['post_visibility'] == ITEM_DELETED) { continue; } $is_disapproving = true; } if (confirm_box(true)) { $disapprove_log = $disapprove_log_topics = $disapprove_log_posts = array(); $topic_posts_unapproved = $post_disapprove_list = $topic_information = array(); // Build a list of posts to be disapproved and get the related topics real replies count foreach ($post_info as $post_id => $post_data) { $post_disapprove_list[$post_id] = $post_data['topic_id']; if (!isset($topic_posts_unapproved[$post_data['topic_id']])) { $topic_information[$post_data['topic_id']] = $post_data; $topic_posts_unapproved[$post_data['topic_id']] = 0; } $topic_posts_unapproved[$post_data['topic_id']]++; } // Now we build the log array foreach ($post_disapprove_list as $post_id => $topic_id) { // If the count of disapproved posts for the topic is equal // to the number of unapproved posts in the topic, and there are no different // posts, we disapprove the hole topic if ($topic_information[$topic_id]['topic_posts_approved'] == 0 && $topic_information[$topic_id]['topic_posts_softdeleted'] == 0 && $topic_information[$topic_id]['topic_posts_unapproved'] == $topic_posts_unapproved[$topic_id]) { // Don't write the log more than once for every topic if (!isset($disapprove_log_topics[$topic_id])) { // Build disapproved topics log $disapprove_log_topics[$topic_id] = array( 'type' => 'topic', 'post_subject' => $post_info[$post_id]['topic_title'], 'forum_id' => $post_info[$post_id]['forum_id'], 'topic_id' => 0, // useless to log a topic id, as it will be deleted 'post_username' => ($post_info[$post_id]['poster_id'] == ANONYMOUS && !empty($post_info[$post_id]['post_username'])) ? $post_info[$post_id]['post_username'] : $post_info[$post_id]['username'], ); } } else { // Build disapproved posts log $disapprove_log_posts[] = array( 'type' => 'post', 'post_subject' => $post_info[$post_id]['post_subject'], 'forum_id' => $post_info[$post_id]['forum_id'], 'topic_id' => $post_info[$post_id]['topic_id'], 'post_username' => ($post_info[$post_id]['poster_id'] == ANONYMOUS && !empty($post_info[$post_id]['post_username'])) ? $post_info[$post_id]['post_username'] : $post_info[$post_id]['username'], ); } } // Get disapproved posts/topics counts separately $num_disapproved_topics = sizeof($disapprove_log_topics); $num_disapproved_posts = sizeof($disapprove_log_posts); // Build the whole log $disapprove_log = array_merge($disapprove_log_topics, $disapprove_log_posts); // Unset unneeded arrays unset($post_data, $disapprove_log_topics, $disapprove_log_posts); // Let's do the job - delete disapproved posts if (sizeof($post_disapprove_list)) { if (!function_exists('delete_posts')) { include($phpbb_root_path . 'includes/functions_admin.' . $phpEx); } // We do not check for permissions here, because the moderator allowed approval/disapproval should be allowed to delete the disapproved posts // Note: function delete_posts triggers related forums/topics sync, // so we don't need to call update_post_information later and to adjust real topic replies or forum topics count manually delete_posts('post_id', array_keys($post_disapprove_list)); foreach ($disapprove_log as $log_data) { if ($is_disapproving) { $l_log_message = ($log_data['type'] == 'topic') ? 'LOG_TOPIC_DISAPPROVED' : 'LOG_POST_DISAPPROVED'; $phpbb_log->add('mod', $user->data['user_id'], $user->ip, $l_log_message, false, array( 'forum_id' => $log_data['forum_id'], 'topic_id' => $log_data['topic_id'], $log_data['post_subject'], $disapprove_reason, $log_data['post_username'] )); } else { $l_log_message = ($log_data['type'] == 'topic') ? 'LOG_DELETE_TOPIC' : 'LOG_DELETE_POST'; $phpbb_log->add('mod', $user->data['user_id'], $user->ip, $l_log_message, false, array( 'forum_id' => $log_data['forum_id'], 'topic_id' => $log_data['topic_id'], $log_data['post_subject'], $log_data['post_username'] )); } } } /* @var $phpbb_notifications \phpbb\notification\manager */ $phpbb_notifications = $phpbb_container->get('notification_manager'); $lang_reasons = array(); foreach ($post_info as $post_id => $post_data) { $disapprove_all_posts_in_topic = $topic_information[$topic_id]['topic_posts_approved'] == 0 && $topic_information[$topic_id]['topic_posts_softdeleted'] == 0 && $topic_information[$topic_id]['topic_posts_unapproved'] == $topic_posts_unapproved[$topic_id]; $phpbb_notifications->delete_notifications('notification.type.post_in_queue', $post_id); // Do we disapprove the whole topic? Remove potential notifications if ($disapprove_all_posts_in_topic) { $phpbb_notifications->delete_notifications('notification.type.topic_in_queue', $post_data['topic_id']); } // Notify Poster? if ($notify_poster) { if ($post_data['poster_id'] == ANONYMOUS) { continue; } $post_data['disapprove_reason'] = ''; if (isset($disapprove_reason_lang)) { // Okay we need to get the reason from the posters language if (!isset($lang_reasons[$post_data['user_lang']])) { // Assign the current users translation as the default, this is not ideal but getting the board default adds another layer of complexity. $lang_reasons[$post_data['user_lang']] = $user->lang['report_reasons']['DESCRIPTION'][$disapprove_reason_lang]; // Only load up the language pack if the language is different to the current one if ($post_data['user_lang'] != $user->lang_name && file_exists($phpbb_root_path . '/language/' . $post_data['user_lang'] . '/mcp.' . $phpEx)) { // Load up the language pack $lang = array(); @include($phpbb_root_path . '/language/' . basename($post_data['user_lang']) . '/mcp.' . $phpEx); // If we find the reason in this language pack use it if (isset($lang['report_reasons']['DESCRIPTION'][$disapprove_reason_lang])) { $lang_reasons[$post_data['user_lang']] = $lang['report_reasons']['DESCRIPTION'][$disapprove_reason_lang]; } unset($lang); // Free memory } } $post_data['disapprove_reason'] = $lang_reasons[$post_data['user_lang']]; $post_data['disapprove_reason'] .= ($reason) ? "\n\n" . $reason : ''; } if ($disapprove_all_posts_in_topic && $topic_information[$topic_id]['topic_posts_unapproved'] == 1) { // If there is only 1 post when disapproving the topic, // we send the user a "disapprove topic" notification... $phpbb_notifications->add_notifications('notification.type.disapprove_topic', $post_data); } else { // ... otherwise there are multiple unapproved posts and // all of them are disapproved as posts. $phpbb_notifications->add_notifications('notification.type.disapprove_post', $post_data); } } } if ($num_disapproved_topics) { $success_msg = ($num_disapproved_topics == 1) ? 'TOPIC' : 'TOPICS'; } else { $success_msg = ($num_disapproved_posts == 1) ? 'POST' : 'POSTS'; } if ($is_disapproving) { $success_msg .= '_DISAPPROVED_SUCCESS'; } else { $success_msg .= '_DELETED_SUCCESS'; } // If we came from viewtopic, we try to go back to it. if (strpos($redirect, $phpbb_root_path . 'viewtopic.' . $phpEx) === 0) { if ($num_disapproved_topics == 0) { // So we need to remove the post id part from the Url $redirect = str_replace("&p={$post_id_list[0]}#p{$post_id_list[0]}", '', $redirect); } else { // However this is only possible if the topic still exists, // Otherwise we go back to the viewforum page $redirect = append_sid($phpbb_root_path . 'viewforum.' . $phpEx, 'f=' . $request->variable('f', 0)); } } /** * Perform additional actions during post(s) disapproval * * @event core.disapprove_posts_after * @var array post_info Array containing info for all posts being disapproved * @var array topic_information Array containing information for the topics * @var array topic_posts_unapproved Array containing list of topic ids and the count of disapproved posts in them * @var array post_disapprove_list Array containing list of posts and their topic id * @var int num_disapproved_topics Variable containing the number of disapproved topics * @var int num_disapproved_posts Variable containing the number of disapproved posts * @var array lang_reasons Array containing the language keys for reasons * @var string disapprove_reason Variable containing the language key for the success message * @var string disapprove_reason_lang Variable containing the language key for the success message * @var bool is_disapproving Variable telling if anything is going to be disapproved * @var bool notify_poster Variable telling if the post should be notified or not * @var string success_msg Variable containing the language key for the success message * @var string redirect Variable containing the redirect url * @since 3.1.4-RC1 */ $vars = array( 'post_info', 'topic_information', 'topic_posts_unapproved', 'post_disapprove_list', 'num_disapproved_topics', 'num_disapproved_posts', 'lang_reasons', 'disapprove_reason', 'disapprove_reason_lang', 'is_disapproving', 'notify_poster', 'success_msg', 'redirect', ); extract($phpbb_dispatcher->trigger_event('core.disapprove_posts_after', compact($vars))); unset($lang_reasons, $post_info, $disapprove_reason, $disapprove_reason_lang); meta_refresh(3, $redirect); $message = $user->lang[$success_msg]; if ($request->is_ajax()) { $json_response = new \phpbb\json_response; $json_response->send(array( 'MESSAGE_TITLE' => $user->lang['INFORMATION'], 'MESSAGE_TEXT' => $message, 'REFRESH_DATA' => null, 'visible' => false, )); } $message .= '

' . $user->lang('RETURN_PAGE', '', ''); trigger_error($message); } else { $show_notify = false; foreach ($post_info as $post_data) { if ($post_data['poster_id'] == ANONYMOUS) { continue; } else { $show_notify = true; break; } } $l_confirm_msg = 'DISAPPROVE_POST'; $confirm_template = 'mcp_approve.html'; if ($is_disapproving) { $phpbb_container->get('phpbb.report.report_reason_list_provider')->display_reasons($reason_id); } else { $user->add_lang('posting'); $l_confirm_msg = 'DELETE_POST_PERMANENTLY'; $confirm_template = 'confirm_delete_body.html'; } $l_confirm_msg .= ((sizeof($post_id_list) == 1) ? '' : 'S'); $template->assign_vars(array( 'S_NOTIFY_POSTER' => $show_notify, 'S_APPROVE' => false, 'REASON' => ($is_disapproving) ? $reason : '', 'ADDITIONAL_MSG' => $additional_msg, )); confirm_box(false, $l_confirm_msg, $s_hidden_fields, $confirm_template); } redirect($redirect); } } a id='n1357' href='#n1357'>1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392
package detect_devices; # $Id: detect_devices.pm 267151 2010-03-30 14:27:41Z blino $

use diagnostics;
use strict;
use vars qw($pcitable_addons $usbtable_addons);

#-######################################################################################
#- misc imports
#-######################################################################################
use log;
use MDK::Common; # help perl_checker
use common;
use devices;
use run_program;
use modules;
use c;
use feature 'state';

#-#####################################################################################
#- Globals
#-#####################################################################################
my %serialprobe;

#-######################################################################################
#- Functions
#-######################################################################################

sub get() {
    #- Detect the default BIOS boot harddrive is kind of tricky. We may have IDE,
    #- SCSI and RAID devices on the same machine. From what I see so far, the default
    #- BIOS boot harddrive will be
    #- 1. The first IDE device if IDE exists. Or
    #- 2. The first SCSI device if SCSI exists. Or
    #- 3. The first RAID device if RAID exists.

    getIDE(), getSCSI(), getXenBlk(), getVirtIO(), getDAC960(), getCompaqSmartArray(), getATARAID();
}
sub hds()         { grep { may_be_a_hd($_) } get() }
sub tapes()       { grep { $_->{media_type} eq 'tape' } get() }
sub cdroms()      { grep { $_->{media_type} eq 'cdrom' } get() }
sub burners()     { grep { isBurner($_) } cdroms() }
sub dvdroms()     { grep { isDvdDrive($_) } cdroms() }
sub raw_zips()    { grep { member($_->{media_type}, 'fd', 'hd') && isZipDrive($_) } get() }
sub ls120s()      { grep { member($_->{media_type}, 'fd', 'hd') && isLS120Drive($_) } get() }
sub zips()        {
    map { 
	$_->{device} .= 4; 
	$_;
    } raw_zips();
}

sub floppies {
    my ($o_not_detect_legacy_floppies) = @_;
    require modules;
    state @fds;
    state $legacy_already_detected;

    $o_not_detect_legacy_floppies = 1 if arch() =~ /mips|arm/;

    if (!$o_not_detect_legacy_floppies && !$legacy_already_detected) {
        $legacy_already_detected = 1;
        eval { modules::load("floppy") if $::isInstall };
        #- do not bother probing /dev/fd0 and loading floppy device uselessly,
        #- it takes time and it is already done by boot process (if not in install):
        #-   /dev/fd0 is created by start_udev (/etc/udev/devices.d/default.nodes)
        #-   then hal probes /dev/fd0 and triggers floppy module loading through kernel's kmod
        if (any { (split)[1] eq 'fd' } cat_("/proc/devices")) {
            @fds = map {
                my $info = c::floppy_info(devices::make("fd$_"));
                if_($info && $info ne '(null)', { device => "fd$_", media_type => 'fd', info => $info });
            } qw(0 1);
        }
    }
        
    my @ide = ls120s() and eval { modules::load("ide_floppy") };

    eval { modules::load("usb_storage") } if $::isInstall && usbStorage();
    my @scsi = grep { $_->{media_type} eq 'fd' } getSCSI();
    @ide, @scsi, @fds;
}
sub floppies_dev() { map { $_->{device} } floppies() }
sub floppy() { first(floppies_dev()) }
#- example ls120, model = "LS-120 SLIM 02 UHD Floppy"

sub removables() {
    floppies(), cdroms(), zips();
}

sub get_sys_cdrom_info {
    my (@drives) = @_;

    my @drives_order;
    foreach (cat_("/proc/sys/dev/cdrom/info")) {
	my ($t, $l) = split ':';
	my @l;
	@l = split(' ', $l) if $l;
	if ($t eq 'drive name') {
	    @drives_order = map {
		my $dev = $_;
		find { $_->{device} eq $dev } @drives;
	    } @l;
	} else {
	    my $capacity;
	    if ($t eq 'Can write CD-R') {
		$capacity = 'burner';
	    } elsif ($t eq 'Can read DVD') {
		$capacity = 'DVD';
	    }
	    if ($capacity) {
		each_index {
		    ($drives_order[$::i] || {})->{capacity} .= "$capacity " if $_;
		} @l;
	    }
	}
    }
}

sub complete_usb_storage_info {
    my (@l) = @_;

    my @usb = grep { exists $_->{usb_vendor} } @l;

    foreach my $usb (usb_probe()) {
	if (my $e = find { !$_->{found} && $_->{usb_vendor} == $usb->{vendor} && $_->{usb_id} == $usb->{id} } @usb) {
         my $host = get_sysfs_usbpath_for_block($e->{device});
         if ($host) {
             my $file = "/sys/block/$host/../serial";
             $e->{info} = chomp_(cat_($file)) if -e $file;
             $e->{usb_description} = join('|', 
                                          chomp_(cat_("/sys/block/$host/../manufacturer")),
                                          chomp_(cat_("/sys/block/$host/../product")));
         }
         local $e->{found} = 1;
	    $e->{"usb_$_"} ||= $usb->{$_} foreach keys %$usb;
	}
    }
}

sub isBurner { 
    my ($e) = @_;
    $e->{capacity} =~ /burner/ and return 1;
      
    #- do not work for SCSI
    my $f = tryOpen($e->{device}); #- SCSI burner are not detected this way.
    $f && c::isBurner(fileno($f));
}
sub isDvdDrive {
    my ($e) = @_;
    $e->{capacity} =~ /DVD/ || $e->{info} =~ /DVD/ and return 1;

    #- do not work for SCSI
    my $f = tryOpen($e->{device});
    $f && c::isDvdDrive(fileno($f));
}
sub isZipDrive { $_[0]{info} =~ /ZIP\s+\d+/ } #- accept ZIP 100, untested for bigger ZIP drive.
sub isLS120Drive { $_[0]{info} =~ /LS-?120|144MB/ }
sub isKeyUsb { begins_with($_[0]{usb_media_type} || '', 'Mass Storage') && $_[0]{media_type} eq 'hd' }
sub isFloppyUsb { $_[0]{usb_driver} && $_[0]{usb_driver} eq 'Removable:floppy' }
sub may_be_a_hd { 
    my ($e) = @_;
    $e->{media_type} eq 'hd' && !(
	isZipDrive($e) 
           || isLS120Drive($e)
           || begins_with($e->{usb_media_type} || '', 'Mass Storage|Floppy (UFI)')
    );
}

sub get_sysfs_field_from_link {
    my ($device, $field) = @_;
    my $l = readlink("$device/$field");
    $l =~ s!.*/!!;
    $l;
}

sub get_sysfs_usbpath_for_block {
    my ($device) = @_;
    my $host = readlink("/sys/block/$device");
    $host =~ s!/host.*!!;
    $host;
}

sub get_scsi_driver {
    my (@l) = @_;
    # find driver of host controller from sysfs:
    foreach (@l) {
	next if $_->{driver};
	my $host = get_sysfs_usbpath_for_block($_->{device});
	require list_modules;
	$_->{driver} = list_modules::filename2modname(get_sysfs_field_from_link("/sys/block/$host", 'driver'));
    }
}

sub getSCSI() {
    my $dev_dir = '/sys/bus/scsi/devices';

    my @scsi_types = (
	"Direct-Access",
	"Sequential-Access",
	"Printer",
	"Processor",
	"WORM",
	"CD-ROM",
	"Scanner",
	"Optical Device",
	"Medium Changer",
	"Communications",
    );

    my @l;
    foreach (all($dev_dir)) {
	my ($host, $channel, $id, $lun) = split ':';
	defined $lun or next;

	my $dir = "$dev_dir/$_";

	# handle both old and new kernels:
	my $node =  find { -e $_ } "$dir/block", top(glob_("$dir/block*")), "$dir/tape", top(glob_("$dir/scsi_generic*"));
	my ($device) = readlink($node) =~ m!/(?:scsi_(?:generic|tape)|block)/(.*)!;
        if (!$device) {
            ($device) = top(glob_("$node/*")) =~ m!/(?:scsi_(?:generic|tape)|block)/(.*)!;
        }
	warn("cannot get info for device ($_)"), next if !$device;

	my $usb_dir = readlink($dir) =~ m!/usb! && "$dir/../../../..";
	my $get_usb = sub { chomp_(cat_("$usb_dir/$_[0]")) };

	my $get = sub {
	    my $s = cat_("$dir/$_[0]");
	    $s =~ s/\s+$//;
	    $s;
	};

	# Old hp scanners report themselves as "Processor"s
	# (see linux/include/scsi/scsi.h and sans-find-scanner.1)
	my $raw_type = $scsi_types[$get->('type')];

	my $media_type = ${{ st => 'tape', sr => 'cdrom', sd => 'hd', sg => 'generic' }}{substr($device, 0, 2)} ||
	  $raw_type =~ /Scanner|Processor/ && 'scanner';

	my ($vendor, $model) = ($get->('vendor'), $get->('model'));
	my ($v, $m) = _get_hd_vendor($model);
	if ($v && $m) {
            ($vendor, $model) = ($v, $m);
	}
	push @l, { info =>  $vendor . ' ' . $model, host => $host, channel => $channel, id => $id, lun => $lun, 
	  description => join('|', $vendor, $model),
	  bus => 'SCSI', media_type => $media_type, device => $device,
	    $usb_dir ? (
	  usb_vendor => hex($get_usb->('idVendor')), usb_id => hex($get_usb->('idProduct')),
	    ) : (),
        };
    } 

    @l = sort { $a->{host} <=> $b->{host} || $a->{channel} <=> $b->{channel} || $a->{id} <=> $b->{id} || $a->{lun} <=> $b->{lun} } @l;

    complete_usb_storage_info(@l);

    foreach (@l) {
	$_->{media_type} = 'fd' if $_->{media_type} eq 'hd' && isFloppyUsb($_);
    }

    get_sys_cdrom_info(@l);
    get_scsi_driver(@l);
    @l;
}


my %hd_vendors = (
    "ASUS" => "Asus",
    "ATA Maxtor" => "Maxtor",
    "CD-ROM CDU" => "Sony",
    "CD-ROM Drive/F5D" => "ASUSTeK",
    "Compaq" => "Compaq",
    "CONNER" => "Conner Peripherals",
    "IBM" => "IBM",
    "FUJITSU" => "Fujitsu",
    "HITACHI" => "Hitachi",
    "Lite-On" => "Lite-On Technology Corp.",
    "LITE-ON" => "Lite-On Technology Corp.",
    "LTN" => "Lite-On Technology Corp.",
    "IOMEGA" => "Iomega",
    "MAXTOR" => "Maxtor",
    "Maxtor" => "Maxtor",
    "Micropolis" => "Micropolis",
    "Pioneer" => "Pioneer",
    "PLEXTOR" => "Plextor",
    "QUANTUM" => "Quantum", 
    "SAMSUNG" => "Samsung",
    "Seagate " => "Seagate Technology",
    "ST3" => "Seagate Technology",
    "TEAC" => "Teac",
    "TOSHIBA" => "Toshiba",
    "WDC" => "Western Digital Corp.",
);

# return ($vendor, $model)
sub _get_hd_vendor {
    my ($info) = @_;
    foreach my $name (keys %hd_vendors) {
        next if !$name;
        return ($hd_vendors{$name}, $2) if $info =~ /^$name(-|\s)*(.*)/;
    }
    return ("Hitachi", $info) if $info =~ /^HD[ST][0-9]/;
}


sub getIDE() {
    my @idi;

    #- what about a system with absolutely no IDE on it, like some sparc machine.
    -e "/proc/ide" or return ();

    #- Great. 2.2 kernel, things are much easier and less error prone.
    foreach my $d (sort @{[glob_('/proc/ide/hd*')]}) {
	cat_("$d/driver") =~ /ide-scsi/ and next; #- already appears in /proc/scsi/scsi
	my $t = chomp_(cat_("$d/media"));
	my $type = ${{ disk => 'hd', cdrom => 'cdrom', tape => 'tape', floppy => 'fd' }}{$t} or next;
	my $info = chomp_(cat_("$d/model")) || "(none)";

	my $num = ord(($d =~ /(.)$/)[0]) - ord 'a';
	my ($vendor, $model) = _get_hd_vendor($info);

	my $host = $num;
	($host, my $id) = divide($host, 2);
	($host, my $channel) = divide($host, 2);

	push @idi, { media_type => $type, device => basename($d), 
		     info => $info, host => $host, channel => $channel, id => $id, bus => 'ide', 
		     if_($vendor, Vendor => $vendor), if_($model, Model => $model) };
    }
    get_sys_cdrom_info(@idi);
    @idi;
}

sub block_devices() {
    -d '/sys/block' 
      ? map { s|!|/|; $_ } all('/sys/block') 
      : map { $_->{dev} } do { require fs::proc_partitions; fs::proc_partitions::read_raw() };
}

sub getCompaqSmartArray() {
    my (@idi, $f);

    foreach ('array/ida', 'cpqarray/ida', 'cciss/cciss') {
	my $prefix = "/proc/driver/$_";
	my ($name) = m|/(.*)|;
	for (my $i = 0; -r ($f = "${prefix}$i"); $i++) {
	    my @raw_devices = cat_($f) =~ m|^\s*($name/.*?):|gm;

	    #- this is ugly and buggy. keeping it for 2007.0
	    #- on a cciss, cciss/cciss0 didn't contain c0d0, but cciss/cciss1 did contain c0d1
	    #- the line below adds both c0d0 and c0d1 for cciss0, and so some duplicates
	    @raw_devices or @raw_devices = grep { m!^$name/! } block_devices();

	    foreach my $raw_device (@raw_devices) {
		my $device = -d "/dev/$raw_device" ? "$raw_device/disc" : $raw_device;
		push @idi, { device => $device, prefix => $raw_device . 'p', 
			     info => "Compaq RAID logical disk",
			     media_type => 'hd', bus => $name };
	    }
	}
    }
    #- workaround the buggy code above. this should be safe though
    uniq_ { $_->{device} } @idi;
}

sub getDAC960() {
    my %idi;

    #- We are looking for lines of this format:DAC960#0:
    #- /dev/rd/c0d0: RAID-7, Online, 17928192 blocks, Write Thru0123456790123456789012
    foreach (syslog()) {
	my ($device, $info) = m|/dev/(rd/.*?): (.*?),| or next;
	$idi{$device} = { info => $info, media_type => 'hd', device => $device, bus => 'dac960' };
    }
    values %idi;
}

sub getATARAID() {
    my %l;
    foreach (syslog()) {
	my ($device) = m|^\s*(ataraid/d\d+):| or next;
	$l{$device} = { info => 'ATARAID block device', media_type => 'hd', device => $device, bus => 'ataraid' };
	log::l("ATARAID: $device");
    }
    values %l;
}

sub getXenBlk() {
    -d '/sys/bus/xen/devices' or return;
    map {   
            s/block://;
            { device => basename($_), info => "Xen block device", media_type => 'xvd', bus => 'xen' };
    } glob("/sys/bus/xen/devices/*/block*");
}

sub getVirtIO() {
    -d '/sys/bus/virtio/devices' or return;
    map {
            { device => basename($_), info => "VirtIO block device", media_type => 'hd', bus => 'virtio' };
    }
    glob("/sys/bus/virtio/devices/*/block/*");
}

# cpu_name : arch() =~ /^alpha/ ? "cpu	" :
# arch() =~ /^ppc/ ? "processor" : "vendor_id"

# cpu_model : arch() =~ /^alpha/ ? "cpu model" :
# arch() =~ /^ppc/ ? "cpu  " : "model name"

# cpu_freq = arch() =~ /^alpha/ ? "cycle frequency [Hz]" :
# arch() =~ /^ppc/ ? "clock" : "cpu MHz"

sub getCPUs() { 
    my (@cpus, $cpu);
    foreach (cat_("/proc/cpuinfo")) {
	   if (/^processor/) { # ix86 specific
		  push @cpus, $cpu if $cpu;
		  $cpu = {};
	   }
	   $cpu->{$1} = $2 if /^([^\t]+).*:\s(.*)$/;
	   $cpu->{processor}++ if $1 eq "processor";
    }
    push @cpus, $cpu;
    @cpus;
}

sub ix86_cpu_frequency() {
    cat_('/proc/cpuinfo') =~ /cpu MHz\s*:\s*(\d+)/ && $1;
}

sub probe_category {
    my ($category) = @_;

    require list_modules;
    my @modules = list_modules::category2modules($category);

    if_($category =~ /sound/ && arch() =~ /ppc/ && get_mac_model() !~ /IBM/,
	{ driver => 'snd_powermac', description => 'Macintosh built-in' },
    ),
    grep {
	if ($category eq 'network/isdn') {
	    my $b = $_->{driver} =~ /ISDN:([^,]*),?([^,]*)(?:,firmware=(.*))?/;
	    if ($b) {
                $_->{driver} = $1;
                $_->{type} = $2;
                $_->{type} =~ s/type=//;
                $_->{firmware} = $3;
                $_->{driver} eq "hisax" and $_->{options} .= " id=HiSax";
	    }
	    $b;
	} else {
	    member($_->{driver}, @modules);
	}
    } probeall();
}

sub getSoundDevices() {
    probe_category('multimedia/sound');
}

sub isTVcardConfigurable { member($_[0]{driver}, qw(bttv cx88 saa7134)) }

sub getTVcards() { probe_category('multimedia/tv') }

sub getInputDevices() {
    my (@devices, $device);
    my $event;
    foreach (cat_('/proc/bus/input/devices')) {
        if (/^I:/) {
            $device = {};
            $device->{vendor} = /Vendor=(\w+)/ && $1;
            $device->{id} = /Product=(\w+)/ && $1;
            $device->{bustype} = /Bus=(\w+)/ && $1;
        } elsif (/N: Name="(.*)"/) {
	    my $descr = $1;
	    $device->{description} = "|$descr";

	    #- I: Bus=0011 Vendor=0002 Product=0008 Version=7321
	    #- N: Name="AlpsPS/2 ALPS GlidePoint"
	    #- P: Phys=isa0060/serio1/input0
	    #- H: Handlers=mouse1 event2 ts1
	    #- B: EV=f
	    #- B: KEY=420 0 70000 0 0 0 0 0 0 0 0 #=> BTN_LEFT BTN_RIGHT BTN_MIDDLE BTN_TOOL_FINGER BTN_TOUCH
	    #-    or B: KEY=420 0 670000 0 0 0 0 0 0 0 0 #=> same with BTN_BACK
	    #- B: REL=3       #=> X Y
	    #- B: ABS=1000003 #=> X Y PRESSURE

	    #- I: Bus=0011 Vendor=0002 Product=0008 Version=2222
	    #- N: Name="AlpsPS/2 ALPS DualPoint TouchPad"
	    #- P: Phys=isa0060/serio1/input0
	    #- S: Sysfs=/class/input/input2
	    #- H: Handlers=mouse1 ts1 event2 
	    #- B: EV=f
	    #- B: KEY=420 0 70000 0 0 0 0 0 0 0 0
	    #- B: REL=3
	    #- B: ABS=1000003

	    #- I: Bus=0011 Vendor=0002 Product=0007 Version=0000
	    #- N: Name="SynPS/2 Synaptics TouchPad"
	    #- P: Phys=isa0060/serio1/input0
	    #- S: Sysfs=/class/input/input1
	    #- H: Handlers=mouse0 event1 ts0
	    #- B: EV=b
	    #- B: KEY=6420 0 70000 0 0 0 0 0 0 0 0 #=> BTN_LEFT BTN_RIGHT BTN_MIDDLE BTN_TOOL_FINGER BTN_TOUCH BTN_TOOL_DOUBLETAP BTN_TOOL_TRIPLETAP
	    #-    or B: KEY=6420 0 670000 0 0 0 0 0 0 0 0  #=> same with BTN_BACK
	    #-    or B: KEY=420 30000 670000 0 0 0 0 0 0 0 0 #=> same without BTN_TOOL_TRIPLETAP but with BTN_B
	    #- B: ABS=11000003 #=> X Y PRESSURE TOOL_WIDTH

	    #- I: Bus=0003 Vendor=056a Product=0065 Version=0108
	    #- N: Name="Wacom Bamboo"
	    #- B: KEY=1c63 0 70033 0 0 0 0 0 0 0 0 #=> BTN_0 BTN_1 BTN_4 BTN_5 BTN_LEFT BTN_RIGHT BTN_MIDDLE TOOL_PEN TOOL_RUBBER TOOL_BRUSH TOOL_FINGER TOOL_MOUSE TOUCH STYLUS STYLUS2
            #- B: ABS=100 3000103 #=> X Y WHEEL PRESSURE DISTANCE MISC

	    #- I: Bus=0003 Vendor=056a Product=0011 Version=0201
	    #- N: Name="Wacom Graphire2 4x5"
            #- B: KEY=1c43 0 70000 0 0 0 0 0 0 0 0 #=> BTN_LEFT BTN_RIGHT BTN_MIDDLE TOOL_PEN TOOL_RUBBER TOOL_FINGER TOOL_MOUSE TOUCH STYLUS STYLUS2
            #- B: ABS=100 3000003 #=> X Y PRESSURE DISTANCE MISC

            #I: Bus=0003 Vendor=049f Product=0024 Version=0001
	    #N: Name="Compaq Compaq Numeric Keypad"
	    #P: Phys=usb-0000:00:03.2-2/input0
	    #S: Sysfs=/class/input/input7
	    #H: Handlers=kbd event3
	    #B: EV=120003
	    #B: KEY=10000 7 ff800000 7ff febeffdf ffefffff ffffffff fffffffe
	    #B: LED=1f

	    $device->{Synaptics} = $descr eq 'SynPS/2 Synaptics TouchPad';
	    $device->{ALPS} = $descr =~ m!^AlpsPS/2 ALPS!;
	    $device->{Elantech} = $descr eq 'ETPS/2 Elantech Touchpad';
	    $device->{Numpad} = $descr =~ /Numeric Keypad/;

	} elsif (/H: Handlers=(.*)/) {
	    my @l = split(' ', $1);
	    $device->{driver} = $l[0]; #- keep it for compatibility
	    $device->{Handlers} = +{ map { (/^(.*?)\d*$/ ? $1 : $_, $_) } split(' ', $1) };
	    $event = $device->{Handlers}{event};
	} elsif (/S: Sysfs=(.+)/) {
	    $device->{sysfs_path} = $1;
	} elsif (/P: Phys=(.*)/) {
            $device->{location} = $1;
            $device->{bus} = 'isa' if $device->{location} =~ /^isa/;
            $device->{bus} = 'usb' if $device->{location} =~ /^usb/i;
	} elsif (/B: REL=(.* )?(.*)/) {
	    #- REL=3   #=> X Y
	    #- REL=103 #=> X Y WHEEL
	    #- REL=143 #=> X Y HWHEEL WHEEL
	    #- REL=1c3 #=> X Y HWHEEL DIAL WHEEL
	    my $REL = hex($2);
	    $device->{HWHEEL} = 1 if $REL & (1 << 6);
	    $device->{WHEEL} = 1 if $REL & (1 << 8); #- not reliable ("Mitsumi Apple USB Mouse" says REL=103 and KEY=1f0000 ...)

	} elsif (/B: KEY=(\S+)/) {	   
	    #- some KEY explained:
	    #- (but note that BTN_MIDDLE can be reported even if missing)
	    #- (and "Mitsumi Apple USB Mouse" reports 1f0000)
	    #- KEY=30000 0 0 0 0 0 0 0 0  #=> BTN_LEFT BTN_RIGHT
	    #- KEY=70000 0 0 0 0 0 0 0 0  #=> BTN_LEFT BTN_RIGHT BTN_MIDDLE
	    #- KEY=1f0000 0 0 0 0 0 0 0 0 #=> BTN_LEFT BTN_RIGHT BTN_MIDDLE BTN_SIDE BTN_EXTRA
	    if (! -f "/dev/input/$event") {
		    devices::make("/dev/input/$event");
	    }
	    my @KEYS = c::EVIocGBitKey("/dev/input/$event");
	    $device->{SIDE} = 1 if $KEYS[0] & (1 << 0x13);

        } elsif (/^\s*$/) {
	    push @devices, $device if $device;
	    undef $device;
	}
    }
    @devices;
}

sub getInputDevices_and_usb() {
    my @l = getInputDevices();

    foreach my $usb (usb_probe()) {
	if (my $e = find { hex($_->{vendor}) == $usb->{vendor} && hex($_->{id}) == $usb->{id} } @l) {
	    $e->{usb} = $usb;
	}
    }

    @l;
}

sub serialPorts() { map { "ttyS$_" } 0..7 }
sub serialPort2text {
    $_[0] =~ /ttyS(\d+)/ ? "$_[0] / COM" . ($1 + 1) : $_[0];
}

sub getSerialModem {
    my ($modules_conf, $o_mouse) = @_;
    my $mouse = $o_mouse || {};
    $mouse->{device} = readlink "/dev/mouse";
    my $serdev = arch() =~ /ppc/ ? "macserial" : arch() =~ /mips/ ? "8250" : "serial";

    eval { modules::load($serdev) };

    my @modems;

    probeSerialDevices();
    foreach my $port (serialPorts()) {
	next if $mouse->{device} =~ /$port/;
     my $device = "/dev/$port";
	next if !-e $device || !hasModem($device);
     $serialprobe{$device}{device} = $device;
     push @modems, $serialprobe{$device};
    }
    my @devs = pcmcia_probe();
    foreach my $modem (@modems) {
        #- add an alias for macserial on PPC
        $modules_conf->set_alias('serial', $serdev) if arch() =~ /ppc/ && $modem->{device};
        foreach (@devs) { $_->{device} and $modem->{device} = $_->{device} }
    }
    @modems;
}

our $detect_serial_modem = 1;
sub getModem {
    my ($modules_conf) = @_;
    ($detect_serial_modem ? getSerialModem($modules_conf, {}) : ()), get_winmodems();
}

sub get_winmodems() {
    matching_driver__regexp('www\.linmodems\.org'),
    matching_driver(list_modules::category2modules('network/modem'),
    list_modules::category2modules('network/slmodem'));
}

sub getBewan() {
    matching_desc__regexp('Bewan Systems\|.*ADSL|BEWAN ADSL USB|\[Unicorn\]');
}

# generate from the following from eci driver sources:
# perl -e 'while (<>) { print qq("$1$2",\n"$3$4",\n) if /\b([a-z\d]*)\s*([a-z\d]*)\s*([a-z\d]*)\s*([a-z\d]*)$/ }' <modems.db|sort|uniq
sub getECI() {
    my @ids = (
              "05090801",
              "05472131",
              "06590915",
              "071dac81",
              "08ea00c9",
              "09150001",
              "09150002",
              "091500ca",
              "091500e7",
              "09150101",
              "09150102",
              "09150204",
              "09150206",
              "09150802",
              "09150916",
              "09158000",
              "09158001",
              "0915ac82",
              "0baf00e6",
              "0e600100",
              "0e600101",
              "0fe88000",
              "16900203",
              "16900205",
             );
    grep { member(sprintf("%04x%04x%04x%04x", $_->{vendor}, $_->{id}, $_->{subvendor}, $_->{subid}), @ids) } usb_probe();
}

sub get_xdsl_usb_devices() {
    my @bewan = detect_devices::getBewan();
    $_->{driver} = $_->{bus} eq 'USB' ? 'unicorn_usb_atm' : 'unicorn_pci_atm' foreach @bewan;
    my @eci = detect_devices::getECI();
    $_->{driver} = 'eciusb' foreach @eci;
    my @usb = detect_devices::probe_category('network/usb_dsl');
    $_->{description} = "USB ADSL modem (eagle chipset)" foreach
      grep { $_->{driver} eq 'ueagle_atm' && $_->{description} eq '(null)' } @usb;
    @usb, @bewan, @eci;
}

sub is_lan_interface {
    #- we want LAN like interfaces here (eg: ath|br|eth|fddi|plip|ra|tr|usb|wlan).
    #- there's also bnep%d for bluetooth, bcp%d...
    #- we do this by blacklisting the following interfaces:
    #-   hso%d are created by drivers/net/usb/hso.c
    #-   ippp|isdn|plip|ppp (initscripts suggest that isdn%d can be created but kernel sources claim not)
    #-   ippp%d are created by drivers/isdn/i4l/isdn_ppp.c
    #-   plip%d are created by drivers/net/plip.c
    #-   ppp%d are created by drivers/net/ppp_generic.c
    #-   pan%d are created by bnep
    is_useful_interface($_[0]) &&
    $_[0] !~ /^(?:hso|ippp|isdn|plip|ppp|pan)/;
}

sub is_useful_interface {
    #- sit0 which is *always* created by net/ipv6/sit.c, thus is always created since net.agent loads ipv6 module
    #- wifi%d are created by 3rdparty/hostap/hostap_hw.c (pseudo statistics devices, #14523)
    #- wmaster%d are created by net/mac80211/ieee80211.c ("master" 802.11 device)
    #- ax*, rose*, nr*, bce* and scc* are Hamradio devices (#28776)
    $_[0] !~ /^(?:lo|sit0|wifi|wmaster|ax|rose|nr|bce|scc)/;
}

sub is_wireless_interface {
    my ($interface) = @_;
    #- some wireless drivers don't always support the SIOCGIWNAME ioctl
    #-   ralink devices need to be up to support it
    #-   wlan-ng (prism2_*) need some special tweaks to support it
    #- use sysfs as fallback to detect wireless interfaces,
    #- i.e interfaces for which get_wireless_stats() is available
    c::isNetDeviceWirelessAware($interface) || -e "/sys/class/net/$interface/wireless";
}

sub get_all_net_devices() {
    #- we need both detection schemes since:
    #-   get_netdevices() use the SIOCGIFCONF ioctl that does not list interfaces that are down
    #-   /proc/net/dev does not list VLAN and IP aliased interfaces
    uniq(
        (map { if_(/^\s*([A-Za-z0-9:\.]*):/, $1) } cat_("/proc/net/dev")),
        c::get_netdevices(),
    );
}

sub get_lan_interfaces() { grep { is_lan_interface($_) } get_all_net_devices() }
sub get_net_interfaces() { grep { is_useful_interface($_) } get_all_net_devices() }
sub get_wireless_interface() { find { is_wireless_interface($_) } get_lan_interfaces() }

sub is_bridge_interface {
    my ($interface) = @_;
    -f "/sys/class/net/$interface/bridge/bridge_id";
}

sub get_ids_from_sysfs_device {
    my ($dev_path) = @_;
    my $dev_cat = sub { chomp_(cat_("$dev_path/$_[0]")) };
    my $usb_root = -f "$dev_path/bInterfaceNumber" && "../" || -f "$dev_path/idVendor" && "";
    my $is_pcmcia = -f "$dev_path/card_id";
    my $sysfs_ids;
    my $bus = get_sysfs_field_from_link($dev_path, "subsystem");
    #- FIXME: use $bus
    if ($is_pcmcia) {
      $sysfs_ids = { modalias => $dev_cat->('modalias') };
    } else {
        $sysfs_ids = $bus eq 'ieee1394' ?
          {
            version => "../vendor_id",
            specifier_id => "specifier_id",
            specifier_version => "version",
          } :
        defined $usb_root ?
          { id => $usb_root . 'idProduct', vendor => $usb_root . 'idVendor' } :
          { id => "device", subid => "subsystem_device", vendor => "vendor", subvendor => "subsystem_vendor" };
        $_ = hex($dev_cat->($_)) foreach values %$sysfs_ids;
        if ($bus eq 'pci') {
            my $device = basename(readlink $dev_path);
            my @ids = $device =~ /^(.{4}):(.{2}):(.{2})\.(.+)$/;
            @$sysfs_ids{qw(pci_domain pci_bus pci_device pci_function)} = map { hex($_) } @ids if @ids;
        }
    }
    $sysfs_ids;
}

sub device_matches_sysfs_ids {
    my ($device, $sysfs_ids) = @_;
    every { defined $device->{$_} && member($device->{$_}, $sysfs_ids->{$_}, 0xffff) } keys %$sysfs_ids;
}

sub device_matches_sysfs_device {
  my ($device, $dev_path) = @_;
  device_matches_sysfs_ids($device, get_ids_from_sysfs_device($dev_path));
}

sub getUPS() {
    # MGE serial PnP devices:
    (map {
        $_->{port} = $_->{DEVICE};
        $_->{bus} = "Serial";
        $_->{driver} = "mge-utalk" if $_->{MODEL} =~ /0001/;
        $_->{driver} = "mge-shut"  if $_->{MODEL} =~ /0002/;
        $_->{media_type} = 'UPS';
        $_->{description} = "MGE UPS SYSTEMS|UPS - Uninterruptible Power Supply" if $_->{MODEL} =~ /000[12]/;
        $_;
    } grep { $_->{DESCRIPTION} =~ /MGE UPS/ } values %serialprobe),
    # USB UPSs;
    (map { ($_->{name} = $_->{description}) =~ s/.*\|//; $_ }
        map {
            if ($_->{description} =~ /^American Power Conversion\|Back-UPS/ && $_->{driver} eq 'usbhid') {
                #- FIXME: should not be hardcoded, use $_->{sysfs_device} . */usb:(hiddev\d+)
                #- the device should also be assigned to the ups user
                $_->{port} = "/dev/hiddev0";
                $_->{driver} = 'hidups';
                $_;
            } elsif ($_->{description} =~ /^MGE UPS Systems\|/ && $_->{driver} =~ /ups$/) {
                $_->{port} = "auto";
                $_->{media_type} = 'UPS';
                $_->{driver} = 'newhidups';
                $_;
            } else {
                ();
            }
        } usb_probe());
}

$pcitable_addons = <<'EOF';
# add here lines conforming the pcitable format (0xXXXX\t0xXXXX\t"\w+"\t".*")
EOF

$usbtable_addons = <<'EOF';
# add here lines conforming the usbtable format (0xXXXX\t0xXXXX\t"\w+"\t".*")
EOF

sub install_addons {
    my ($prefix) = @_;

    #- this test means install_addons can only be called after ldetect-lst has been installed.
    if (-d "$prefix/usr/share/ldetect-lst") {
	my $update = 0;
	foreach ([ 'pcitable.d', $pcitable_addons ], [ 'usbtable.d', $usbtable_addons ]) {
	    my ($dir, $str) = @$_;
	    -d "$prefix/usr/share/ldetect-lst/$dir" && $str =~ /^[^#]/m and $update = 1 and
	      output "$prefix/usr/share/ldetect-lst/$dir/95drakx.lst", $str;
	}
	$update and run_program::rooted($prefix, "/usr/sbin/update-ldetect-lst");
    }
}

sub add_addons {
    my ($addons, @l) = @_;

    foreach (split "\n", $addons) {
	/^\s/ and die qq(bad detect_devices::probeall_addons line "$_");
	s/^#.*//;
	s/"(.*?)"/$1/g;
	next if /^$/;
	my ($vendor, $id, $driver, $description) = split("\t", $_, 4) or die qq(bad detect_devices::probeall_addons line "$_");
	foreach (@l) {
	    $_->{vendor} == hex $vendor && $_->{id} == hex $id or next;
	    put_in_hash($_, { driver => $driver, description => $description });
	}
    }
    @l;
}

sub get_pci_sysfs_path {
    my ($l) = @_;
    sprintf('%04x:%02x:%02x.%d', $l->{pci_domain}, $l->{pci_bus}, $l->{pci_device}, $l->{pci_function});
}


my (@pci, @usb);

sub pci_probe__real() {
    add_addons($pcitable_addons, map {
	my %l;
	@l{qw(vendor id subvendor subid pci_domain pci_bus pci_device pci_function pci_revision is_pciexpress media_type nice_media_type driver description)} = split "\t";
	$l{$_} = hex $l{$_} foreach qw(vendor id subvendor subid);
	$l{bus} = 'PCI';
	$l{sysfs_device} = '/sys/bus/pci/devices/' . get_pci_sysfs_path(\%l);
	\%l;
    } c::pci_probe());
}
sub pci_probe() {
    state $done;
    if (!$done) {
        @pci = pci_probe__real() if !@pci;
        foreach (@pci) {
            $_->{nice_bus} = $_->{is_pciexpress} ? "PCI Express" : "PCI";
        }
    }
    @pci;
}

sub usb_probe__real() {
    -e "/sys/kernel/debug/usb/devices" or return;

    add_addons($usbtable_addons, map {
	my %l;
	@l{qw(vendor id media_type driver description pci_bus pci_device usb_port)} = split "\t";
	$l{media_type} = join('|', grep { $_ ne '(null)' } split('\|', $l{media_type}));
	$l{$_} = hex $l{$_} foreach qw(vendor id);
	$l{sysfs_device} = "/sys/bus/usb/devices/$l{pci_bus}-" . ($l{usb_port} + 1);
	$l{bus} = 'USB';
	\%l;
    } c::usb_probe());
}
sub usb_probe() {
    if ($::isStandalone && @usb) {
	    @usb;
    } else {
	    @usb = usb_probe__real();
    }
}

sub firewire_probe() {
    my $dev_dir = '/sys/bus/ieee1394/devices';
    my @l = map {
        my $dir = "$dev_dir/$_";
        my $get = sub { chomp_(cat_($_[0])) };
        {
            version => hex($get->("$dir/../vendor_id")),
            specifier_id => hex($get->("$dir/specifier_id")),
            specifier_version => hex($get->("$dir/version")),
            bus => 'Firewire',
            sysfs_device => $dir,
        };
    } grep { -f "$dev_dir/$_/specifier_id" } all($dev_dir);

    my $e;
    foreach (cat_('/proc/bus/ieee1394/devices')) {
	if (m!Vendor/Model ID: (.*) \[(\w+)\] / (.*) \[(\w+)\]!) {
	    push @l, $e = { 
			   vendor => hex($2), id => hex($4), 
			   description => join('|', $1, $3),
			   bus => 'Firewire',
			  };
	} elsif (/Software Specifier ID: (\w+)/) {
	    $e->{specifier_id} = hex $1;
	} elsif (/Software Version: (\w+)/) {
	    $e->{specifier_version} = hex $1;	    
	}
    }

    foreach (@l) {
	if ($_->{specifier_id} == 0x00609e && $_->{specifier_version} == 0x010483) {
	    add2hash($_, { driver => 'sbp2', description => "Generic Firewire Storage Controller" });
	} elsif ($_->{specifier_id} == 0x00005e && $_->{specifier_version} == 0x000001) {
	    add2hash($_, { driver => 'eth1394', description => "IEEE 1394 IPv4 Driver (IPv4-over-1394 as per RFC 2734)" });
	}
    }
    @l;
}

sub pcmcia_controller_probe() {
    my ($controller) =  probe_category('bus/pcmcia');
    if (!$controller && !$::testing && !$::noauto && arch() =~ /i.86/) {
        my $driver = c::pcmcia_probe();
        $controller = { driver => $driver, description => "PCMCIA controller ($driver)" } if $driver;
    }
    $controller;
}

sub pcmcia_probe() {
    require modalias;
    require modules;
    my $dev_dir = '/sys/bus/pcmcia/devices';
    map {
        my $dir = "$dev_dir/$_";
        my $get = sub { chomp_(cat_("$dir/$_[0]")) };
        my $class_dev = first(glob_("$dir/tty/tty*"));
        my $device = $class_dev && basename($class_dev);
        my $modalias = $get->('modalias');
        my $driver = get_sysfs_field_from_link($dir, 'driver');
        #- fallback on modalias result
        #- but only if the module isn't loaded yet (else, it would already be binded)
        #- this prevents from guessing the wrong driver for multi-function devices
        my $module = $modalias && first(modalias::get_modules($modalias));
        $driver ||= !member($module, modules::loaded_modules()) && $module;
        {
            description => join(' ', grep { $_ } map { $get->("prod_id$_") } 1 .. 4),
            driver => $driver,
            if_($modalias, modalias => $modalias),
            if_($device, device => $device),
            bus => 'PCMCIA',
            sysfs_device => $dir,
        };
    } all($dev_dir);
}

sub dmi_probe() {
    state $dmi_probe;
    if (arch() !~ /86/) {
        return [];
    }
    $dmi_probe ||= [ map {
	/(.*?)\t(.*)/ && { bus => 'DMI', driver => $1, description => $2 };
    } $> ? () : c::dmi_probe() ];
    @$dmi_probe;
}

# pcmcia_probe provides field "device", used in network.pm
# => probeall with $probe_type is unsafe
sub probeall() {
    return if $::noauto;

    pci_probe(), usb_probe(), firewire_probe(), pcmcia_probe(), dmi_probe(), getInputDevices_and_usb();
}
sub probeall_update_cache() {
    return if $::noauto;
    @pci = pci_probe__real(), @usb = usb_probe__real(), firewire_probe(), pcmcia_probe(), dmi_probe();
}
sub matching_desc__regexp {
    my ($regexp) = @_;
    grep { $_->{description} =~ /$regexp/i } probeall();
}
sub matching_driver__regexp {
    my ($regexp) = @_;
    grep { $_->{driver} =~ /$regexp/i } probeall();
}

sub matching_driver {
    my (@list) = @_;
    grep { member($_->{driver}, @list) } probeall();
}
sub probe_name {
    my ($name) = @_;
    map { $_->{driver} =~ /^$name:(.*)/ } probeall();
}
sub probe_unique_name {
    my ($name) = @_;
    my @l = uniq(probe_name($name));
    if (@l > 1) {
	log::l("oops, more than one $name from probe: ", join(' ', @l));
    }
    $l[0];
}

sub stringlist {
    my ($b_verbose) = @_;
    map {
	my $ids = $b_verbose || $_->{description} eq '(null)' ?  sprintf("vendor:%04x device:%04x", $_->{vendor}, $_->{id}) : '';
	my $subids = $_->{subid} && $_->{subid} != 0xffff ? sprintf("subv:%04x subd:%04x", $_->{subvendor}, $_->{subid}) : '';
	sprintf("%-16s: %s%s%s", 
		$_->{driver} || 'unknown', 
		$_->{description},
		$_->{media_type} ? sprintf(" [%s]", $_->{media_type}) : '',
		$ids || $subids ? " ($ids" . ($ids && $subids && " ") . "$subids)" : '',
	       );
    } probeall(); 
}

sub tryOpen($) {
    my $F;
    sysopen($F, devices::make($_[0]), c::O_NONBLOCK()) && $F;
}

sub tryWrite($) {
    my $F;
    sysopen($F, devices::make($_[0]), 1 | c::O_NONBLOCK()) && $F;
}

my @dmesg;
sub syslog() {
    if (-r "/tmp/syslog") {
	map { /<\d+>(.*)/ } cat_("/tmp/syslog");
    } else {
	@dmesg = `/bin/dmesg` if !@dmesg;
	@dmesg;
    }
}

sub get_mac_model() {
    my $mac_model = cat_("/proc/device-tree/model") || die "Cannot open /proc/device-tree/model";
    log::l("Mac model: $mac_model");
    $mac_model;	
}

sub get_mac_generation() {
    cat_('/proc/cpuinfo') =~ /^pmac-generation\s*:\s*(.*)/m ? $1 : "Unknown Generation";	
}

sub hasSMP() { 
    return if $::testing;
    (any { /NR_CPUS limit of 1 reached/ } syslog()) ||
     (any { /^processor\s*:\s*(\d+)/ && $1 > 0 } cat_('/proc/cpuinfo')) ||
      any { /\bProcessor #(\d+)\s+(\S*)/ && $1 > 0 && $2 ne 'invalid' } syslog();
}
sub hasPCMCIA() { $::o->{pcmcia} }

my (@dmis, $dmidecode_already_runned);

# we return a list b/c several DMIs have the same name:
sub dmidecode() {
    return @dmis if $dmidecode_already_runned;

    return if $>;
    my ($ver, @l) = arch() =~ /86/ ? run_program::get_stdout('dmidecode') : ();

    my $tab = "\t";

    my ($major, $minor) = $ver =~ /(\d+)\.(\d+)/;

    if ($major > 2 || $major == 2 && $minor > 7) {
	#- new dmidecode output is less indented
	$tab = '';
	#- drop header
	shift @l while @l && $l[0] ne "\n";
    }

    foreach (@l) {
	next if /TRUNCATED/;
	if (/^$tab\t(.*)/) {
	    $dmis[-1]{string} .= "$1\n";
	    $dmis[-1]{$1} = $2 if /^$tab\t(.*): (.*)$/;
	} elsif (my ($s) = /^$tab(.*)/) {
	    next if $s =~ /^$/ || $s =~ /\bDMI type \d+/;
	    $s =~ s/ Information$//;
	    push @dmis, { name => $s };
	}
    }
    $dmidecode_already_runned = 1;
    @dmis;
}
sub dmidecode_category {
    my ($cat) = @_;
    my @l = grep { $_->{name} eq $cat } dmidecode();
    wantarray() ? @l : $l[0] || {};
}

#- size in MB
sub dmi_detect_memory() {
    my @l1 = map { $_->{'Enabled Size'} =~ /(\d+) MB/ && $1 } dmidecode_category('Memory Module');
    my @l2 = map { $_->{'Form Factor'} =~ /^(SIMM|SIP|DIP|DIMM|FB-DIMM|RIMM|SODIMM|SRIMM)$/ && 		     
		     ($_->{Size} =~ /(\d+) MB/ && $1 || $_->{Size} =~ /(\d+) kB/ && $1 * 1024);
		 } dmidecode_category('Memory Device');
    max(sum(@l1), sum(@l2));
}

sub computer_info() {
     my $Chassis = dmidecode_category('Chassis')->{Type} =~ /(\S+)/ && $1;

     my $date = dmidecode_category('BIOS')->{'Release Date'} || '';
     my $BIOS_Year = $date =~ m!(\d{4})! && $1 ||
	             $date =~ m!\d\d/\d\d/(\d\d)! && "20$1";
	
     +{ 
	 isLaptop => member($Chassis, 'Portable', 'Laptop', 'Notebook', 'Hand Held', 'Sub Notebook', 'Docking Station'),
	 isServer => member($Chassis, 'Pizza Box', 'Main Server Chassis', 'Rack Mount Chassis', 'Blade'),
	 if_($BIOS_Year, BIOS_Year => $BIOS_Year),
     };
}

#- try to detect a laptop, we assume pcmcia service is an indication of a laptop or
#- the following regexp to match graphics card apparently only used for such systems.
sub isLaptop() {
    arch() =~ /ppc/ ? 
      get_mac_model() =~ /Book/ :
      computer_info()->{isLaptop}
	|| glob_("/sys/bus/acpi/devices/PNP0C0D:*") #- ACPI lid button
	|| (matching_desc__regexp('C&T.*655[45]\d') || matching_desc__regexp('C&T.*68554') ||
	    matching_desc__regexp('Neomagic.*Magic(Media|Graph)') ||
	    matching_desc__regexp('ViRGE.MX') || matching_desc__regexp('S3.*Savage.*[IM]X') ||
	    matching_desc__regexp('Intel Corporation\|Mobile') ||
	    matching_desc__regexp('\bATI\b.*(Mobility|\bLT\b)'))
	|| (any { $_->{'model name'} =~ /\b(mobile|C7-M)\b/i } getCPUs())
	|| probe_unique_name("Type") eq 'laptop'
        #- ipw2100/2200/3945 are Mini-PCI (Express) adapters
	|| (any { member($_->{driver}, qw(ipw2100 ipw2200 ipw3945)) } pci_probe());
}

sub isServer() {
    computer_info()->{isServer}
      || (any { $_->{Type} =~ /ECC/ } dmidecode_category('Memory Module'))
      || dmidecode_category('System Information')->{Manufacturer} =~ /Supermicro/i
      || dmidecode_category('System Information')->{'Product Name'} =~ /NetServer|Proliant|PowerEdge|eServer|IBM System x|ThinkServer/i
      || matching_desc__regexp('LSI Logic.*SCSI')
      || matching_desc__regexp('MegaRAID')
      || matching_desc__regexp('NetServer')
      || (any { $_->{'model name'} =~ /(Xeon|Opteron)/i } getCPUs());
}

sub isHyperv() {
      dmidecode_category('System')->{Manufacturer} =~ /Microsoft Corporation/i
      && dmidecode_category('System')->{'Product Name'} =~ /Virtual Machine/i;
}

sub BIGMEM() {
    arch() !~ /x86_64|ia64/ && $> == 0 && dmi_detect_memory() > 4 * 1024;
}

sub is_i586() {
    return 0 if arch() !~ /86/;
    my $cpuinfo = cat_('/proc/cpuinfo');
    $cpuinfo =~ /^cpu family\s*:\s*(\d+)/m && $1 < 6 ||
      $cpuinfo =~ /^model name\s*:\s*Transmeta.* TM5800/m || # mdvbz#37866
      !has_cpu_flag('cmov');
}

sub is_mips_lemote() {
    to_bool(cat_('/proc/cpuinfo') =~ /lemote/);
}

sub is_mips_ict() {
    to_bool(cat_('/proc/cpuinfo') =~ /ict/);
}

sub is_mips_gdium() {
    to_bool(cat_('/proc/cpuinfo') =~ /gdium/);
}

sub is_mips_st_ls2f() {
    to_bool(cat_('/proc/cpuinfo') =~ /st-ls2f/);
}

sub is_arm_openrd_client() {
    to_bool(cat_('/proc/cpuinfo') =~ /OpenRD Client/);
}

sub is_arm_versatile() {
    to_bool(cat_('/proc/cpuinfo') =~ /ARM-Versatile/);
}

sub is_arm_efikamix() {
    to_bool(cat_('/proc/cpuinfo') =~ /Efika MX/);
}

sub is_xbox() {
    any { $_->{vendor} == 0x10de && $_->{id} == 0x02a5 } pci_probe();
}

sub is_virtualbox() {
    any { $_->{driver} eq 'vboxadd' } detect_devices::pci_probe();
}

sub is_vmware() {
    any { $_->{driver} =~ /Card:VMware/ } detect_devices::pci_probe();
}

sub is_netbook_nettop() {
    my @cpus = getCPUs();
    (any { $_->{'model name'} =~ /(\bIntel\(R\) Atom\(TM\)\B)/i } @cpus) ||
    (any { $_->{'model name'} =~ /(\bIntel\(R\) Celeron\(R\) M processor\b|\bVIA C7-M Processor\b|\bGeode\(TM\)\B)/i && $_->{'cpu MHz'} < 1500 } @cpus);
}

sub has_low_resources() {
    availableRamMB() < 100 || arch() =~ /i.86/ && ix86_cpu_frequency() < 350;
}

sub need_light_desktop() {
    has_low_resources() || is_netbook_nettop();
}

sub has_cpu_flag {
    my ($flag) = @_;
    cat_('/proc/cpuinfo') =~ /^flags.*\b$flag\b/m;
}

sub matching_types() {
    +{
	mips_lemote => is_mips_lemote(),
	mips_ict => is_mips_ict(),
	mips_st_ls2f => is_mips_st_ls2f(),
	laptop => isLaptop(),
	hyperv => isHyperv(),
	'numpad' => hasNumpad(),
	'touchpad' => hasTouchpad(),
	'64bit' => to_bool(arch() =~ /64/),
	wireless => to_bool(get_wireless_interface() || probe_category('network/wireless')),
    };
}

sub hasCPUMicrocode() {
    state $hasCPUMicrocode;
    if (!defined $hasCPUMicrocode) {
        $hasCPUMicrocode = to_bool(find { 'microcode' } modules::loaded_modules());
    }
    return $hasCPUMicrocode;
}

sub hasCPUFreq()     {
    require cpufreq;
     to_bool(cpufreq::get_modules())
       || cat_('/proc/cpuinfo') =~ /AuthenticAMD/ && arch() =~ /x86_64/
       || cat_('/proc/cpuinfo') =~ /model name.*Intel\(R\) Core\(TM\)2 CPU/;
}
sub hasWacom()     { find { $_->{vendor} == 0x056a || $_->{driver} =~ /wacom/ } usb_probe() }
sub hasTouchpad()  { any { $_->{Synaptics} || $_->{ALPS} || $_->{Elantech} } getInputDevices() }
sub hasNumpad()    { any { $_->{Numpad} } getInputDevices() }

sub usbWacom()     { grep { $_->{vendor} eq '056a' } getInputDevices() }
sub usbKeyboards() { grep { $_->{media_type} =~ /\|Keyboard/ } usb_probe() }
sub usbStorage()   { grep { $_->{media_type} =~ /Mass Storage\|/ } usb_probe() }
sub has_mesh()     { find { /mesh/ } all_files_rec("/proc/device-tree") }
sub has_53c94()    { find { /53c94/ } all_files_rec("/proc/device-tree") }

sub usbKeyboard2country_code {
    my ($usb_kbd) = @_;
    my ($F, $tmp);
    # FIXME: usbfs is dead! we should poke somewhere in /sys/ !!!!
    sysopen($F, sprintf("/proc/bus/usb/%03d/%03d", $usb_kbd->{pci_bus}, $usb_kbd->{pci_device}), 0) and
      sysseek $F, 0x28, 0 and
      sysread $F, $tmp, 1 and
      unpack("C", $tmp);
}

sub probeSerialDevices() {
    require list_modules;
    require modules;
    modules::append_to_modules_loaded_at_startup_for_all_kernels(modules::load_category($::o->{modules_conf}, 'various/serial'));
    foreach (0..3) {
	#- make sure the device are created before probing,
	devices::make("/dev/ttyS$_");