<?php
/*
功能：自定义通用
作者：启肯科技
Q Q：328493711
微信：13738373177（同手机）
官网：http://www.qiken.com
说明：QKCMS-轻量级AI智能内容管理建站系统
版权：© 2025 温州启肯网络有限公司 保留所有权利，盗版必究
*/

?>

<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>{qkcms:posts_title}-{qkcms:site_name}</title>
  <meta name="keywords" content="{qkcms:posts_keywords}">
  <meta name="description" content="{qkcms:posts_description}">
  <style>
    body.qk-post1 .topics-section.content {
      overflow: hidden;
    }

    body.qk-post1 .topics-section.content .ql-align-center {
      text-align: center;
    }

    body.qk-post1 .topics-section.content .ql-align-right {
      text-align: right;
    }

    body.qk-post1 .topics-section.content .ql-align-justify {
      text-align: justify;
    }

    body.qk-post1 .topics-section.content img {
      max-width: 100% !important;
      height: auto !important;
      display: block;
      box-sizing: border-box;
    }

    body.qk-post1 .topics-section.content .ql-align-center img,
    body.qk-post1 .topics-section.content .ql-align-center video,
    body.qk-post1 .topics-section.content .ql-align-center iframe {
      margin-left: auto;
      margin-right: auto;
    }

    body.qk-post1 .topics-section.content .ql-align-right img,
    body.qk-post1 .topics-section.content .ql-align-right video,
    body.qk-post1 .topics-section.content .ql-align-right iframe {
      margin-left: auto;
      margin-right: 0;
    }
  </style>
  <link rel="stylesheet" href="/assets/css/ts_post.css" />
</head>

<body class="qk-post1">
  {qkcms:head.html}
  <?php
  // 获取文章缩略图，根据文件名判断
  $thumbnail = '{qkcms:posts_thumbnail}';
  $debug_info = '无缩略图';
  $banner_thumbnail = '';
  $qk_stamp_plugin_exists = file_exists(dirname(dirname(__DIR__)) . '/admin/Plugin/40_stamp.php');
  $qk_stamp_enabled = false;
  if ($qk_stamp_plugin_exists) {
    $plugin_content = @file_get_contents(dirname(dirname(__DIR__)) . '/admin/Plugin/40_stamp.php');
    if ($plugin_content && preg_match('/盖章总开关\s*=\s*(true|false)/i', $plugin_content, $matches)) {
      $qk_stamp_enabled = strtolower($matches[1]) === 'true';
    }
  }

  // 直接检查路径是否包含thumbnail_前缀
  if (strpos($thumbnail, 'thumbnail_') !== false && $thumbnail !== '{qkcms:posts_thumbnail}') {
    $banner_thumbnail = $thumbnail;
    $debug_info = '有缩略图: ' . $thumbnail;
  } else {
    $debug_info = '无缩略图: ' . $thumbnail;
  }
  $banner_class = !empty($banner_thumbnail) ? 'has-thumbnail' : 'no-thumbnail';
  if (!function_exists('getPostPasswordSessionKey')) {
    function getPostPasswordSessionKey($postId)
    {
      return 'qk_post_password_access_' . intval($postId);
    }
  }
  if (!function_exists('hasPostPasswordAccess')) {
    function hasPostPasswordAccess($postId)
    {
      $sessionKey = getPostPasswordSessionKey($postId);
      return !empty($_SESSION[$sessionKey]);
    }
  }
  if (!function_exists('isPostPasswordAjaxRequest')) {
    function isPostPasswordAjaxRequest()
    {
      if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_POST['post_password_submit'])) {
        return false;
      }
      if (isset($_POST['post_password_ajax']) && $_POST['post_password_ajax'] === '1') {
        return true;
      }
      return !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';
    }
  }
  $post_password_required = '';
  $post_password_error = '';
  $post_password_access_granted = true;
  if (!empty($post_id)) {
    $post_password_row = get_single_row($GLOBALS['conn'], "SELECT access_password FROM posts WHERE id = ?", array($post_id));
    if ($post_password_row && isset($post_password_row['access_password'])) {
      $post_password_required = trim((string)$post_password_row['access_password']);
      if ($post_password_required !== '') {
        $post_password_access_granted = hasPostPasswordAccess($post_id);
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['post_password_submit']) && isset($_POST['post_password_post_id']) && intval($_POST['post_password_post_id']) === intval($post_id)) {
          $submittedPassword = isset($_POST['post_password']) ? trim((string)$_POST['post_password']) : '';
          if ($submittedPassword !== '' && hash_equals($post_password_required, $submittedPassword)) {
            $_SESSION[getPostPasswordSessionKey($post_id)] = 1;
            $post_password_access_granted = true;
          } else {
            $post_password_access_granted = false;
            $post_password_error = '密码不正确，请重新输入';
          }
        }
      }
    }
  }
  if (!empty($post_id) && isPostPasswordAjaxRequest() && isset($_POST['post_password_post_id']) && intval($_POST['post_password_post_id']) === intval($post_id)) {
    ob_clean();
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(array(
      'success' => $post_password_access_granted,
      'message' => $post_password_access_granted ? '密码验证成功' : ($post_password_error !== '' ? $post_password_error : '密码验证失败'),
      'reload' => $post_password_access_granted
    ), JSON_UNESCAPED_UNICODE);
    exit;
  }
  ?>
  <div class="about-banner no-thumbnail" id="about-banner">
    <div class="tech-grid"></div>
    <div class="light-beam"></div>
    <div class="about-banner-content">
      <h1>{qkcms:posts_title}
        <?php if (!empty($qk_stamp_plugin_exists) && $qk_stamp_enabled): ?>
          <button type="button" class="post-stamp-btn" id="postStampBtn" data-post-id="<?php echo $post_id; ?>" data-post-property="{qkcms:posts_property}" data-post-property-id="<?php $pp = get_single_row($GLOBALS['conn'], 'SELECT property FROM posts WHERE id = ?', array($post_id));
                                                                                                                                                                                    echo isset($pp['property']) ? intval($pp['property']) : 0; ?>" data-require-login="1" data-login-action="stamp" style="display:none">盖章</button>
        <?php endif; ?>
      </h1>
      <div class="banner-desc">{qkcms:posts_description}</div>
    </div>
  </div>
  <script>
    window.qkStampEntity = 'posts';
    window.postId = <?php echo $post_id; ?>;
    // 使用JavaScript在浏览器中判断缩略图
    document.addEventListener('DOMContentLoaded', function() {
      const banner = document.getElementById('about-banner');
      // 获取实际的缩略图路径
      const thumbnail = '{qkcms:posts_thumbnail}';

      // 直接检查路径是否包含thumbnail_前缀
      if (thumbnail && thumbnail.includes('thumbnail_')) {
        banner.classList.remove('no-thumbnail');
        banner.classList.add('has-thumbnail');
        banner.style.backgroundImage = 'url(' + thumbnail + ')';
      }
    });
  </script>

  <main class="about-main">

    <div class="about-content-layout" id="contentLayout">
      <div class="post1_1">
        {qkcms:current_position}-专题单页
      </div>
      <div class="topics-section content<?php echo (!$post_password_access_granted && $post_password_required !== '') ? ' post-password-content is-locked' : ''; ?>" style="padding-bottom: 40px;">
        <?php
        $content_result = get_single_row($GLOBALS['conn'], "SELECT content FROM posts WHERE id = ?", array($post_id));
        $content = $content_result && isset($content_result['content']) ? $content_result['content'] : '';

        function processCodeBlocks($content)
        {
          if (strpos($content, 'code-block-container') !== false) {
            return $content;
          }

          $content = preg_replace_callback('/\[qkcms:code\]([\s\S]*?)\[\/qkcms:code\]/i', function ($matches) {
            $code = $matches[1];
            $code = trim($code);
            if (empty($code)) {
              $code = '// 空代码块';
            }
            return formatCodeBlock($code);
          }, $content);

          return $content;
        }

        /**
         * 格式化代码块
         * @param string $code 代码内容
         * @return string 格式化后的代码块HTML
         */
        function formatCodeBlock($code)
        {
          // 确保代码内容不为空
          if (empty($code)) {
            $code = '// 空代码块';
          }

          // 检查代码是否包含HTML转义字符，如果是则解码
          if (strpos($code, '&lt;') !== false || strpos($code, '&gt;') !== false || strpos($code, '&amp;') !== false) {
            $code = htmlspecialchars_decode($code, ENT_QUOTES);
          }

          // 处理HTML换行标签，转换为换行符
          $code = str_replace('<br>', "\n", $code);
          $code = str_replace('<br/>', "\n", $code);
          $code = str_replace('<br />', "\n", $code);
          $code = str_replace('</p>', "\n", $code);
          $code = str_replace('</div>', "\n", $code);
          $code = str_replace('</li>', "\n", $code);

          // 移除HTML开始标签（保留内容）
          $code = preg_replace('/<p[^>]*>/', '', $code);
          $code = preg_replace('/<div[^>]*>/', '', $code);
          $code = preg_replace('/<li[^>]*>/', '', $code);

          // 保留换行符，不要在HTML转义中丢失
          $code = str_replace("\r\n", "\n", $code);
          $code = str_replace("\r", "\n", $code);

          // 生成唯一ID用于复制按钮
          $codeId = 'code-' . uniqid();

          // 将代码按行分割，为每行生成对应的行号
          $lines = explode("\n", $code);
          $lineCount = count($lines);

          // 生成带行号的代码HTML - 不转义HTML特殊字符，保持富文本格式
          $codeWithLineNumbers = '';
          for ($i = 0; $i < $lineCount; $i++) {
            $lineNumber = $i + 1;
            // 不转义HTML特殊字符，直接显示原始内容
            $lineContent = $lines[$i];
            // 跳过空行（可选）
            if (trim($lineContent) === '' && $i < $lineCount - 1) {
              // 保留空行但显示为空
              $lineContent = '';
            }
            $codeWithLineNumbers .= '<div class="code-line">';
            $codeWithLineNumbers .= '<span class="line-number">' . $lineNumber . '</span>';
            $codeWithLineNumbers .= '<span class="line-content">' . $lineContent . '</span>';
            $codeWithLineNumbers .= '</div>';
          }

          // 将原始代码存储在data属性中，用于复制时使用
          $encodedCode = base64_encode($code);

          // 返回格式化后的代码块
          return '<div class="code-block-container">'
            . '<div class="code-block-header">'
            . '<button class="copy-code-btn" data-code-id="' . $codeId . '" data-original-code="' . $encodedCode . '">复制</button>'
            . '</div>'
            . '<div class="code-block-content" id="' . $codeId . '">'
            . $codeWithLineNumbers
            . '</div>'
            . '</div>';
        }

        if ($post_password_access_granted || $post_password_required === '') {
          $content_clean = preg_replace('/\[qkcms:buy——(\d+)个积分\]([\s\S]*?)\[\/qkcms:buy\]/', '$2', $content);

          if (strpos($content_clean, '[qkcms:code]') !== false) {
            $content_clean = processCodeBlocks($content_clean);
          }

          echo $content_clean;
        } else {
          echo '<div class="post-password-placeholder" aria-hidden="true"></div>';
        }
        ?>

        <?php if (!$post_password_access_granted && $post_password_required !== ''): ?>
          <div class="post-password-overlay">
            <div class="post-password-panel">
              <div class="post-password-icon">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
                  <rect x="3" y="11" width="18" height="10" rx="2"></rect>
                  <path d="M7 11V8a5 5 0 0 1 10 0v3"></path>
                </svg>
              </div>
              <div class="post-password-title">本文需要密码才可访问</div>
              <form method="post" class="post-password-form js-post-password-form">
                <input type="hidden" name="post_password_submit" value="1">
                <input type="hidden" name="post_password_post_id" value="<?php echo intval($post_id); ?>">
                <input type="password" name="post_password" class="post-password-input" placeholder="请输入访问密码" autocomplete="off">
                <button type="submit" class="post-password-button">确认访问</button>
              </form>
            </div>
          </div>
        <?php endif; ?>

        <script>
          <?php if ($post_password_error !== ''): ?>
          if (typeof showToast === 'function') {
            showToast('<?php echo addslashes($post_password_error); ?>', 'error');
          } else {
            alert('<?php echo addslashes($post_password_error); ?>');
          }
          <?php endif; ?>
          function bindPostPasswordForms() {
            const passwordForms = document.querySelectorAll('.js-post-password-form');
            passwordForms.forEach(form => {
              form.addEventListener('submit', function(e) {
                e.preventDefault();
                if (form.dataset.submitting === '1') return;
                const submitButton = form.querySelector('.post-password-button');
                const passwordInput = form.querySelector('.post-password-input');
                if (!submitButton || !passwordInput) return;
                const formData = new FormData(form);
                formData.append('post_password_ajax', '1');
                form.dataset.submitting = '1';
                submitButton.disabled = true;
                fetch(window.location.href, {
                  method: 'POST',
                  body: formData,
                  headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                    'Accept': 'application/json'
                  },
                  credentials: 'same-origin'
                }).then(response => response.json()).then(result => {
                  if (typeof showToast === 'function') {
                    showToast(result.message || (result.success ? '密码验证成功' : '密码验证失败'), result.success ? 'success' : 'error');
                  } else if (!result.success) {
                    alert(result.message || '密码验证失败');
                  }
                  if (result.success) {
                    setTimeout(function() {
                      window.location.reload();
                    }, 240);
                    return;
                  }
                  passwordInput.focus();
                  passwordInput.select();
                }).catch(() => {
                  if (typeof showToast === 'function') {
                    showToast('请求失败，请稍后重试', 'error');
                  } else {
                    alert('请求失败，请稍后重试');
                  }
                }).finally(() => {
                  delete form.dataset.submitting;
                  submitButton.disabled = false;
                });
              });
            });
          }
          // 复制代码功能
          function bindCopyButtons() {
            const copyButtons = document.querySelectorAll('.copy-code-btn');

            copyButtons.forEach(button => {
              button.addEventListener('click', function() {
                // 获取代码块容器
                const codeContainer = this.closest('.code-block-container');
                if (!codeContainer) return;

                // 获取代码内容区域
                const codeContent = codeContainer.querySelector('.code-block-content');
                if (!codeContent) return;

                // 提取纯文本代码（移除HTML标签，保留纯文本和换行）
                let codeText = '';
                const lines = codeContent.querySelectorAll('.code-line');
                lines.forEach((line, index) => {
                  const lineContent = line.querySelector('.line-content');
                  if (lineContent) {
                    // 获取纯文本内容，保留原始格式
                    let text = lineContent.innerText || lineContent.textContent;
                    // 添加换行符（除了最后一行）
                    if (index < lines.length - 1) {
                      text += '\n';
                    }
                    codeText += text;
                  }
                });

                // 移除开头和结尾的空行
                codeText = codeText.replace(/^\n+/, '').replace(/\n+$/, '');

                // 移除多余的空行（连续的多个换行符替换为一个）
                codeText = codeText.replace(/\n\s*\n/g, '\n');

                navigator.clipboard.writeText(codeText).then(() => {
                  // 显示复制成功状态
                  const originalText = this.textContent;
                  this.textContent = '已复制';
                  this.classList.add('copied');

                  // 2秒后恢复原状
                  setTimeout(() => {
                    this.textContent = originalText;
                    this.classList.remove('copied');
                  }, 2000);
                }).catch(err => {});
              });
            });
          }

          document.addEventListener('DOMContentLoaded', function() {
            bindPostPasswordForms();
            bindCopyButtons();
          });
        </script>
      </div>

      <div class="topics-section content" style="padding-bottom: 25px;">


        <div class="post51">
          <h3>建议反馈交流区</h3>
        </div>
        {qkcms:comment.php}
      </div>
    </div>
    </div>


    </div>
    </div>
  </main>
  <?php if (!empty($qk_stamp_plugin_exists) && $qk_stamp_enabled): ?>
    {qk_Plugin:ID40}
  <?php endif; ?>
  {qkcms:footer.html}
</body>

</html>

