function getAttachments($imap, $mailNum, $part, $partNum)
{
    $attachments = array();
    if (isset($part->parts)) {
        foreach ($part->parts as $key => $subpart) {
            if ($partNum != "") {
                $newPartNum = $partNum . "." . ($key + 1);
            } else {
                $newPartNum = $key + 1;
            }
            $result = getAttachments($imap, $mailNum, $subpart, $newPartNum);
            if (count($result) != 0) {
                array_push($attachments, $result);
            }
        }
    } else {
        if (isset($part->disposition)) {
            if ($part->disposition == "ATTACHMENT") {
                $partStruct = imap_bodystruct($imap, $mailNum, $partNum);
                $attachmentDetails = array("name" => $part->dparameters[0]->value, "partNum" => $partNum, "enc" => $partStruct->encoding);
                return $attachmentDetails;
            }
        }
    }
    return $attachments;
}
示例#2
0
 function get_attachments($id)
 {
     global $log;
     $log->debug("Entering get_attachments() method ...");
     $query = "SELECT ec_attachments.*, ec_users.user_name\n\t\t\t\tFROM ec_attachments\t\t\t\n\t\t\t\tINNER JOIN ec_users\n\t\t\t\t\tON ec_attachments.smcreatorid = ec_users.id\n\t\t\t\tINNER JOIN ec_seattachmentsrel ON ec_seattachmentsrel.attachmentsid = ec_attachments.attachmentsid\n\t\t\t\tWHERE  ec_attachments.deleted=0 and ec_seattachmentsrel.crmid = " . $id;
     $log->debug("Exiting get_attachments method ...");
     return getAttachments($this->module_name, $query, $id);
 }
示例#3
0
文件: ttml.php 项目: ragi79/Textcube
function FM_TTML_bindAttachments($entryId, $folderPath, $folderURL, $content, $useAbsolutePath = false, $bRssMode = false)
{
    $context = Model_Context::getInstance();
    requireModel('blog.attachment');
    $blogid = getBlogId();
    getAttachments($blogid, $entryId);
    // For attachment caching.
    $view = str_replace('[##_ATTACH_PATH_##]', $useAbsolutePath ? $context->getProperty('uri.service') . "/attach/{$blogid}" : $folderURL, $content);
    $view = str_replace('http://tt_attach_path/', $useAbsolutePath ? $context->getProperty('uri.service') . "/attach/{$blogid}/" : $folderURL . '/', $view);
    $count = 0;
    $bWritedGalleryJS = false;
    while (($start = strpos($view, '[##_')) !== false && ($end = strpos($view, '_##]', $start + 4)) !== false) {
        $count++;
        $attributes = explode('|', substr($view, $start + 4, $end - $start - 4));
        $prefix = '';
        $buf = '';
        if ($attributes[0] == 'Gallery') {
            if (count($attributes) % 2 == 1) {
                array_pop($attributes);
            }
            if (defined('__TEXTCUBE_MOBILE__') || defined('__TEXTCUBE_IPHONE__')) {
                $images = array_slice($attributes, 1, count($attributes) - 2);
                for ($i = 0; $i < count($images); $i++) {
                    if (!empty($images[$i])) {
                        if ($i % 2 == 0) {
                            $buf .= '<div align="center">' . FM_TTML_getAttachmentBinder($images[$i], '', $folderPath, $folderURL, 1, $useAbsolutePath, $bRssMode) . '</div>';
                        } else {
                            if (strlen($images[$i]) > 0) {
                                $buf .= "<div align=\"center\">{$images[$i]}</div>";
                            }
                        }
                    }
                }
            } else {
                if ($bRssMode == true) {
                    $items = array();
                    for ($i = 1; $i < sizeof($attributes) - 2; $i += 2) {
                        array_push($items, array($attributes[$i], $attributes[$i + 1]));
                    }
                    $galleryAttributes = Misc::getAttributesFromString($attributes[sizeof($attributes) - 1]);
                    $images = array_slice($attributes, 1, count($attributes) - 2);
                    for ($i = 0; $i < count($images); $i++) {
                        if (!empty($images[$i])) {
                            if ($i % 2 == 0) {
                                $setWidth = $setHeight = 0;
                                if (list($width, $height) = @getimagesize("{$folderPath}/{$images[$i]}")) {
                                    $setWidth = $width;
                                    $setHeight = $height;
                                    if (isset($galleryAttributes['width']) && $galleryAttributes['width'] < $setWidth) {
                                        $setHeight = $setHeight * $galleryAttributes['width'] / $setWidth;
                                        $setWidth = $galleryAttributes['width'];
                                    }
                                    if (isset($galleryAttributes['height']) && $galleryAttributes['height'] < $setHeight) {
                                        $setWidth = $setWidth * $galleryAttributes['height'] / $setHeight;
                                        $setHeight = $galleryAttributes['height'];
                                    }
                                    if (intval($setWidth > 0) && intval($setHeight) > 0) {
                                        $tempProperty = 'width="' . intval($setWidth) . '" height="' . intval($setHeight) . '"';
                                    } else {
                                        $tempProperty = '';
                                    }
                                    $buf .= '<div align="center">' . FM_TTML_getAttachmentBinder($images[$i], $tempProperty, $folderPath, $folderURL, 1, $useAbsolutePath, $bRssMode) . '</div>';
                                }
                            } else {
                                if (strlen($images[$i]) > 0) {
                                    $buf .= "<div align=\"center\">{$images[$i]}</div>";
                                }
                            }
                        }
                    }
                } else {
                    $id = "gallery{$entryId}{$count}";
                    $cssId = "tt-gallery-{$entryId}-{$count}";
                    $contentWidth = Misc::getContentWidth();
                    $items = array();
                    for ($i = 1; $i < sizeof($attributes) - 2; $i += 2) {
                        array_push($items, array($attributes[$i], $attributes[$i + 1]));
                    }
                    $galleryAttributes = Misc::getAttributesFromString($attributes[sizeof($attributes) - 1]);
                    if (!isset($galleryAttributes['width'])) {
                        $galleryAttributes['width'] = $contentWidth;
                    }
                    if (!isset($galleryAttributes['height'])) {
                        $galleryAttributes['height'] = 3 / 4 * $galleryAttributes['width'];
                    }
                    if ($galleryAttributes['width'] > $contentWidth) {
                        $galleryAttributes['height'] = $galleryAttributes['height'] * $contentWidth / $galleryAttributes['width'];
                        $galleryAttributes['width'] = $contentWidth;
                    }
                    if ($useAbsolutePath == true && $bWritedGalleryJS == false) {
                        $bWritedGalleryJS = true;
                        $buf .= printScript('gallery.js');
                    }
                    $buf .= CRLF . '<div id="' . $cssId . '" class="tt-gallery-box">' . CRLF;
                    $buf .= '	<script type="text/javascript">' . CRLF;
                    $buf .= '		//<![CDATA[' . CRLF;
                    $buf .= "\t\t\tvar {$id} = new TTGallery(\"{$cssId}\");" . CRLF;
                    $buf .= "\t\t\t{$id}.prevText = \"" . _text('이전 이미지 보기') . "\"; " . CRLF;
                    $buf .= "\t\t\t{$id}.nextText = \"" . _text('다음 이미지 보기') . "\"; " . CRLF;
                    $buf .= "\t\t\t{$id}.enlargeText = \"" . _text('원본 크기로 보기') . "\"; " . CRLF;
                    $buf .= "\t\t\t{$id}.altText = \"" . _text('갤러리 이미지') . "\"; " . CRLF;
                    foreach ($items as $item) {
                        $setWidth = $setHeight = 0;
                        if (list($width, $height) = @getimagesize("{$folderPath}/{$item['0']}")) {
                            $setWidth = $width;
                            $setHeight = $height;
                            if (isset($galleryAttributes['width']) && $galleryAttributes['width'] < $setWidth) {
                                $setHeight = $setHeight * $galleryAttributes['width'] / $setWidth;
                                $setWidth = $galleryAttributes['width'];
                            }
                            if (isset($galleryAttributes['height']) && $galleryAttributes['height'] < $setHeight) {
                                $setWidth = $setWidth * $galleryAttributes['height'] / $setHeight;
                                $setHeight = $galleryAttributes['height'];
                            }
                            $item[1] = str_replace("'", '&#39;', $item[1]);
                            $buf .= $id . '.appendImage("' . ($useAbsolutePath ? $context->getProperty('uri.service') . "/attach/{$blogid}/{$item['0']}" : "{$folderURL}/{$item['0']}") . '", "' . htmlspecialchars($item[1]) . '", ' . intval($setWidth) . ', ' . intval($setHeight) . ");";
                        }
                    }
                    $buf .= "\t\t\t{$id}.show();" . CRLF;
                    $buf .= "\t\t//]]>" . CRLF;
                    $buf .= '	</script>' . CRLF;
                    $buf .= '	<noscript>' . CRLF;
                    foreach ($items as $item) {
                        $setWidth = $setHeight = 0;
                        if (list($width, $height) = @getimagesize("{$folderPath}/{$item['0']}")) {
                            $setWidth = $width;
                            $setHeight = $height;
                            if (isset($galleryAttributes['width']) && $galleryAttributes['width'] < $setWidth) {
                                $setHeight = $setHeight * $galleryAttributes['width'] / $setWidth;
                                $setWidth = $galleryAttributes['width'];
                            }
                            if (isset($galleryAttributes['height']) && $galleryAttributes['height'] < $setHeight) {
                                $setWidth = $setWidth * $galleryAttributes['height'] / $setHeight;
                                $setHeight = $galleryAttributes['height'];
                            }
                            $buf .= '<div class="imageblock center" style="text-align: center; clear: both;">';
                            if ($useAbsolutePath) {
                                $buf .= '		<img src="' . $context->getProperty('uri.service') . "/attach/" . $blogid . "/" . $item[0] . '" width="' . intval($setWidth) . '" height="' . intval($setHeight) . '" alt="' . _text('사용자 삽입 이미지') . '" />' . CRLF;
                            } else {
                                $buf .= '		<img src="' . $folderURL . "/" . $item[0] . '" width="' . intval($setWidth) . '" height="' . intval($setHeight) . '" alt="' . _text('사용자 삽입 이미지') . '" />' . CRLF;
                            }
                            if (!empty($item[1])) {
                                $buf .= '		<p class="cap1">' . $item[1] . '</p>' . CRLF;
                            }
                            $buf .= '</div>';
                        }
                    }
                    $buf .= '	</noscript>' . CRLF;
                    $buf .= '</div>' . CRLF;
                }
            }
        } else {
            if ($attributes[0] == 'iMazing') {
                if (defined('__TEXTCUBE_MOBILE__') || defined('__TEXTCUBE_IPHONE__') || $bRssMode == true) {
                    $images = array_slice($attributes, 1, count($attributes) - 3);
                    for ($i = 0; $i < count($images); $i += 2) {
                        if (!empty($images[$i])) {
                            $buf .= '<div>' . FM_TTML_getAttachmentBinder($images[$i], '', $folderPath, $folderURL, 1, $useAbsolutePath) . '</div>';
                        }
                    }
                    $buf .= $attributes[count($attributes) - 1];
                } else {
                    $params = Misc::getAttributesFromString($attributes[sizeof($attributes) - 2]);
                    $id = $entryId . $count;
                    $imgs = array_slice($attributes, 1, count($attributes) - 3);
                    $imgStr = '';
                    for ($i = 0; $i < count($imgs); $i += 2) {
                        if ($imgs[$i] != '') {
                            $imgStr .= $context->getProperty('service.path') . '/attach/' . $blogid . '/' . $imgs[$i];
                            if ($i < count($imgs) - 2) {
                                $imgStr .= '*!';
                            }
                        }
                    }
                    if (!empty($attributes[count($attributes) - 1])) {
                        $caption = '<p class="cap1">' . $attributes[count($attributes) - 1] . '</p>';
                    } else {
                        $caption = '';
                    }
                    $buf .= '<div style="clear: both; text-align: center"><img src="' . ($useAbsolutePath ? $context->getProperty('uri.service') : $context->getProperty('service.path')) . '/resources/image/gallery/gallery_enlarge.gif" alt="' . _text('확대') . '" style="cursor:pointer" onclick="openFullScreen(\'' . $context->getProperty('service.path') . '/iMazing?d=' . urlencode($id) . '&f=' . urlencode($params['frame']) . '&t=' . urlencode($params['transition']) . '&n=' . urlencode($params['navigation']) . '&si=' . urlencode($params['slideshowinterval']) . '&p=' . urlencode($params['page']) . '&a=' . urlencode($params['align']) . '&o=' . $blogid . '&i=' . $imgStr . '\',\'' . htmlspecialchars(str_replace("'", "&#39;", $attributes[count($attributes) - 1])) . '\',\'' . $context->getProperty('service.path') . '\')" />';
                    $buf .= '<div id="iMazingContainer' . $id . '" class="iMazingContainer" style="width:' . $params['width'] . 'px; height:' . $params['height'] . 'px;"></div><script type="text/javascript">//<![CDATA[' . CRLF;
                    $buf .= 'iMazing' . $id . 'Str = getEmbedCode(\'' . $context->getProperty('service.path') . '/resources/script/gallery/iMazing/main.swf\',\'100%\',\'100%\',\'iMazing' . $id . '\',\'#FFFFFF\',"image=' . $imgStr . '&amp;frame=' . $params['frame'] . '&amp;transition=' . $params['transition'] . '&amp;navigation=' . $params['navigation'] . '&amp;slideshowInterval=' . $params['slideshowinterval'] . '&amp;page=' . $params['page'] . '&amp;align=' . $params['align'] . '&amp;skinPath=' . $context->getProperty('service.path') . '/resources/script/gallery/iMazing/&amp;","false"); writeCode(iMazing' . $id . 'Str, "iMazingContainer' . $id . '");';
                    $buf .= '//]]></script><noscript>';
                    for ($i = 0; $i < count($imgs); $i += 2) {
                        $buf .= '<img src="' . ($useAbsolutePath ? $context->getProperty('uri.service') : $context->getProperty('service.path')) . '/attach/' . $blogid . '/' . $imgs[$i] . '" alt="" />';
                    }
                    $buf .= '</noscript>';
                    $buf .= $caption . '</div>';
                }
            } else {
                if ($attributes[0] == 'Jukebox') {
                    if (defined('__TEXTCUBE_MOBILE__') || defined('__TEXTCUBE_IPHONE__')) {
                        $sounds = array_slice($attributes, 1, count($attributes) - 3);
                        for ($i = 0; $i < count($sounds); $i += 2) {
                            if (!empty($sounds[$i])) {
                                echo "<a href=\"{$folderURL}/{$sounds[$i]}\">{$sounds[$i]}</a><br />";
                            }
                        }
                    } else {
                        $params = Misc::getAttributesFromString($attributes[sizeof($attributes) - 2]);
                        foreach ($params as $key => $value) {
                            if ($key == 'autoPlay') {
                                unset($params['autoplay']);
                                $params['autoplay'] = $value;
                            }
                        }
                        if ($params['visible'] == 1) {
                            $width = '250px';
                            $height = '27px';
                        } else {
                            $width = '0px';
                            $height = '0px';
                        }
                        $id = $entryId . $count;
                        $imgs = array_slice($attributes, 1, count($attributes) - 3);
                        $imgStr = '';
                        for ($i = 0; $i < count($imgs); $i++) {
                            if ($imgs[$i] == '') {
                                continue;
                            }
                            if ($i % 2 == 1) {
                                $imgStr .= urlencode($imgs[$i]) . '_*';
                                continue;
                            } else {
                                if ($i < count($imgs) - 1) {
                                    $imgStr .= $context->getProperty('service.path') . "/attach/{$blogid}/" . urlencode($imgs[$i]) . '*!';
                                }
                            }
                        }
                        if (!empty($attributes[count($attributes) - 1])) {
                            $caption = '<div class="cap1" style="text-align: center">' . $attributes[count($attributes) - 1] . '</div>';
                        } else {
                            $caption = '';
                        }
                        $buf .= '<div id="jukeBox' . $id . 'Div" style="margin-left: auto; margin-right: auto; width:' . $width . '; height:' . $height . ';"><div id="jukeBoxContainer' . $id . '" style="width:' . $width . '; height:' . $height . ';"></div>';
                        $buf .= '<script type="text/javascript">//<![CDATA[' . CRLF;
                        $buf .= 'writeCode(getEmbedCode(\'' . $context->getProperty('service.path') . '/resources/script/jukebox/flash/main.swf\',\'100%\',\'100%\',\'jukeBox' . $id . 'Flash\',\'#FFFFFF\',"sounds=' . $imgStr . '&amp;autoplay=' . $params['autoplay'] . '&amp;visible=' . $params['visible'] . '&amp;id=' . $id . '","false"), "jukeBoxContainer' . $id . '")';
                        $buf .= '//]]></script><noscript>';
                        for ($i = 0; $i < count($imgs); $i++) {
                            if ($i % 2 == 0) {
                                $buf .= '<a href="' . ($useAbsolutePath ? $context->getProperty('uri.service') : $context->getProperty('service.path')) . '/attach/' . $blogid . '/' . $imgs[$i] . '">';
                            } else {
                                $buf .= htmlspecialchars($imgs[$i]) . '</a><br/>';
                            }
                        }
                        $buf .= '</noscript>';
                        $buf .= '</div>';
                    }
                } else {
                    $contentWidth = Misc::getContentWidth();
                    switch (count($attributes)) {
                        case 4:
                            list($newProperty, $onclickFlag) = FM_TTML_createNewProperty($attributes[1], $contentWidth, $attributes[2]);
                            if (defined('__TEXTCUBE_MOBILE__') || defined('__TEXTCUBE_IPHONE__')) {
                                $buf = '<div>' . FM_TTML_getAttachmentBinder($attributes[1], $newProperty, $folderPath, $folderURL, 1, $useAbsolutePath) . "</div><div>{$attributes['3']}</div>";
                            } else {
                                if (trim($attributes[3]) == '') {
                                    $caption = '';
                                } else {
                                    $caption = '<p class="cap1">' . $attributes[3] . '</p>';
                                }
                                switch ($attributes[0]) {
                                    case '1L':
                                        $prefix = '<div class="imageblock left" style="float: left; margin-right: 10px;">';
                                        break;
                                    case '1R':
                                        $prefix = '<div class="imageblock right" style="float: right; margin-left: 10px;">';
                                        break;
                                    case '1C':
                                    default:
                                        $prefix = '<div class="imageblock center" style="text-align: center; clear: both;">';
                                        break;
                                }
                                $buf = $prefix . FM_TTML_getAttachmentBinder($attributes[1], $newProperty, $folderPath, $folderURL, 1, $useAbsolutePath, $bRssMode, $onclickFlag) . $caption . '</div>';
                            }
                            break;
                        case 7:
                            $eachImageWidth = floor(($contentWidth - 5 * 3) / 2);
                            list($newProperty1, $onclickFlag1) = FM_TTML_createNewProperty($attributes[1], $eachImageWidth, $attributes[2]);
                            list($newProperty2, $onclickFlag2) = FM_TTML_createNewProperty($attributes[4], $eachImageWidth, $attributes[5]);
                            if (defined('__TEXTCUBE_MOBILE__') || defined('__TEXTCUBE_IPHONE__')) {
                                $buf = '<div>' . FM_TTML_getAttachmentBinder($attributes[1], $newProperty1, $folderPath, $folderURL, 1, $useAbsolutePath, $bRssMode) . "</div><div>{$attributes['3']}</div>";
                                $buf .= '<div>' . FM_TTML_getAttachmentBinder($attributes[4], $newProperty2, $folderPath, $folderURL, 1, $useAbsolutePath, $bRssMode) . "</div><div>{$attributes['6']}</div>";
                            } else {
                                $cap1 = strlen(trim($attributes[3])) > 0 ? '<p class="cap1">' . $attributes[3] . '</p>' : '';
                                $cap2 = strlen(trim($attributes[6])) > 0 ? '<p class="cap1">' . $attributes[6] . '</p>' : '';
                                $buf = '<div class="imageblock dual" style="text-align: center;"><table cellspacing="5" cellpadding="0" border="0" style="margin: 0 auto;"><tr><td>' . FM_TTML_getAttachmentBinder($attributes[1], $newProperty1, $folderPath, $folderURL, 2, $useAbsolutePath, $bRssMode, $onclickFlag1) . $cap1 . '</td><td>' . FM_TTML_getAttachmentBinder($attributes[4], $newProperty2, $folderPath, $folderURL, 2, $useAbsolutePath, $bRssMode, $onclickFlag2) . $cap2 . '</td></tr></table></div>';
                            }
                            break;
                        case 10:
                            $eachImageWidth = floor(($contentWidth - 5 * 4) / 3);
                            list($newProperty1, $onclickFlag1) = FM_TTML_createNewProperty($attributes[1], $eachImageWidth, $attributes[2]);
                            list($newProperty2, $onclickFlag2) = FM_TTML_createNewProperty($attributes[4], $eachImageWidth, $attributes[5]);
                            list($newProperty3, $onclickFlag3) = FM_TTML_createNewProperty($attributes[7], $eachImageWidth, $attributes[8]);
                            if (defined('__TEXTCUBE_MOBILE__') || defined('__TEXTCUBE_IPHONE__')) {
                                $buf = '<div>' . FM_TTML_getAttachmentBinder($attributes[1], $newProperty1, $folderPath, $folderURL, 1, $useAbsolutePath, $bRssMode) . "</div><div>{$attributes['3']}</div>";
                                $buf .= '<div>' . FM_TTML_getAttachmentBinder($attributes[4], $newProperty2, $folderPath, $folderURL, 1, $useAbsolutePath, $bRssMode) . "</div><div>{$attributes['6']}</div>";
                                $buf .= '<div>' . FM_TTML_getAttachmentBinder($attributes[7], $newProperty3, $folderPath, $folderURL, 1, $useAbsolutePath, $bRssMode) . "</div><div>{$attributes['9']}</div>";
                            } else {
                                $cap1 = strlen(trim($attributes[3])) > 0 ? '<p class="cap1">' . $attributes[3] . '</p>' : '';
                                $cap2 = strlen(trim($attributes[6])) > 0 ? '<p class="cap1">' . $attributes[6] . '</p>' : '';
                                $cap3 = strlen(trim($attributes[9])) > 0 ? '<p class="cap1">' . $attributes[9] . '</p>' : '';
                                $buf = '<div class="imageblock triple" style="text-align: center"><table cellspacing="5" cellpadding="0" border="0" style="margin: 0 auto;"><tr><td>' . FM_TTML_getAttachmentBinder($attributes[1], $newProperty1, $folderPath, $folderURL, 3, $useAbsolutePath, $bRssMode, $onclickFlag1) . $cap1 . '</td><td>' . FM_TTML_getAttachmentBinder($attributes[4], $newProperty2, $folderPath, $folderURL, 3, $useAbsolutePath, $bRssMode, $onclickFlag2) . $cap2 . '</td><td>' . FM_TTML_getAttachmentBinder($attributes[7], $newProperty3, $folderPath, $folderURL, 3, $useAbsolutePath, $bRssMode, $onclickFlag3) . $cap3 . '</td></tr></table></div>';
                            }
                            break;
                            // 어디에도 해당되지 않을 경우 임시 태그를 되살림.
                        // 어디에도 해당되지 않을 경우 임시 태그를 되살림.
                        default:
                            $buf = '[###_###_###_' . implode('|', $attributes) . '_###_###_###]';
                            break;
                    }
                }
            }
        }
        $view = substr($view, 0, $start) . $buf . substr($view, $end + 4);
    }
    $view = preg_replace(array("@\\[###_###_###_@", "@_###_###_###\\]@"), array('[##_', '_##]'), $view);
    return $view;
}
示例#4
0
function getAttachments($message, &$composeMessage, $passed_id, $entities, $imapConnection)
{
    global $attachment_dir, $username, $data_dir, $squirrelmail_language;
    $hashed_attachment_dir = getHashedDir($username, $attachment_dir);
    if (!count($message->entities) || $message->type0 == 'message' && $message->type1 == 'rfc822') {
        if (!in_array($message->entity_id, $entities) && $message->entity_id) {
            switch ($message->type0) {
                case 'message':
                    if ($message->type1 == 'rfc822') {
                        $filename = $message->rfc822_header->subject;
                        if ($filename == "") {
                            $filename = "untitled-" . $message->entity_id;
                        }
                        $filename .= '.msg';
                    } else {
                        $filename = $message->getFilename();
                    }
                    break;
                default:
                    if (!$message->mime_header) {
                        /* temporary hack */
                        $message->mime_header = $message->header;
                    }
                    $filename = $message->getFilename();
                    break;
            }
            $filename = str_replace('&#32;', ' ', decodeHeader($filename));
            if (isset($languages[$squirrelmail_language]['XTRA_CODE']) && function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_encode')) {
                $filename = call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_encode', $filename);
            }
            $localfilename = GenerateRandomString(32, '', 7);
            $full_localfilename = "{$hashed_attachment_dir}/{$localfilename}";
            while (file_exists($full_localfilename)) {
                $localfilename = GenerateRandomString(32, '', 7);
                $full_localfilename = "{$hashed_attachment_dir}/{$localfilename}";
            }
            $message->att_local_name = $full_localfilename;
            $composeMessage->initAttachment($message->type0 . '/' . $message->type1, $filename, $full_localfilename);
            /* Write Attachment to file */
            $fp = fopen("{$hashed_attachment_dir}/{$localfilename}", 'wb');
            fputs($fp, decodeBody(mime_fetch_body($imapConnection, $passed_id, $message->entity_id), $message->header->encoding));
            fclose($fp);
        }
    } else {
        for ($i = 0, $entCount = count($message->entities); $i < $entCount; $i++) {
            $composeMessage = getAttachments($message->entities[$i], $composeMessage, $passed_id, $entities, $imapConnection);
        }
    }
    return $composeMessage;
}
示例#5
0
function AdkViewDownload()
{
    global $sourcedir, $txt, $modSettings, $context, $user_info, $scripturl, $smcFunc, $boardurl, $memberContext;
    if (!empty($_REQUEST['down']) && is_numeric($_REQUEST['down'])) {
        $id_view = (int) $_REQUEST['down'];
    } else {
        fatal_lang_error('adkfatal_require_id_file', false);
    }
    //Get All information
    $sql = $smcFunc['db_query']('', '
		SELECT
		p.id_file, p.id_cat, 
	 	p.approved, p.views, p.title, p.id_member, m.real_name, p.date, p.description, p.main_image, p.id_topic, c.error,
	   	c.title AS CAT_TITLE, c.id_parent, p.totaldownloads,  p.lastdownload, m.avatar, c.id_parent, t.id_board,
			IFNULL(a.id_attach, 0) AS id_attach, a.filename, a.attachment_type,
			IFNULL(t.id_topic, p.id_topic) AS id_topic
		FROM ({db_prefix}adk_down_file as p,  {db_prefix}adk_down_cat AS c)
		LEFT JOIN {db_prefix}members AS m ON  (p.id_member = m.id_member)
		LEFT JOIN {db_prefix}attachments AS a ON (a.id_member = m.id_member)
		LEFT JOIN {db_prefix}topics AS t ON (t.id_topic = p.id_topic)
		WHERE p.id_file = {int:id} AND p.id_cat = c.id_cat LIMIT 1', array('id' => $id_view));
    //If no query
    if ($smcFunc['db_num_rows']($sql) == 0) {
        fatal_lang_error('adkfatal_this_download_not_exist', false);
    }
    $row = $smcFunc['db_fetch_assoc']($sql);
    $smcFunc['db_free_result']($sql);
    if (!empty($row['error'])) {
        fatal_lang_error('adkfatal_this_download_not_exist', false);
    }
    //Verify if we can view
    verifyCatPermissions('view', $row['id_cat']);
    //It's not approved? (dissaproved :|)
    if ($row['approved'] == 0 && $user_info['id'] != $row['id_member'] && !allowedTo('adk_downloads_manage')) {
        fatal_lang_error('adkfatal_this_download_not_approved', false);
    }
    //$height and width
    $width = 75;
    $height = 75;
    $context['adkDownloadInformation'] = array('id_file' => $row['id_file'], 'id_cat' => $row['id_cat'], 'views' => $row['views'], 'file_title' => $row['title'], 'id_member' => $row['id_member'], 'member' => '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '">' . $row['real_name'] . '</a>', 'date' => timeformat($row['date'], '%d/%m/%Y (%I:%M:%S %p)'), 'description' => parse_bbc($row['description']), 'cat' => '<a href="' . $scripturl . '?action=downloads;cat=' . $row['id_cat'] . '">' . $row['CAT_TITLE'] . '</a>', 'id_parent' => $row['id_parent'], 'totaldownloads' => $row['totaldownloads'], 'lastdownload' => empty($row['lastdownload']) ? $txt['adkdown_never'] : timeformat($row['lastdownload'], '%d/%m/%Y'), 'approved' => $row['approved'], 'image' => $row['main_image'], 'id_topic' => $row['id_topic'], 'id_board' => $row['id_board'], 'topic_exists' => checkTopicDownload($row['id_topic']), 'avatar' => $row['avatar'] == '' ? $row['id_attach'] > 0 ? '<img title="' . $row['real_name'] . '" style="vertical-align: middle;" width="' . $width . '" height="' . $height . '" src="' . (empty($row['attachment_type']) ? $scripturl . '?action=dlattach;attach=' . $row['id_attach'] . ';type=avatar' : $modSettings['custom_avatar_url'] . '/' . $row['filename']) . '" alt="" border="0" />' : '' : (stristr($row['avatar'], 'http://') ? '<img title="' . $row['real_name'] . '" style="vertical-align: middle;" width="' . $width . '" height="' . $height . '"src="' . $row['avatar'] . '" alt="" border="0" />' : '<img title="' . $row['real_name'] . '" style="vertical-align: middle;" width="' . $width . '" height="' . $height . '"src="' . $modSettings['avatar_url'] . '/' . $smcFunc['htmlspecialchars']($row['avatar']) . '" alt="" border="0" />'));
    //Set the lintkree
    setLinktree('downloads', 'adkdown_downloads');
    CheckCatParent($row['id_parent']);
    setLinktree('downloads;cat=' . $row['id_cat'], $row['CAT_TITLE'], false, true);
    setLinktree('downloads;sa=view;down=' . $row['id_file'], $row['title'], false, true);
    $context['sub_template'] = 'adk_view_file';
    $context['page_title'] = $row['title'];
    //Views + 1 if i can
    if (empty($_SESSION['adk_download_view'][$id_view])) {
        $smcFunc['db_query']('', "UPDATE {db_prefix}adk_down_file\n\t\t\tSET views = views + 1 WHERE id_file = {int:id} LIMIT 1", array('id' => $id_view));
        $_SESSION['adk_download_view'][$id_view] = true;
    }
    //Load Attachments
    $context['load_attachments'] = getAttachments($id_view);
    //Please, load all info member.
    loadMemberData($context['adkDownloadInformation']['id_member'], false, 'profile');
    loadMemberContext($context['adkDownloadInformation']['id_member']);
    //Finaly, make my context string ;)
    $context['member'] = $memberContext[$context['adkDownloadInformation']['id_member']];
}
示例#6
0
文件: minigf.php 项目: npds/npds_dune
/* This program is free software. You can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 2 of the License.       */
/************************************************************************/
global $ModPath, $ModStart, $IdPost, $IdForum, $apli, $Mmod;
echo '
   <form method="post" action="' . $_SERVER['PHP_SELF'] . '" enctype="multipart/form-data" name="form0" onsubmit="return checkForm(this);">
      <input type="hidden" name="actiontype" value="" />
      <input type="hidden" name="ModPath" value="' . $ModPath . '" />
      <input type="hidden" name="ModStart" value="' . $ModStart . '" />
      <input type="hidden" name="IdPost" value="' . $IdPost . '" />
      <input type="hidden" name="IdForum" value="' . $IdForum . '" />
      <input type="hidden" name="IdTopic" value="' . $IdTopic . '" />
      <input type="hidden" name="apli" value="' . $apli . '" />';
$tsz = 0;
$att = getAttachments($apli, $IdPost, 0, $Mmod);
$visible_list = '';
$vizut = '';
if (is_array($att)) {
    $att_count = count($att);
    $display_att = true;
    if ($Mmod) {
        $vizut = '<th>' . upload_translate("Visible") . '</th>';
    }
    $att_table = '
      <table class="table table-striped table-hover" border="0">
         <thead>
            <tr>
               <th>&nbsp;</th>
               <th data-sortable="true">' . upload_translate("Fichier") . '</th>
               <th data-sortable="true">' . upload_translate("Type") . '</th>
示例#7
0
/**
 * downloads attachments from original message, stores them in attachment directory and adds
 * them to composed message.
 * @param object $message
 * @param object $composeMessage
 * @param integer $passed_id
 * @param mixed $entities
 * @param mixed $imapConnection
 * @return object
 */
function getAttachments($message, &$composeMessage, $passed_id, $entities, $imapConnection)
{
    global $squirrelmail_language, $languages, $username, $attachment_dir;
    if (!count($message->entities) || $message->type0 == 'message' && $message->type1 == 'rfc822') {
        if (!in_array($message->entity_id, $entities) && $message->entity_id) {
            switch ($message->type0) {
                case 'message':
                    if ($message->type1 == 'rfc822') {
                        $filename = $message->rfc822_header->subject;
                        if ($filename == "") {
                            $filename = "untitled-" . $message->entity_id;
                        }
                        $filename .= '.eml';
                    } else {
                        $filename = $message->getFilename();
                    }
                    break;
                default:
                    if (!$message->mime_header) {
                        /* temporary hack */
                        $message->mime_header = $message->header;
                    }
                    $filename = $message->getFilename();
                    break;
            }
            //FIXME: added three args to the following, so as to set the last one to TRUE, to mimick a fix in 1.4.21 (#2994865), but didn't test this (note that in 1.4.21, the 2nd and 3rd args are FALSE, but here in this code, they weren't being specified (thus defaulting to TRUE), so I don't know if that means this code is outdated and should have been changed to FALSE, FALSE or if this code is completely different and the addition of the TRUE for arg #4 is wrong
            $filename = str_replace('&#32;', ' ', decodeHeader($filename, true, true, true));
            if (isset($languages[$squirrelmail_language]['XTRA_CODE']) && function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_encode')) {
                $filename = call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_encode', $filename);
            }
            $hashed_attachment_dir = getHashedDir($username, $attachment_dir);
            $localfilename = sq_get_attach_tempfile();
            $message->att_local_name = $localfilename;
            $composeMessage->initAttachment($message->type0 . '/' . $message->type1, $filename, $localfilename);
            /* Write Attachment to file */
            $fp = fopen($hashed_attachment_dir . '/' . $localfilename, 'wb');
            mime_print_body_lines($imapConnection, $passed_id, $message->entity_id, $message->header->encoding, $fp);
            fclose($fp);
        }
    } else {
        for ($i = 0, $entCount = count($message->entities); $i < $entCount; $i++) {
            $composeMessage = getAttachments($message->entities[$i], $composeMessage, $passed_id, $entities, $imapConnection);
        }
    }
    return $composeMessage;
}
示例#8
0
文件: index.php 项目: ragi79/Textcube
									<div id="setting-section">
									<script type="text/javascript">
									//<![CDATA[
										var settingMenus = new Array("upload-container","tag-location-container","power-container");
									//]]>
									</script>
									<div id="upload-section" class="section">
										<h3><a href="#void" onclick="focusLayer('upload-container',settingMenus);return false;"><?php 
echo _t('업로드');
?>
</a></h3>
										<div id="upload-container">
											<div id="attachment-container" class="container">
<?php 
$param = array('uploadPath' => $context->getProperty('uri.blog') . "/owner/entry/attachmulti/", 'singleUploadPath' => $context->getProperty('uri.blog') . "/owner/entry/attach/", 'deletePath' => $context->getProperty('uri.blog') . "/owner/entry/detach/multi/", 'labelingPath' => $context->getProperty('uri.blog') . "/owner/entry/attachmulti/list/", 'refreshPath' => $context->getProperty('uri.blog') . "/owner/entry/attachmulti/refresh/", 'fileSizePath' => $context->getProperty('uri.blog') . "/owner/entry/size?parent=");
printEntryFileList(getAttachments($blogid, $entry['id'], 'label'), $param);
?>
											</div>
										
											<div id="insert-container" class="container">
												<a class="image-left" href="#void" onclick="editorAddObject(editor, 'Image1L');return false;" title="<?php 
echo _t('선택한 파일을 글의 왼쪽에 정렬합니다.');
?>
"><span class="text"><?php 
echo _t('왼쪽 정렬');
?>
</span></a>
												<a class="image-center" href="#void" onclick="editorAddObject(editor, 'Image1C');return false;" title="<?php 
echo _t('선택한 파일을 글의 중앙에 정렬합니다.');
?>
"><span class="text"><?php 
示例#9
0
文件: index.php 项目: ragi79/Textcube
<?php

/// Copyright (c) 2004-2012, Needlworks  / Tatter Network Foundation
/// All rights reserved. Licensed under the GPL.
/// See the GNU General Public License for more details. (/documents/LICENSE, /documents/COPYRIGHT)
require ROOT . '/library/preprocessor.php';
requireModel("blog.attachment");
$entryId = $suri['id'];
$attachments = getAttachments($blogid, $entryId, 'label');
$initialFileListForFlash = '';
$enclosureFileName = '';
?>
<select name="TCfilelist" id="TCfilelist" multiple="multiple" size="8" onchange="selectAttachment();">
<?php 
foreach ($attachments as $i => $attachment) {
    if (strpos($attachment['mime'], 'application') !== false) {
        $class = 'class="MimeApplication"';
    } else {
        if (strpos($attachment['mime'], 'audio') !== false) {
            $class = 'class="MimeAudio"';
        } else {
            if (strpos($attachment['mime'], 'image') !== false) {
                $class = 'class="MimeImage"';
            } else {
                if (strpos($attachment['mime'], 'message') !== false) {
                    $class = 'class="MimeMessage"';
                } else {
                    if (strpos($attachment['mime'], 'model') !== false) {
                        $class = 'class="MimeModel"';
                    } else {
                        if (strpos($attachment['mime'], 'multipart') !== false) {
示例#10
0
                </div>
            </div>
        </nav>

        <?php 
$valid_input = false;
$project_id_input = htmlspecialchars(filter_input(INPUT_POST, 'projectid', FILTER_SANITIZE_STRING));
if (!($project_id_input == "")) {
    require 'lib.php';
    require_once 'database.ini';
    //If project id is a number
    if (is_numeric($project_id_input)) {
        //Get all of the stories, epics and attachments from pivotal API
        $raw_data = getStories(PT_TOKEN, $project_id_input);
        $epics_raw_data = getEpics(PT_TOKEN, $project_id_input);
        $attachments_raw_data = getAttachments(PT_TOKEN, $project_id_input);
        //if the pivotal story contains a field named 'error' (leads to error message)
        if (!isset($raw_data["error"]) || !isset($epics_raw_data["error"]) || !isset($attachments_raw_data["error"])) {
            $connection = connectToDb();
            $history_id_check = getHistoryId($connection, $project_id_input);
            //If the project already exists, perform update
            if ($history_id_check == NULL) {
                //Get project name
                $project_data = getProject(PT_TOKEN, $project_id_input);
                if ($connection == true) {
                    try {
                        //Make an entry in the history table
                        insertIntoHistory($connection, $project_data["id"], $project_data["name"]);
                        $latest_history_sql = 'SELECT MAX(history.id) FROM history;';
                        //Send the sql command
                        $latest_history_id = $connection->query($latest_history_sql);
示例#11
0
    }
    $_SESSION['adminGameId'] = $gameId;
    $attachmentId = -1;
    if (isset($_GET['attachment'])) {
        $attachmentId = intval($_GET['attachment']);
    }
    $_SESSION['adminAttachmentId'] = $attachmentId;
    $gameList = getGameList();
    if ($gameId == -1 && !empty($gameList)) {
        $gameId = $gameList[0]['id'];
        $_SESSION['adminGameId'] = $gameId;
    }
    $currentGame = getGameList($gameId);
    $gameAttachments = array();
    if ($gameId != -1) {
        $gameAttachments = getAttachments($gameId);
    }
    $currentAttachment = array();
    if ($attachmentId != -1) {
        $currentAttachment = getAttachmentById($attachmentId);
    }
    ?>

    <script>
        changeActiveAdminButton('attachmentsButton');
    </script>

    <script>
        function loadGameData(gameId, attachmentId)
        {
            $('#dataContainer').load('APattachments.php?game=' + gameId + "&attachment=" + attachmentId);
示例#12
0
文件: index.php 项目: ragi79/Textcube
/**
 * @brief Send abstract about specific entry.
 * @see Tag, User, DBModel, Model_Context
 */
function sendAbstractToEolin()
{
    // TODO : Rewrite routines to fit Textcube 1.8 or later.
    requireModel('blog.category');
    $entryId = $_GET['entryId'];
    $context = Model_Context::getInstance();
    $blogid = $context->getProperty('blog.id');
    echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<response>\r\n";
    list($allComments, $allTrackbacks) = POD::queryRow("SELECT \n\t\t\tSUM(comments), SUM(trackbacks) \n\t\t\tFROM {$context->getProperty('database.prefix')}Entries \n\t\t\tWHERE blogid = " . $blogid . " AND draft = 0 AND visibility = 3", 'num');
    if ($entry = POD::queryRow("SELECT e.*, c.name AS categoryName \n\t\t\t\tFROM {$context->getProperty('database.prefix')}Entries e \n\t\t\t\tLEFT JOIN {$context->getProperty('database.prefix')}Categories c ON e.blogid = c.blogid AND e.category = c.id \n\t\t\t\tWHERE e.blogid = " . $blogid . " AND e.id = " . $entryId . " AND e.draft = 0 AND e.visibility = 3" . getPrivateCategoryExclusionQuery($blogid))) {
        header('Content-Type: text/xml; charset=utf-8');
        echo '<version>1.1</version>', "\r\n";
        echo '<status>1</status>', "\r\n";
        echo '<blog>', "\r\n";
        echo '<generator>' . TEXTCUBE_NAME . '/' . TEXTCUBE_VERSION . '</generator>', "\r\n";
        echo '<language>', htmlspecialchars($context->getProperty('blog.language')), '</language>', "\r\n";
        echo '<url>', htmlspecialchars($context->getProperty('uri.default')), '</url>', "\r\n";
        echo '<title>', htmlspecialchars($context->getProperty('blog.title')), '</title>', "\r\n";
        echo '<description>', htmlspecialchars($context->getProperty('blog.description')), '</description>', "\r\n";
        echo '<comments>', $allComments, '</comments>', "\r\n";
        echo '<trackbacks>', $allTrackbacks, '</trackbacks>', "\r\n";
        echo '</blog>', "\r\n";
        echo '<entry>', "\r\n";
        echo '<permalink>', htmlspecialchars($context->getProperty('uri.default') . "/" . ($context->getProperty('blog.useSloganOnPost') ? "entry/{$entry['slogan']}" : $entry['id'])), '</permalink>', "\r\n";
        echo '<title>', htmlspecialchars($entry['title']), '</title>', "\r\n";
        echo '<content>', htmlspecialchars(getEntryContentView($blogid, $entryId, $entry['content'], $entry['contentformatter'])), '</content>', "\r\n";
        echo '<author>', htmlspecialchars(User::authorName($blogid, $entryId)), '</author>', "\r\n";
        echo '<category>', htmlspecialchars($entry['categoryName']), '</category>', "\r\n";
        $tags = Tag::getTagsWithEntryId($blogid, $entry);
        foreach ($tags as $tag) {
            echo '<tag>', htmlspecialchars($tag), '</tag>', "\r\n";
        }
        echo '<location>', htmlspecialchars($entry['location']), '</location>', "\r\n";
        echo '<comments>', $entry['comments'], '</comments>', "\r\n";
        echo '<trackbacks>', $entry['trackbacks'], '</trackbacks>', "\r\n";
        echo '<written>', Timestamp::getRFC1123($entry['published']), '</written>', "\r\n";
        foreach (getAttachments($blogid, $entry['id']) as $attachment) {
            echo '<attachment>', "\r\n";
            echo '<mimeType>', $attachment['mime'], '</mimeType>', "\r\n";
            echo '<filename>', $attachment['label'], '</filename>', "\r\n";
            echo '<length>', $attachment['size'], '</length>', "\r\n";
            echo '<url>', $context->getProperty('uri.service'), '/attachment/', $attachment['name'], '</url>', "\r\n";
            echo '</attachment>', "\r\n";
        }
        echo '</entry>', "\r\n";
    } else {
        echo '<version>1.1</version>', "\r\n", '<status>0</status>', "\r\n";
    }
    echo "</response>";
    exit;
}
示例#13
0
function deleteAttachments($blogid, $parent)
{
    $attachments = getAttachments($blogid, $parent);
    foreach ($attachments as $attachment) {
        deleteAttachment($blogid, $parent, $attachment['name']);
    }
}
示例#14
0
function display_upload($apli, $post_id, $Mmod)
{
    $att_size = '';
    $att_type = '';
    $att_name = '';
    $att_url = '';
    $att_link = '';
    $attachments = '';
    $att_icon = '';
    $num_cells = 5;
    $att = getAttachments($apli, $post_id, 0, $Mmod);
    if (is_array($att)) {
        $att_count = count($att);
        //      $attachments = "\n<table id=\"ooo\" class=\"fo-post-mes\" border=\"0\" cellpadding=\"2\" cellspacing=\"1\" width=\"100%\">\n<tr>";
        $attachments = '
      <div class="list-group">
         <div class="list-group-item">
            <img class="smil" src="themes/npds-boost/images/forum/subject/1F4CE.png" border="0" alt="icon_post" />
            <span class="text-muted">' . upload_translate("Pièces jointes") . '</span>
            <span class="label label-default label-pill pull-right">' . $att_count . '</span>
         </div>';
        $ncell = 0;
        for ($i = 0; $i < $att_count; $i++) {
            $att_id = $att[$i]["att_id"];
            $att_name = $att[$i]["att_name"];
            $att_path = $att[$i]["att_path"];
            $att_type = $att[$i]["att_type"];
            $att_size = (int) $att[$i]["att_size"];
            $compteur = $att[$i]["compteur"];
            $visible = $att[$i]["visible"];
            $att_inline = $att[$i]["inline"];
            if (!$visible) {
                $marqueurV = "@";
            } else {
                $marqueurV = "";
            }
            $att_link = getAttachmentUrl($apli, $post_id, $att_id, "{$att_path}/{$att_id}.{$apli}." . $marqueurV . "{$att_name}", $att_type, $att_size, $att_inline, $compteur, $visible, $Mmod);
            // check for full row
            if (++$ncell > $num_cells) {
                //            $attachments .= "</tr>\n<tr>";
                $ncell = 1;
            }
            if (getAttDisplayMode($att_type, $att_inline) != ATT_DSP_LINK) {
                if ($ncell > 1) {
                    while ($ncell++ <= $num_cells) {
                        //                  $attachments .= "<td>&nbsp;</td>";
                        $attachments .= "</tr>\n<tr>";
                    }
                }
                $ncell = $num_cells + 1;
                //            $td = "<td colspan=\"".$num_cells."\">";
            } else {
                //            $td = "<td>";
            }
            //         $attachments .= $td.$att_link."</td>";
            $attachments .= $att_link;
            $att_list[$att_id] = $att_name;
        }
        //      $attachments .= "</tr></table>";
        $attachments .= '</div>';
        return $attachments;
    }
}
$gui->user_is_admin = $args->user->globalRole->name == 'admin' ? true : false;
$gui->execPlatformSet = null;
$gui->cfexec = null;
$gui->attachments = null;
if (!is_null($gui->execSet)) {
    $gui->execPlatformSet = $tcase_mgr->getExecutedPlatforms($args->tcase_id);
    // get issue tracker config and object to manage TestLink - BTS integration
    $its = null;
    $tproject_mgr = new testproject($db);
    $info = $tproject_mgr->get_by_id($gui->tproject_id);
    if ($info['issue_tracker_enabled']) {
        $gui->bugs = getIssues($db, $gui->execSet, $gui->tproject_id);
    }
    // get custom fields brute force => do not check if this call is needed
    $gui->cfexec = getCustomFields($tcase_mgr, $gui->execSet);
    $gui->attachments = getAttachments($db, $gui->execSet);
}
$gui->displayPlatformCol = !is_null($gui->execPlatformSet) ? 1 : 0;
$gui->main_descr = lang_get('execution_history');
$gui->detailed_descr = lang_get('test_case') . ' ' . $idCard;
$gui->tcase_id = intval($args->tcase_id);
$gui->onlyActiveTestPlans = intval($args->onlyActiveTestPlans);
$smarty = new TLSmarty();
$smarty->assign('gui', $gui);
$smarty->display($templateCfg->template_dir . $templateCfg->default_template);
/**
 *
 *
 */
function init_args()
{
示例#16
0
    /**
     * The central part of the board - topic display.
     *
     * What it does:
     * - This function loads the posts in a topic up so they can be displayed.
     * - It uses the main sub template of the Display template.
     * - It requires a topic, and can go to the previous or next topic from it.
     * - It jumps to the correct post depending on a number/time/IS_MSG passed.
     * - It depends on the messages_per_page, defaultMaxMessages and enableAllMessages settings.
     * - It is accessed by ?topic=id_topic.START.
     */
    public function action_display()
    {
        global $scripturl, $txt, $modSettings, $context, $settings;
        global $options, $user_info, $board_info, $topic, $board;
        global $attachments, $messages_request;
        // What are you gonna display if these are empty?!
        if (empty($topic)) {
            fatal_lang_error('no_board', false);
        }
        // Load the template
        loadTemplate('Display');
        $context['sub_template'] = 'messages';
        // And the topic functions
        require_once SUBSDIR . '/Topic.subs.php';
        require_once SUBSDIR . '/Messages.subs.php';
        // Not only does a prefetch make things slower for the server, but it makes it impossible to know if they read it.
        if (isset($_SERVER['HTTP_X_MOZ']) && $_SERVER['HTTP_X_MOZ'] == 'prefetch') {
            @ob_end_clean();
            header('HTTP/1.1 403 Prefetch Forbidden');
            die;
        }
        // How much are we sticking on each page?
        $context['messages_per_page'] = empty($modSettings['disableCustomPerPage']) && !empty($options['messages_per_page']) ? $options['messages_per_page'] : $modSettings['defaultMaxMessages'];
        $template_layers = Template_Layers::getInstance();
        $template_layers->addEnd('messages_informations');
        $includeUnapproved = !$modSettings['postmod_active'] || allowedTo('approve_posts');
        // Let's do some work on what to search index.
        if (count($_GET) > 2) {
            foreach ($_GET as $k => $v) {
                if (!in_array($k, array('topic', 'board', 'start', session_name()))) {
                    $context['robot_no_index'] = true;
                }
            }
        }
        if (!empty($_REQUEST['start']) && (!is_numeric($_REQUEST['start']) || $_REQUEST['start'] % $context['messages_per_page'] != 0)) {
            $context['robot_no_index'] = true;
        }
        // Find the previous or next topic.  Make a fuss if there are no more.
        if (isset($_REQUEST['prev_next']) && ($_REQUEST['prev_next'] == 'prev' || $_REQUEST['prev_next'] == 'next')) {
            // No use in calculating the next topic if there's only one.
            if ($board_info['num_topics'] > 1) {
                $includeStickies = !empty($modSettings['enableStickyTopics']);
                $topic = $_REQUEST['prev_next'] === 'prev' ? previousTopic($topic, $board, $user_info['id'], $includeUnapproved, $includeStickies) : nextTopic($topic, $board, $user_info['id'], $includeUnapproved, $includeStickies);
                $context['current_topic'] = $topic;
            }
            // Go to the newest message on this topic.
            $_REQUEST['start'] = 'new';
        }
        // Add 1 to the number of views of this topic (except for robots).
        if (!$user_info['possibly_robot'] && (empty($_SESSION['last_read_topic']) || $_SESSION['last_read_topic'] != $topic)) {
            increaseViewCounter($topic);
            $_SESSION['last_read_topic'] = $topic;
        }
        $topic_selects = array();
        $topic_tables = array();
        $topic_parameters = array('topic' => $topic, 'member' => $user_info['id'], 'board' => (int) $board);
        // Allow addons to add additional details to the topic query
        call_integration_hook('integrate_topic_query', array(&$topic_selects, &$topic_tables, &$topic_parameters));
        // Load the topic details
        $topicinfo = getTopicInfo($topic_parameters, 'all', $topic_selects, $topic_tables);
        if (empty($topicinfo)) {
            fatal_lang_error('not_a_topic', false);
        }
        // Is this a moved topic that we are redirecting to?
        if (!empty($topicinfo['id_redirect_topic']) && !isset($_GET['noredir'])) {
            markTopicsRead(array($user_info['id'], $topic, $topicinfo['id_last_msg'], 0), $topicinfo['new_from'] !== 0);
            redirectexit('topic=' . $topicinfo['id_redirect_topic'] . '.0;redirfrom=' . $topicinfo['id_topic']);
        }
        $context['real_num_replies'] = $context['num_replies'] = $topicinfo['num_replies'];
        $context['topic_first_message'] = $topicinfo['id_first_msg'];
        $context['topic_last_message'] = $topicinfo['id_last_msg'];
        $context['topic_unwatched'] = isset($topicinfo['unwatched']) ? $topicinfo['unwatched'] : 0;
        if (isset($_GET['redirfrom'])) {
            $redir_topics = topicsList(array((int) $_GET['redirfrom']));
            if (!empty($redir_topics[(int) $_GET['redirfrom']])) {
                $context['topic_redirected_from'] = $redir_topics[(int) $_GET['redirfrom']];
                $context['topic_redirected_from']['redir_href'] = $scripturl . '?topic=' . $context['topic_redirected_from']['id_topic'] . '.0;noredir';
            }
        }
        // Add up unapproved replies to get real number of replies...
        if ($modSettings['postmod_active'] && allowedTo('approve_posts')) {
            $context['real_num_replies'] += $topicinfo['unapproved_posts'] - ($topicinfo['approved'] ? 0 : 1);
        }
        // If this topic was derived from another, set the followup details
        if (!empty($topicinfo['derived_from'])) {
            require_once SUBSDIR . '/FollowUps.subs.php';
            $context['topic_derived_from'] = topicStartedHere($topic, $includeUnapproved);
        }
        // If this topic has unapproved posts, we need to work out how many posts the user can see, for page indexing.
        if (!$includeUnapproved && $topicinfo['unapproved_posts'] && !$user_info['is_guest']) {
            $myUnapprovedPosts = unapprovedPosts($topic, $user_info['id']);
            $context['total_visible_posts'] = $context['num_replies'] + $myUnapprovedPosts + ($topicinfo['approved'] ? 1 : 0);
        } elseif ($user_info['is_guest']) {
            $context['total_visible_posts'] = $context['num_replies'] + ($topicinfo['approved'] ? 1 : 0);
        } else {
            $context['total_visible_posts'] = $context['num_replies'] + $topicinfo['unapproved_posts'] + ($topicinfo['approved'] ? 1 : 0);
        }
        // When was the last time this topic was replied to?  Should we warn them about it?
        if (!empty($modSettings['oldTopicDays'])) {
            $mgsOptions = basicMessageInfo($topicinfo['id_last_msg'], true);
            $context['oldTopicError'] = $mgsOptions['poster_time'] + $modSettings['oldTopicDays'] * 86400 < time() && empty($topicinfo['is_sticky']);
        } else {
            $context['oldTopicError'] = false;
        }
        // The start isn't a number; it's information about what to do, where to go.
        if (!is_numeric($_REQUEST['start'])) {
            // Redirect to the page and post with new messages, originally by Omar Bazavilvazo.
            if ($_REQUEST['start'] == 'new') {
                // Guests automatically go to the last post.
                if ($user_info['is_guest']) {
                    $context['start_from'] = $context['total_visible_posts'] - 1;
                    $_REQUEST['start'] = $context['start_from'];
                } else {
                    // Fall through to the next if statement.
                    $_REQUEST['start'] = 'msg' . $topicinfo['new_from'];
                }
            }
            // Start from a certain time index, not a message.
            if (substr($_REQUEST['start'], 0, 4) == 'from') {
                $timestamp = (int) substr($_REQUEST['start'], 4);
                if ($timestamp === 0) {
                    $_REQUEST['start'] = 0;
                } else {
                    // Find the number of messages posted before said time...
                    $context['start_from'] = countNewPosts($topic, $topicinfo, $timestamp);
                    $_REQUEST['start'] = $context['start_from'];
                }
            } elseif (substr($_REQUEST['start'], 0, 3) == 'msg') {
                $virtual_msg = (int) substr($_REQUEST['start'], 3);
                if (!$topicinfo['unapproved_posts'] && $virtual_msg >= $topicinfo['id_last_msg']) {
                    $context['start_from'] = $context['total_visible_posts'] - 1;
                } elseif (!$topicinfo['unapproved_posts'] && $virtual_msg <= $topicinfo['id_first_msg']) {
                    $context['start_from'] = 0;
                } else {
                    $only_approved = $modSettings['postmod_active'] && $topicinfo['unapproved_posts'] && !allowedTo('approve_posts');
                    $context['start_from'] = countMessagesBefore($topic, $virtual_msg, false, $only_approved, !$user_info['is_guest']);
                }
                // We need to reverse the start as well in this case.
                $_REQUEST['start'] = $context['start_from'];
            }
        }
        // Mark the mention as read if requested
        if (isset($_REQUEST['mentionread']) && !empty($virtual_msg)) {
            require_once CONTROLLERDIR . '/Mentions.controller.php';
            $mentions = new Mentions_Controller();
            $mentions->setData(array('id_mention' => $_REQUEST['item'], 'mark' => $_REQUEST['mark']));
            $mentions->action_markread();
        }
        // Create a previous next string if the selected theme has it as a selected option.
        if ($modSettings['enablePreviousNext']) {
            $context['links'] += array('go_prev' => $scripturl . '?topic=' . $topic . '.0;prev_next=prev#new', 'go_next' => $scripturl . '?topic=' . $topic . '.0;prev_next=next#new');
        }
        // Derived from, set the link back
        if (!empty($context['topic_derived_from'])) {
            $context['links']['derived_from'] = $scripturl . '?msg=' . $context['topic_derived_from']['derived_from'];
        }
        // Check if spellchecking is both enabled and actually working. (for quick reply.)
        $context['show_spellchecking'] = !empty($modSettings['enableSpellChecking']) && function_exists('pspell_new');
        if ($context['show_spellchecking']) {
            loadJavascriptFile('spellcheck.js', array('defer' => true));
        }
        // Do we need to show the visual verification image?
        $context['require_verification'] = !$user_info['is_mod'] && !$user_info['is_admin'] && !empty($modSettings['posts_require_captcha']) && ($user_info['posts'] < $modSettings['posts_require_captcha'] || $user_info['is_guest'] && $modSettings['posts_require_captcha'] == -1);
        if ($context['require_verification']) {
            require_once SUBSDIR . '/VerificationControls.class.php';
            $verificationOptions = array('id' => 'post');
            $context['require_verification'] = create_control_verification($verificationOptions);
            $context['visual_verification_id'] = $verificationOptions['id'];
        }
        // Are we showing signatures - or disabled fields?
        $context['signature_enabled'] = substr($modSettings['signature_settings'], 0, 1) == 1;
        $context['disabled_fields'] = isset($modSettings['disabled_profile_fields']) ? array_flip(explode(',', $modSettings['disabled_profile_fields'])) : array();
        // Censor the title...
        censorText($topicinfo['subject']);
        $context['page_title'] = $topicinfo['subject'];
        // Is this topic sticky, or can it even be?
        $topicinfo['is_sticky'] = empty($modSettings['enableStickyTopics']) ? '0' : $topicinfo['is_sticky'];
        // Allow addons access to the topicinfo array
        call_integration_hook('integrate_display_topic', array($topicinfo));
        // Default this topic to not marked for notifications... of course...
        $context['is_marked_notify'] = false;
        // Did we report a post to a moderator just now?
        $context['report_sent'] = isset($_GET['reportsent']);
        if ($context['report_sent']) {
            $template_layers->add('report_sent');
        }
        // Let's get nosey, who is viewing this topic?
        if (!empty($settings['display_who_viewing'])) {
            require_once SUBSDIR . '/Who.subs.php';
            formatViewers($topic, 'topic');
        }
        // If all is set, but not allowed... just unset it.
        $can_show_all = !empty($modSettings['enableAllMessages']) && $context['total_visible_posts'] > $context['messages_per_page'] && $context['total_visible_posts'] < $modSettings['enableAllMessages'];
        if (isset($_REQUEST['all']) && !$can_show_all) {
            unset($_REQUEST['all']);
        } elseif (isset($_REQUEST['all'])) {
            $_REQUEST['start'] = -1;
        }
        // Construct the page index, allowing for the .START method...
        $context['page_index'] = constructPageIndex($scripturl . '?topic=' . $topic . '.%1$d', $_REQUEST['start'], $context['total_visible_posts'], $context['messages_per_page'], true, array('all' => $can_show_all, 'all_selected' => isset($_REQUEST['all'])));
        $context['start'] = $_REQUEST['start'];
        // This is information about which page is current, and which page we're on - in case you don't like the constructed page index. (again, wireles..)
        $context['page_info'] = array('current_page' => $_REQUEST['start'] / $context['messages_per_page'] + 1, 'num_pages' => floor(($context['total_visible_posts'] - 1) / $context['messages_per_page']) + 1);
        // Figure out all the link to the next/prev
        $context['links'] += array('prev' => $_REQUEST['start'] >= $context['messages_per_page'] ? $scripturl . '?topic=' . $topic . '.' . ($_REQUEST['start'] - $context['messages_per_page']) : '', 'next' => $_REQUEST['start'] + $context['messages_per_page'] < $context['total_visible_posts'] ? $scripturl . '?topic=' . $topic . '.' . ($_REQUEST['start'] + $context['messages_per_page']) : '');
        // If they are viewing all the posts, show all the posts, otherwise limit the number.
        if ($can_show_all && isset($_REQUEST['all'])) {
            // No limit! (actually, there is a limit, but...)
            $context['messages_per_page'] = -1;
            // Set start back to 0...
            $_REQUEST['start'] = 0;
        }
        // Build the link tree.
        $context['linktree'][] = array('url' => $scripturl . '?topic=' . $topic . '.0', 'name' => $topicinfo['subject']);
        // Build a list of this board's moderators.
        $context['moderators'] =& $board_info['moderators'];
        $context['link_moderators'] = array();
        // Information about the current topic...
        $context['is_locked'] = $topicinfo['locked'];
        $context['is_sticky'] = $topicinfo['is_sticky'];
        $context['is_very_hot'] = $topicinfo['num_replies'] >= $modSettings['hotTopicVeryPosts'];
        $context['is_hot'] = $topicinfo['num_replies'] >= $modSettings['hotTopicPosts'];
        $context['is_approved'] = $topicinfo['approved'];
        $context['is_poll'] = $topicinfo['id_poll'] > 0 && !empty($modSettings['pollMode']) && allowedTo('poll_view');
        determineTopicClass($context);
        // Did this user start the topic or not?
        $context['user']['started'] = $user_info['id'] == $topicinfo['id_member_started'] && !$user_info['is_guest'];
        $context['topic_starter_id'] = $topicinfo['id_member_started'];
        // Set the topic's information for the template.
        $context['subject'] = $topicinfo['subject'];
        $context['num_views'] = $topicinfo['num_views'];
        $context['num_views_text'] = $context['num_views'] == 1 ? $txt['read_one_time'] : sprintf($txt['read_many_times'], $context['num_views']);
        $context['mark_unread_time'] = !empty($virtual_msg) ? $virtual_msg : $topicinfo['new_from'];
        // Set a canonical URL for this page.
        $context['canonical_url'] = $scripturl . '?topic=' . $topic . '.' . $context['start'];
        // For quick reply we need a response prefix in the default forum language.
        $context['response_prefix'] = response_prefix();
        // If we want to show event information in the topic, prepare the data.
        if (allowedTo('calendar_view') && !empty($modSettings['cal_showInTopic']) && !empty($modSettings['cal_enabled'])) {
            // We need events details and all that jazz
            require_once SUBSDIR . '/Calendar.subs.php';
            // First, try create a better time format, ignoring the "time" elements.
            if (preg_match('~%[AaBbCcDdeGghjmuYy](?:[^%]*%[AaBbCcDdeGghjmuYy])*~', $user_info['time_format'], $matches) == 0 || empty($matches[0])) {
                $date_string = $user_info['time_format'];
            } else {
                $date_string = $matches[0];
            }
            // Get event information for this topic.
            $events = eventInfoForTopic($topic);
            $context['linked_calendar_events'] = array();
            foreach ($events as $event) {
                // Prepare the dates for being formatted.
                $start_date = sscanf($event['start_date'], '%04d-%02d-%02d');
                $start_date = mktime(12, 0, 0, $start_date[1], $start_date[2], $start_date[0]);
                $end_date = sscanf($event['end_date'], '%04d-%02d-%02d');
                $end_date = mktime(12, 0, 0, $end_date[1], $end_date[2], $end_date[0]);
                $context['linked_calendar_events'][] = array('id' => $event['id_event'], 'title' => $event['title'], 'can_edit' => allowedTo('calendar_edit_any') || $event['id_member'] == $user_info['id'] && allowedTo('calendar_edit_own'), 'modify_href' => $scripturl . '?action=post;msg=' . $topicinfo['id_first_msg'] . ';topic=' . $topic . '.0;calendar;eventid=' . $event['id_event'] . ';' . $context['session_var'] . '=' . $context['session_id'], 'can_export' => allowedTo('calendar_edit_any') || $event['id_member'] == $user_info['id'] && allowedTo('calendar_edit_own'), 'export_href' => $scripturl . '?action=calendar;sa=ical;eventid=' . $event['id_event'] . ';' . $context['session_var'] . '=' . $context['session_id'], 'start_date' => standardTime($start_date, $date_string, 'none'), 'start_timestamp' => $start_date, 'end_date' => standardTime($end_date, $date_string, 'none'), 'end_timestamp' => $end_date, 'is_last' => false);
            }
            if (!empty($context['linked_calendar_events'])) {
                $context['linked_calendar_events'][count($context['linked_calendar_events']) - 1]['is_last'] = true;
                $template_layers->add('display_calendar');
            }
        }
        // Create the poll info if it exists.
        if ($context['is_poll']) {
            $template_layers->add('display_poll');
            require_once SUBSDIR . '/Poll.subs.php';
            loadPollContext($topicinfo['id_poll']);
            // Build the poll moderation button array.
            $context['poll_buttons'] = array('vote' => array('test' => 'allow_return_vote', 'text' => 'poll_return_vote', 'image' => 'poll_options.png', 'lang' => true, 'url' => $scripturl . '?topic=' . $context['current_topic'] . '.' . $context['start']), 'results' => array('test' => 'allow_poll_view', 'text' => 'poll_results', 'image' => 'poll_results.png', 'lang' => true, 'url' => $scripturl . '?topic=' . $context['current_topic'] . '.' . $context['start'] . ';viewresults'), 'change_vote' => array('test' => 'allow_change_vote', 'text' => 'poll_change_vote', 'image' => 'poll_change_vote.png', 'lang' => true, 'url' => $scripturl . '?action=poll;sa=vote;topic=' . $context['current_topic'] . '.' . $context['start'] . ';poll=' . $context['poll']['id'] . ';' . $context['session_var'] . '=' . $context['session_id']), 'lock' => array('test' => 'allow_lock_poll', 'text' => !$context['poll']['is_locked'] ? 'poll_lock' : 'poll_unlock', 'image' => 'poll_lock.png', 'lang' => true, 'url' => $scripturl . '?action=lockvoting;topic=' . $context['current_topic'] . '.' . $context['start'] . ';' . $context['session_var'] . '=' . $context['session_id']), 'edit' => array('test' => 'allow_edit_poll', 'text' => 'poll_edit', 'image' => 'poll_edit.png', 'lang' => true, 'url' => $scripturl . '?action=editpoll;topic=' . $context['current_topic'] . '.' . $context['start']), 'remove_poll' => array('test' => 'can_remove_poll', 'text' => 'poll_remove', 'image' => 'admin_remove_poll.png', 'lang' => true, 'custom' => 'onclick="return confirm(\'' . $txt['poll_remove_warn'] . '\');"', 'url' => $scripturl . '?action=poll;sa=remove;topic=' . $context['current_topic'] . '.' . $context['start'] . ';' . $context['session_var'] . '=' . $context['session_id']));
            // Allow mods to add additional buttons here
            call_integration_hook('integrate_poll_buttons');
        }
        // Calculate the fastest way to get the messages!
        $ascending = true;
        $start = $_REQUEST['start'];
        $limit = $context['messages_per_page'];
        $firstIndex = 0;
        if ($start >= $context['total_visible_posts'] / 2 && $context['messages_per_page'] != -1) {
            $ascending = !$ascending;
            $limit = $context['total_visible_posts'] <= $start + $limit ? $context['total_visible_posts'] - $start : $limit;
            $start = $context['total_visible_posts'] <= $start + $limit ? 0 : $context['total_visible_posts'] - $start - $limit;
            $firstIndex = $limit - 1;
        }
        // Taking care of member specific settings
        $limit_settings = array('messages_per_page' => $context['messages_per_page'], 'start' => $start, 'offset' => $limit);
        // Get each post and poster in this topic.
        $topic_details = getTopicsPostsAndPoster($topic, $limit_settings, $ascending);
        $messages = $topic_details['messages'];
        $posters = array_unique($topic_details['all_posters']);
        $all_posters = $topic_details['all_posters'];
        unset($topic_details);
        call_integration_hook('integrate_display_message_list', array(&$messages, &$posters));
        // Guests can't mark topics read or for notifications, just can't sorry.
        if (!$user_info['is_guest'] && !empty($messages)) {
            $mark_at_msg = max($messages);
            if ($mark_at_msg >= $topicinfo['id_last_msg']) {
                $mark_at_msg = $modSettings['maxMsgID'];
            }
            if ($mark_at_msg >= $topicinfo['new_from']) {
                markTopicsRead(array($user_info['id'], $topic, $mark_at_msg, $topicinfo['unwatched']), $topicinfo['new_from'] !== 0);
            }
            updateReadNotificationsFor($topic, $board);
            // Have we recently cached the number of new topics in this board, and it's still a lot?
            if (isset($_REQUEST['topicseen']) && isset($_SESSION['topicseen_cache'][$board]) && $_SESSION['topicseen_cache'][$board] > 5) {
                $_SESSION['topicseen_cache'][$board]--;
            } elseif (isset($_REQUEST['topicseen'])) {
                // Use the mark read tables... and the last visit to figure out if this should be read or not.
                $numNewTopics = getUnreadCountSince($board, empty($_SESSION['id_msg_last_visit']) ? 0 : $_SESSION['id_msg_last_visit']);
                // If there're no real new topics in this board, mark the board as seen.
                if (empty($numNewTopics)) {
                    $_REQUEST['boardseen'] = true;
                } else {
                    $_SESSION['topicseen_cache'][$board] = $numNewTopics;
                }
            } elseif (isset($_SESSION['topicseen_cache'][$board])) {
                $_SESSION['topicseen_cache'][$board]--;
            }
            // Mark board as seen if we came using last post link from BoardIndex. (or other places...)
            if (isset($_REQUEST['boardseen'])) {
                require_once SUBSDIR . '/Boards.subs.php';
                markBoardsRead($board, false, false);
            }
        }
        $attachments = array();
        // If there _are_ messages here... (probably an error otherwise :!)
        if (!empty($messages)) {
            require_once SUBSDIR . '/Attachments.subs.php';
            // Fetch attachments.
            $includeUnapproved = !$modSettings['postmod_active'] || allowedTo('approve_posts');
            if (!empty($modSettings['attachmentEnable']) && allowedTo('view_attachments')) {
                $attachments = getAttachments($messages, $includeUnapproved, 'filter_accessible_attachment', $all_posters);
            }
            $msg_parameters = array('message_list' => $messages, 'new_from' => $topicinfo['new_from']);
            $msg_selects = array();
            $msg_tables = array();
            call_integration_hook('integrate_message_query', array(&$msg_selects, &$msg_tables, &$msg_parameters));
            // What?  It's not like it *couldn't* be only guests in this topic...
            if (!empty($posters)) {
                loadMemberData($posters);
            }
            // Load in the likes for this group of messages
            if (!empty($modSettings['likes_enabled'])) {
                require_once SUBSDIR . '/Likes.subs.php';
                $context['likes'] = loadLikes($messages, true);
                // ajax controller for likes
                loadJavascriptFile('like_posts.js', array('defer' => true));
                loadLanguage('Errors');
                // Initiate likes and the tooltips for likes
                addInlineJavascript('
				$(document).ready(function () {
					var likePostInstance = likePosts.prototype.init({
						oTxt: ({
							btnText : ' . JavaScriptEscape($txt['ok_uppercase']) . ',
							likeHeadingError : ' . JavaScriptEscape($txt['like_heading_error']) . ',
							error_occurred : ' . JavaScriptEscape($txt['error_occurred']) . '
						}),
					});

					$(".like_button, .unlike_button").SiteTooltip({
						hoverIntent: {
							sensitivity: 10,
							interval: 150,
							timeout: 50
						}
					});
				});', true);
            }
            $messages_request = loadMessageRequest($msg_selects, $msg_tables, $msg_parameters);
            if (!empty($modSettings['enableFollowup'])) {
                require_once SUBSDIR . '/FollowUps.subs.php';
                $context['follow_ups'] = followupTopics($messages, $includeUnapproved);
            }
            // Go to the last message if the given time is beyond the time of the last message.
            if (isset($context['start_from']) && $context['start_from'] >= $topicinfo['num_replies']) {
                $context['start_from'] = $topicinfo['num_replies'];
            }
            // Since the anchor information is needed on the top of the page we load these variables beforehand.
            $context['first_message'] = isset($messages[$firstIndex]) ? $messages[$firstIndex] : $messages[0];
            $context['first_new_message'] = isset($context['start_from']) && $_REQUEST['start'] == $context['start_from'];
        } else {
            $messages_request = false;
            $context['first_message'] = 0;
            $context['first_new_message'] = false;
        }
        $context['jump_to'] = array('label' => addslashes(un_htmlspecialchars($txt['jump_to'])), 'board_name' => htmlspecialchars(strtr(strip_tags($board_info['name']), array('&amp;' => '&')), ENT_COMPAT, 'UTF-8'), 'child_level' => $board_info['child_level']);
        // Set the callback.  (do you REALIZE how much memory all the messages would take?!?)
        // This will be called from the template.
        $context['get_message'] = array($this, 'prepareDisplayContext_callback');
        // Now set all the wonderful, wonderful permissions... like moderation ones...
        $common_permissions = array('can_approve' => 'approve_posts', 'can_ban' => 'manage_bans', 'can_sticky' => 'make_sticky', 'can_merge' => 'merge_any', 'can_split' => 'split_any', 'calendar_post' => 'calendar_post', 'can_mark_notify' => 'mark_any_notify', 'can_send_topic' => 'send_topic', 'can_send_pm' => 'pm_send', 'can_send_email' => 'send_email_to_members', 'can_report_moderator' => 'report_any', 'can_moderate_forum' => 'moderate_forum', 'can_issue_warning' => 'issue_warning', 'can_restore_topic' => 'move_any', 'can_restore_msg' => 'move_any');
        foreach ($common_permissions as $contextual => $perm) {
            $context[$contextual] = allowedTo($perm);
        }
        // Permissions with _any/_own versions.  $context[YYY] => ZZZ_any/_own.
        $anyown_permissions = array('can_move' => 'move', 'can_lock' => 'lock', 'can_delete' => 'remove', 'can_add_poll' => 'poll_add', 'can_remove_poll' => 'poll_remove', 'can_reply' => 'post_reply', 'can_reply_unapproved' => 'post_unapproved_replies');
        foreach ($anyown_permissions as $contextual => $perm) {
            $context[$contextual] = allowedTo($perm . '_any') || $context['user']['started'] && allowedTo($perm . '_own');
        }
        // Cleanup all the permissions with extra stuff...
        $context['can_mark_notify'] &= !$context['user']['is_guest'];
        $context['can_sticky'] &= !empty($modSettings['enableStickyTopics']);
        $context['calendar_post'] &= !empty($modSettings['cal_enabled']) && (allowedTo('modify_any') || $context['user']['started'] && allowedTo('modify_own'));
        $context['can_add_poll'] &= !empty($modSettings['pollMode']) && $topicinfo['id_poll'] <= 0;
        $context['can_remove_poll'] &= !empty($modSettings['pollMode']) && $topicinfo['id_poll'] > 0;
        $context['can_reply'] &= empty($topicinfo['locked']) || allowedTo('moderate_board');
        $context['can_reply_unapproved'] &= $modSettings['postmod_active'] && (empty($topicinfo['locked']) || allowedTo('moderate_board'));
        $context['can_issue_warning'] &= in_array('w', $context['admin_features']) && !empty($modSettings['warning_enable']);
        // Handle approval flags...
        $context['can_reply_approved'] = $context['can_reply'];
        $context['can_reply'] |= $context['can_reply_unapproved'];
        $context['can_quote'] = $context['can_reply'] && (empty($modSettings['disabledBBC']) || !in_array('quote', explode(',', $modSettings['disabledBBC'])));
        $context['can_mark_unread'] = !$user_info['is_guest'] && $settings['show_mark_read'];
        $context['can_unwatch'] = !$user_info['is_guest'] && $modSettings['enable_unwatch'];
        $context['can_send_topic'] = (!$modSettings['postmod_active'] || $topicinfo['approved']) && allowedTo('send_topic');
        $context['can_print'] = empty($modSettings['disable_print_topic']);
        // Start this off for quick moderation - it will be or'd for each post.
        $context['can_remove_post'] = allowedTo('delete_any') || allowedTo('delete_replies') && $context['user']['started'];
        // Can restore topic?  That's if the topic is in the recycle board and has a previous restore state.
        $context['can_restore_topic'] &= !empty($modSettings['recycle_enable']) && $modSettings['recycle_board'] == $board && !empty($topicinfo['id_previous_board']);
        $context['can_restore_msg'] &= !empty($modSettings['recycle_enable']) && $modSettings['recycle_board'] == $board && !empty($topicinfo['id_previous_topic']);
        $context['can_follow_up'] = !empty($modSettings['enableFollowup']) && boardsallowedto('post_new') !== array();
        // Check if the draft functions are enabled and that they have permission to use them (for quick reply.)
        $context['drafts_save'] = !empty($modSettings['drafts_enabled']) && !empty($modSettings['drafts_post_enabled']) && allowedTo('post_draft') && $context['can_reply'];
        $context['drafts_autosave'] = !empty($context['drafts_save']) && !empty($modSettings['drafts_autosave_enabled']) && allowedTo('post_autosave_draft');
        if (!empty($context['drafts_save'])) {
            loadLanguage('Drafts');
        }
        if (!empty($context['drafts_autosave']) && empty($options['use_editor_quick_reply'])) {
            loadJavascriptFile('drafts.js');
        }
        if (!empty($modSettings['mentions_enabled'])) {
            $context['mentions_enabled'] = true;
            // Just using the plain text quick reply and not the editor
            if (empty($options['use_editor_quick_reply'])) {
                loadJavascriptFile(array('jquery.atwho.js', 'jquery.caret.min.js', 'mentioning.js'));
            }
            loadCSSFile('jquery.atwho.css');
            addInlineJavascript('
			$(document).ready(function () {
				for (var i = 0, count = all_elk_mentions.length; i < count; i++)
					all_elk_mentions[i].oMention = new elk_mentions(all_elk_mentions[i].oOptions);
			});');
        }
        // Load up the Quick ModifyTopic and Quick Reply scripts
        loadJavascriptFile('topic.js');
        // Auto video embeding enabled?
        if (!empty($modSettings['enableVideoEmbeding'])) {
            addInlineJavascript('
		$(document).ready(function() {
			$().linkifyvideo(oEmbedtext);
		});');
        }
        // Load up the "double post" sequencing magic.
        if (!empty($options['display_quick_reply'])) {
            checkSubmitOnce('register');
            $context['name'] = isset($_SESSION['guest_name']) ? $_SESSION['guest_name'] : '';
            $context['email'] = isset($_SESSION['guest_email']) ? $_SESSION['guest_email'] : '';
            if (!empty($options['use_editor_quick_reply']) && $context['can_reply']) {
                // Needed for the editor and message icons.
                require_once SUBSDIR . '/Editor.subs.php';
                // Now create the editor.
                $editorOptions = array('id' => 'message', 'value' => '', 'labels' => array('post_button' => $txt['post']), 'height' => '250px', 'width' => '100%', 'preview_type' => 0);
                create_control_richedit($editorOptions);
                $context['attached'] = '';
                $context['make_poll'] = isset($_REQUEST['poll']);
                // Message icons - customized icons are off?
                $context['icons'] = getMessageIcons($board);
                if (!empty($context['icons'])) {
                    $context['icons'][count($context['icons']) - 1]['is_last'] = true;
                }
            }
        }
        addJavascriptVar(array('notification_topic_notice' => $context['is_marked_notify'] ? $txt['notification_disable_topic'] : $txt['notification_enable_topic']), true);
        if ($context['can_send_topic']) {
            addJavascriptVar(array('sendtopic_cancel' => $txt['modify_cancel'], 'sendtopic_back' => $txt['back'], 'sendtopic_close' => $txt['find_close'], 'sendtopic_error' => $txt['send_error_occurred'], 'required_field' => $txt['require_field']), true);
        }
        // Build the normal button array.
        $context['normal_buttons'] = array('reply' => array('test' => 'can_reply', 'text' => 'reply', 'image' => 'reply.png', 'lang' => true, 'url' => $scripturl . '?action=post;topic=' . $context['current_topic'] . '.' . $context['start'] . ';last_msg=' . $context['topic_last_message'], 'active' => true), 'notify' => array('test' => 'can_mark_notify', 'text' => $context['is_marked_notify'] ? 'unnotify' : 'notify', 'image' => ($context['is_marked_notify'] ? 'un' : '') . 'notify.png', 'lang' => true, 'custom' => 'onclick="return notifyButton(this);"', 'url' => $scripturl . '?action=notify;sa=' . ($context['is_marked_notify'] ? 'off' : 'on') . ';topic=' . $context['current_topic'] . '.' . $context['start'] . ';' . $context['session_var'] . '=' . $context['session_id']), 'mark_unread' => array('test' => 'can_mark_unread', 'text' => 'mark_unread', 'image' => 'markunread.png', 'lang' => true, 'url' => $scripturl . '?action=markasread;sa=topic;t=' . $context['mark_unread_time'] . ';topic=' . $context['current_topic'] . '.' . $context['start'] . ';' . $context['session_var'] . '=' . $context['session_id']), 'unwatch' => array('test' => 'can_unwatch', 'text' => ($context['topic_unwatched'] ? '' : 'un') . 'watch', 'image' => ($context['topic_unwatched'] ? '' : 'un') . 'watched.png', 'lang' => true, 'custom' => 'onclick="return unwatchButton(this);"', 'url' => $scripturl . '?action=unwatchtopic;topic=' . $context['current_topic'] . '.' . $context['start'] . ';sa=' . ($context['topic_unwatched'] ? 'off' : 'on') . ';' . $context['session_var'] . '=' . $context['session_id']), 'send' => array('test' => 'can_send_topic', 'text' => 'send_topic', 'image' => 'sendtopic.png', 'lang' => true, 'url' => $scripturl . '?action=emailuser;sa=sendtopic;topic=' . $context['current_topic'] . '.0', 'custom' => 'onclick="return sendtopicOverlayDiv(this.href, \'' . $txt['send_topic'] . '\');"'), 'print' => array('test' => 'can_print', 'text' => 'print', 'image' => 'print.png', 'lang' => true, 'custom' => 'rel="nofollow"', 'class' => 'new_win', 'url' => $scripturl . '?action=topic;sa=printpage;topic=' . $context['current_topic'] . '.0'));
        // Build the mod button array
        $context['mod_buttons'] = array('move' => array('test' => 'can_move', 'text' => 'move_topic', 'image' => 'admin_move.png', 'lang' => true, 'url' => $scripturl . '?action=movetopic;current_board=' . $context['current_board'] . ';topic=' . $context['current_topic'] . '.0'), 'delete' => array('test' => 'can_delete', 'text' => 'remove_topic', 'image' => 'admin_rem.png', 'lang' => true, 'custom' => 'onclick="return confirm(\'' . $txt['are_sure_remove_topic'] . '\');"', 'url' => $scripturl . '?action=removetopic2;topic=' . $context['current_topic'] . '.0;' . $context['session_var'] . '=' . $context['session_id']), 'lock' => array('test' => 'can_lock', 'text' => empty($context['is_locked']) ? 'set_lock' : 'set_unlock', 'image' => 'admin_lock.png', 'lang' => true, 'url' => $scripturl . '?action=topic;sa=lock;topic=' . $context['current_topic'] . '.' . $context['start'] . ';' . $context['session_var'] . '=' . $context['session_id']), 'sticky' => array('test' => 'can_sticky', 'text' => empty($context['is_sticky']) ? 'set_sticky' : 'set_nonsticky', 'image' => 'admin_sticky.png', 'lang' => true, 'url' => $scripturl . '?action=topic;sa=sticky;topic=' . $context['current_topic'] . '.' . $context['start'] . ';' . $context['session_var'] . '=' . $context['session_id']), 'merge' => array('test' => 'can_merge', 'text' => 'merge', 'image' => 'merge.png', 'lang' => true, 'url' => $scripturl . '?action=mergetopics;board=' . $context['current_board'] . '.0;from=' . $context['current_topic']), 'calendar' => array('test' => 'calendar_post', 'text' => 'calendar_link', 'image' => 'linktocal.png', 'lang' => true, 'url' => $scripturl . '?action=post;calendar;msg=' . $context['topic_first_message'] . ';topic=' . $context['current_topic'] . '.0'));
        // Restore topic. eh?  No monkey business.
        if ($context['can_restore_topic']) {
            $context['mod_buttons'][] = array('text' => 'restore_topic', 'image' => '', 'lang' => true, 'url' => $scripturl . '?action=restoretopic;topics=' . $context['current_topic'] . ';' . $context['session_var'] . '=' . $context['session_id']);
        }
        if ($context['can_reply'] && !empty($options['display_quick_reply'])) {
            $template_layers->add('quickreply');
        }
        $template_layers->add('pages_and_buttons');
        // Allow adding new buttons easily.
        call_integration_hook('integrate_display_buttons');
        call_integration_hook('integrate_mod_buttons');
    }
示例#17
0
function createGameZip($gameId, $filename)
{
    $gameId = intval($gameId);
    $z = new ZipArchive();
    $z->open($filename, ZIPARCHIVE::CREATE);
    $checkers = getCheckerListByGameId($gameId);
    $game = getFromDB("games", "id={$gameId}");
    $meta = "NAME=" . getGameName($gameId) . "\nDESCRIPTION=" . getGameDescription($gameId) . "\nTL=" . $game[0]["timeLimit"] . "\nML=" . $game[0]["memoryLimit"];
    $i = 0;
    foreach ($checkers as $a) {
        $z->addFile(getcwd() . "./testers/" . $a["id"], ++$i . ".checker");
        $z->addFromString($i . ".checkermeta", "LANG=cpp\nname=" . $a["name"] . "\nSEED=" . $a["hasSeed"]);
    }
    $attachments = getAttachments($gameId);
    $i = 0;
    foreach ($attachments as $b) {
        $z->addFile("./attachments/" . $b["id"], ++$i . ".attachment");
        $z->addFromString($i . ".attachmentmeta", "NAME=" . $b["originalName"] . "\nDESCRIPTION=" . $b["description"]);
    }
    $z->addFromString("META", $meta);
    $z->close();
}
示例#18
0
					<input id="upload" name="upload" type="file" size="64" tabindex="260" />
				</p>
		<?php 
}
?>
		<p id="descriptionlabel">
			<label for="content">description</label><br />
			<textarea name="description" cols="45" rows="4" id="content"><?php 
echo htmlQuotes($therecord["description"]);
?>
</textarea>
		</p>
	</fieldset>
	<?php 
if ($therecord["id"]) {
    $attchmentsquery = getAttachments($db, $therecord["uuid"]);
    if ($db->numRows($attchmentsquery)) {
        ?>
		<h2>Record Attachments</h2>
		<div class="fauxP">
		<div style="" class="smallQueryTableHolder">
		<table border="0" cellpadding="0" cellspacing="0" class="smallQueryTable">
			<tr>
				<th align="left">table</th>
				<th align="left" nowrap="nowrap" width="99%">ID</th>
				<th align="right" nowrap="nowrap">attached</th>
				<th align="left" nowrap="nowrap">&nbsp;</th>
			</tr>
		<?php 
        while ($attachmentrecord = $db->fetchArray($attchmentsquery)) {
            ?>
示例#19
0
function getAttachments($message, &$composeMessage, $passed_id, $entities, $imapConnection)
{
    global $attachment_dir, $username, $data_dir, $squirrelmail_language, $languages;
    $hashed_attachment_dir = getHashedDir($username, $attachment_dir);
    if (!count($message->entities) || $message->type0 == 'message' && $message->type1 == 'rfc822') {
        if (!in_array($message->entity_id, $entities) && $message->entity_id) {
            switch ($message->type0) {
                case 'message':
                    if ($message->type1 == 'rfc822') {
                        $filename = $message->rfc822_header->subject;
                        if ($filename == "") {
                            $filename = "untitled-" . $message->entity_id;
                        }
                        $filename .= '.msg';
                    } else {
                        $filename = $message->getFilename();
                    }
                    break;
                default:
                    if (!$message->mime_header) {
                        /* temporary hack */
                        $message->mime_header = $message->header;
                    }
                    $filename = $message->getFilename();
                    break;
            }
            $filename = decodeHeader($filename, false, false);
            if (isset($languages[$squirrelmail_language]['XTRA_CODE']) && function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
                $filename = $languages[$squirrelmail_language]['XTRA_CODE']('encode', $filename);
            }
            $localfilename = GenerateRandomString(32, '', 7);
            $full_localfilename = "{$hashed_attachment_dir}/{$localfilename}";
            while (file_exists($full_localfilename)) {
                $localfilename = GenerateRandomString(32, '', 7);
                $full_localfilename = "{$hashed_attachment_dir}/{$localfilename}";
            }
            $fp = fopen("{$hashed_attachment_dir}/{$localfilename}", 'wb');
            $message->att_local_name = $full_localfilename;
            $composeMessage->initAttachment($message->type0 . '/' . $message->type1, $filename, $full_localfilename);
            /* Write Attachment to file 
                  The function mime_print_body_lines writes directly to the 
                  provided resource $fp. That prohibits large memory consumption in
                  case of forwarding mail with large attachments.
               */
            mime_print_body_lines($imapConnection, $passed_id, $message->entity_id, $message->header->encoding, $fp);
            fclose($fp);
        }
    } else {
        for ($i = 0, $entCount = count($message->entities); $i < $entCount; $i++) {
            $composeMessage = getAttachments($message->entities[$i], $composeMessage, $passed_id, $entities, $imapConnection);
        }
    }
    return $composeMessage;
}