๐Ÿ“ Dynamic_Attachments_Checkpoint.mdv4.7.5 · 2026-12-05

Checkpoint โ€” Dynamic Attachments + LTV v1.15.0

Date: 03/12/2026 (Sydney) ยท Operator: Andrew (Chip) ยท Collaborator: Claude Systems: Live (forum.drugs-and-users.org, SMF 2.0.19, db smf209), Live Test/smf20 (db smf20) Deliverable: ltv_bbcode_v1.15.0.zip


1. Problem & Resolution

Problem

Updating a report in a post meant marking text on screen, opening the post, scrolling to the right section and pasting. The operator wanted a post to show a file's current contents straight from Linux, with no manual step: a dynamic attachment.

Resolution

A dynamic attachment is a normal SMF attachment whose file on disk is a symlink.

First one in service: attachment 10217 on Live (topic 8049), the attachment file-type report.

Item Value
Link /var/www/html/attachments2/10217_976fdcaed992f874182f7ff6c0da8bb3d4b762e0 โ†’ /var/www/html/dynattached/attach_filetypes.txt
Display name attach_filetypes.txt (renamed in smf209_attachments.filename; the placeholder was dummy.txt)
Tag in the post [ltv=10217-theme-sky-blue]DYN[/ltv], at the top of the post
Writer the operator's report script, with two lines added at the end (below)
cp /var/www/html/ISE_Data/attach_filetypes.lst /var/www/html/dynattached/attach_filetypes.tmp
mv -f /var/www/html/dynattached/attach_filetypes.tmp /var/www/html/dynattached/attach_filetypes.txt

Source folder /var/www/html/dynattached:

How to add one (planned scale: 10โ€“20, special purpose):

  1. Attach a placeholder under its final name through the post screen, and note the ID from attach=NNN.
  2. ls /var/www/html/attachments*/NNN_* to get the full file name.
  3. Move it out and link it back, typing the exact name (no shell variables):
    mv <full path> /var/www/html/dynattached/<name>
    ln -s /var/www/html/dynattached/<name> <full path>
  4. Put [ltv=NNN-theme-NAME]DYN[/ltv] (text files) or [lmv=NNN] (Markdown) where the card should appear.
  5. Every update writes a temporary file, then mv -f onto the real file (no empty-file moment).

LTV v1.15.0 (built for this, from v1.14.1):

Proven during this session


2. Risk Analysis

# Risk Likelihood / impact Mitigation / status
R1 Empty or missing source file. SMF's attachment repair, with "size of zero" or "missing" ticked, deletes the attachment row (the source survives, only the link goes). Low / medium Always update with a temporary file plus mv -f. Never move or rename a source. A link to nothing shows LTV's red Attachment file could not be read on disk.
R2 Stale size in the database. Maintenance reports "1 attachments/avatars are being reported as the wrong filesize" (10217). Certain / cosmetic Harmless. Optional: the script sets size after each run (UPDATE smf209_attachments SET size=$(stat -L -c %s โ€ฆ) WHERE id_attach=10217;).
R3 Browser cache. SMF sends attachments with a one-year Cache-Control: max-age. Was real / medium Fixed for LTV's ID form and autodisplay (;v= in v1.15.0). Not fixed for listatt's click-through or for a plain download link; LMV reads server-side, so it's unaffected.
R4 SMF parse cache. A long post (over 1,000 characters at cache level 2+, otherwise over 2,400) is cached for 240 seconds. Only if caching is on / low Up to 4 minutes' lag. Documented in the LTV manual, section 9.
R5 Mirrors. --safe-links, -L or --copy-links in the mirror1_* rsync lines would drop the links or freeze them as copies. Unknown / low Check: grep -nE 'rsync.*(safe-links|copy-links|copy-unsafe|-[a-zA-Z]*L)' /bin/mirror1_Clone /bin/mirror1_Dev. After a mirror, find /var/www/html/attachments2 -xtype l should print nothing.
R6 Web exposure of dynattached. Mitigated .htaccess deny verified (403).
R7 LMV leaks content across boards. [lmv=NNN] reads any .md attachment server-side with no check of post or board. Any poster could show the contents of an .md from the owner-only board. Real / high (confidentiality) Open. Needs the same same-post check as LTV v1.15.0, in the LMV package. Not changed this session.
R8 Unguarded shell variables in instructions. An empty $F moved the whole smf20 attachments folder into dynattached/.orig. Happened / recovered Restored with mv /var/www/html/dynattached/.orig /var/www/html/smf20/attachments. Rule from now on: exact full names in commands, no variables. Lemon library candidate.
R9 Zip format. Built with zip -X, not the operator's own legacy zipper. Low Verified the same layout as the 1.14.1 zip: no data descriptors, no extra fields, testzip OK.
R10 Zero-byte files. 134 zero-byte files in the attachment folders (application/x-empty). Info Maintenance flagged none as attachments, so they are loose files, untouched by SMF's repair.

To verify (not confirmed in chat)


3. Code Change

Package: ltv_bbcode_v1.15.0.zip (from v1.14.1, 01-12-2026)

File Change
LTVBBC.php 1.14.1 โ†’ 1.15.0 ID form, same-post check, no duplicates with autodisplay, ;v= on viewer addresses, resolveAttachmentPath() copied from LMV 4.7.4, theme-error wording names the ID form
tests/build_page.php 1.2 โ†’ 1.3 checks I1โ€“I12, page D, a stub for lookup by ID, a temporary attachment folder with a real symlink
tests/browser_checks.js 1.1 โ†’ 1.2 checks D1โ€“D7
package-info.xml 1.15.0, description, change-history comment (xmllint OK)
readme.txt, LTV_manual.md (complete file, new section 3c), CHANGELOG.md documentation
tests/run_tests.sh and the install scripts unchanged

Unrequested changes, listed before the build: the same-post check, no duplicates with autodisplay, ;v= on autodisplay addresses too, and LMV's URL form left out.

Not supported in the ID form: LMV's position form attach-NN, auto-pick [lmv=0], and the URL form. Scroll words on the ID form are accepted and ignored (possible next step: LMV's 800px / 1400px boxes).

Correction made in chat: LMV's attach-NN is counted from 00 (attach-00 = first .md); Claude had first said it was counted from 01.

Diff โ€” LTVBBC.php v1.14.1 โ†’ v1.15.0

--- LTVBBC.php  (v1.14.1, 2026-12-01)
+++ LTVBBC.php (v1.15.0, 2026-12-03)
@@ -3,8 +3,8 @@
* ========================================================
* Module: LTVBBC.php
*
- * @version 1.14.1
- * @date 2026-12-01
+ * @version 1.15.0
+ * @date 2026-12-03
*
* Another Collabware Open-Source code project, with:
* Andrew.human (Architect / Project Manager),
@@ -12,6 +12,28 @@
* and Gemini.ai (Consultant / Themeing (Presentation))
* ===========================================================
*
+ * AE 03/12/2026 -- v1.15.0: NEW [ltv=NNN]x[/ltv] - one text attachment
+ * of this post, by its permanent attachment ID
+ * (id_attach), drawn where the tag sits, as LMV's
+ * [lmv=NNN]. Takes a theme word ([ltv=NNN-theme-
+ * highcontrast], fixed, as inline) and a scroll word
+ * (accepted and ignored: the viewer frame scrolls on
+ * its own, as on the switch). Red errors, LMV wording
+ * where LMV has one: no ID / not found or pending
+ * save / not on this post / not a text file / could
+ * not be read on disk. The ID must belong to the post
+ * the tag is in (LMV does not check this). A file
+ * shown by ID is not drawn again by autodisplay on
+ * the same post. Every viewer address (ID form and
+ * autodisplay) now ends ;v=<file modified time>, so
+ * a changed file - e.g. one behind a symlink that a
+ * script rewrites - is fetched fresh instead of
+ * coming from the browser's cache (SMF sends
+ * attachments with a one-year cache time).
+ * resolveAttachmentPath() copied from LMVBBCode
+ * v4.7.4. Theme-on-non-inline error now also names
+ * the ID form. Tests v1.3 / v1.2.
+ *
* AE 01/12/2026 -- v1.14.1: [ltv=autodisplay-scroll] (also -scroll-lg,
* -noscroll, any position) now switches autodisplay on,
* the same as [ltv=autodisplay] - the way the switch is
@@ -265,8 +287,8 @@
class LTVBBCode
{
const TAG = 'ltv';
- const VERSION = '1.14.1';
- const VERSION_DATE = '2026-12-01';
+ const VERSION = '1.15.0';
+ const VERSION_DATE = '2026-12-03';

/** v1.11.0: $modSettings key holding the text-extension list. */
const EXT_SETTING = 'ltv_text_exts';
@@ -301,6 +323,16 @@
private static $autoDisplay = array();

/**
+ * v1.15.0: attachments already drawn by [ltv=NNN] on each message,
+ * message id => (attachment id => true). render() skips these so a
+ * file is not drawn twice on one post. Written while the post body
+ * is parsed, read later from the Display.template.php patch.
+ *
+ * @var array<int,array<int,bool>>
+ */
+ private static $shownById = array();
+
+ /**
* v1.10.0: per-message "start open" flag. v1.12.0: set for every
* [ltv=autodisplay] (with or without the word "open"), so cards
* start open. No entry = collapsed (no tag form produces that now).
@@ -513,9 +545,18 @@
*
* "x" (the content between the tags) is discarded either way -
* this tag produces no visible output itself, only a side-effect
- * flag read later by shouldAutoDisplay(). Any other =value is
- * currently just ignored (content passed through unchanged) -
- * there is no [ltv=N] attachment-render form in this version.
+ * flag read later by shouldAutoDisplay().
+ *
+ * and one attachment by ID (v1.15.0):
+ *
+ * [ltv=NNN]x[/ltv] - text attachment NNN (its id_attach,
+ * which never changes) drawn where the
+ * tag sits. Must be on this post.
+ * [ltv=NNN-theme-NAME]x[/ltv] - the same, fixed theme NAME. A
+ * scroll word is accepted and ignored.
+ * See renderById().
+ *
+ * Any other =value is ignored and the tag shows nothing.
*
* Uses unparsed_equals_content (not the newer 'parameters' regex
* machinery) - same reason PDFBBCode does: confirmed on this fork
@@ -592,9 +633,18 @@
return;
}

+ // v1.15.0: [ltv=NNN] - one attachment of this post by its ID,
+ // drawn here. Takes the theme word; the scroll word (already
+ // taken out above) is ignored, as on the switch.
+ if (preg_match('/^\d+$/', $rest))
+ {
+ $data[0] = self::renderById((int) $rest, $theme, $rawValue);
+ return;
+ }
+
if ($theme !== null)
{
- $data[0] = self::renderError('A theme can only be set on inline text, e.g. [ltv=inline-theme-' . $theme . ']. Not valid: [ltv=' . $rawValue . '].');
+ $data[0] = self::renderError('A theme can only be set on inline text or an attachment ID, e.g. [ltv=inline-theme-' . $theme . '] or [ltv=123-theme-' . $theme . ']. Not valid: [ltv=' . $rawValue . '].');
return;
}

@@ -766,6 +816,167 @@
}

/**
+ * v1.15.0: [ltv=NNN] - one text attachment of the current post, by
+ * its attachment ID (id_attach), as a card drawn where the tag sits.
+ *
+ * Checks, in order, each failing with a red line where the tag was
+ * typed (LMV's wording where LMV has the same check):
+ * ID 0 -> "No attachment ID provided."
+ * no message ID known -> RedBox (as the autodisplay switch)
+ * no such row / not approved
+ * -> "Attachment #N not found or pending save."
+ * row on another post -> "Attachment #N is not on this post."
+ * (LMV has no such check; without it any post could show any
+ * board's file name in its card header)
+ * extension not in the ltv_text_exts list
+ * -> "File #N is not a text file (...)."
+ * file missing/unreadable -> "Attachment file could not be read on disk."
+ *
+ * The card is the autodisplay card (same viewer frame, 85vh) with
+ * no Show/Hide link - LMV's tag-placed cards are not collapsible
+ * either. A theme named in the tag is fixed, as inline. The output
+ * goes back through parse_bbc(), so it is flatten()ed (it holds no
+ * user text, so the whole card can be). The ID is recorded so
+ * render() does not draw the same file again on this post.
+ *
+ * @param int $id Attachment ID from the tag.
+ * @param string|null $theme Theme named in the tag, or null.
+ * @param string $rawValue The whole value after '=', for messages.
+ * @return string HTML for the card, or a red error line.
+ */
+ private static function renderById($id, $theme, $rawValue)
+ {
+ global $smcFunc;
+
+ $id = (int) $id;
+ if (empty($id))
+ return self::renderError('No attachment ID provided.');
+
+ $msgId = (int) self::currentMsgId();
+ if (empty($msgId))
+ return RedBoxBBCode::noMessageId('[ltv=' . $rawValue . ']', 'the attachment cannot be checked against this post here.');
+
+ $request = $smcFunc['db_query']('', '
+ SELECT id_attach, id_msg, filename, file_hash, id_folder, approved
+ FROM {db_prefix}attachments
+ WHERE id_attach = {int:id}',
+ array('id' => $id)
+ );
+ $row = $smcFunc['db_fetch_assoc']($request);
+ $smcFunc['db_free_result']($request);
+
+ if (empty($row) || empty($row['approved']))
+ return self::renderError('Attachment #' . $id . ' not found or pending save.');
+
+ if ((int) $row['id_msg'] !== $msgId)
+ return self::renderError('Attachment #' . $id . ' is not on this post.');
+
+ if (!in_array(self::fileExt($row['filename']), self::textExtensions(), true))
+ return self::renderError('File #' . $id . ' is not a text file (' . implode(', ', self::textExtensions()) . ').');
+
+ $mtime = self::fileMtime($id, $row);
+ if ($mtime === false)
+ return self::renderError('Attachment file could not be read on disk.');
+
+ self::$shownById[$msgId][$id] = true;
+
+ $iframe = '<iframe src="' . self::viewerUrl(self::downloadHref($id, $mtime), $row['filename'])
+ . '" height="500" style="border: none; width: 100%; max-width: 100%; display: block; height: 85vh; min-height: 500px;"></iframe>';
+
+ return self::flatten(self::wrapCard($iframe, $row['filename'], null, $theme, $msgId));
+ }
+
+ /**
+ * v1.15.0: the download address the viewer frame fetches. With a
+ * file modified time it ends ;v=<time>: SMF ignores the extra
+ * parameter, but the address changes whenever the file does, so the
+ * browser fetches a changed file fresh instead of using its cached
+ * copy (SMF sends attachments with a one-year cache time). An
+ * unchanged file keeps its address and stays cached.
+ *
+ * @param int $id Attachment ID.
+ * @param int|bool $mtime File modified time, or false/0 for none.
+ * @return string
+ */
+ private static function downloadHref($id, $mtime)
+ {
+ global $scripturl, $topic;
+
+ return $scripturl . '?action=dlattach'
+ . (!empty($topic) ? ';topic=' . (int) $topic . '.0' : '')
+ . ';attach=' . (int) $id
+ . (!empty($mtime) ? ';v=' . (int) $mtime : '');
+ }
+
+ /**
+ * v1.15.0: modified time of an attachment's file on disk, or false
+ * if it cannot be found or read. Follows a symlink to its target,
+ * so a file kept elsewhere and linked into the attachment folder
+ * reports its own time.
+ *
+ * @param int $id Attachment ID.
+ * @param array $row Row with filename, file_hash, id_folder.
+ * @return int|bool
+ */
+ private static function fileMtime($id, $row)
+ {
+ $path = self::resolveAttachmentPath($id, $row['filename'],
+ isset($row['file_hash']) ? $row['file_hash'] : '',
+ isset($row['id_folder']) ? $row['id_folder'] : null);
+ if ($path === false || !is_readable($path))
+ return false;
+
+ $t = @filemtime($path);
+ return ($t === false) ? false : (int) $t;
+ }
+
+ /**
+ * v1.15.0: copied unchanged from LMVBBCode::resolveAttachmentPath()
+ * (LMV 4.7.4). SMF's own getAttachmentFilename() when it exists,
+ * otherwise a guess at the legacy names, checked with is_readable().
+ *
+ * @return string|bool Path, or false.
+ */
+ private static function resolveAttachmentPath($id, $filename, $file_hash, $id_folder = null)
+ {
+ global $modSettings;
+
+ if (function_exists('getAttachmentFilename') && !empty($file_hash))
+ {
+ return getAttachmentFilename($filename, $id, $id_folder, false, $file_hash);
+ }
+
+ $dirSetting = $modSettings['attachmentUploadDir'] ?? '';
+ if (is_string($dirSetting) && $dirSetting !== '' && $dirSetting[0] === 'a')
+ {
+ $unserialized = @unserialize($dirSetting);
+ if (is_array($unserialized))
+ {
+ $dirSetting = (!empty($modSettings['currentAttachmentUploadDir']) && $id_folder !== null && isset($unserialized[$id_folder]))
+ ? $unserialized[$id_folder]
+ : reset($unserialized);
+ }
+ }
+ if (empty($dirSetting) || !is_string($dirSetting))
+ return false;
+
+ $dir = rtrim($dirSetting, '/');
+ $candidates = array(
+ $dir . '/' . $id,
+ $dir . '/' . $id . '_' . $file_hash,
+ $dir . '/' . $filename,
+ );
+
+ foreach ($candidates as $candidate)
+ {
+ if (is_readable($candidate))
+ return $candidate;
+ }
+
+ return false;
+ }
+
+ /**
* Per-message guard so a post with N .txt/.text attachments only
* queries/renders once no matter how many times the native
* per-attachment loop calls in. Mirrors PDFBBCode's own static
@@ -797,19 +1008,28 @@
return '';

$atts = self::fetchTxtAttachments($msgId);
+
+ // v1.15.0: files already drawn by [ltv=NNN] on this post are not
+ // drawn again.
+ if (!empty(self::$shownById[$msgId]))
+ {
+ foreach ($atts as $k => $a)
+ if (isset(self::$shownById[$msgId][(int) $a['id_attach']]))
+ unset($atts[$k]);
+ $atts = array_values($atts);
+ }
+
if (empty($atts))
return '';

- global $scripturl, $topic;
-
$open = !empty(self::$autoDisplayOpen[$msgId]);

$out = '';
foreach ($atts as $a)
{
- $dlHref = $scripturl . '?action=dlattach'
- . (!empty($topic) ? ';topic=' . (int) $topic . '.0' : '')
- . ';attach=' . (int) $a['id_attach'];
+ // v1.15.0: ;v=<modified time> on the address - see downloadHref().
+ // A file that cannot be read still gets its card, as before.
+ $dlHref = self::downloadHref($a['id_attach'], self::fileMtime($a['id_attach'], $a));

// v1.10.0: a closed card keeps the viewer address in data-src;
// the first Show copies it into src (see wrapCard()'s script).
@@ -1729,15 +1949,18 @@
* fetchAttachments() - this class is meant to stand alone, with
* no install-order dependency on listatt being present.
*
+ * v1.15.0: also selects file_hash and id_folder, so render() can
+ * find each file and add its modified time to the viewer address.
+ *
* @param int $msgId
- * @return array List of ['id_attach' => int, 'filename' => string]
+ * @return array List of ['id_attach', 'filename', 'file_hash', 'id_folder']
*/
private static function fetchTxtAttachments($msgId)
{
global $smcFunc;

$request = $smcFunc['db_query']('', '
- SELECT id_attach, filename
+ SELECT id_attach, filename, file_hash, id_folder
FROM {db_prefix}attachments
WHERE id_msg = {int:msg}
AND approved = 1