Пример #1
0
/**
 * Gets data from the error log
 *
 * @param int $start
 * @param string $sort_direction
 * @param mixed[]|null $filter
 */
function getErrorLogData($start, $sort_direction = 'DESC', $filter = null)
{
    global $modSettings, $scripturl, $txt;
    $db = database();
    // Find and sort out the errors.
    $request = $db->query('', '
		SELECT id_error, id_member, ip, url, log_time, message, session, error_type, file, line
		FROM {db_prefix}log_errors' . (isset($filter) ? '
		WHERE ' . $filter['variable'] . ' LIKE {string:filter}' : '') . '
		ORDER BY id_error ' . ($sort_direction == 'down' ? 'DESC' : '') . '
		LIMIT ' . $start . ', ' . $modSettings['defaultMaxMessages'], array('filter' => isset($filter) ? $filter['value']['sql'] : ''));
    $log = array();
    for ($i = 0; $row = $db->fetch_assoc($request); $i++) {
        $search_message = preg_replace('~<span class="remove">(.+?)</span>~', '%', $db->escape_wildcard_string($row['message']));
        if ($search_message == $filter['value']['sql']) {
            $search_message = $db->escape_wildcard_string($row['message']);
        }
        $show_message = strtr(strtr(preg_replace('~&lt;span class=&quot;remove&quot;&gt;(.+?)&lt;/span&gt;~', '$1', $row['message']), array("\r" => '', '<br />' => "\n", '<' => '&lt;', '>' => '&gt;', '"' => '&quot;')), array("\n" => '<br />'));
        $log['errors'][$row['id_error']] = array('alternate' => $i % 2 == 0, 'member' => array('id' => $row['id_member'], 'ip' => $row['ip'], 'session' => $row['session']), 'time' => standardTime($row['log_time']), 'html_time' => htmlTime($row['log_time']), 'timestamp' => forum_time(true, $row['log_time']), 'url' => array('html' => htmlspecialchars((substr($row['url'], 0, 1) == '?' ? $scripturl : '') . $row['url'], ENT_COMPAT, 'UTF-8'), 'href' => base64_encode($db->escape_wildcard_string($row['url']))), 'message' => array('html' => $show_message, 'href' => base64_encode($search_message)), 'id' => $row['id_error'], 'error_type' => array('type' => $row['error_type'], 'name' => isset($txt['errortype_' . $row['error_type']]) ? $txt['errortype_' . $row['error_type']] : $row['error_type']), 'file' => array());
        if (!empty($row['file']) && !empty($row['line'])) {
            // Eval'd files rarely point to the right location and cause havoc for linking, so don't link them.
            $linkfile = strpos($row['file'], 'eval') === false || strpos($row['file'], '?') === false;
            // De Morgan's Law.  Want this true unless both are present.
            $log['errors'][$row['id_error']]['file'] = array('file' => $row['file'], 'line' => $row['line'], 'href' => $scripturl . '?action=admin;area=logs;sa=errorlog;activity=file;file=' . base64_encode($row['file']) . ';line=' . $row['line'], 'link' => $linkfile ? '<a href="' . $scripturl . '?action=admin;area=logs;sa=errorlog;activity=file;file=' . base64_encode($row['file']) . ';line=' . $row['line'] . '" onclick="return reqWin(this.href, 600, 480, false);">' . $row['file'] . '</a>' : $row['file'], 'search' => base64_encode($row['file']));
        }
        // Make a list of members to load later.
        $log['members'][$row['id_member']] = $row['id_member'];
    }
    $db->free_result($request);
    return $log;
}
 public static function formatExpireCol($time)
 {
     if ($time == 0) {
         return '<i class="fa fa-check success"></i>';
     } elseif ($time > forum_time(false)) {
         return standardTime($time) . ' <i class="fa fa-clock-o success"></i>';
     } else {
         return '<i class="fa fa-times-circle-o  error"></i>';
     }
 }
Пример #3
0
 /**
  * Handles the sending of the forum mailing in batches.
  *
  * What it does:
  * - Called by ?action=admin;area=news;sa=mailingsend
  * - Requires the send_mail permission.
  * - Redirects to itself when more batches need to be sent.
  * - Redirects to ?action=admin after everything has been sent.
  *
  * @uses the ManageNews template and email_members_send sub template.
  * @param bool $clean_only = false; if set, it will only clean the variables, put them in context, then return.
  */
 public function action_mailingsend($clean_only = false)
 {
     global $txt, $context, $scripturl, $modSettings, $user_info;
     // A nice successful screen if you did it
     if (isset($_REQUEST['success'])) {
         $context['sub_template'] = 'email_members_succeeded';
         loadTemplate('ManageNews');
         return;
     }
     // If just previewing we prepare a message and return it for viewing
     if (isset($_POST['preview'])) {
         $context['preview'] = true;
         return $this->action_mailingcompose();
     }
     // How many to send at once? Quantity depends on whether we are queueing or not.
     // @todo Might need an interface? (used in Post.controller.php too with different limits)
     $num_at_once = empty($modSettings['mail_queue']) ? 60 : 1000;
     // If by PM's I suggest we half the above number.
     if (!empty($_POST['send_pm'])) {
         $num_at_once /= 2;
     }
     checkSession();
     // Where are we actually to?
     $context['start'] = isset($_REQUEST['start']) ? (int) $_REQUEST['start'] : 0;
     $context['email_force'] = !empty($_POST['email_force']) ? 1 : 0;
     $context['send_pm'] = !empty($_POST['send_pm']) ? 1 : 0;
     $context['total_emails'] = !empty($_POST['total_emails']) ? (int) $_POST['total_emails'] : 0;
     $context['max_id_member'] = !empty($_POST['max_id_member']) ? (int) $_POST['max_id_member'] : 0;
     $context['send_html'] = !empty($_POST['send_html']) ? 1 : 0;
     $context['parse_html'] = !empty($_POST['parse_html']) ? 1 : 0;
     // Create our main context.
     $context['recipients'] = array('groups' => array(), 'exclude_groups' => array(), 'members' => array(), 'exclude_members' => array(), 'emails' => array());
     // Have we any excluded members?
     if (!empty($_POST['exclude_members'])) {
         $members = explode(',', $_POST['exclude_members']);
         foreach ($members as $member) {
             if ($member >= $context['start']) {
                 $context['recipients']['exclude_members'][] = (int) $member;
             }
         }
     }
     // What about members we *must* do?
     if (!empty($_POST['members'])) {
         $members = explode(',', $_POST['members']);
         foreach ($members as $member) {
             if ($member >= $context['start']) {
                 $context['recipients']['members'][] = (int) $member;
             }
         }
     }
     // Cleaning groups is simple - although deal with both checkbox and commas.
     if (isset($_POST['groups'])) {
         if (is_array($_POST['groups'])) {
             foreach ($_POST['groups'] as $group => $dummy) {
                 $context['recipients']['groups'][] = (int) $group;
             }
         } elseif (trim($_POST['groups']) != '') {
             $groups = explode(',', $_POST['groups']);
             foreach ($groups as $group) {
                 $context['recipients']['groups'][] = (int) $group;
             }
         }
     }
     // Same for excluded groups
     if (isset($_POST['exclude_groups'])) {
         if (is_array($_POST['exclude_groups'])) {
             foreach ($_POST['exclude_groups'] as $group => $dummy) {
                 $context['recipients']['exclude_groups'][] = (int) $group;
             }
         } elseif (trim($_POST['exclude_groups']) != '') {
             $groups = explode(',', $_POST['exclude_groups']);
             foreach ($groups as $group) {
                 $context['recipients']['exclude_groups'][] = (int) $group;
             }
         }
     }
     // Finally - emails!
     if (!empty($_POST['emails'])) {
         $addressed = array_unique(explode(';', strtr($_POST['emails'], array("\n" => ';', "\r" => ';', ',' => ';'))));
         foreach ($addressed as $curmem) {
             $curmem = trim($curmem);
             if ($curmem != '') {
                 $context['recipients']['emails'][$curmem] = $curmem;
             }
         }
     }
     // If we're only cleaning drop out here.
     if ($clean_only) {
         return;
     }
     // Some functions we will need
     require_once SUBSDIR . '/Mail.subs.php';
     if ($context['send_pm']) {
         require_once SUBSDIR . '/PersonalMessage.subs.php';
     }
     // We are relying too much on writing to superglobals...
     $base_subject = !empty($_POST['subject']) ? $_POST['subject'] : '';
     $base_message = !empty($_POST['message']) ? $_POST['message'] : '';
     // Save the message and its subject in $context
     $context['subject'] = htmlspecialchars($base_subject, ENT_COMPAT, 'UTF-8');
     $context['message'] = htmlspecialchars($base_message, ENT_COMPAT, 'UTF-8');
     // Prepare the message for sending it as HTML
     if (!$context['send_pm'] && !empty($_POST['send_html'])) {
         // Prepare the message for HTML.
         if (!empty($_POST['parse_html'])) {
             $base_message = str_replace(array("\n", '  '), array('<br />' . "\n", '&nbsp; '), $base_message);
         }
         // This is here to prevent spam filters from tagging this as spam.
         if (preg_match('~\\<html~i', $base_message) == 0) {
             if (preg_match('~\\<body~i', $base_message) == 0) {
                 $base_message = '<html><head><title>' . $base_subject . '</title></head>' . "\n" . '<body>' . $base_message . '</body></html>';
             } else {
                 $base_message = '<html>' . $base_message . '</html>';
             }
         }
     }
     if (empty($base_message) || empty($base_subject)) {
         $context['preview'] = true;
         return $this->action_mailingcompose();
     }
     // Use the default time format.
     $user_info['time_format'] = $modSettings['time_format'];
     $variables = array('{$board_url}', '{$current_time}', '{$latest_member.link}', '{$latest_member.id}', '{$latest_member.name}');
     // We might need this in a bit
     $cleanLatestMember = empty($_POST['send_html']) || $context['send_pm'] ? un_htmlspecialchars($modSettings['latestRealName']) : $modSettings['latestRealName'];
     // Replace in all the standard things.
     $base_message = str_replace($variables, array(!empty($_POST['send_html']) ? '<a href="' . $scripturl . '">' . $scripturl . '</a>' : $scripturl, standardTime(forum_time(), false), !empty($_POST['send_html']) ? '<a href="' . $scripturl . '?action=profile;u=' . $modSettings['latestMember'] . '">' . $cleanLatestMember . '</a>' : ($context['send_pm'] ? '[url=' . $scripturl . '?action=profile;u=' . $modSettings['latestMember'] . ']' . $cleanLatestMember . '[/url]' : $cleanLatestMember), $modSettings['latestMember'], $cleanLatestMember), $base_message);
     $base_subject = str_replace($variables, array($scripturl, standardTime(forum_time(), false), $modSettings['latestRealName'], $modSettings['latestMember'], $modSettings['latestRealName']), $base_subject);
     $from_member = array('{$member.email}', '{$member.link}', '{$member.id}', '{$member.name}');
     // If we still have emails, do them first!
     $i = 0;
     foreach ($context['recipients']['emails'] as $k => $email) {
         // Done as many as we can?
         if ($i >= $num_at_once) {
             break;
         }
         // Don't sent it twice!
         unset($context['recipients']['emails'][$k]);
         // Dammit - can't PM emails!
         if ($context['send_pm']) {
             continue;
         }
         $to_member = array($email, !empty($_POST['send_html']) ? '<a href="mailto:' . $email . '">' . $email . '</a>' : $email, '??', $email);
         sendmail($email, str_replace($from_member, $to_member, $base_subject), str_replace($from_member, $to_member, $base_message), null, null, !empty($_POST['send_html']), 5);
         // Done another...
         $i++;
     }
     // Got some more to send this batch?
     $last_id_member = 0;
     if ($i < $num_at_once) {
         // Need to build quite a query!
         $sendQuery = '(';
         $sendParams = array();
         if (!empty($context['recipients']['groups'])) {
             // Take the long route...
             $queryBuild = array();
             foreach ($context['recipients']['groups'] as $group) {
                 $sendParams['group_' . $group] = $group;
                 $queryBuild[] = 'mem.id_group = {int:group_' . $group . '}';
                 if (!empty($group)) {
                     $queryBuild[] = 'FIND_IN_SET({int:group_' . $group . '}, mem.additional_groups) != 0';
                     $queryBuild[] = 'mem.id_post_group = {int:group_' . $group . '}';
                 }
             }
             if (!empty($queryBuild)) {
                 $sendQuery .= implode(' OR ', $queryBuild);
             }
         }
         if (!empty($context['recipients']['members'])) {
             $sendQuery .= ($sendQuery == '(' ? '' : ' OR ') . 'mem.id_member IN ({array_int:members})';
             $sendParams['members'] = $context['recipients']['members'];
         }
         $sendQuery .= ')';
         // If we've not got a query then we must be done!
         if ($sendQuery == '()') {
             redirectexit('action=admin');
         }
         // Anything to exclude?
         if (!empty($context['recipients']['exclude_groups']) && in_array(0, $context['recipients']['exclude_groups'])) {
             $sendQuery .= ' AND mem.id_group != {int:regular_group}';
         }
         if (!empty($context['recipients']['exclude_members'])) {
             $sendQuery .= ' AND mem.id_member NOT IN ({array_int:exclude_members})';
             $sendParams['exclude_members'] = $context['recipients']['exclude_members'];
         }
         // Force them to have it?
         if (empty($context['email_force'])) {
             $sendQuery .= ' AND mem.notify_announcements = {int:notify_announcements}';
         }
         require_once SUBSDIR . '/News.subs.php';
         // Get the smelly people - note we respect the id_member range as it gives us a quicker query.
         $recipients = getNewsletterRecipients($sendQuery, $sendParams, $context['start'], $num_at_once, $i);
         foreach ($recipients as $row) {
             $last_id_member = $row['id_member'];
             // What groups are we looking at here?
             if (empty($row['additional_groups'])) {
                 $groups = array($row['id_group'], $row['id_post_group']);
             } else {
                 $groups = array_merge(array($row['id_group'], $row['id_post_group']), explode(',', $row['additional_groups']));
             }
             // Excluded groups?
             if (array_intersect($groups, $context['recipients']['exclude_groups'])) {
                 continue;
             }
             // We might need this
             $cleanMemberName = empty($_POST['send_html']) || $context['send_pm'] ? un_htmlspecialchars($row['real_name']) : $row['real_name'];
             // Replace the member-dependant variables
             $message = str_replace($from_member, array($row['email_address'], !empty($_POST['send_html']) ? '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '">' . $cleanMemberName . '</a>' : ($context['send_pm'] ? '[url=' . $scripturl . '?action=profile;u=' . $row['id_member'] . ']' . $cleanMemberName . '[/url]' : $cleanMemberName), $row['id_member'], $cleanMemberName), $base_message);
             $subject = str_replace($from_member, array($row['email_address'], $row['real_name'], $row['id_member'], $row['real_name']), $base_subject);
             // Send the actual email - or a PM!
             if (!$context['send_pm']) {
                 sendmail($row['email_address'], $subject, $message, null, null, !empty($_POST['send_html']), 5);
             } else {
                 sendpm(array('to' => array($row['id_member']), 'bcc' => array()), $subject, $message);
             }
         }
     }
     // If used our batch assume we still have a member.
     if ($i >= $num_at_once) {
         $last_id_member = $context['start'];
     } elseif (empty($last_id_member) && $context['start'] + $num_at_once < $context['max_id_member']) {
         $last_id_member = $context['start'] + $num_at_once;
     } elseif (empty($last_id_member) && empty($context['recipients']['emails'])) {
         // Log this into the admin log.
         logAction('newsletter', array(), 'admin');
         redirectexit('action=admin;area=news;sa=mailingsend;success');
     }
     $context['start'] = $last_id_member;
     // Working out progress is a black art of sorts.
     $percentEmails = $context['total_emails'] == 0 ? 0 : count($context['recipients']['emails']) / $context['total_emails'] * ($context['total_emails'] / ($context['total_emails'] + $context['max_id_member']));
     $percentMembers = $context['start'] / $context['max_id_member'] * ($context['max_id_member'] / ($context['total_emails'] + $context['max_id_member']));
     $context['percentage_done'] = round(($percentEmails + $percentMembers) * 100, 2);
     $context['page_title'] = $txt['admin_newsletters'];
     $context['sub_template'] = 'email_members_send';
 }
Пример #4
0
/**
 * Generates a file listing for a given directory
 *
 * @param string $path
 * @param string $relative
 */
function get_file_listing($path, $relative)
{
    global $scripturl, $txt, $context;
    // Only files with these extensions will be deemed editable
    $editable = 'php|pl|css|js|vbs|xml|xslt|txt|xsl|html|htm|shtm|shtml|asp|aspx|cgi|py';
    // Is it even a directory?
    if (!is_dir($path)) {
        fatal_lang_error('error_invalid_dir', 'critical');
    }
    // Read this directorys contents
    $entries = array();
    $dir = dir($path);
    while ($entry = $dir->read()) {
        $entries[] = $entry;
    }
    $dir->close();
    // Sort it so it looks natural to the user
    natcasesort($entries);
    $listing1 = array();
    $listing2 = array();
    foreach ($entries as $entry) {
        // Skip all dot files, including .htaccess.
        if (substr($entry, 0, 1) === '.' || $entry === 'CVS') {
            continue;
        }
        // A directory entry
        if (is_dir($path . '/' . $entry)) {
            $listing1[] = array('filename' => $entry, 'is_writable' => is_writable($path . '/' . $entry), 'is_directory' => true, 'is_template' => false, 'is_image' => false, 'is_editable' => false, 'href' => $scripturl . '?action=admin;area=theme;th=' . $_GET['th'] . ';' . $context['session_var'] . '=' . $context['session_id'] . ';sa=browse;directory=' . $relative . $entry, 'size' => '');
        } else {
            $size = filesize($path . '/' . $entry);
            if ($size > 2048 || $size == 1024) {
                $size = comma_format($size / 1024) . ' ' . $txt['themeadmin_edit_kilobytes'];
            } else {
                $size = comma_format($size) . ' ' . $txt['themeadmin_edit_bytes'];
            }
            $writable = is_writable($path . '/' . $entry);
            $listing2[] = array('filename' => $entry, 'is_writable' => $writable, 'is_directory' => false, 'is_template' => preg_match('~\\.template\\.php$~', $entry) != 0, 'is_image' => preg_match('~\\.(jpg|jpeg|gif|bmp|png|ico)$~', $entry) != 0, 'is_editable' => $writable && preg_match('~\\.(' . $editable . ')$~', $entry) != 0, 'href' => $scripturl . '?action=admin;area=theme;th=' . $_GET['th'] . ';' . $context['session_var'] . '=' . $context['session_id'] . ';sa=edit;filename=' . $relative . $entry, 'size' => $size, 'last_modified' => standardTime(filemtime($path . '/' . $entry)));
        }
    }
    return array_merge($listing1, $listing2);
}
Пример #5
0
        if ($found_duration !== 0) {
            $notify = true;
            addSubscription($subscription_id, $member_id, $found_duration);
        }
    } else {
        $actual_cost = $cost['fixed'];
        // It must be at least the right amount.
        if ($total_cost != 0 && $total_cost >= $actual_cost) {
            // Add the subscription.
            $notify = true;
            addSubscription($subscription_id, $member_id);
        }
    }
    // Send a receipt?
    if (!empty($modSettings['paid_email']) && $modSettings['paid_email'] == 2 && $notify) {
        $replacements = array('NAME' => $subscription_info['name'], 'SUBNAME' => $member_info['member_name'], 'SUBUSER' => $member_info['real_name'], 'SUBEMAIL' => $member_info['email_address'], 'PRICE' => sprintf($modSettings['paid_currency_symbol'], $total_cost), 'PROFILELINK' => $scripturl . '?action=profile;u=' . $member_id, 'DATE' => standardTime(time(), false));
        emailAdmins('paid_subscription_new', $replacements, $notify_users);
    }
} elseif ($gatewayClass->isCancellation()) {
    if (method_exists($gatewayClass, 'processCancelation')) {
        $gatewayClass->processCancelation($subscription_id, $member_id, $subscription_info);
    }
} else {
    // Some other "valid" transaction such as:
    //
    // subscr_signup: This IPN response (txn_type) is sent only the first time the user signs up for a subscription.
    // It then does not fire in any event later. This response is received somewhere before or after the first payment of
    // subscription is received (txn_type=subscr_payment) which is what we do process
    //
    // Should we log any of these ...
}
Пример #6
0
/**
 * We want to show the recent attachments outside of the forum.
 *
 * @param int $num_attachments = 10
 * @param string[] $attachment_ext = array()
 * @param string $output_method = 'echo'
 */
function ssi_recentAttachments($num_attachments = 10, $attachment_ext = array(), $output_method = 'echo')
{
    global $modSettings, $scripturl, $txt, $settings;
    // We want to make sure that we only get attachments for boards that we can see *if* any.
    $attachments_boards = boardsAllowedTo('view_attachments');
    // No boards?  Adios amigo.
    if (empty($attachments_boards)) {
        return array();
    }
    $db = database();
    // Is it an array?
    if (!is_array($attachment_ext)) {
        $attachment_ext = array($attachment_ext);
    }
    // Lets build the query.
    $request = $db->query('', '
		SELECT
			att.id_attach, att.id_msg, att.filename, IFNULL(att.size, 0) AS filesize, att.downloads, mem.id_member,
			IFNULL(mem.real_name, m.poster_name) AS poster_name, m.id_topic, m.subject, t.id_board, m.poster_time,
			att.width, att.height' . (empty($modSettings['attachmentShowImages']) || empty($modSettings['attachmentThumbnails']) ? '' : ', IFNULL(thumb.id_attach, 0) AS id_thumb, thumb.width AS thumb_width, thumb.height AS thumb_height') . '
		FROM {db_prefix}attachments AS att
			INNER JOIN {db_prefix}messages AS m ON (m.id_msg = att.id_msg)
			INNER JOIN {db_prefix}topics AS t ON (t.id_topic = m.id_topic)
			LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)' . (empty($modSettings['attachmentShowImages']) || empty($modSettings['attachmentThumbnails']) ? '' : '
			LEFT JOIN {db_prefix}attachments AS thumb ON (thumb.id_attach = att.id_thumb)') . '
		WHERE att.attachment_type = 0' . ($attachments_boards === array(0) ? '' : '
			AND m.id_board IN ({array_int:boards_can_see})') . (!empty($attachment_ext) ? '
			AND att.fileext IN ({array_string:attachment_ext})' : '') . (!$modSettings['postmod_active'] || allowedTo('approve_posts') ? '' : '
			AND t.approved = {int:is_approved}
			AND m.approved = {int:is_approved}
			AND att.approved = {int:is_approved}') . '
		ORDER BY att.id_attach DESC
		LIMIT {int:num_attachments}', array('boards_can_see' => $attachments_boards, 'attachment_ext' => $attachment_ext, 'num_attachments' => $num_attachments, 'is_approved' => 1));
    // We have something.
    $attachments = array();
    while ($row = $db->fetch_assoc($request)) {
        $filename = preg_replace('~&amp;#(\\d{1,7}|x[0-9a-fA-F]{1,6});~', '&#\\1;', htmlspecialchars($row['filename'], ENT_COMPAT, 'UTF-8'));
        // Is it an image?
        $attachments[$row['id_attach']] = array('member' => array('id' => $row['id_member'], 'name' => $row['poster_name'], 'link' => empty($row['id_member']) ? $row['poster_name'] : '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '">' . $row['poster_name'] . '</a>'), 'file' => array('filename' => $filename, 'filesize' => round($row['filesize'] / 1024, 2) . $txt['kilobyte'], 'downloads' => $row['downloads'], 'href' => $scripturl . '?action=dlattach;topic=' . $row['id_topic'] . '.0;attach=' . $row['id_attach'], 'link' => '<img src="' . $settings['images_url'] . '/icons/clip.png" alt="" /> <a href="' . $scripturl . '?action=dlattach;topic=' . $row['id_topic'] . '.0;attach=' . $row['id_attach'] . '">' . $filename . '</a>', 'is_image' => !empty($row['width']) && !empty($row['height']) && !empty($modSettings['attachmentShowImages'])), 'topic' => array('id' => $row['id_topic'], 'subject' => $row['subject'], 'href' => $scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . '#msg' . $row['id_msg'], 'link' => '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . '#msg' . $row['id_msg'] . '">' . $row['subject'] . '</a>', 'time' => standardTime($row['poster_time']), 'html_time' => htmlTime($row['poster_time']), 'timestamp' => forum_time(true, $row['poster_time'])));
        // Images.
        if ($attachments[$row['id_attach']]['file']['is_image']) {
            $id_thumb = empty($row['id_thumb']) ? $row['id_attach'] : $row['id_thumb'];
            $attachments[$row['id_attach']]['file']['image'] = array('id' => $id_thumb, 'width' => $row['width'], 'height' => $row['height'], 'img' => '<img src="' . $scripturl . '?action=dlattach;topic=' . $row['id_topic'] . '.0;attach=' . $row['id_attach'] . ';image" alt="' . $filename . '" />', 'thumb' => '<img src="' . $scripturl . '?action=dlattach;topic=' . $row['id_topic'] . '.0;attach=' . $id_thumb . ';image" alt="' . $filename . '" />', 'href' => $scripturl . '?action=dlattach;topic=' . $row['id_topic'] . '.0;attach=' . $id_thumb . ';image', 'link' => '<a href="' . $scripturl . '?action=dlattach;topic=' . $row['id_topic'] . '.0;attach=' . $row['id_attach'] . ';image"><img src="' . $scripturl . '?action=dlattach;topic=' . $row['id_topic'] . '.0;attach=' . $id_thumb . ';image" alt="' . $filename . '" /></a>');
        }
    }
    $db->free_result($request);
    // So you just want an array?  Here you can have it.
    if ($output_method == 'array' || empty($attachments)) {
        return $attachments;
    }
    // Give them the default.
    echo '
		<table class="ssi_downloads" cellpadding="2">
			<tr>
				<th align="left">', $txt['file'], '</th>
				<th align="left">', $txt['posted_by'], '</th>
				<th align="left">', $txt['downloads'], '</th>
				<th align="left">', $txt['filesize'], '</th>
			</tr>';
    foreach ($attachments as $attach) {
        echo '
			<tr>
				<td>', $attach['file']['link'], '</td>
				<td>', $attach['member']['link'], '</td>
				<td align="center">', $attach['file']['downloads'], '</td>
				<td>', $attach['file']['filesize'], '</td>
			</tr>';
    }
    echo '
		</table>';
}
Пример #7
0
/**
 * Loads in $context whatever is needed to show a poll
 *
 * @param int $poll_id simply a poll id...
 */
function loadPollContext($poll_id)
{
    global $context, $user_info, $txt, $scripturl, $settings;
    // Get the question and if it's locked.
    $pollinfo = pollInfo($poll_id);
    // Get all the options, and calculate the total votes.
    $pollOptions = pollOptionsForMember($poll_id, $user_info['id']);
    // Compute total votes.
    $realtotal = 0;
    $pollinfo['has_voted'] = false;
    foreach ($pollOptions as $choice) {
        $realtotal += $choice['votes'];
        $pollinfo['has_voted'] |= $choice['voted_this'] != -1;
    }
    // If this is a guest we need to do our best to work out if they have voted, and what they voted for.
    if ($user_info['is_guest'] && $pollinfo['guest_vote'] && allowedTo('poll_vote')) {
        if (!empty($_COOKIE['guest_poll_vote']) && preg_match('~^[0-9,;]+$~', $_COOKIE['guest_poll_vote']) && strpos($_COOKIE['guest_poll_vote'], ';' . $poll_id . ',') !== false) {
            // ;id,timestamp,[vote,vote...]; etc
            $guestinfo = explode(';', $_COOKIE['guest_poll_vote']);
            // Find the poll we're after.
            foreach ($guestinfo as $i => $guestvoted) {
                $guestvoted = explode(',', $guestvoted);
                if ($guestvoted[0] == $poll_id) {
                    break;
                }
            }
            // Has the poll been reset since guest voted?
            if ($pollinfo['reset_poll'] > $guestvoted[1]) {
                // Remove the poll info from the cookie to allow guest to vote again
                unset($guestinfo[$i]);
                if (!empty($guestinfo)) {
                    $_COOKIE['guest_poll_vote'] = ';' . implode(';', $guestinfo);
                } else {
                    unset($_COOKIE['guest_poll_vote']);
                }
            } else {
                // What did they vote for?
                unset($guestvoted[0], $guestvoted[1]);
                foreach ($pollOptions as $choice => $details) {
                    $pollOptions[$choice]['voted_this'] = in_array($choice, $guestvoted) ? 1 : -1;
                    $pollinfo['has_voted'] |= $pollOptions[$choice]['voted_this'] != -1;
                }
                unset($choice, $details, $guestvoted);
            }
            unset($guestinfo, $guestvoted, $i);
        }
    }
    // Set up the basic poll information.
    $context['poll'] = array('id' => $poll_id, 'image' => 'normal_' . (empty($pollinfo['voting_locked']) ? 'poll' : 'locked_poll'), 'question' => parse_bbc($pollinfo['question']), 'total_votes' => $pollinfo['total'], 'change_vote' => !empty($pollinfo['change_vote']), 'is_locked' => !empty($pollinfo['voting_locked']), 'options' => array(), 'lock' => allowedTo('poll_lock_any') || $context['user']['started'] && allowedTo('poll_lock_own'), 'edit' => allowedTo('poll_edit_any') || $context['user']['started'] && allowedTo('poll_edit_own'), 'allowed_warning' => $pollinfo['max_votes'] > 1 ? sprintf($txt['poll_options6'], min(count($pollOptions), $pollinfo['max_votes'])) : '', 'is_expired' => !empty($pollinfo['expire_time']) && $pollinfo['expire_time'] < time(), 'expire_time' => !empty($pollinfo['expire_time']) ? standardTime($pollinfo['expire_time']) : 0, 'has_voted' => !empty($pollinfo['has_voted']), 'starter' => array('id' => $pollinfo['id_member'], 'name' => $pollinfo['poster_name'], 'href' => $pollinfo['id_member'] == 0 ? '' : $scripturl . '?action=profile;u=' . $pollinfo['id_member'], 'link' => $pollinfo['id_member'] == 0 ? $pollinfo['poster_name'] : '<a href="' . $scripturl . '?action=profile;u=' . $pollinfo['id_member'] . '">' . $pollinfo['poster_name'] . '</a>'));
    // Make the lock and edit permissions defined above more directly accessible.
    $context['allow_lock_poll'] = $context['poll']['lock'];
    $context['allow_edit_poll'] = $context['poll']['edit'];
    // You're allowed to vote if:
    // 1. the poll did not expire, and
    // 2. you're either not a guest OR guest voting is enabled... and
    // 3. you're not trying to view the results, and
    // 4. the poll is not locked, and
    // 5. you have the proper permissions, and
    // 6. you haven't already voted before.
    $context['allow_vote'] = !$context['poll']['is_expired'] && (!$user_info['is_guest'] || $pollinfo['guest_vote'] && allowedTo('poll_vote')) && empty($pollinfo['voting_locked']) && allowedTo('poll_vote') && !$context['poll']['has_voted'];
    // You're allowed to view the results if:
    // 1. you're just a super-nice-guy, or
    // 2. anyone can see them (hide_results == 0), or
    // 3. you can see them after you voted (hide_results == 1), or
    // 4. you've waited long enough for the poll to expire. (whether hide_results is 1 or 2.)
    $context['allow_poll_view'] = allowedTo('moderate_board') || $pollinfo['hide_results'] == 0 || $pollinfo['hide_results'] == 1 && $context['poll']['has_voted'] || $context['poll']['is_expired'];
    $context['poll']['show_results'] = $context['allow_poll_view'] && (isset($_REQUEST['viewresults']) || isset($_REQUEST['viewResults']));
    // You're allowed to change your vote if:
    // 1. the poll did not expire, and
    // 2. you're not a guest... and
    // 3. the poll is not locked, and
    // 4. you have the proper permissions, and
    // 5. you have already voted, and
    // 6. the poll creator has said you can!
    $context['allow_change_vote'] = !$context['poll']['is_expired'] && !$user_info['is_guest'] && empty($pollinfo['voting_locked']) && allowedTo('poll_vote') && $context['poll']['has_voted'] && $context['poll']['change_vote'];
    // You're allowed to return to voting options if:
    // 1. you are (still) allowed to vote.
    // 2. you are currently seeing the results.
    $context['allow_return_vote'] = $context['allow_vote'] && $context['poll']['show_results'];
    // Calculate the percentages and bar lengths...
    $divisor = $realtotal == 0 ? 1 : $realtotal;
    // Determine if a decimal point is needed in order for the options to add to 100%.
    $precision = $realtotal == 100 ? 0 : 1;
    // Now look through each option, and...
    foreach ($pollOptions as $i => $option) {
        // First calculate the percentage, and then the width of the bar...
        $bar = round($option['votes'] * 100 / $divisor, $precision);
        $barWide = $bar == 0 ? 1 : floor($bar * 8 / 3);
        // Now add it to the poll's contextual theme data.
        $context['poll']['options'][$i] = array('id' => 'options-' . $i, 'percent' => $bar, 'votes' => $option['votes'], 'voted_this' => $option['voted_this'] != -1, 'bar' => '<span style="white-space: nowrap;"><img src="' . $settings['images_url'] . '/poll_' . ($context['right_to_left'] ? 'right' : 'left') . '.png" alt="" /><img src="' . $settings['images_url'] . '/poll_middle.png" style="width:' . $barWide . 'px; height: 12px;" alt="-" /><img src="' . $settings['images_url'] . '/poll_' . ($context['right_to_left'] ? 'left' : 'right') . '.png" alt="" /></span>', 'bar_ndt' => $bar > 0 ? '<div class="bar" style="width: ' . $bar . '%;"><div style="width: ' . $bar . '%;"></div></div>' : '<div class="bar"></div>', 'bar_width' => $barWide, 'option' => parse_bbc($option['label']), 'vote_button' => '<input type="' . ($pollinfo['max_votes'] > 1 ? 'checkbox' : 'radio') . '" name="options[]" id="options-' . $i . '" value="' . $i . '" class="input_' . ($pollinfo['max_votes'] > 1 ? 'check' : 'radio') . '" />');
    }
}
Пример #8
0
/**
 * Retrieve all topic notifications for the given user.
 * (used by createList() callbacks)
 *
 * @param int $start
 * @param int $items_per_page
 * @param string $sort
 * @param int $memID id_member
 * @return array
 */
function topicNotifications($start, $items_per_page, $sort, $memID)
{
    global $scripturl, $user_info, $modSettings;
    $db = database();
    // All the topics with notification on...
    $request = $db->query('', '
		SELECT
			IFNULL(lt.id_msg, IFNULL(lmr.id_msg, -1)) + 1 AS new_from, b.id_board, b.name,
			t.id_topic, ms.subject, ms.id_member, IFNULL(mem.real_name, ms.poster_name) AS real_name_col,
			ml.id_msg_modified, ml.poster_time, ml.id_member AS id_member_updated,
			IFNULL(mem2.real_name, ml.poster_name) AS last_real_name
		FROM {db_prefix}log_notify AS ln
			INNER JOIN {db_prefix}topics AS t ON (t.id_topic = ln.id_topic' . ($modSettings['postmod_active'] ? ' AND t.approved = {int:is_approved}' : '') . ')
			INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board AND {query_see_board})
			INNER JOIN {db_prefix}messages AS ms ON (ms.id_msg = t.id_first_msg)
			INNER JOIN {db_prefix}messages AS ml ON (ml.id_msg = t.id_last_msg)
			LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = ms.id_member)
			LEFT JOIN {db_prefix}members AS mem2 ON (mem2.id_member = ml.id_member)
			LEFT JOIN {db_prefix}log_topics AS lt ON (lt.id_topic = t.id_topic AND lt.id_member = {int:current_member})
			LEFT JOIN {db_prefix}log_mark_read AS lmr ON (lmr.id_board = b.id_board AND lmr.id_member = {int:current_member})
		WHERE ln.id_member = {int:selected_member}
		ORDER BY {raw:sort}
		LIMIT {int:offset}, {int:items_per_page}', array('current_member' => $user_info['id'], 'is_approved' => 1, 'selected_member' => $memID, 'sort' => $sort, 'offset' => $start, 'items_per_page' => $items_per_page));
    $notification_topics = array();
    while ($row = $db->fetch_assoc($request)) {
        censorText($row['subject']);
        $notification_topics[] = array('id' => $row['id_topic'], 'poster_link' => empty($row['id_member']) ? $row['real_name_col'] : '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '">' . $row['real_name_col'] . '</a>', 'poster_updated_link' => empty($row['id_member_updated']) ? $row['last_real_name'] : '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member_updated'] . '">' . $row['last_real_name'] . '</a>', 'subject' => $row['subject'], 'href' => $scripturl . '?topic=' . $row['id_topic'] . '.0', 'link' => '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.0">' . $row['subject'] . '</a>', 'new' => $row['new_from'] <= $row['id_msg_modified'], 'new_from' => $row['new_from'], 'updated' => standardTime($row['poster_time']), 'new_href' => $scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['new_from'] . '#new', 'new_link' => '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['new_from'] . '#new">' . $row['subject'] . '</a>', 'board_link' => '<a href="' . $scripturl . '?board=' . $row['id_board'] . '.0">' . $row['name'] . '</a>');
    }
    $db->free_result($request);
    return $notification_topics;
}
Пример #9
0
 /**
  * Who's online, and what are they doing?
  * This function prepares the who's online data for the Who template.
  * It requires the who_view permission.
  * It is enabled with the who_enabled setting.
  * It is accessed via ?action=who.
  *
  * @uses Who template, main sub-template
  * @uses Who language file.
  */
 public function action_who()
 {
     global $context, $scripturl, $txt, $modSettings, $memberContext;
     // Permissions, permissions, permissions.
     isAllowedTo('who_view');
     // You can't do anything if this is off.
     if (empty($modSettings['who_enabled'])) {
         fatal_lang_error('who_off', false);
     }
     // Load the 'Who' template.
     loadTemplate('Who');
     loadLanguage('Who');
     // Sort out... the column sorting.
     $sort_methods = array('user' => 'mem.real_name', 'time' => 'lo.log_time');
     $show_methods = array('members' => '(lo.id_member != 0)', 'guests' => '(lo.id_member = 0)', 'all' => '1=1');
     // Store the sort methods and the show types for use in the template.
     $context['sort_methods'] = array('user' => $txt['who_user'], 'time' => $txt['who_time']);
     $context['show_methods'] = array('all' => $txt['who_show_all'], 'members' => $txt['who_show_members_only'], 'guests' => $txt['who_show_guests_only']);
     // Can they see spiders too?
     if (!empty($modSettings['show_spider_online']) && ($modSettings['show_spider_online'] == 2 || allowedTo('admin_forum')) && !empty($modSettings['spider_name_cache'])) {
         $show_methods['spiders'] = '(lo.id_member = 0 AND lo.id_spider > 0)';
         $show_methods['guests'] = '(lo.id_member = 0 AND lo.id_spider = 0)';
         $context['show_methods']['spiders'] = $txt['who_show_spiders_only'];
     } elseif (empty($modSettings['show_spider_online']) && isset($_SESSION['who_online_filter']) && $_SESSION['who_online_filter'] == 'spiders') {
         unset($_SESSION['who_online_filter']);
     }
     // Does the user prefer a different sort direction?
     if (isset($_REQUEST['sort']) && isset($sort_methods[$_REQUEST['sort']])) {
         $context['sort_by'] = $_SESSION['who_online_sort_by'] = $_REQUEST['sort'];
         $sort_method = $sort_methods[$_REQUEST['sort']];
     } elseif (isset($_SESSION['who_online_sort_by'])) {
         $context['sort_by'] = $_SESSION['who_online_sort_by'];
         $sort_method = $sort_methods[$_SESSION['who_online_sort_by']];
     } else {
         $context['sort_by'] = $_SESSION['who_online_sort_by'] = 'time';
         $sort_method = 'lo.log_time';
     }
     $context['sort_direction'] = isset($_REQUEST['asc']) || isset($_REQUEST['sort_dir']) && $_REQUEST['sort_dir'] == 'asc' ? 'up' : 'down';
     $conditions = array();
     if (!allowedTo('moderate_forum')) {
         $conditions[] = '(IFNULL(mem.show_online, 1) = 1)';
     }
     // Fallback to top filter?
     if (isset($_REQUEST['submit_top']) && isset($_REQUEST['show_top'])) {
         $_REQUEST['show'] = $_REQUEST['show_top'];
     }
     // Does the user wish to apply a filter?
     if (isset($_REQUEST['show']) && isset($show_methods[$_REQUEST['show']])) {
         $context['show_by'] = $_SESSION['who_online_filter'] = $_REQUEST['show'];
         $conditions[] = $show_methods[$_REQUEST['show']];
     } elseif (isset($_SESSION['who_online_filter'])) {
         $context['show_by'] = $_SESSION['who_online_filter'];
         $conditions[] = $show_methods[$_SESSION['who_online_filter']];
     } else {
         $context['show_by'] = $_SESSION['who_online_filter'] = 'all';
     }
     require_once SUBSDIR . '/Members.subs.php';
     $totalMembers = countMembersOnline($conditions);
     // Prepare some page index variables.
     $context['page_index'] = constructPageIndex($scripturl . '?action=who;sort=' . $context['sort_by'] . ($context['sort_direction'] == 'up' ? ';asc' : '') . ';show=' . $context['show_by'], $_REQUEST['start'], $totalMembers, $modSettings['defaultMaxMembers']);
     $context['start'] = $_REQUEST['start'];
     $context['sub_template'] = 'whos_online';
     Template_Layers::getInstance()->add('whos_selection');
     // Look for people online, provided they don't mind if you see they are.
     $members = onlineMembers($conditions, $sort_method, $context['sort_direction'], $context['start']);
     $context['members'] = array();
     $member_ids = array();
     $url_data = array();
     foreach ($members as $row) {
         $actions = @unserialize($row['url']);
         if ($actions === false) {
             continue;
         }
         // Send the information to the template.
         $context['members'][$row['session']] = array('id' => $row['id_member'], 'ip' => allowedTo('moderate_forum') ? $row['ip'] : '', 'time' => standardTime($row['log_time'], true), 'html_time' => htmlTime($row['log_time']), 'timestamp' => forum_time(true, $row['log_time']), 'query' => $actions, 'is_hidden' => $row['show_online'] == 0, 'id_spider' => $row['id_spider'], 'color' => empty($row['online_color']) ? '' : $row['online_color']);
         $url_data[$row['session']] = array($row['url'], $row['id_member']);
         $member_ids[] = $row['id_member'];
     }
     // Load the user data for these members.
     loadMemberData($member_ids);
     // Load up the guest user.
     $memberContext[0] = array('id' => 0, 'name' => $txt['guest_title'], 'group' => $txt['guest_title'], 'href' => '', 'link' => $txt['guest_title'], 'email' => $txt['guest_title'], 'is_guest' => true);
     // Are we showing spiders?
     $spiderContext = array();
     if (!empty($modSettings['show_spider_online']) && ($modSettings['show_spider_online'] == 2 || allowedTo('admin_forum')) && !empty($modSettings['spider_name_cache'])) {
         foreach (unserialize($modSettings['spider_name_cache']) as $id => $name) {
             $spiderContext[$id] = array('id' => 0, 'name' => $name, 'group' => $txt['spiders'], 'href' => '', 'link' => $name, 'email' => $name, 'is_guest' => true);
         }
     }
     require_once SUBSDIR . '/Who.subs.php';
     $url_data = determineActions($url_data);
     // Setup the linktree and page title (do it down here because the language files are now loaded..)
     $context['page_title'] = $txt['who_title'];
     $context['linktree'][] = array('url' => $scripturl . '?action=who', 'name' => $txt['who_title']);
     // Put it in the context variables.
     foreach ($context['members'] as $i => $member) {
         if ($member['id'] != 0) {
             $member['id'] = loadMemberContext($member['id']) ? $member['id'] : 0;
         }
         // Keep the IP that came from the database.
         $memberContext[$member['id']]['ip'] = $member['ip'];
         $context['members'][$i]['action'] = isset($url_data[$i]) ? $url_data[$i] : $txt['who_hidden'];
         if ($member['id'] == 0 && isset($spiderContext[$member['id_spider']])) {
             $context['members'][$i] += $spiderContext[$member['id_spider']];
         } else {
             $context['members'][$i] += $memberContext[$member['id']];
         }
     }
     // Some people can't send personal messages...
     $context['can_send_pm'] = allowedTo('pm_send');
     $context['can_send_email'] = allowedTo('send_email_to_members');
     // Any profile fields disabled?
     $context['disabled_fields'] = isset($modSettings['disabled_profile_fields']) ? array_flip(explode(',', $modSettings['disabled_profile_fields'])) : array();
 }
Пример #10
0
/**
 * Prepare context for a message.
 *
 * @param mixed[] $message the message array
 */
function prepareMessageContext($message)
{
    global $context, $txt;
    // Load up 'em attachments!
    foreach ($message['attachment_stuff'] as $attachment) {
        $context['attachments']['current'][] = array('name' => htmlspecialchars($attachment['filename'], ENT_COMPAT, 'UTF-8'), 'size' => $attachment['filesize'], 'id' => $attachment['id_attach'], 'approved' => $attachment['attachment_approved']);
    }
    // Allow moderators to change names....
    if (allowedTo('moderate_forum') && empty($message['message']['id_member'])) {
        $context['name'] = htmlspecialchars($message['message']['poster_name'], ENT_COMPAT, 'UTF-8');
        $context['email'] = htmlspecialchars($message['message']['poster_email'], ENT_COMPAT, 'UTF-8');
    }
    // When was it last modified?
    if (!empty($message['message']['modified_time'])) {
        $context['last_modified'] = standardTime($message['message']['modified_time']);
        $context['last_modified_text'] = sprintf($txt['last_edit_by'], $context['last_modified'], $message['message']['modified_name']);
    }
    // Show an "approve" box if the user can approve it, and the message isn't approved.
    if (!$message['message']['approved'] && !$context['show_approval']) {
        $context['show_approval'] = allowedTo('approve_posts');
    }
}
Пример #11
0
/**
 * Make sure the "current user" (uses $user_info) cannot go outside of the limit for the day.
 *
 * @param string $approve_query additional condition for the query
 * @param string $current_view defined whether return the topics (first
 *                messages) or the messages. If set to 'topics' it returns
 *                the topics, otherwise the messages
 * @param mixed[] $boards_allowed array of arrays, it must contain three
 *                 indexes:
 *                  - delete_own_boards
 *                  - delete_any_boards
 *                  - delete_own_replies
 *                 each of which must be an array of boards the user is allowed
 *                 to perform a certain action (return of boardsAllowedTo)
 * @param int $start start of the query LIMIT
 * @param int $limit number of elements to return (default 10)
 */
function getUnapprovedPosts($approve_query, $current_view, $boards_allowed, $start, $limit = 10)
{
    global $context, $scripturl, $user_info;
    $db = database();
    $request = $db->query('', '
		SELECT m.id_msg, m.id_topic, m.id_board, m.subject, m.body, m.id_member,
			IFNULL(mem.real_name, m.poster_name) AS poster_name, m.poster_time, m.smileys_enabled,
			t.id_member_started, t.id_first_msg, b.name AS board_name, c.id_cat, c.name AS cat_name
		FROM {db_prefix}messages AS m
			INNER JOIN {db_prefix}topics AS t ON (t.id_topic = m.id_topic)
			INNER JOIN {db_prefix}boards AS b ON (b.id_board = m.id_board)
			LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)
			LEFT JOIN {db_prefix}categories AS c ON (c.id_cat = b.id_cat)
		WHERE m.approved = {int:not_approved}
			AND t.id_first_msg ' . ($current_view == 'topics' ? '=' : '!=') . ' m.id_msg
			AND {query_see_board}
			' . $approve_query . '
		LIMIT {int:start}, {int:limit}', array('start' => $start, 'limit' => $limit, 'not_approved' => 0));
    $unapproved_items = array();
    for ($i = 1; $row = $db->fetch_assoc($request); $i++) {
        // Can delete is complicated, let's solve it first... is it their own post?
        if ($row['id_member'] == $user_info['id'] && ($boards_allowed['delete_own_boards'] == array(0) || in_array($row['id_board'], $boards_allowed['delete_own_boards']))) {
            $can_delete = true;
        } elseif ($row['id_member'] == $row['id_member_started'] && $row['id_msg'] != $row['id_first_msg'] && ($boards_allowed['delete_own_replies'] == array(0) || in_array($row['id_board'], $boards_allowed['delete_own_replies']))) {
            $can_delete = true;
        } elseif ($row['id_member'] != $user_info['id'] && ($boards_allowed['delete_any_boards'] == array(0) || in_array($row['id_board'], $boards_allowed['delete_any_boards']))) {
            $can_delete = true;
        } else {
            $can_delete = false;
        }
        $unapproved_items[] = array('id' => $row['id_msg'], 'alternate' => $i % 2, 'counter' => $context['start'] + $i, 'href' => $scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . '#msg' . $row['id_msg'], 'link' => '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . '#msg' . $row['id_msg'] . '">' . $row['subject'] . '</a>', 'subject' => $row['subject'], 'body' => parse_bbc($row['body'], $row['smileys_enabled'], $row['id_msg']), 'time' => standardTime($row['poster_time']), 'html_time' => htmlTime($row['poster_time']), 'timestamp' => forum_time(true, $row['poster_time']), 'poster' => array('id' => $row['id_member'], 'name' => $row['poster_name'], 'link' => $row['id_member'] ? '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '">' . $row['poster_name'] . '</a>' : $row['poster_name'], 'href' => $scripturl . '?action=profile;u=' . $row['id_member']), 'topic' => array('id' => $row['id_topic']), 'board' => array('id' => $row['id_board'], 'name' => $row['board_name'], 'link' => '<a href="' . $scripturl . '?board=' . $row['id_board'] . '.0">' . $row['board_name'] . '</a>'), 'category' => array('id' => $row['id_cat'], 'name' => $row['cat_name'], 'link' => '<a href="' . $scripturl . '#c' . $row['id_cat'] . '">' . $row['cat_name'] . '</a>'), 'can_delete' => $can_delete);
    }
    $db->free_result($request);
    return $unapproved_items;
}
Пример #12
0
 /**
  * Format a topic to be printer friendly.
  * Must be called with a topic specified.
  * Accessed via ?action=topic;sa=printpage.
  *
  * @uses Printpage template, main sub-template.
  * @uses print_above/print_below later without the main layer.
  */
 public function action_printpage()
 {
     global $topic, $scripturl, $context, $user_info, $board_info, $modSettings;
     // Redirect to the boardindex if no valid topic id is provided.
     if (empty($topic)) {
         redirectexit();
     }
     $template_layers = Template_Layers::getInstance();
     $template_layers->removeAll();
     if (!empty($modSettings['disable_print_topic'])) {
         unset($_REQUEST['action']);
         $context['theme_loaded'] = false;
         fatal_lang_error('feature_disabled', false);
     }
     require_once SUBSDIR . '/Topic.subs.php';
     // Get the topic starter information.
     $topicinfo = getTopicInfo($topic, 'starter');
     $context['user']['started'] = $user_info['id'] == $topicinfo['id_member'] && !$user_info['is_guest'];
     // Whatever happens don't index this.
     $context['robot_no_index'] = true;
     // Redirect to the boardindex if no valid topic id is provided.
     if (empty($topicinfo)) {
         redirectexit();
     }
     // @todo this code is almost the same as the one in Display.controller.php
     if ($topicinfo['id_poll'] > 0 && !empty($modSettings['pollMode']) && allowedTo('poll_view')) {
         loadLanguage('Post');
         require_once SUBSDIR . '/Poll.subs.php';
         loadPollContext($topicinfo['id_poll']);
         $template_layers->addAfter('print_poll', 'print');
     }
     // Lets "output" all that info.
     loadTemplate('Printpage');
     $template_layers->add('print');
     $context['sub_template'] = 'print_page';
     $context['board_name'] = $board_info['name'];
     $context['category_name'] = $board_info['cat']['name'];
     $context['poster_name'] = $topicinfo['poster_name'];
     $context['post_time'] = standardTime($topicinfo['poster_time'], false);
     $context['parent_boards'] = array();
     foreach ($board_info['parent_boards'] as $parent) {
         $context['parent_boards'][] = $parent['name'];
     }
     // Split the topics up so we can print them.
     $context['posts'] = topicMessages($topic);
     $posts_id = array_keys($context['posts']);
     if (!isset($context['topic_subject'])) {
         $context['topic_subject'] = $context['posts'][min($posts_id)]['subject'];
     }
     // Fetch attachments so we can print them if asked, enabled and allowed
     if (isset($_REQUEST['images']) && !empty($modSettings['attachmentEnable']) && allowedTo('view_attachments')) {
         require_once SUBSDIR . '/Topic.subs.php';
         $context['printattach'] = messagesAttachments(array_keys($context['posts']));
         $context['viewing_attach'] = true;
     }
     // Set a canonical URL for this page.
     $context['canonical_url'] = $scripturl . '?topic=' . $topic . '.0';
     $context['view_attach_mode'] = array('text' => $scripturl . '?action=topic;sa=printpage;topic=' . $topic . '.0', 'images' => $scripturl . '?action=topic;sa=printpage;topic=' . $topic . '.0;images');
 }
Пример #13
0
 function showBusinessHours($str)
 {
     $day_key = array(0 => "Sun", 1 => "Mon", 2 => "Tue", 3 => "Wed", 4 => "Thu", 5 => "Fri", 6 => "Sat");
     $days = explode("|", $str);
     $result = "<div class=\"hofo-container\">\r\n";
     $result .= "<h5 class=\"medium black\" style=\"margin: 3px 0px;\"><u>Business Hours</u></h5>\r\n";
     foreach ($days as $key => $hours) {
         if ($hours != "00:00-00:00") {
             $subresult .= "\t<div class=\"hofo-days small\">\r\n";
             $subresult .= "\t" . $day_key[$key] . "</div>\r\n";
             $subresult .= "\t<div class=\"hofo-hours small\">\r\n";
             $time = null;
             if ($hours == "CL") {
                 $time = "Closed";
             } elseif ($hours == "BA") {
                 $time = "By Appointment";
             } else {
                 $hour = explode("-", $hours);
                 $time = standardTime($hour[0]) . " - " . standardTime($hour[1]);
             }
             $subresult .= "\t" . $time . "</div>\r\n";
         }
     }
     if ($subresult != "") {
         $result .= $subresult . "</div>\r\n";
     } else {
         $result = "Hours not available.  Contact company for hours of operation.";
     }
     return $result;
 }
Пример #14
0
 /**
  * Callback to return messages - saves memory.
  *
  * @todo Fix this, update it, whatever... from Display.controller.php mainly.
  * Note that the call to loadAttachmentContext() doesn't work:
  * this function doesn't fulfill the pre-condition to fill $attachments global...
  * So all it does is to fallback and return.
  *
  * What it does:
  * - callback function for the results sub template.
  * - loads the necessary contextual data to show a search result.
  *
  * @param boolean $reset = false
  * @return array of messages that match the search
  */
 public function prepareSearchContext_callback($reset = false)
 {
     global $txt, $modSettings, $scripturl, $user_info;
     global $memberContext, $context, $settings, $options, $messages_request;
     global $boards_can, $participants;
     // Remember which message this is.  (ie. reply #83)
     static $counter = null;
     if ($counter == null || $reset) {
         $counter = $_REQUEST['start'] + 1;
     }
     // Start from the beginning...
     if ($reset) {
         return currentContext($messages_request, $reset);
     }
     // Attempt to get the next in line
     $message = currentContext($messages_request);
     if (!$message) {
         return false;
     }
     // Can't have an empty subject can we?
     $message['subject'] = $message['subject'] != '' ? $message['subject'] : $txt['no_subject'];
     $message['first_subject'] = $message['first_subject'] != '' ? $message['first_subject'] : $txt['no_subject'];
     $message['last_subject'] = $message['last_subject'] != '' ? $message['last_subject'] : $txt['no_subject'];
     // If it couldn't load, or the user was a guest.... someday may be done with a guest table.
     if (!loadMemberContext($message['id_member'])) {
         // Notice this information isn't used anywhere else.... *cough guest table cough*.
         $memberContext[$message['id_member']]['name'] = $message['poster_name'];
         $memberContext[$message['id_member']]['id'] = 0;
         $memberContext[$message['id_member']]['group'] = $txt['guest_title'];
         $memberContext[$message['id_member']]['link'] = $message['poster_name'];
         $memberContext[$message['id_member']]['email'] = $message['poster_email'];
     }
     $memberContext[$message['id_member']]['ip'] = $message['poster_ip'];
     // Do the censor thang...
     censorText($message['body']);
     censorText($message['subject']);
     censorText($message['first_subject']);
     censorText($message['last_subject']);
     // Shorten this message if necessary.
     if ($context['compact']) {
         // Set the number of characters before and after the searched keyword.
         $charLimit = 50;
         $message['body'] = strtr($message['body'], array("\n" => ' ', '<br />' => "\n"));
         $message['body'] = parse_bbc($message['body'], $message['smileys_enabled'], $message['id_msg']);
         $message['body'] = strip_tags(strtr($message['body'], array('</div>' => '<br />', '</li>' => '<br />')), '<br>');
         if (Util::strlen($message['body']) > $charLimit) {
             if (empty($context['key_words'])) {
                 $message['body'] = Util::substr($message['body'], 0, $charLimit) . '<strong>...</strong>';
             } else {
                 $matchString = '';
                 $force_partial_word = false;
                 foreach ($context['key_words'] as $keyword) {
                     $keyword = un_htmlspecialchars($keyword);
                     $keyword = preg_replace_callback('~(&amp;#(\\d{1,7}|x[0-9a-fA-F]{1,6});)~', 'entity_fix__callback', strtr($keyword, array('\\\'' => '\'', '&' => '&amp;')));
                     if (preg_match('~[\'\\.,/@%&;:(){}\\[\\]_\\-+\\\\]$~', $keyword) != 0 || preg_match('~^[\'\\.,/@%&;:(){}\\[\\]_\\-+\\\\]~', $keyword) != 0) {
                         $force_partial_word = true;
                     }
                     $matchString .= strtr(preg_quote($keyword, '/'), array('\\*' => '.+?')) . '|';
                 }
                 $matchString = un_htmlspecialchars(substr($matchString, 0, -1));
                 $message['body'] = un_htmlspecialchars(strtr($message['body'], array('&nbsp;' => ' ', '<br />' => "\n", '&#91;' => '[', '&#93;' => ']', '&#58;' => ':', '&#64;' => '@')));
                 if (empty($modSettings['search_method']) || $force_partial_word) {
                     preg_match_all('/([^\\s\\W]{' . $charLimit . '}[\\s\\W]|[\\s\\W].{0,' . $charLimit . '}?|^)(' . $matchString . ')(.{0,' . $charLimit . '}[\\s\\W]|[^\\s\\W]{0,' . $charLimit . '})/isu', $message['body'], $matches);
                 } else {
                     preg_match_all('/([^\\s\\W]{' . $charLimit . '}[\\s\\W]|[\\s\\W].{0,' . $charLimit . '}?[\\s\\W]|^)(' . $matchString . ')([\\s\\W].{0,' . $charLimit . '}[\\s\\W]|[\\s\\W][^\\s\\W]{0,' . $charLimit . '})/isu', $message['body'], $matches);
                 }
                 $message['body'] = '';
                 foreach ($matches[0] as $index => $match) {
                     $match = strtr(htmlspecialchars($match, ENT_QUOTES, 'UTF-8'), array("\n" => '&nbsp;'));
                     $message['body'] .= '<strong>......</strong>&nbsp;' . $match . '&nbsp;<strong>......</strong>';
                 }
             }
             // Re-fix the international characters.
             $message['body'] = preg_replace_callback('~(&amp;#(\\d{1,7}|x[0-9a-fA-F]{1,6});)~', 'entity_fix__callback', $message['body']);
         }
     } else {
         // Run BBC interpreter on the message.
         $message['body'] = parse_bbc($message['body'], $message['smileys_enabled'], $message['id_msg']);
     }
     // Make sure we don't end up with a practically empty message body.
     $message['body'] = preg_replace('~^(?:&nbsp;)+$~', '', $message['body']);
     // Sadly, we need to check that the icon is not broken.
     if (!empty($modSettings['messageIconChecks_enable'])) {
         if (!isset($context['icon_sources'][$message['first_icon']])) {
             $context['icon_sources'][$message['first_icon']] = file_exists($settings['theme_dir'] . '/images/post/' . $message['first_icon'] . '.png') ? 'images_url' : 'default_images_url';
         }
         if (!isset($context['icon_sources'][$message['last_icon']])) {
             $context['icon_sources'][$message['last_icon']] = file_exists($settings['theme_dir'] . '/images/post/' . $message['last_icon'] . '.png') ? 'images_url' : 'default_images_url';
         }
         if (!isset($context['icon_sources'][$message['icon']])) {
             $context['icon_sources'][$message['icon']] = file_exists($settings['theme_dir'] . '/images/post/' . $message['icon'] . '.png') ? 'images_url' : 'default_images_url';
         }
     } else {
         if (!isset($context['icon_sources'][$message['first_icon']])) {
             $context['icon_sources'][$message['first_icon']] = 'images_url';
         }
         if (!isset($context['icon_sources'][$message['last_icon']])) {
             $context['icon_sources'][$message['last_icon']] = 'images_url';
         }
         if (!isset($context['icon_sources'][$message['icon']])) {
             $context['icon_sources'][$message['icon']] = 'images_url';
         }
     }
     // Do we have quote tag enabled?
     $quote_enabled = empty($modSettings['disabledBBC']) || !in_array('quote', explode(',', $modSettings['disabledBBC']));
     $output = array_merge($context['topics'][$message['id_msg']], array('id' => $message['id_topic'], 'is_sticky' => !empty($modSettings['enableStickyTopics']) && !empty($message['is_sticky']), 'is_locked' => !empty($message['locked']), 'is_poll' => !empty($modSettings['pollMode']) && $message['id_poll'] > 0, 'is_hot' => !empty($modSettings['useLikesNotViews']) ? $message['num_likes'] >= $modSettings['hotTopicPosts'] : $message['num_replies'] >= $modSettings['hotTopicPosts'], 'is_very_hot' => !empty($modSettings['useLikesNotViews']) ? $message['num_likes'] >= $modSettings['hotTopicVeryPosts'] : $message['num_replies'] >= $modSettings['hotTopicVeryPosts'], 'posted_in' => !empty($participants[$message['id_topic']]), 'views' => $message['num_views'], 'replies' => $message['num_replies'], 'tests' => array('can_reply' => in_array($message['id_board'], $boards_can['post_reply_any']) || in_array(0, $boards_can['post_reply_any']), 'can_quote' => (in_array($message['id_board'], $boards_can['post_reply_any']) || in_array(0, $boards_can['post_reply_any'])) && $quote_enabled, 'can_mark_notify' => in_array($message['id_board'], $boards_can['mark_any_notify']) || in_array(0, $boards_can['mark_any_notify']) && !$context['user']['is_guest']), 'first_post' => array('id' => $message['first_msg'], 'time' => standardTime($message['first_poster_time']), 'html_time' => htmlTime($message['first_poster_time']), 'timestamp' => forum_time(true, $message['first_poster_time']), 'subject' => $message['first_subject'], 'href' => $scripturl . '?topic=' . $message['id_topic'] . '.0', 'link' => '<a href="' . $scripturl . '?topic=' . $message['id_topic'] . '.0">' . $message['first_subject'] . '</a>', 'icon' => $message['first_icon'], 'icon_url' => $settings[$context['icon_sources'][$message['first_icon']]] . '/post/' . $message['first_icon'] . '.png', 'member' => array('id' => $message['first_member_id'], 'name' => $message['first_member_name'], 'href' => !empty($message['first_member_id']) ? $scripturl . '?action=profile;u=' . $message['first_member_id'] : '', 'link' => !empty($message['first_member_id']) ? '<a href="' . $scripturl . '?action=profile;u=' . $message['first_member_id'] . '" title="' . $txt['profile_of'] . ' ' . $message['first_member_name'] . '">' . $message['first_member_name'] . '</a>' : $message['first_member_name'])), 'last_post' => array('id' => $message['last_msg'], 'time' => standardTime($message['last_poster_time']), 'html_time' => htmlTime($message['last_poster_time']), 'timestamp' => forum_time(true, $message['last_poster_time']), 'subject' => $message['last_subject'], 'href' => $scripturl . '?topic=' . $message['id_topic'] . ($message['num_replies'] == 0 ? '.0' : '.msg' . $message['last_msg']) . '#msg' . $message['last_msg'], 'link' => '<a href="' . $scripturl . '?topic=' . $message['id_topic'] . ($message['num_replies'] == 0 ? '.0' : '.msg' . $message['last_msg']) . '#msg' . $message['last_msg'] . '">' . $message['last_subject'] . '</a>', 'icon' => $message['last_icon'], 'icon_url' => $settings[$context['icon_sources'][$message['last_icon']]] . '/post/' . $message['last_icon'] . '.png', 'member' => array('id' => $message['last_member_id'], 'name' => $message['last_member_name'], 'href' => !empty($message['last_member_id']) ? $scripturl . '?action=profile;u=' . $message['last_member_id'] : '', 'link' => !empty($message['last_member_id']) ? '<a href="' . $scripturl . '?action=profile;u=' . $message['last_member_id'] . '" title="' . $txt['profile_of'] . ' ' . $message['last_member_name'] . '">' . $message['last_member_name'] . '</a>' : $message['last_member_name'])), 'board' => array('id' => $message['id_board'], 'name' => $message['board_name'], 'href' => $scripturl . '?board=' . $message['id_board'] . '.0', 'link' => '<a href="' . $scripturl . '?board=' . $message['id_board'] . '.0">' . $message['board_name'] . '</a>'), 'category' => array('id' => $message['id_cat'], 'name' => $message['cat_name'], 'href' => $scripturl . '#c' . $message['id_cat'], 'link' => '<a href="' . $scripturl . '#c' . $message['id_cat'] . '">' . $message['cat_name'] . '</a>')));
     determineTopicClass($output);
     if ($output['posted_in']) {
         $output['class'] = 'my_' . $output['class'];
     }
     $body_highlighted = $message['body'];
     $subject_highlighted = $message['subject'];
     if (!empty($options['display_quick_mod'])) {
         $started = $output['first_post']['member']['id'] == $user_info['id'];
         $output['quick_mod'] = array('lock' => in_array(0, $boards_can['lock_any']) || in_array($output['board']['id'], $boards_can['lock_any']) || $started && (in_array(0, $boards_can['lock_own']) || in_array($output['board']['id'], $boards_can['lock_own'])), 'sticky' => (in_array(0, $boards_can['make_sticky']) || in_array($output['board']['id'], $boards_can['make_sticky'])) && !empty($modSettings['enableStickyTopics']), 'move' => in_array(0, $boards_can['move_any']) || in_array($output['board']['id'], $boards_can['move_any']) || $started && (in_array(0, $boards_can['move_own']) || in_array($output['board']['id'], $boards_can['move_own'])), 'remove' => in_array(0, $boards_can['remove_any']) || in_array($output['board']['id'], $boards_can['remove_any']) || $started && (in_array(0, $boards_can['remove_own']) || in_array($output['board']['id'], $boards_can['remove_own'])));
         $context['can_lock'] |= $output['quick_mod']['lock'];
         $context['can_sticky'] |= $output['quick_mod']['sticky'];
         $context['can_move'] |= $output['quick_mod']['move'];
         $context['can_remove'] |= $output['quick_mod']['remove'];
         $context['can_merge'] |= in_array($output['board']['id'], $boards_can['merge_any']);
         $context['can_markread'] = $context['user']['is_logged'];
         $context['qmod_actions'] = array('remove', 'lock', 'sticky', 'move', 'markread');
         call_integration_hook('integrate_quick_mod_actions_search');
     }
     foreach ($context['key_words'] as $query) {
         // Fix the international characters in the keyword too.
         $query = un_htmlspecialchars($query);
         $query = trim($query, '\\*+');
         $query = strtr(Util::htmlspecialchars($query), array('\\\'' => '\''));
         $body_highlighted = preg_replace_callback('/((<[^>]*)|' . preg_quote(strtr($query, array('\'' => '&#039;')), '/') . ')/iu', array($this, '_highlighted_callback'), $body_highlighted);
         $subject_highlighted = preg_replace('/(' . preg_quote($query, '/') . ')/iu', '<strong class="highlight">$1</strong>', $subject_highlighted);
     }
     require_once SUBSDIR . '/Attachments.subs.php';
     $output['matches'][] = array('id' => $message['id_msg'], 'attachment' => loadAttachmentContext($message['id_msg']), 'alternate' => $counter % 2, 'member' => &$memberContext[$message['id_member']], 'icon' => $message['icon'], 'icon_url' => $settings[$context['icon_sources'][$message['icon']]] . '/post/' . $message['icon'] . '.png', 'subject' => $message['subject'], 'subject_highlighted' => $subject_highlighted, 'time' => standardTime($message['poster_time']), 'html_time' => htmlTime($message['poster_time']), 'timestamp' => forum_time(true, $message['poster_time']), 'counter' => $counter, 'modified' => array('time' => standardTime($message['modified_time']), 'html_time' => htmlTime($message['modified_time']), 'timestamp' => forum_time(true, $message['modified_time']), 'name' => $message['modified_name']), 'body' => $message['body'], 'body_highlighted' => $body_highlighted, 'start' => 'msg' . $message['id_msg']);
     $counter++;
     if (!$context['compact']) {
         $output['buttons'] = array('notify' => array('href' => $scripturl . '?action=notify;topic=' . $output['id'] . '.msg' . $message['id_msg'], 'text' => $txt['notify'], 'test' => 'can_mark_notify'), 'reply' => array('href' => $scripturl . '?action=post;topic=' . $output['id'] . '.msg' . $message['id_msg'], 'text' => $txt['reply'], 'test' => 'can_reply'), 'quote' => array('href' => $scripturl . '?action=post;topic=' . $output['id'] . '.msg' . $message['id_msg'] . ';quote=' . $message['id_msg'], 'text' => $txt['quote'], 'test' => 'can_quote'));
     }
     call_integration_hook('integrate_search_message_context', array($counter, &$output));
     return $output;
 }
/**
 * RSS Block, Displays rss feed in a block.
 *
 * @param mixed[] $parameters
 *		'url' => url of the feed
 *		'show_title' => Show the feed title
 *		'show_content' => Show the content of the feed
 *		'show_date' => Show the date of the feed item
 *		'strip_preserve' => preserve tags
 * 		'count' => number of items to show
 * 		'limit' => number of characters of content to show
 * @param int $id - not used in this block
 * @param boolean $return_parameters if true returns the configuration options for the block
 */
function sp_rssFeed($parameters, $id, $return_parameters = false)
{
    global $txt;
    $block_parameters = array('url' => 'text', 'show_title' => 'check', 'show_content' => 'check', 'show_date' => 'check', 'strip_preserve' => 'text', 'count' => 'int', 'limit' => 'int');
    if ($return_parameters) {
        return $block_parameters;
    }
    $feed = !empty($parameters['url']) ? un_htmlspecialchars($parameters['url']) : '';
    $show_title = !empty($parameters['show_title']);
    $show_content = !empty($parameters['show_content']);
    $show_date = !empty($parameters['show_date']);
    $strip_preserve = !empty($parameters['strip_preserve']) ? $parameters['strip_preserve'] : 'br';
    $strip_preserve = preg_match_all('~[A-Za-z0-9]+~', $strip_preserve, $match) ? $match[0] : array();
    $count = !empty($parameters['count']) ? (int) $parameters['count'] : 5;
    $limit = !empty($parameters['limit']) ? (int) $parameters['limit'] : 0;
    // Need a feed name to load it
    if (empty($feed)) {
        echo '
								', $txt['error_sp_invalid_feed'];
        return;
    }
    $rss = array();
    require_once SUBSDIR . '/Package.subs.php';
    $data = fetch_web_data($feed);
    $data_save = $data;
    // Convert it to UTF8 if we can and its not already
    preg_match('~encoding="([^"]*)"~', $data, $charset);
    if (!empty($charset[1]) && $charset != 'UTF-8') {
        // Use iconv if its available
        if (function_exists('iconv')) {
            $data = @iconv($charset[1], 'UTF-8' . '//TRANSLIT//IGNORE', $data);
        }
        // No iconv or a false response from it
        if (!function_exists('iconv') || $data == false) {
            // PHP (some 5.4 versions) mishandles //TRANSLIT//IGNORE and returns false: see https://bugs.php.net/bug.php?id=61484
            if ($data == false) {
                $data = $data_save;
            }
            if (function_exists('mb_convert_encoding')) {
                // Replace unknown characters with a space
                @ini_set('mbstring.substitute_character', '32');
                $data = @mb_convert_encoding($data, 'UTF-8', $charset[1]);
            } elseif (function_exists('recode_string')) {
                $data = @recode_string($charset[1] . '..' . 'UTF-8', $data);
            }
        }
    }
    $data = str_replace(array("\n", "\r", "\t"), '', $data);
    $data = preg_replace('~<\\!\\[CDATA\\[(.+?)\\]\\]>~eu', '\'#cdata_escape_encode#\' . Util::htmlspecialchars(\'$1\')', $data);
    // Find all the feed items
    preg_match_all('~<item>(.+?)</item>~', $data, $items);
    foreach ($items[1] as $item_id => $item) {
        if ($item_id === $count) {
            break;
        }
        preg_match_all('~<([A-Za-z]+)>(.+?)</\\1>~', $item, $match);
        foreach ($match[0] as $tag_id => $dummy) {
            if (Util::strpos($match[2][$tag_id], '#cdata_escape_encode#') === 0) {
                $match[2][$tag_id] = stripslashes(un_htmlspecialchars(Util::substr($match[2][$tag_id], 21)));
            }
            $rss[$item_id][strtolower($match[1][$tag_id])] = un_htmlspecialchars($match[2][$tag_id]);
        }
    }
    // Nothing, say its invalid
    if (empty($rss)) {
        echo '
								', $txt['error_sp_invalid_feed'];
        return;
    }
    // Add all the items to an array
    $items = array();
    foreach ($rss as $item) {
        $item['title'] = isset($item['title']) ? strip_tags($item['title']) : '';
        $item['description'] = isset($item['description']) ? strip_tags($item['description'], empty($strip_preserve) ? '' : '<' . implode('><', $strip_preserve) . '>') : '';
        $items[] = array('title' => $item['title'], 'href' => $item['link'], 'link' => $item['title'] == '' ? '' : ($item['link'] == '' ? $item['title'] : '<a href="' . $item['link'] . '" target="_blank" class="new_win">' . $item['title'] . '</a>'), 'content' => $limit > 0 ? Util::shorten_text($item['description'], $limit, true) : $item['description'], 'date' => !empty($item['pubdate']) ? standardTime(strtotime($item['pubdate']), '%d %B') : '');
    }
    // No items in the feed
    if (empty($items)) {
        echo '
								', $txt['error_sp_invalid_feed'];
        return;
    } else {
        $items[count($items) - 1]['is_last'] = true;
    }
    if ($show_content) {
        echo '
								<div class="sp_rss_flow">
									<ul class="sp_list">';
        foreach ($items as $item) {
            if ($show_title && !empty($item['link'])) {
                echo '
										<li ', sp_embed_class('post', '', 'sp_list_top'), '><strong>', $item['link'], '</strong>', $show_date && !empty($item['date']) ? ' - ' . $item['date'] : '', '</li>';
            }
            echo '
										<li', empty($item['is_last']) ? ' class="sp_list_divider"' : '', '>', $item['content'], '</li>';
        }
        echo '
									</ul>
								</div>';
    } else {
        echo '
								<ul class="sp_list">';
        foreach ($items as $item) {
            echo '
									<li ', sp_embed_class('dot_feed'), '> ', $item['link'], $show_date && !empty($item['date']) ? ' - ' . $item['date'] : '', '</li>';
        }
        echo '
								</ul>';
    }
}
 public function action_save()
 {
     global $context, $txt;
     require_once SUBSDIR . '/Post.subs.php';
     if (empty($_POST['expire_alt'])) {
         $expire = strtotime($_POST['expire']);
     } else {
         // This is the case date-picker doesn't kick in and the format is still an unix timestamp
         if (is_numeric($_POST['expire_alt'])) {
             $expire = $_POST['expire_alt'];
         } else {
             $expire = strtotime($_POST['expire_alt']);
         }
     }
     $expire = (int) $expire;
     $id = isset($_REQUEST['idnotice']) ? (int) $_REQUEST['idnotice'] : 0;
     $body = isset($_REQUEST['body']) ? Util::htmlspecialchars($_REQUEST['body']) : '';
     $class = isset($_REQUEST['class']) ? Util::htmlspecialchars($_REQUEST['class']) : 'success';
     preparsecode($body);
     $groups = json_encode(array_map('intval', array_keys($_POST['default_groups_list'])));
     $positioning = array('element' => $this->validPositioning(isset($_REQUEST['positioning']) ? $_REQUEST['positioning'] : null), 'element_name' => isset($_REQUEST['element_name']) ? Util::htmlspecialchars($_REQUEST['element_name']) : '', 'position' => isset($_REQUEST['position']) ? (int) $_REQUEST['position'] : 0);
     require_once SUBSDIR . '/DismissibleNotices.class.php';
     $notice = new Dismissible_Notices();
     $new = $notice->save($id, $expire, $body, $class, $groups, $positioning);
     loadTemplate('Json');
     $context['sub_template'] = 'send_json';
     $context['json_data'] = array('id' => $new['id_notice'], 'added' => standardTime($new['added']), 'expire' => Dismissible_Notices_Integrate::formatExpireCol($expire), 'body' => un_htmlspecialchars($body), 'class' => $new['class'], 'groups' => $new['show_to'], 'edit' => '<a data-idnotice="' . $new['id_notice'] . '" class="dismissnotice_editable" href="#">' . $txt['modify'] . '</a>');
 }
Пример #17
0
/**
 * Do some important security checks:
 *
 * What it does:
 * - checks the existence of critical files e.g. install.php
 * - checks for an active admin session.
 * - checks cache directory is writable.
 * - calls secureDirectory to protect attachments & cache.
 * - checks if the forum is in maintance mode.
 */
function doSecurityChecks()
{
    global $modSettings, $context, $maintenance, $user_info, $txt, $scripturl, $user_settings, $options;
    $show_warnings = false;
    if (allowedTo('admin_forum') && !$user_info['is_guest']) {
        // If agreement is enabled, at least the english version shall exists
        if ($modSettings['requireAgreement'] && !file_exists(BOARDDIR . '/agreement.txt')) {
            $context['security_controls_files']['title'] = $txt['generic_warning'];
            $context['security_controls_files']['errors']['agreement'] = $txt['agreement_missing'];
            $show_warnings = true;
        }
        // Cache directory writeable?
        if (!empty($modSettings['cache_enable']) && !is_writable(CACHEDIR)) {
            $context['security_controls_files']['title'] = $txt['generic_warning'];
            $context['security_controls_files']['errors']['cache'] = $txt['cache_writable'];
            $show_warnings = true;
        }
        // @todo add a hook here
        $securityFiles = array('install.php', 'upgrade.php', 'convert.php', 'repair_paths.php', 'repair_settings.php', 'Settings.php~', 'Settings_bak.php~');
        foreach ($securityFiles as $securityFile) {
            if (file_exists(BOARDDIR . '/' . $securityFile)) {
                $context['security_controls_files']['title'] = $txt['security_risk'];
                $context['security_controls_files']['errors'][$securityFile] = sprintf($txt['not_removed'], $securityFile);
                $show_warnings = true;
                if ($securityFile == 'Settings.php~' || $securityFile == 'Settings_bak.php~') {
                    $context['security_controls_files']['errors'][$securityFile] .= '<span class="smalltext">' . sprintf($txt['not_removed_extra'], $securityFile, substr($securityFile, 0, -1)) . '</span>';
                }
            }
        }
        // We are already checking so many files...just few more doesn't make any difference! :P
        require_once SUBSDIR . '/Attachments.subs.php';
        $path = getAttachmentPath();
        secureDirectory($path, true);
        secureDirectory(CACHEDIR);
        // Active admin session?
        if (empty($modSettings['securityDisable']) && (isset($_SESSION['admin_time']) && $_SESSION['admin_time'] + $modSettings['admin_session_lifetime'] * 60 > time())) {
            $context['warning_controls']['admin_session'] = sprintf($txt['admin_session_active'], $scripturl . '?action=admin;area=adminlogoff;redir;' . $context['session_var'] . '=' . $context['session_id']);
        }
        // Maintenance mode enabled?
        if (!empty($maintenance)) {
            $context['warning_controls']['maintenance'] = sprintf($txt['admin_maintenance_active'], $scripturl . '?action=admin;area=serversettings;' . $context['session_var'] . '=' . $context['session_id']);
        }
        // New updates
        if (defined('FORUM_VERSION')) {
            $index = 'new_in_' . str_replace(array('ElkArte ', '.'), array('', '_'), FORUM_VERSION);
            if (!empty($modSettings[$index]) && empty($options['dismissed_' . $index])) {
                $show_warnings = true;
                $context['new_version_updates'] = array('title' => $txt['new_version_updates'], 'errors' => array(replaceBasicActionUrl($txt['new_version_updates_text'])));
            }
        }
    }
    // Check for database errors.
    if (!empty($_SESSION['query_command_denied'])) {
        if ($user_info['is_admin']) {
            $context['security_controls_query']['title'] = $txt['query_command_denied'];
            $show_warnings = true;
            foreach ($_SESSION['query_command_denied'] as $command => $error) {
                $context['security_controls_query']['errors'][$command] = '<pre>' . Util::htmlspecialchars($error) . '</pre>';
            }
        } else {
            $context['security_controls_query']['title'] = $txt['query_command_denied_guests'];
            foreach ($_SESSION['query_command_denied'] as $command => $error) {
                $context['security_controls_query']['errors'][$command] = '<pre>' . sprintf($txt['query_command_denied_guests_msg'], Util::htmlspecialchars($command)) . '</pre>';
            }
        }
    }
    // Are there any members waiting for approval?
    if (allowedTo('moderate_forum') && (!empty($modSettings['registration_method']) && $modSettings['registration_method'] == 2 || !empty($modSettings['approveAccountDeletion'])) && !empty($modSettings['unapprovedMembers'])) {
        $context['warning_controls']['unapproved_members'] = sprintf($txt[$modSettings['unapprovedMembers'] == 1 ? 'approve_one_member_waiting' : 'approve_many_members_waiting'], $scripturl . '?action=admin;area=viewmembers;sa=browse;type=approve', $modSettings['unapprovedMembers']);
    }
    if (!empty($context['open_mod_reports']) && (empty($user_settings['mod_prefs']) || $user_settings['mod_prefs'][0] == 1)) {
        $context['warning_controls']['open_mod_reports'] = '<a href="' . $scripturl . '?action=moderate;area=reports">' . sprintf($txt['mod_reports_waiting'], $context['open_mod_reports']) . '</a>';
    }
    if (isset($_SESSION['ban']['cannot_post'])) {
        // An admin cannot be banned (technically he could), and if it is better he knows.
        $context['security_controls_ban']['title'] = sprintf($txt['you_are_post_banned'], $user_info['is_guest'] ? $txt['guest_title'] : $user_info['name']);
        $show_warnings = true;
        $context['security_controls_ban']['errors']['reason'] = '';
        if (!empty($_SESSION['ban']['cannot_post']['reason'])) {
            $context['security_controls_ban']['errors']['reason'] = $_SESSION['ban']['cannot_post']['reason'];
        }
        if (!empty($_SESSION['ban']['expire_time'])) {
            $context['security_controls_ban']['errors']['reason'] .= '<span class="smalltext">' . sprintf($txt['your_ban_expires'], standardTime($_SESSION['ban']['expire_time'], false)) . '</span>';
        } else {
            $context['security_controls_ban']['errors']['reason'] .= '<span class="smalltext">' . $txt['your_ban_expires_never'] . '</span>';
        }
    }
    // Finally, let's show the layer.
    if ($show_warnings || !empty($context['warning_controls'])) {
        Template_Layers::getInstance()->addAfter('admin_warning', 'body');
    }
}
Пример #18
0
/**
 * Gets the badbehavior log entries that match the specified parameters.
 *
 * @package BadBehavior
 * @param int $start
 * @param int $items_per_page
 * @param string $sort
 * @param string|mixed[]|null $filter
 */
function getBadBehaviorLogEntries($start, $items_per_page, $sort, $filter = '')
{
    global $scripturl;
    $db = database();
    require_once EXTDIR . '/bad-behavior/bad-behavior/responses.inc.php';
    $bb_entries = array();
    $request = $db->query('', '
		SELECT id, ip, date, request_method, request_uri, server_protocol, http_headers, user_agent, request_entity, valid, id_member, session
		FROM {db_prefix}log_badbehavior' . (!empty($filter) ? '
		WHERE ' . $filter['variable'] . ' LIKE {string:filter}' : '') . '
		ORDER BY id ' . ($sort === 'down' ? 'DESC' : '') . '
		LIMIT ' . $start . ', ' . $items_per_page, array('filter' => !empty($filter) ? $filter['value']['sql'] : ''));
    for ($i = 0; $row = $db->fetch_assoc($request); $i++) {
        // Turn the key in to something nice to show
        $key_response = bb2_get_response($row['valid']);
        // Prevent undefined errors and log ..
        if (isset($key_response[0]) && $key_response[0] == '00000000') {
            $key_response['response'] = '';
            $key_response['explanation'] = '';
            $key_response['log'] = '';
        }
        $bb_entries[$row['id']] = array('alternate' => $i % 2 == 0, 'ip' => $row['ip'], 'request_method' => $row['request_method'], 'server_protocol' => $row['server_protocol'], 'user_agent' => array('html' => $row['user_agent'], 'href' => base64_encode($db->escape_wildcard_string($row['user_agent']))), 'request_entity' => $row['request_entity'], 'valid' => array('code' => $row['valid'], 'response' => $key_response['response'], 'explanation' => $key_response['explanation'], 'log' => $key_response['log']), 'member' => array('id' => $row['id_member'], 'ip' => $row['ip'], 'session' => $row['session']), 'time' => standardTime($row['date']), 'html_time' => htmlTime($row['date']), 'timestamp' => forum_time(true, $row['date']), 'request_uri' => array('html' => htmlspecialchars((substr($row['request_uri'], 0, 1) === '?' ? $scripturl : '') . $row['request_uri'], ENT_COMPAT, 'UTF-8'), 'href' => base64_encode($db->escape_wildcard_string($row['request_uri']))), 'http_headers' => array('html' => str_replace("\n", '<br />', $row['http_headers']), 'href' => '#'), 'id' => $row['id']);
    }
    $db->free_result($request);
    return $bb_entries;
}
Пример #19
0
/**
 * Prepare subject and message of an email for the preview box
 *
 * Used in action_mailingcompose and RetrievePreview (Xml.controller.php)
 *
 * @package Mail
 */
function prepareMailingForPreview()
{
    global $context, $modSettings, $scripturl, $user_info, $txt;
    loadLanguage('Errors');
    require_once SUBSDIR . '/Post.subs.php';
    $processing = array('preview_subject' => 'subject', 'preview_message' => 'message');
    // Use the default time format.
    $user_info['time_format'] = $modSettings['time_format'];
    $variables = array('{$board_url}', '{$current_time}', '{$latest_member.link}', '{$latest_member.id}', '{$latest_member.name}');
    $html = $context['send_html'];
    // We might need this in a bit
    $cleanLatestMember = empty($context['send_html']) || $context['send_pm'] ? un_htmlspecialchars($modSettings['latestRealName']) : $modSettings['latestRealName'];
    foreach ($processing as $key => $post) {
        $context[$key] = !empty($_REQUEST[$post]) ? $_REQUEST[$post] : '';
        if (empty($context[$key]) && empty($_REQUEST['xml'])) {
            $context['post_error']['messages'][] = $txt['error_no_' . $post];
        } elseif (!empty($_REQUEST['xml'])) {
            continue;
        }
        preparsecode($context[$key]);
        // Sending as html then we convert any bbc
        if ($html) {
            $enablePostHTML = $modSettings['enablePostHTML'];
            $modSettings['enablePostHTML'] = $context['send_html'];
            $context[$key] = parse_bbc($context[$key]);
            $modSettings['enablePostHTML'] = $enablePostHTML;
        }
        // Replace in all the standard things.
        $context[$key] = str_replace($variables, array(!empty($context['send_html']) ? '<a href="' . $scripturl . '">' . $scripturl . '</a>' : $scripturl, standardTime(forum_time(), false), !empty($context['send_html']) ? '<a href="' . $scripturl . '?action=profile;u=' . $modSettings['latestMember'] . '">' . $cleanLatestMember . '</a>' : ($context['send_pm'] ? '[url=' . $scripturl . '?action=profile;u=' . $modSettings['latestMember'] . ']' . $cleanLatestMember . '[/url]' : $cleanLatestMember), $modSettings['latestMember'], $cleanLatestMember), $context[$key]);
    }
}
Пример #20
0
    /**
     * Fetches a list of boards and (optional) categories including
     * statistical information, sub-boards and moderators.
     *  - Used by both the board index (main data) and the message index (child
     * boards).
     *  - Depending on the include_categories setting returns an associative
     * array with categories->boards->child_boards or an associative array
     * with boards->child_boards.
     *
     * @return array
     */
    public function getBoards()
    {
        global $txt;
        // Find all boards and categories, as well as related information.
        $result_boards = $this->_db->query('boardindex_fetch_boards', '
			SELECT' . ($this->_options['include_categories'] ? '
				c.id_cat, c.name AS cat_name,' : '') . '
				b.id_board, b.name AS board_name, b.description,
				CASE WHEN b.redirect != {string:blank_string} THEN 1 ELSE 0 END AS is_redirect,
				b.num_posts, b.num_topics, b.unapproved_posts, b.unapproved_topics, b.id_parent,
				IFNULL(m.poster_time, 0) AS poster_time, IFNULL(mem.member_name, m.poster_name) AS poster_name,
				m.subject, m.id_topic, IFNULL(mem.real_name, m.poster_name) AS real_name,
				' . ($this->_user['is_guest'] ? ' 1 AS is_read, 0 AS new_from,' : '
				(IFNULL(lb.id_msg, 0) >= b.id_msg_updated) AS is_read, IFNULL(lb.id_msg, -1) + 1 AS new_from,' . ($this->_options['include_categories'] ? '
				c.can_collapse, IFNULL(cc.id_member, 0) AS is_collapsed,' : '')) . '
				IFNULL(mem.id_member, 0) AS id_member, mem.avatar, m.id_msg' . ($this->_options['avatars_on_indexes'] ? ',
				IFNULL(a.id_attach, 0) AS id_attach, a.filename, a.attachment_type, mem.email_address' : '') . '
			FROM {db_prefix}boards AS b' . ($this->_options['include_categories'] ? '
				LEFT JOIN {db_prefix}categories AS c ON (c.id_cat = b.id_cat)' : '') . '
				LEFT JOIN {db_prefix}messages AS m ON (m.id_msg = b.id_last_msg)
				LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)' . ($this->_user['is_guest'] ? '' : '
				LEFT JOIN {db_prefix}log_boards AS lb ON (lb.id_board = b.id_board AND lb.id_member = {int:current_member})' . ($this->_options['include_categories'] ? '
				LEFT JOIN {db_prefix}collapsed_categories AS cc ON (cc.id_cat = c.id_cat AND cc.id_member = {int:current_member})' : '')) . ($this->_options['avatars_on_indexes'] ? '
				LEFT JOIN {db_prefix}attachments AS a ON (a.id_member = m.id_member AND a.id_member != 0)' : '') . '
			WHERE {query_see_board}' . (empty($this->_options['countChildPosts']) ? empty($this->_options['base_level']) ? '' : '
				AND b.child_level >= {int:child_level}' : '
				AND b.child_level BETWEEN ' . $this->_options['base_level'] . ' AND ' . ($this->_options['base_level'] + 1)) . '
			ORDER BY' . ($this->_options['include_categories'] ? ' c.cat_order,' : '') . ' b.board_order', array('current_member' => $this->_user['id'], 'child_level' => $this->_options['base_level'], 'blank_string' => ''));
        // Run through the categories and boards (or only boards)....
        while ($row_board = $this->_db->fetch_assoc($result_boards)) {
            // Perhaps we are ignoring this board?
            $ignoreThisBoard = in_array($row_board['id_board'], $this->_user['ignoreboards']);
            $row_board['is_read'] = !empty($row_board['is_read']) || $ignoreThisBoard ? '1' : '0';
            // Not a child.
            $isChild = false;
            if ($this->_options['include_categories']) {
                // Haven't set this category yet.
                if (empty($this->_categories[$row_board['id_cat']])) {
                    $this->_categories[$row_board['id_cat']] = array('id' => $row_board['id_cat'], 'name' => $row_board['cat_name'], 'is_collapsed' => isset($row_board['can_collapse']) && $row_board['can_collapse'] == 1 && $row_board['is_collapsed'] > 0, 'can_collapse' => isset($row_board['can_collapse']) && $row_board['can_collapse'] == 1, 'collapse_href' => isset($row_board['can_collapse']) ? $this->_scripturl . '?action=collapse;c=' . $row_board['id_cat'] . ';sa=' . ($row_board['is_collapsed'] > 0 ? 'expand;' : 'collapse;') . $this->_session_url . '#c' . $row_board['id_cat'] : '', 'collapse_image' => isset($row_board['can_collapse']) ? '<img src="' . $this->_images_url . ($row_board['is_collapsed'] > 0 ? 'expand.png" alt="+"' : 'collapse.png" alt="-"') . ' />' : '', 'href' => $this->_scripturl . '#c' . $row_board['id_cat'], 'boards' => array(), 'new' => false);
                    $this->_categories[$row_board['id_cat']]['link'] = '<a id="c' . $row_board['id_cat'] . '"></a>' . (!$this->_user['is_guest'] ? '<a href="' . $this->_scripturl . '?action=unread;c=' . $row_board['id_cat'] . '" title="' . sprintf($txt['new_posts_in_category'], strip_tags($row_board['cat_name'])) . '">' . $row_board['cat_name'] . '</a>' : $row_board['cat_name']);
                }
                // If this board has new posts in it (and isn't the recycle bin!) then the category is new.
                if ($this->_recycle_board != $row_board['id_board']) {
                    $this->_categories[$row_board['id_cat']]['new'] |= empty($row_board['is_read']) && $row_board['poster_name'] != '';
                }
                // Avoid showing category unread link where it only has redirection boards.
                $this->_categories[$row_board['id_cat']]['show_unread'] = !empty($this->_categories[$row_board['id_cat']]['show_unread']) ? 1 : !$row_board['is_redirect'];
                // Collapsed category - don't do any of this.
                if ($this->_categories[$row_board['id_cat']]['is_collapsed']) {
                    continue;
                }
                // Let's save some typing.  Climbing the array might be slower, anyhow.
                $this->_current_boards =& $this->_categories[$row_board['id_cat']]['boards'];
            }
            // This is a parent board.
            if ($row_board['id_parent'] == $this->_options['parent_id']) {
                // Is this a new board, or just another moderator?
                if (!isset($this->_current_boards[$row_board['id_board']])) {
                    $this->_current_boards[$row_board['id_board']] = array('new' => empty($row_board['is_read']), 'id' => $row_board['id_board'], 'name' => $row_board['board_name'], 'description' => $row_board['description'], 'moderators' => array(), 'link_moderators' => array(), 'children' => array(), 'link_children' => array(), 'children_new' => false, 'topics' => $row_board['num_topics'], 'posts' => $row_board['num_posts'], 'is_redirect' => $row_board['is_redirect'], 'unapproved_topics' => $row_board['unapproved_topics'], 'unapproved_posts' => $row_board['unapproved_posts'] - $row_board['unapproved_topics'], 'can_approve_posts' => $this->_user['mod_cache_ap'] == array(0) || in_array($row_board['id_board'], $this->_user['mod_cache_ap']), 'href' => $this->_scripturl . '?board=' . $row_board['id_board'] . '.0', 'link' => '<a href="' . $this->_scripturl . '?board=' . $row_board['id_board'] . '.0">' . $row_board['board_name'] . '</a>');
                }
                $this->_boards[$row_board['id_board']] = $this->_options['include_categories'] ? $row_board['id_cat'] : 0;
            } elseif (isset($this->_current_boards[$row_board['id_parent']]['children']) && !isset($this->_current_boards[$row_board['id_parent']]['children'][$row_board['id_board']])) {
                // A valid child!
                $isChild = true;
                $this->_current_boards[$row_board['id_parent']]['children'][$row_board['id_board']] = array('id' => $row_board['id_board'], 'name' => $row_board['board_name'], 'description' => $row_board['description'], 'new' => empty($row_board['is_read']) && $row_board['poster_name'] != '', 'topics' => $row_board['num_topics'], 'posts' => $row_board['num_posts'], 'is_redirect' => $row_board['is_redirect'], 'unapproved_topics' => $row_board['unapproved_topics'], 'unapproved_posts' => $row_board['unapproved_posts'] - $row_board['unapproved_topics'], 'can_approve_posts' => $this->_user['mod_cache_ap'] == array(0) || in_array($row_board['id_board'], $this->_user['mod_cache_ap']), 'href' => $this->_scripturl . '?board=' . $row_board['id_board'] . '.0', 'link' => '<a href="' . $this->_scripturl . '?board=' . $row_board['id_board'] . '.0">' . $row_board['board_name'] . '</a>');
                // Counting sub-board posts is... slow :/.
                if (!empty($this->_options['countChildPosts']) && !$row_board['is_redirect']) {
                    $this->_current_boards[$row_board['id_parent']]['posts'] += $row_board['num_posts'];
                    $this->_current_boards[$row_board['id_parent']]['topics'] += $row_board['num_topics'];
                }
                // Does this board contain new boards?
                $this->_current_boards[$row_board['id_parent']]['children_new'] |= empty($row_board['is_read']);
                // This is easier to use in many cases for the theme....
                $this->_current_boards[$row_board['id_parent']]['link_children'][] =& $this->_current_boards[$row_board['id_parent']]['children'][$row_board['id_board']]['link'];
            } elseif (!empty($this->_options['countChildPosts'])) {
                // @todo why this is not initialized outside the loop?
                if (!isset($parent_map)) {
                    $parent_map = array();
                }
                if (!isset($parent_map[$row_board['id_parent']])) {
                    foreach ($this->_current_boards as $id => $board) {
                        if (!isset($board['children'][$row_board['id_parent']])) {
                            continue;
                        }
                        $parent_map[$row_board['id_parent']] = array(&$this->_current_boards[$id], &$this->_current_boards[$id]['children'][$row_board['id_parent']]);
                        $parent_map[$row_board['id_board']] = array(&$this->_current_boards[$id], &$this->_current_boards[$id]['children'][$row_board['id_parent']]);
                        break;
                    }
                }
                if (isset($parent_map[$row_board['id_parent']]) && !$row_board['is_redirect']) {
                    $parent_map[$row_board['id_parent']][0]['posts'] += $row_board['num_posts'];
                    $parent_map[$row_board['id_parent']][0]['topics'] += $row_board['num_topics'];
                    $parent_map[$row_board['id_parent']][1]['posts'] += $row_board['num_posts'];
                    $parent_map[$row_board['id_parent']][1]['topics'] += $row_board['num_topics'];
                    continue;
                }
                continue;
            } else {
                continue;
            }
            // Prepare the subject, and make sure it's not too long.
            censorText($row_board['subject']);
            $row_board['short_subject'] = Util::shorten_text($row_board['subject'], $this->_subject_length);
            $this_last_post = array('id' => $row_board['id_msg'], 'time' => $row_board['poster_time'] > 0 ? standardTime($row_board['poster_time']) : $txt['not_applicable'], 'html_time' => $row_board['poster_time'] > 0 ? htmlTime($row_board['poster_time']) : $txt['not_applicable'], 'timestamp' => forum_time(true, $row_board['poster_time']), 'subject' => $row_board['short_subject'], 'member' => array('id' => $row_board['id_member'], 'username' => $row_board['poster_name'] != '' ? $row_board['poster_name'] : $txt['not_applicable'], 'name' => $row_board['real_name'], 'href' => $row_board['poster_name'] != '' && !empty($row_board['id_member']) ? $this->_scripturl . '?action=profile;u=' . $row_board['id_member'] : '', 'link' => $row_board['poster_name'] != '' ? !empty($row_board['id_member']) ? '<a href="' . $this->_scripturl . '?action=profile;u=' . $row_board['id_member'] . '">' . $row_board['real_name'] . '</a>' : $row_board['real_name'] : $txt['not_applicable']), 'start' => 'msg' . $row_board['new_from'], 'topic' => $row_board['id_topic']);
            if ($this->_options['avatars_on_indexes']) {
                $this_last_post['member']['avatar'] = determineAvatar($row_board);
            }
            // Provide the href and link.
            if ($row_board['subject'] != '') {
                $this_last_post['href'] = $this->_scripturl . '?topic=' . $row_board['id_topic'] . '.msg' . ($this->_user['is_guest'] ? $row_board['id_msg'] : $row_board['new_from']) . (empty($row_board['is_read']) ? ';boardseen' : '') . '#new';
                $this_last_post['link'] = '<a href="' . $this_last_post['href'] . '" title="' . $row_board['subject'] . '">' . $row_board['short_subject'] . '</a>';
                /* The board's and children's 'last_post's have:
                			time, timestamp (a number that represents the time.), id (of the post), topic (topic id.),
                			link, href, subject, start (where they should go for the first unread post.),
                			and member. (which has id, name, link, href, username in it.) */
                $this_last_post['last_post_message'] = sprintf($txt['last_post_message'], $this_last_post['member']['link'], $this_last_post['link'], $this_last_post['html_time']);
            } else {
                $this_last_post['href'] = '';
                $this_last_post['link'] = $txt['not_applicable'];
                $this_last_post['last_post_message'] = '';
            }
            // Set the last post in the parent board.
            if ($row_board['id_parent'] == $this->_options['parent_id'] || $isChild && !empty($row_board['poster_time']) && $this->_current_boards[$row_board['id_parent']]['last_post']['timestamp'] < forum_time(true, $row_board['poster_time'])) {
                $this->_current_boards[$isChild ? $row_board['id_parent'] : $row_board['id_board']]['last_post'] = $this_last_post;
            }
            // Just in the child...?
            if ($isChild) {
                $this->_current_boards[$row_board['id_parent']]['children'][$row_board['id_board']]['last_post'] = $this_last_post;
                // If there are no posts in this board, it really can't be new...
                $this->_current_boards[$row_board['id_parent']]['children'][$row_board['id_board']]['new'] &= $row_board['poster_name'] != '';
            } elseif ($row_board['poster_name'] == '') {
                $this->_current_boards[$row_board['id_board']]['new'] = false;
            }
            // Determine a global most recent topic.
            if ($this->_options['set_latest_post'] && !empty($row_board['poster_time']) && $row_board['poster_time'] > $this->_latest_post['timestamp'] && !$ignoreThisBoard) {
                $this->_latest_post =& $this->_current_boards[$isChild ? $row_board['id_parent'] : $row_board['id_board']]['last_post'];
            }
        }
        $this->_db->free_result($result_boards);
        if ($this->_options['get_moderators'] && !empty($this->_boards)) {
            $this->_getBoardModerators();
        }
        return $this->_options['include_categories'] ? $this->_categories : $this->_current_boards;
    }
Пример #21
0
/**
 * Dumps the database.
 *
 * What it does:
 * - It writes all of the database to standard output.
 * - It uses gzip compression if compress is set in the URL/post data.
 * - It may possibly time out, and mess up badly if you were relying on it. :P
 * - The data dumped depends on whether "struct" and "data" are passed.
 * - It is called from ManageMaintenance.controller.php.
 */
function DumpDatabase2()
{
    global $db_name, $scripturl, $modSettings, $db_prefix, $db_show_debug;
    // We'll need a db to dump :P
    $database = database();
    // We don't need debug when dumping the database
    $modSettings['disableQueryCheck'] = true;
    $db_show_debug = false;
    // You can't dump nothing!
    if (!isset($_REQUEST['struct']) && !isset($_REQUEST['data'])) {
        $_REQUEST['data'] = true;
    }
    // Attempt to stop from dying...
    @set_time_limit(600);
    $time_limit = ini_get('max_execution_time');
    $start_time = time();
    // @todo ... fail on not getting the requested memory?
    setMemoryLimit('256M');
    $memory_limit = memoryReturnBytes(ini_get('memory_limit')) / 4;
    $current_used_memory = 0;
    $db_backup = '';
    $output_function = 'un_compressed';
    @ob_end_clean();
    // Start saving the output... (don't do it otherwise for memory reasons.)
    if (isset($_REQUEST['compress']) && function_exists('gzencode')) {
        $output_function = 'gzencode';
        // Send faked headers so it will just save the compressed output as a gzip.
        header('Content-Type: application/x-gzip');
        header('Accept-Ranges: bytes');
        header('Content-Encoding: none');
        // Gecko browsers... don't like this. (Mozilla, Firefox, etc.)
        if (!isBrowser('gecko')) {
            header('Content-Transfer-Encoding: binary');
        }
        // The file extension will include .gz...
        $extension = '.sql.gz';
    } else {
        // Get rid of the gzipping alreading being done.
        if (!empty($modSettings['enableCompressedOutput'])) {
            @ob_end_clean();
        } elseif (ob_get_length() != 0) {
            ob_clean();
        }
        // Tell the client to save this file, even though it's text.
        header('Content-Type: ' . (isBrowser('ie') || isBrowser('opera') ? 'application/octetstream' : 'application/octet-stream'));
        header('Content-Encoding: none');
        // This time the extension should just be .sql.
        $extension = '.sql';
    }
    // This should turn off the session URL parser.
    $scripturl = '';
    // Send the proper headers to let them download this file.
    header('Content-Disposition: attachment; filename="' . $db_name . '-' . (empty($_REQUEST['struct']) ? 'data' : (empty($_REQUEST['data']) ? 'structure' : 'complete')) . '_' . strftime('%Y-%m-%d') . $extension . '"');
    header('Cache-Control: private');
    header('Connection: close');
    // This makes things simpler when using it so very very often.
    $crlf = "\r\n";
    // SQL Dump Header.
    $db_chunks = '-- ==========================================================' . $crlf . '--' . $crlf . '-- Database dump of tables in `' . $db_name . '`' . $crlf . '-- ' . standardTime(time(), false) . $crlf . '--' . $crlf . '-- ==========================================================' . $crlf . $crlf;
    // Get all tables in the database....for our installation
    $real_prefix = preg_match('~^(`?)(.+?)\\1\\.(.*?)$~', $db_prefix, $match) === 1 ? $match[3] : $db_prefix;
    $tables = $database->db_list_tables(false, $real_prefix . '%');
    // Dump each table.
    foreach ($tables as $tableName) {
        // Are we dumping the structures?
        if (isset($_REQUEST['struct'])) {
            $db_chunks .= $crlf . '--' . $crlf . '-- Table structure for table `' . $tableName . '`' . $crlf . '--' . $crlf . $crlf . $database->db_table_sql($tableName) . ';' . $crlf;
        } else {
            // This is needed to speedup things later
            $database->db_table_sql($tableName);
        }
        // How about the data?
        if (!isset($_REQUEST['data']) || substr($tableName, -10) == 'log_errors') {
            continue;
        }
        $first_round = true;
        $close_table = false;
        // Are there any rows in this table?
        while ($get_rows = $database->insert_sql($tableName, $first_round)) {
            if (empty($get_rows)) {
                break;
            }
            // Time is what we need here!
            if (function_exists('apache_reset_timeout')) {
                @apache_reset_timeout();
            } elseif (!empty($time_limit) && $start_time + $time_limit - 20 > time()) {
                $start_time = time();
                @set_time_limit(150);
            }
            // for the first pass, start the output with a custom line...
            if ($first_round) {
                $db_chunks .= $crlf . '--' . $crlf . '-- Dumping data in `' . $tableName . '`' . $crlf . '--' . $crlf . $crlf;
                $first_round = false;
            }
            $db_chunks .= $get_rows;
            $current_used_memory += Util::strlen($db_chunks);
            $db_backup .= $db_chunks;
            unset($db_chunks);
            $db_chunks = '';
            if ($current_used_memory > $memory_limit) {
                echo $output_function($db_backup);
                $current_used_memory = 0;
                // This is probably redundant
                unset($db_backup);
                $db_backup = '';
            }
            $close_table = true;
        }
        // No rows to get - skip it.
        if ($close_table) {
            $db_backup .= '-- --------------------------------------------------------' . $crlf;
        }
    }
    // write the last line
    $db_backup .= $crlf . '-- Done' . $crlf;
    echo $output_function($db_backup);
    exit;
}
Пример #22
0
 /**
  * Show an area for the moderator to type into.
  */
 public function block_notes()
 {
     global $context, $scripturl, $txt, $user_info;
     // Are we saving a note?
     if (isset($_POST['makenote']) && isset($_POST['new_note'])) {
         checkSession();
         $new_note = Util::htmlspecialchars(trim($_POST['new_note']));
         // Make sure they actually entered something.
         if (!empty($new_note) && $new_note !== $txt['mc_click_add_note']) {
             // Insert it into the database then!
             addModeratorNote($user_info['id'], $user_info['name'], $new_note);
             // Clear the cache.
             cache_put_data('moderator_notes', null, 240);
             cache_put_data('moderator_notes_total', null, 240);
         }
         // Redirect otherwise people can resubmit.
         redirectexit('action=moderate');
     }
     // Bye... bye...
     if (isset($_GET['notes']) && isset($_GET['delete']) && is_numeric($_GET['delete'])) {
         checkSession('get');
         // Just checkin'!
         $id_delete = (int) $_GET['delete'];
         // Lets delete it.
         removeModeratorNote($id_delete);
         // Clear the cache.
         cache_put_data('moderator_notes', null, 240);
         cache_put_data('moderator_notes_total', null, 240);
         redirectexit('action=moderate');
     }
     // How many notes in total?
     $moderator_notes_total = countModeratorNotes();
     // Grab the current notes. We can only use the cache for the first page of notes.
     $offset = isset($_GET['notes']) && isset($_GET['start']) ? $_GET['start'] : 0;
     $moderator_notes = moderatorNotes($offset);
     // Lets construct a page index.
     $context['page_index'] = constructPageIndex($scripturl . '?action=moderate;area=index;notes', $_GET['start'], $moderator_notes_total, 10);
     $context['start'] = $_GET['start'];
     $context['notes'] = array();
     foreach ($moderator_notes as $note) {
         $context['notes'][] = array('author' => array('id' => $note['id_member'], 'link' => $note['id_member'] ? '<a href="' . $scripturl . '?action=profile;u=' . $note['id_member'] . '" title="' . $txt['on'] . ' ' . strip_tags(standardTime($note['log_time'])) . '">' . $note['member_name'] . '</a>' : $note['member_name']), 'time' => standardTime($note['log_time']), 'html_time' => htmlTime($note['log_time']), 'timestamp' => forum_time(true, $note['log_time']), 'text' => parse_bbc($note['body']), 'delete_href' => $scripturl . '?action=moderate;area=index;notes;delete=' . $note['id_note'] . ';' . $context['session_var'] . '=' . $context['session_id']);
     }
     return 'notes';
 }
Пример #23
0
 /**
  * Callback for the message display.
  * It actually gets and prepares the message context.
  * This method will start over from the beginning if reset is set to true, which is
  * useful for showing an index before or after the posts.
  *
  * @param bool $reset default false.
  */
 public function prepareDisplayContext_callback($reset = false)
 {
     global $settings, $txt, $modSettings, $scripturl, $options, $user_info;
     global $memberContext, $context, $messages_request, $topic;
     static $counter = null;
     // If the query returned false, bail.
     if ($messages_request == false) {
         return false;
     }
     // Remember which message this is.  (ie. reply #83)
     if ($counter === null || $reset) {
         $counter = $context['start'];
     }
     // Start from the beginning...
     if ($reset) {
         return currentContext($messages_request, $reset);
     }
     // Attempt to get the next message.
     $message = currentContext($messages_request);
     if (!$message) {
         return false;
     }
     // $context['icon_sources'] says where each icon should come from - here we set up the ones which will always exist!
     if (empty($context['icon_sources'])) {
         require_once SUBSDIR . '/MessageIndex.subs.php';
         $context['icon_sources'] = MessageTopicIcons();
     }
     // Message Icon Management... check the images exist.
     if (empty($modSettings['messageIconChecks_disable'])) {
         // If the current icon isn't known, then we need to do something...
         if (!isset($context['icon_sources'][$message['icon']])) {
             $context['icon_sources'][$message['icon']] = file_exists($settings['theme_dir'] . '/images/post/' . $message['icon'] . '.png') ? 'images_url' : 'default_images_url';
         }
     } elseif (!isset($context['icon_sources'][$message['icon']])) {
         $context['icon_sources'][$message['icon']] = 'images_url';
     }
     // If you're a lazy bum, you probably didn't give a subject...
     $message['subject'] = $message['subject'] != '' ? $message['subject'] : $txt['no_subject'];
     // Are you allowed to remove at least a single reply?
     $context['can_remove_post'] |= allowedTo('delete_own') && (empty($modSettings['edit_disable_time']) || $message['poster_time'] + $modSettings['edit_disable_time'] * 60 >= time()) && $message['id_member'] == $user_info['id'];
     // Have you liked this post, can you?
     $message['you_liked'] = !empty($context['likes'][$message['id_msg']]['member']) && isset($context['likes'][$message['id_msg']]['member'][$user_info['id']]);
     $message['use_likes'] = allowedTo('like_posts') && ($message['id_member'] != $user_info['id'] || !empty($modSettings['likeAllowSelf'])) && (empty($modSettings['likeMinPosts']) ? true : $modSettings['likeMinPosts'] <= $user_info['posts']);
     $message['like_count'] = !empty($context['likes'][$message['id_msg']]['count']) ? $context['likes'][$message['id_msg']]['count'] : 0;
     // If it couldn't load, or the user was a guest.... someday may be done with a guest table.
     if (!loadMemberContext($message['id_member'], true)) {
         // Notice this information isn't used anywhere else....
         $memberContext[$message['id_member']]['name'] = $message['poster_name'];
         $memberContext[$message['id_member']]['id'] = 0;
         $memberContext[$message['id_member']]['group'] = $txt['guest_title'];
         $memberContext[$message['id_member']]['link'] = $message['poster_name'];
         $memberContext[$message['id_member']]['email'] = $message['poster_email'];
         $memberContext[$message['id_member']]['show_email'] = showEmailAddress(true, 0);
         $memberContext[$message['id_member']]['is_guest'] = true;
     } else {
         $memberContext[$message['id_member']]['can_view_profile'] = allowedTo('profile_view_any') || $message['id_member'] == $user_info['id'] && allowedTo('profile_view_own');
         $memberContext[$message['id_member']]['is_topic_starter'] = $message['id_member'] == $context['topic_starter_id'];
         $memberContext[$message['id_member']]['can_see_warning'] = !isset($context['disabled_fields']['warning_status']) && $memberContext[$message['id_member']]['warning_status'] && ($context['user']['can_mod'] || !$user_info['is_guest'] && !empty($modSettings['warning_show']) && ($modSettings['warning_show'] > 1 || $message['id_member'] == $user_info['id']));
     }
     $memberContext[$message['id_member']]['ip'] = $message['poster_ip'];
     $memberContext[$message['id_member']]['show_profile_buttons'] = $settings['show_profile_buttons'] && (!empty($memberContext[$message['id_member']]['can_view_profile']) || !empty($memberContext[$message['id_member']]['website']['url']) && !isset($context['disabled_fields']['website']) || in_array($memberContext[$message['id_member']]['show_email'], array('yes', 'yes_permission_override', 'no_through_forum')) || $context['can_send_pm']);
     // Do the censor thang.
     censorText($message['body']);
     censorText($message['subject']);
     // Run BBC interpreter on the message.
     $message['body'] = parse_bbc($message['body'], $message['smileys_enabled'], $message['id_msg']);
     // Compose the memory eat- I mean message array.
     require_once SUBSDIR . '/Attachments.subs.php';
     $output = array('attachment' => loadAttachmentContext($message['id_msg']), 'alternate' => $counter % 2, 'id' => $message['id_msg'], 'href' => $scripturl . '?topic=' . $topic . '.msg' . $message['id_msg'] . '#msg' . $message['id_msg'], 'link' => '<a href="' . $scripturl . '?topic=' . $topic . '.msg' . $message['id_msg'] . '#msg' . $message['id_msg'] . '" rel="nofollow">' . $message['subject'] . '</a>', 'member' => &$memberContext[$message['id_member']], 'icon' => $message['icon'], 'icon_url' => $settings[$context['icon_sources'][$message['icon']]] . '/post/' . $message['icon'] . '.png', 'subject' => $message['subject'], 'time' => standardTime($message['poster_time']), 'html_time' => htmlTime($message['poster_time']), 'timestamp' => forum_time(true, $message['poster_time']), 'counter' => $counter, 'modified' => array('time' => standardTime($message['modified_time']), 'html_time' => htmlTime($message['modified_time']), 'timestamp' => forum_time(true, $message['modified_time']), 'name' => $message['modified_name']), 'body' => $message['body'], 'new' => empty($message['is_read']), 'approved' => $message['approved'], 'first_new' => isset($context['start_from']) && $context['start_from'] == $counter, 'is_ignored' => !empty($modSettings['enable_buddylist']) && in_array($message['id_member'], $context['user']['ignoreusers']), 'is_message_author' => $message['id_member'] == $user_info['id'], 'can_approve' => !$message['approved'] && $context['can_approve'], 'can_unapprove' => !empty($modSettings['postmod_active']) && $context['can_approve'] && $message['approved'], 'can_modify' => (!$context['is_locked'] || allowedTo('moderate_board')) && (allowedTo('modify_any') || allowedTo('modify_replies') && $context['user']['started'] || allowedTo('modify_own') && $message['id_member'] == $user_info['id'] && (empty($modSettings['edit_disable_time']) || !$message['approved'] || $message['poster_time'] + $modSettings['edit_disable_time'] * 60 > time())), 'can_remove' => allowedTo('delete_any') || allowedTo('delete_replies') && $context['user']['started'] || allowedTo('delete_own') && $message['id_member'] == $user_info['id'] && (empty($modSettings['edit_disable_time']) || $message['poster_time'] + $modSettings['edit_disable_time'] * 60 > time()), 'can_see_ip' => allowedTo('moderate_forum') || $message['id_member'] == $user_info['id'] && !empty($user_info['id']), 'can_like' => $message['use_likes'] && !$message['you_liked'], 'can_unlike' => $message['use_likes'] && $message['you_liked'], 'like_counter' => $message['like_count'], 'likes_enabled' => !empty($modSettings['likes_enabled']) && ($message['use_likes'] || $message['like_count'] != 0));
     if (!empty($output['modified']['name'])) {
         $output['modified']['last_edit_text'] = sprintf($txt['last_edit_by'], $output['modified']['time'], $output['modified']['name'], standardTime($output['modified']['timestamp']));
     }
     if (!empty($output['member']['karma']['allow'])) {
         $output['member']['karma'] += array('applaud_url' => $scripturl . '?action=karma;sa=applaud;uid=' . $output['member']['id'] . ';topic=' . $context['current_topic'] . '.' . $context['start'] . ';m=' . $output['id'] . ';' . $context['session_var'] . '=' . $context['session_id'], 'smite_url' => $scripturl . '?action=karma;sa=smite;uid=' . $output['member']['id'] . ';topic=' . $context['current_topic'] . '.' . $context['start'] . ';m=' . $output['id'] . ';' . $context['session_var'] . '=' . $context['session_id']);
     }
     call_integration_hook('integrate_prepare_display_context', array(&$output, &$message));
     $counter++;
     return $output;
 }
Пример #24
0
/**
 * Loads all of the members subscriptions from those that are active
 *
 * @param int $memID id of the member
 * @param mixed[] $active_subscriptions array of active subscriptions they can have
 */
function loadMemberSubscriptions($memID, $active_subscriptions)
{
    global $txt;
    $db = database();
    // Get the current subscriptions.
    $request = $db->query('', '
		SELECT
			id_sublog, id_subscribe, start_time, end_time, status, payments_pending, pending_details
		FROM {db_prefix}log_subscribed
		WHERE id_member = {int:selected_member}', array('selected_member' => $memID));
    $current = array();
    while ($row = $db->fetch_assoc($request)) {
        // The subscription must exist!
        if (!isset($active_subscriptions[$row['id_subscribe']])) {
            continue;
        }
        $current[$row['id_subscribe']] = array('id' => $row['id_sublog'], 'sub_id' => $row['id_subscribe'], 'hide' => $row['status'] == 0 && $row['end_time'] == 0 && $row['payments_pending'] == 0, 'name' => $active_subscriptions[$row['id_subscribe']]['name'], 'start' => standardTime($row['start_time'], false), 'end' => $row['end_time'] == 0 ? $txt['not_applicable'] : standardTime($row['end_time'], false), 'pending_details' => $row['pending_details'], 'status' => $row['status'], 'status_text' => $row['status'] == 0 ? $row['payments_pending'] ? $txt['paid_pending'] : $txt['paid_finished'] : $txt['paid_active']);
    }
    $db->free_result($request);
    return $current;
}
/**
 * Loads all of the articles in the system
 * Returns an indexed array of the articles
 *
 * @param int $start
 * @param int $items_per_page
 * @param string $sort
 */
function sp_load_articles($start, $items_per_page, $sort)
{
    global $scripturl, $txt, $context;
    $db = database();
    $request = $db->query('', '
		SELECT
			spa.id_article, spa.id_category, spc.name, spc.namespace AS category_namespace,
			IFNULL(m.id_member, 0) AS id_author, IFNULL(m.real_name, spa.member_name) AS author_name,
			spa.namespace AS article_namespace, spa.title, spa.type, spa.date, spa.status
		FROM {db_prefix}sp_articles AS spa
			INNER JOIN {db_prefix}sp_categories AS spc ON (spc.id_category = spa.id_category)
			LEFT JOIN {db_prefix}members AS m ON (m.id_member = spa.id_member)
		ORDER BY {raw:sort}
		LIMIT {int:start}, {int:limit}', array('sort' => $sort, 'start' => $start, 'limit' => $items_per_page));
    $articles = array();
    while ($row = $db->fetch_assoc($request)) {
        $articles[$row['id_article']] = array('id' => $row['id_article'], 'article_id' => $row['article_namespace'], 'title' => $row['title'], 'href' => $scripturl . '?article=' . $row['article_namespace'], 'link' => '<a href="' . $scripturl . '?article=' . $row['article_namespace'] . '">' . $row['title'] . '</a>', 'category_name' => $row['name'], 'author_name' => $row['author_name'], 'category' => array('id' => $row['id_category'], 'name' => $row['name'], 'href' => $scripturl . '?category=' . $row['category_namespace'], 'link' => '<a href="' . $scripturl . '?category=' . $row['category_namespace'] . '">' . $row['name'] . '</a>'), 'author' => array('id' => $row['id_author'], 'name' => $row['author_name'], 'href' => $scripturl . '?action=profile;u=' . $row['id_author'], 'link' => $row['id_author'] ? '<a href="' . $scripturl . '?action=profile;u=' . $row['id_author'] . '">' . $row['author_name'] . '</a>' : $row['author_name']), 'type' => $row['type'], 'type_text' => $txt['sp_articles_type_' . $row['type']], 'date' => standardTime($row['date']), 'status' => $row['status'], 'status_image' => '<a href="' . $scripturl . '?action=admin;area=portalarticles;sa=status;article_id=' . $row['id_article'] . ';' . $context['session_var'] . '=' . $context['session_id'] . '">' . sp_embed_image(empty($row['status']) ? 'deactive' : 'active', $txt['sp_admin_articles_' . (!empty($row['status']) ? 'de' : '') . 'activate']) . '</a>', 'actions' => array('edit' => '<a href="' . $scripturl . '?action=admin;area=portalarticles;sa=edit;article_id=' . $row['id_article'] . ';' . $context['session_var'] . '=' . $context['session_id'] . '">' . sp_embed_image('modify') . '</a>', 'delete' => '<a href="' . $scripturl . '?action=admin;area=portalarticles;sa=delete;article_id=' . $row['id_article'] . ';' . $context['session_var'] . '=' . $context['session_id'] . '" onclick="return confirm(\'', $txt['sp_admin_articles_delete_confirm'], '\');">' . sp_embed_image('delete') . '</a>'));
    }
    $db->free_result($request);
    return $articles;
}
Пример #26
0
/**
 * Get the data about a users warnings.
 * Returns an array of them
 *
 * @param int $start
 * @param int $items_per_page
 * @param string $sort
 * @param int $memID the member ID
 */
function list_getUserWarnings($start, $items_per_page, $sort, $memID)
{
    global $scripturl;
    $db = database();
    $request = $db->query('', '
		SELECT IFNULL(mem.id_member, 0) AS id_member, IFNULL(mem.real_name, lc.member_name) AS member_name,
			lc.log_time, lc.body, lc.counter, lc.id_notice
		FROM {db_prefix}log_comments AS lc
			LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = lc.id_member)
		WHERE lc.id_recipient = {int:selected_member}
			AND lc.comment_type = {string:warning}
		ORDER BY ' . $sort . '
		LIMIT ' . $start . ', ' . $items_per_page, array('selected_member' => $memID, 'warning' => 'warning'));
    $previous_warnings = array();
    while ($row = $db->fetch_assoc($request)) {
        $previous_warnings[] = array('issuer' => array('id' => $row['id_member'], 'link' => $row['id_member'] ? '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '">' . $row['member_name'] . '</a>' : $row['member_name']), 'time' => standardTime($row['log_time']), 'html_time' => htmlTime($row['log_time']), 'timestamp' => forum_time(true, $row['log_time']), 'reason' => $row['body'], 'counter' => $row['counter'] > 0 ? '+' . $row['counter'] : $row['counter'], 'id_notice' => $row['id_notice']);
    }
    $db->free_result($request);
    return $previous_warnings;
}
Пример #27
0
/**
 * Get the latest post made on the system
 *
 * - respects approved, recycled, and board permissions
 *
 * @package Posts
 * @return array
 */
function lastPost()
{
    global $scripturl, $modSettings;
    $db = database();
    // Find it by the board - better to order by board than sort the entire messages table.
    $request = $db->query('substring', '
		SELECT ml.poster_time, ml.subject, ml.id_topic, ml.poster_name, SUBSTRING(ml.body, 1, 385) AS body,
			ml.smileys_enabled
		FROM {db_prefix}boards AS b
			INNER JOIN {db_prefix}messages AS ml ON (ml.id_msg = b.id_last_msg)
		WHERE {query_wanna_see_board}' . (!empty($modSettings['recycle_enable']) && $modSettings['recycle_board'] > 0 ? '
			AND b.id_board != {int:recycle_board}' : '') . '
			AND ml.approved = {int:is_approved}
		ORDER BY b.id_msg_updated DESC
		LIMIT 1', array('recycle_board' => $modSettings['recycle_board'], 'is_approved' => 1));
    if ($db->num_rows($request) == 0) {
        return array();
    }
    $row = $db->fetch_assoc($request);
    $db->free_result($request);
    // Censor the subject and post...
    censorText($row['subject']);
    censorText($row['body']);
    $row['body'] = strip_tags(strtr(parse_bbc($row['body'], $row['smileys_enabled']), array('<br />' => '&#10;')));
    $row['body'] = Util::shorten_text($row['body'], !empty($modSettings['lastpost_preview_characters']) ? $modSettings['lastpost_preview_characters'] : 128, true);
    // Send the data.
    return array('topic' => $row['id_topic'], 'subject' => $row['subject'], 'short_subject' => Util::shorten_text($row['subject'], $modSettings['subject_length']), 'preview' => $row['body'], 'time' => standardTime($row['poster_time']), 'html_time' => htmlTime($row['poster_time']), 'timestamp' => forum_time(true, $row['poster_time']), 'href' => $scripturl . '?topic=' . $row['id_topic'] . '.new;topicseen#new', 'link' => '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.new;topicseen#new">' . $row['subject'] . '</a>');
}
/**
 * Loads all the shouts for a given shoutbox
 *
 * @param int $shoutbox id of the shoutbox to get data from
 * @param mixed[] $parameters
 *
 * @return type
 */
function sportal_get_shouts($shoutbox, $parameters)
{
    global $scripturl, $context, $user_info, $modSettings, $txt;
    $db = database();
    // Set defaults or used what was passed
    $shoutbox = !empty($shoutbox) ? (int) $shoutbox : 0;
    $start = !empty($parameters['start']) ? (int) $parameters['start'] : 0;
    $limit = !empty($parameters['limit']) ? (int) $parameters['limit'] : 20;
    $bbc = !empty($parameters['bbc']) ? $parameters['bbc'] : array();
    $reverse = !empty($parameters['reverse']);
    $cache = !empty($parameters['cache']);
    $can_delete = !empty($parameters['can_moderate']);
    // Cached, use it first
    if (!empty($start) || !$cache || ($shouts = cache_get_data('shoutbox_shouts-' . $shoutbox, 240)) === null) {
        $request = $db->query('', '
			SELECT
				sh.id_shout, sh.body, IFNULL(mem.id_member, 0) AS id_member,
				IFNULL(mem.real_name, sh.member_name) AS member_name, sh.log_time,
				mg.online_color AS member_group_color, pg.online_color AS post_group_color
			FROM {db_prefix}sp_shouts AS sh
				LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = sh.id_member)
				LEFT JOIN {db_prefix}membergroups AS pg ON (pg.id_group = mem.id_post_group)
				LEFT JOIN {db_prefix}membergroups AS mg ON (mg.id_group = mem.id_group)
			WHERE sh.id_shoutbox = {int:id_shoutbox}
			ORDER BY sh.id_shout DESC
			LIMIT {int:start}, {int:limit}', array('id_shoutbox' => $shoutbox, 'start' => $start, 'limit' => $limit));
        $shouts = array();
        while ($row = $db->fetch_assoc($request)) {
            // Disable the aeva mod for the shoutbox.
            $context['aeva_disable'] = true;
            $online_color = !empty($row['member_group_color']) ? $row['member_group_color'] : $row['post_group_color'];
            $shouts[$row['id_shout']] = array('id' => $row['id_shout'], 'author' => array('id' => $row['id_member'], 'name' => $row['member_name'], 'link' => $row['id_member'] ? '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '" title="' . $txt['on'] . ' ' . strip_tags(standardTime($row['log_time'])) . '"' . (!empty($online_color) ? ' style="color: ' . $online_color . ';"' : '') . '>' . $row['member_name'] . '</a>' : $row['member_name'], 'color' => $online_color), 'time' => $row['log_time'], 'text' => parse_bbc($row['body'], true, '', $bbc));
        }
        $db->free_result($request);
        if (empty($start) && $cache) {
            cache_put_data('shoutbox_shouts-' . $shoutbox, $shouts, 240);
        }
    }
    foreach ($shouts as $shout) {
        // Private shouts @username: only get shown to the shouter and shoutee, and the admin
        if (preg_match('~^@(.+?): ~u', $shout['text'], $target) && Util::strtolower($target[1]) !== Util::strtolower($user_info['name']) && $shout['author']['id'] != $user_info['id'] && !$user_info['is_admin']) {
            unset($shouts[$shout['id']]);
            continue;
        }
        $shouts[$shout['id']] += array('is_me' => preg_match('~^<div\\sclass="meaction">\\* ' . preg_quote($shout['author']['name'], '~') . '.+</div>$~', $shout['text']) != 0, 'delete_link' => $can_delete ? '<a class="dot dotdelete" href="' . $scripturl . '?action=shoutbox;shoutbox_id=' . $shoutbox . ';delete=' . $shout['id'] . ';' . $context['session_var'] . '=' . $context['session_id'] . '"></a> ' : '', 'delete_link_js' => $can_delete ? '<a class="dot dotdelete" href="' . $scripturl . '?action=shoutbox;shoutbox_id=' . $shoutbox . ';delete=' . $shout['id'] . ';' . $context['session_var'] . '=' . $context['session_id'] . '" onclick="sp_delete_shout(' . $shoutbox . ', ' . $shout['id'] . ', \'' . $context['session_var'] . '\', \'' . $context['session_id'] . '\'); return false;"></a> ' : '');
        // Prepare for display in the box
        $shouts[$shout['id']]['time'] = standardTime($shouts[$shout['id']]['time']);
        $shouts[$shout['id']]['text'] = preg_replace('~(</?)div([^<]*>)~', '$1span$2', $shouts[$shout['id']]['text']);
        $shouts[$shout['id']]['text'] = preg_replace('~<a([^>]+>)([^<]+)</a>~', '<a$1' . $txt['sp_link'] . '</a>', $shouts[$shout['id']]['text']);
        $shouts[$shout['id']]['text'] = censorText($shouts[$shout['id']]['text']);
        // Ignored user, hide the shout with option to show it
        if (!empty($modSettings['enable_buddylist']) && in_array($shout['author']['id'], $context['user']['ignoreusers'])) {
            $shouts[$shout['id']]['text'] = '<a href="#toggle" id="ignored_shout_link_' . $shout['id'] . '" onclick="sp_show_ignored_shout(' . $shout['id'] . '); return false;">[' . $txt['sp_shoutbox_show_ignored'] . ']</a><span id="ignored_shout_' . $shout['id'] . '" style="display: none;">' . $shouts[$shout['id']]['text'] . '</span>';
        }
    }
    if ($reverse) {
        $shouts = array_reverse($shouts);
    }
    return $shouts;
}
 /**
  * Function for editing a task.
  *
  * @uses ManageScheduledTasks template, edit_scheduled_tasks sub-template
  */
 public function action_edit()
 {
     global $context, $txt;
     // Just set up some lovely context stuff.
     $context[$context['admin_menu_name']]['current_subsection'] = 'tasks';
     $context['sub_template'] = 'edit_scheduled_tasks';
     $context['page_title'] = $txt['scheduled_task_edit'];
     $context['server_time'] = standardTime(time(), false, 'server');
     // We'll need this to calculate the next event.
     require_once SUBSDIR . '/ScheduledTasks.subs.php';
     // Cleaning...
     if (!isset($_GET['tid'])) {
         fatal_lang_error('no_access', false);
     }
     $_GET['tid'] = (int) $_GET['tid'];
     // Saving?
     if (isset($_GET['save'])) {
         checkSession();
         validateToken('admin-st');
         // Do we have a valid offset?
         preg_match('~(\\d{1,2}):(\\d{1,2})~', $_POST['offset'], $matches);
         // If a half is empty then assume zero offset!
         if (!isset($matches[2]) || $matches[2] > 59) {
             $matches[2] = 0;
         }
         if (!isset($matches[1]) || $matches[1] > 23) {
             $matches[1] = 0;
         }
         // Now the offset is easy; easy peasy - except we need to offset by a few hours...
         $offset = $matches[1] * 3600 + $matches[2] * 60 - date('Z');
         // The other time bits are simple!
         $interval = max((int) $_POST['regularity'], 1);
         $unit = in_array(substr($_POST['unit'], 0, 1), array('m', 'h', 'd', 'w')) ? substr($_POST['unit'], 0, 1) : 'd';
         // Don't allow one minute intervals.
         if ($interval == 1 && $unit == 'm') {
             $interval = 2;
         }
         // Is it disabled?
         $disabled = !isset($_POST['enabled']) ? 1 : 0;
         // Do the update!
         $_GET['tid'] = (int) $_GET['tid'];
         updateTask($_GET['tid'], $disabled, $offset, $interval, $unit);
         // Check the next event.
         calculateNextTrigger($_GET['tid'], true);
         // Return to the main list.
         redirectexit('action=admin;area=scheduledtasks');
     }
     // Load the task, understand? Que? Que?
     $_GET['tid'] = (int) $_GET['tid'];
     $context['task'] = loadTaskDetails($_GET['tid']);
     createToken('admin-st');
 }
Пример #30
0
/**
 * For a supplied list of message id's, loads the posting details for each.
 *  - Intended to get all the most recent posts.
 *  - Tracks the posts made by this user (from the supplied message list) and
 *    loads the id's in to the 'own' or 'any' array.
 *    Reminder The controller needs to check permissions
 *  - Returns two arrays, one of the posts one of any/own
 *
 * @param int[] $messages
 * @param int $start
 */
function getRecentPosts($messages, $start)
{
    global $user_info, $scripturl, $modSettings;
    $db = database();
    // Get all the most recent posts.
    $request = $db->query('', '
		SELECT
			m.id_msg, m.subject, m.smileys_enabled, m.poster_time, m.body, m.id_topic, t.id_board, b.id_cat,
			b.name AS bname, c.name AS cname, t.num_replies, m.id_member, m2.id_member AS id_first_member,
			IFNULL(mem2.real_name, m2.poster_name) AS first_poster_name, t.id_first_msg,
			IFNULL(mem.real_name, m.poster_name) AS poster_name, t.id_last_msg
		FROM {db_prefix}messages AS m
			INNER JOIN {db_prefix}topics AS t ON (t.id_topic = m.id_topic)
			INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board)
			INNER JOIN {db_prefix}categories AS c ON (c.id_cat = b.id_cat)
			INNER JOIN {db_prefix}messages AS m2 ON (m2.id_msg = t.id_first_msg)
			LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)
			LEFT JOIN {db_prefix}members AS mem2 ON (mem2.id_member = m2.id_member)
		WHERE m.id_msg IN ({array_int:message_list})
		ORDER BY m.id_msg DESC
		LIMIT ' . count($messages), array('message_list' => $messages));
    $counter = $start + 1;
    $posts = array();
    $board_ids = array('own' => array(), 'any' => array());
    while ($row = $db->fetch_assoc($request)) {
        // Censor everything.
        censorText($row['body']);
        censorText($row['subject']);
        // BBC-atize the message.
        $row['body'] = parse_bbc($row['body'], $row['smileys_enabled'], $row['id_msg']);
        // And build the array.
        $posts[$row['id_msg']] = array('id' => $row['id_msg'], 'counter' => $counter++, 'alternate' => $counter % 2, 'category' => array('id' => $row['id_cat'], 'name' => $row['cname'], 'href' => $scripturl . '#c' . $row['id_cat'], 'link' => '<a href="' . $scripturl . '#c' . $row['id_cat'] . '">' . $row['cname'] . '</a>'), 'board' => array('id' => $row['id_board'], 'name' => $row['bname'], 'href' => $scripturl . '?board=' . $row['id_board'] . '.0', 'link' => '<a href="' . $scripturl . '?board=' . $row['id_board'] . '.0">' . $row['bname'] . '</a>'), 'topic' => $row['id_topic'], 'href' => $scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . '#msg' . $row['id_msg'], 'link' => '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . '#msg' . $row['id_msg'] . '" rel="nofollow">' . $row['subject'] . '</a>', 'start' => $row['num_replies'], 'subject' => $row['subject'], 'time' => standardTime($row['poster_time']), 'html_time' => htmlTime($row['poster_time']), 'timestamp' => forum_time(true, $row['poster_time']), 'first_poster' => array('id' => $row['id_first_member'], 'name' => $row['first_poster_name'], 'href' => empty($row['id_first_member']) ? '' : $scripturl . '?action=profile;u=' . $row['id_first_member'], 'link' => empty($row['id_first_member']) ? $row['first_poster_name'] : '<a href="' . $scripturl . '?action=profile;u=' . $row['id_first_member'] . '">' . $row['first_poster_name'] . '</a>'), 'poster' => array('id' => $row['id_member'], 'name' => $row['poster_name'], 'href' => empty($row['id_member']) ? '' : $scripturl . '?action=profile;u=' . $row['id_member'], 'link' => empty($row['id_member']) ? $row['poster_name'] : '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '">' . $row['poster_name'] . '</a>'), 'body' => $row['body'], 'message' => $row['body'], 'tests' => array('can_reply' => false, 'can_mark_notify' => false, 'can_delete' => false), 'delete_possible' => ($row['id_first_msg'] != $row['id_msg'] || $row['id_last_msg'] == $row['id_msg']) && (empty($modSettings['edit_disable_time']) || $row['poster_time'] + $modSettings['edit_disable_time'] * 60 >= time()));
        if ($user_info['id'] == $row['id_first_member']) {
            $board_ids['own'][$row['id_board']][] = $row['id_msg'];
        }
        $board_ids['any'][$row['id_board']][] = $row['id_msg'];
    }
    $db->free_result($request);
    return array($posts, $board_ids);
}