Files
Brad ArantandClaude Sonnet 5 b8f7793773 Add global music player, invoicing/payment system, account subpages, mail account admin, and the qualityiron.vegas Jet 2.0 port
Jet interpreter (Tag.cpp, __call.cpp, __imap*.cpp/h, __smtpsend.cpp/h,
__imapemptyfolder.cpp/h - new): assorted parser/tag fixes found across
this work - a stray literal-tag-in-comment and backslash-quote parser
corruption class, a dangling-pointer fix, a __call.cpp fd leak, IMAP
folder-management tags, multi-account/per-host IMAP support, and a
smtpsend Message-ID fix.

barant.com site (jetc/barant-site/):
- A site-wide persistent music player (header band, playlist/queue,
  stereo FFT EQ, session-persisted state) fed by new library/
  ianslibrary/music song-list subpages.
- /account split into info/phones/invoices subpages; a full invoicing
  and Square payment system (create/edit/copy/pay/email invoice);
  admin invoice management and mail-account management subpages.
- /services split into overview/hosting/siptrunking/documents
  subpages, retiring the old standalone pages.
- SIPPHONE.tag: a Jet 2.0 WebRTC softphone tag.
- main.css/spa.js/email.js: the SPA loading indicator, the music
  player band styling, and assorted fixes accumulated alongside this
  work.

qualityiron-site/: the qualityiron.vegas job/contractor/customer/
document management app, ported from its original Jet 1.4 codebase to
Jet 2.0 as barant.coms APIServers second multi-tenant site.

wcwc/wcwc.jet: the WCWC site Jet source (wcwc.jtc build output not
included).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-06 17:42:01 +00:00

1373 lines
58 KiB
C++

#include "Tag.h"
#include <set>
#include <utility>
#include <unordered_map>
#include "Exception.h"
#include "Global.h"
#include "__mysql.h"
#include "__sql.h"
#include "__imap.h"
#include "__imaplist.h"
#include "__imapmessage.h"
#include "__imapflag.h"
#include "__imapdelete.h"
#include "__imapemptyfolder.h"
#include "__imapmove.h"
#include "__imapfolders.h"
#include "__imapsearch.h"
#include "__smtpsend.h"
#include "__imapaccounts.h"
#include "__whilerow.h"
#include "__comment.h"
#include "__eval.h"
#include <cstdio>
#include "__exclude.h"
#include "__for.h"
#include "__if.h"
#include "__ifrow.h"
#include "__include.h"
#include "__read.h"
#include "__write.h"
#include "__set.h"
#include "__call.h"
#include "__system.h"
#include "__jet.h"
#include "__while.h"
#include "__until.h"
#include "__header.h"
#include "__cookie.h"
#include "__whiledir.h"
#include "__tag.h"
#include "__dotag.h"
#include "__stream.h"
#include "__dump.h"
#include "__trytag.h"
#include "Operand.h"
#include <iostream>
namespace jet {
Tag::Tag(coreutils::ZString &in, coreutils::MString &parentOut, Global &global, Tag *parent, Tag *local, coreutils::ZString splitTagName)
: ZString(in), parentOut(parentOut), global(global), parent(parent), local(local) {
this->splitTagName = splitTagName;
global.errorCursor = in.getCursor();
// Previously gated on "parent &&" too, which meant the sole
// parent==NULL construction site (jet-2.0.cpp's top-level __jet, see
// main()) never parsed its own opening <jet ...> tag/attributes at
// all - the whole wrapper (including cgi="yes" and every other
// attribute) was silently treated as literal passthrough content
// instead. parent is otherwise always non-NULL (every nested tag
// construction already passes a real parent), so dropping this
// requirement only changes behavior for that one top-level case.
if(in.ifNext("<")) {
name = in.getTokenInclude("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_!");
if(in.startsWith(" ") || in.startsWith("/") || in.startsWith(">")) {
bool finished = false;
while(!finished) {
in.skipWhitespace();
if(in.ifNext(">")) {
// jet-1.4's real parser knew which built-ins never take
// a body (its own "void element" list) - real 1.4
// content (SESSIONCTL.tag, config.cfg, index.cgi) is
// written with a bare closing '>' and no explicit
// </tag> for these, which a plain "bare '>' always means
// scan for a body" rule can't tell apart from a real
// container tag that happens to be immediately followed
// by more content. Kept in sync with jetc's own
// JetParser.cpp::isVoidTag - same list, same reasoning,
// this is the runtime-interpreted-fallback-path
// equivalent of that compile-time fix.
coreutils::MString nameLower = coreutils::MString(name).toLower();
// exclude was wrongly listed here - __exclude.cpp's own
// constructor explicitly throws "exclude must have a
// container" if hasContainer is false, so it always
// needs a real body (e.g. mainpagetemplate.temp's own
// <exclude><title></exclude>) - it was never actually
// void, this was a miscategorization.
bool isVoid = (nameLower == "set") || (nameLower == "include") ||
(nameLower == "cookie") || (nameLower == "header") ||
(nameLower == "read") || (nameLower == "write") ||
(nameLower == "call") || (nameLower == "system") ||
(nameLower == "dump");
// A CUSTOM tag (not one of jet's own built-ins above)
// written bare, with no explicit close, is genuinely
// ambiguous: is a real body coming (scan for
// </thisname>), or is this self-closing and whatever
// follows is unrelated sibling content? Real 1.4
// content writes multiple bare invocations of the SAME
// custom tag back-to-back with no close at all
// (login.page's own two <field .../> entries, no
// </field> anywhere) - scanning for a body in that case
// doesn't just fail to find one, it finds the NEXT
// sibling invocation of the same tag name via ifNested
// (which recognizes it as "another <field>", recurses
// into IT looking for ITS OWN close, and so on) and
// silently swallows everything through EOF as this
// tag's own unused body - since a tag whose own
// definition never references <container> never reads
// that captured text anyway, the result is silent,
// undetectable content loss, confirmed live: the second
// <field>, <buttonbay>, and the login button all
// vanished from real rendered output with zero errors.
// Resolve the ambiguity the same way the built-in list
// above already does: if this tag's own DEFINITION
// never references a bare <container> (so it could
// never use captured body text even if it had one),
// treat it as void too - genuinely no way to lose
// content that would never have been read regardless.
if(!isVoid) {
coreutils::ZString customDef;
if(findTagDefinition(name, customDef)) {
coreutils::MString defLower(customDef);
defLower.reset();
defLower = defLower.toLower();
defLower.reset();
isVoid = (defLower.find(coreutils::MString("<container")) == -1);
}
}
hasContainer = !isVoid;
hasContainer2 = false;
finished = true;
break;
} else if(in.ifNext("/>")) {
hasContainer = false;
hasContainer2 = false;
finished = true;
break;
}
if(!finished) {
// Every keyword lookup site in this codebase (keywordDefined("name"),
// resolveKeyword("host"), etc.) uses a lowercase literal - real
// 1.4 content writes attribute NAMES in any case too (e.g.
// SESSIONCTL.tag's <TAG NAME="ABUTTON" ...>), so the key has to
// be normalized to lowercase here, at the point of storage, or
// every lookup against it silently misses (keywordDefined("name")
// doesn't find "NAME") rather than erroring clearly.
coreutils::MString keywordName = coreutils::MString(in.getTokenInclude("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_")).toLower();
// Real 1.4 content quotes attribute values with either " or '
// (SESSIONCTL.tag's own <tag name='sessionctl' keywords="page
// stylesheet"> uses both in the same tag) - accept either,
// closing with whichever character opened it.
bool dq = in.ifNext("=\"");
bool sq = !dq && in.ifNext("='");
if(dq || sq) {
if(keywords.count(keywordName) == 0)
keywords[keywordName] = in.getTokenExclude(dq ? "\"" : "'");
else
throw coreutils::Exception("keyword name must be unique for tag.");
in.ifNext(dq ? "\"" : "'");
} else if(keywordName.getLength() > 0) {
// Unquoted attribute value (e.g. TYPE=NE, SCOPE=LOCAL - real
// 1.4 content throughout). Neither quote style matched, but
// getTokenInclude() above already consumed the attribute NAME
// and left the cursor sitting exactly on '=' - without also
// consuming '=' and the unquoted value here, the next
// iteration's getTokenInclude() call returns empty (cursor is
// still at '=', not a name character) and this loops forever
// with zero forward progress. Same bug class already found and
// fixed in ifNested()'s own copy of this logic - this is
// Tag::Tag's main constructor's separate, parallel copy.
if(in.ifNext("=")) {
coreutils::MString value;
while(!in.eod()) {
char c = in.charAt(0);
if(c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '>' || c == '/')
break;
value.write(c);
in.nextChar();
}
if(keywords.count(keywordName) == 0)
keywords[keywordName] = value;
else
throw coreutils::Exception("keyword name must be unique for tag.");
}
}
}
}
if(keywordDefined("filterblanklines")) {
filterBlankLines = keywords["filterblanklines"] == "true" ? true: false;
}
if(keywordDefined("trimlines")) {
trimLines = keywords["trimlines"] == "true" ? true: false;
}
if(hasContainer) {
bool hasSplitTag = splitTagName == "" ? false: true;
char *start = in.getCursor();
while(!in.eod()) {
char *end = in.getCursor();
if(ifEndTagName(in)) {
if(hasContainer2)
container2 = coreutils::ZString(start, end - start);
else
container = coreutils::ZString(start, end - start);
break;
} else if(hasSplitTag && ifSplitTagName(in)) {
hasContainer2 = true;
container = coreutils::ZString(start, end - start);
// ifSplitTagName() is a pure lookahead (push()/pop()'s the
// cursor back regardless of match - see its own body), so
// the actual split-tag opening delimiter still has to be
// consumed here. This used to be hardcoded to the literal
// "<else>" - fine for <if>/<while>/<until> (which all use
// splitTagName "else"), but wrong for any other split tag
// name (e.g. <try>'s "catch") - a hardcoded literal that
// never matches means this ifNext() silently fails, the
// cursor never advances past <catch>, and the outer loop
// matches the same unconsumed <catch> on every subsequent
// iteration forever. Build the real expected delimiter
// from splitTagName itself so it works for any split tag.
in.ifNext("<");
in.getTokenInclude("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_");
while(!in.eod()) {
in.skipWhitespace();
if(in.ifNext(">"))
break;
else if(in.getTokenExclude("=").getLength() != 0) {
bool dq = in.ifNext("=\"");
bool sq = !dq && in.ifNext("='");
if(dq || sq) {
while(1) {
if(in.ifNext(dq ? "\"" : "'"))
break;
in.nextChar();
}
} else {
in.nextChar();
while(!in.eod()) {
char c = in.charAt(0);
if(c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '>' || c == '/')
break;
in.nextChar();
}
}
} else
break;
}
start = in.getCursor();
} else if(ifNested(in)) {
} else
in.nextChar();
}
}
setZString(in.parsed());
if(keywordDefined("eval")) {
if(keywords["eval"] == "yes") {
evaluate = true;
} else if(keywords["eval"] == "no") {
evaluate = false;
} else
throw coreutils::Exception("keyword 'eval' must be 'yes' or 'no'.");
}
}
} else
parseContainer(in, out);
}
Tag::~Tag() {
if(evaluate)
if(output)
copyContainer(out, parentOut);
else if(output)
copyContainer(container, parentOut);
}
// Tracks (scope, keyword-name) pairs whose resolution is currently
// in progress, shared between resolveKeyword (populates it around its
// own body) and getVariable's #[...] parent-chain walk (consults it).
// Real content passes a keyword straight through under the SAME name
// to a nested invocation that also declares a keyword by that name -
// e.g. barant.tag's own <linkbutton page="#[page]" ...> (linkbutton
// itself declares "page" as one of its own keywords too, coincidentally
// the same name as the enclosing tag's own "page" being forwarded).
// #[page] here means "my CALLER's page value", but by the time it's
// lazily resolved (raw text is stored unresolved at attribute-parse
// time, only interpreted later when actually read), there's no record
// of which scope originally wrote it - a naive parent-chain walk
// restarts from `local` every time and immediately re-finds THIS SAME
// tag's own "page" keyword (the one currently being resolved) instead
// of continuing outward to the real caller, recursing forever. Once a
// (scope, name) pair is already being resolved, the walk below skips
// that scope for that name and continues to scope->parent instead of
// recursing back into it.
static thread_local std::set<std::pair<Tag*, coreutils::MString>> resolvingKeywords;
coreutils::MString Tag::resolveKeyword(coreutils::ZString keyword) {
// Defensive recursion guard, kept as a backstop for any OTHER
// self-referential chain the (scope, keyword) tracking above
// doesn't happen to cover (e.g. a longer, indirect cycle through
// several different keyword names) - crashing the whole process
// via stack overflow is never acceptable, even for a case not
// specifically identified yet.
static thread_local int resolveDepth = 0;
if(resolveDepth > 100)
throw coreutils::Exception("keyword resolution recursion limit exceeded - likely a self-referential #[name]/$[name] value.");
struct DepthGuard {
int &d;
DepthGuard(int &d) : d(d) { ++d; }
~DepthGuard() { --d; }
} depthGuard(resolveDepth);
coreutils::MString keywordNameCopy(keyword);
std::pair<Tag*, coreutils::MString> resolvingKey(this, keywordNameCopy);
bool alreadyTracked = resolvingKeywords.count(resolvingKey) > 0;
if(!alreadyTracked)
resolvingKeywords.insert(resolvingKey);
struct ResolvingGuard {
std::set<std::pair<Tag*, coreutils::MString>> &s;
std::pair<Tag*, coreutils::MString> k;
bool owns;
ResolvingGuard(std::set<std::pair<Tag*, coreutils::MString>> &s, std::pair<Tag*, coreutils::MString> k, bool owns) : s(s), k(k), owns(owns) {}
~ResolvingGuard() { if(owns) s.erase(k); }
} resolvingGuard(resolvingKeywords, resolvingKey, !alreadyTracked);
coreutils::MString resolved;
keywords[keyword].reset();
while(!keywords[keyword].eod()) {
if(keywords[keyword].startsWith("$[") || keywords[keyword].startsWith("#[")) {
resolved.write(getVariable(keywords[keyword]));
} else {
resolved.write(keywords[keyword].charAt(0));
keywords[keyword].nextChar();
}
}
keywords[keyword].reset();
return resolved;
}
void Tag::processContainer(coreutils::ZString &container, coreutils::ZString container2, bool topLevel) {
if(hasContainer && evaluate)
parseContainer(container, out, container2, topLevel);
}
// Extracted, unchanged, from parseContainer's own "container" dispatch
// branch below - see that branch's original comment (preserved there)
// and Tag.h's own doc comment for the full explanation of the
// scope-walk/recursion-guard behavior this preserves exactly. The
// hasContainer/evaluate gate matches processContainer's own gate
// (both call sites this replaced went through processContainer,
// which silently no-ops unless both are true) - collapsed to one
// check here since it's the same guard either branch below would
// have applied individually.
void Tag::renderContainer(coreutils::MString &out, coreutils::ZString container2) {
if(!(hasContainer && evaluate))
return;
static thread_local std::set<Tag*> resolvingContainerScopes;
Tag *containerScope = local;
while(containerScope &&
(!containerScope->isCustomTagBoundary ||
resolvingContainerScopes.count(containerScope) > 0))
containerScope = containerScope->parent;
if(containerScope != NULL) {
resolvingContainerScopes.insert(containerScope);
try {
// ZString tracks its own read cursor (see ZString.h's own
// reset() doc comment) - containerScope->container is a
// persistent member reused across EVERY <container> reference
// within the same custom tag invocation, not a fresh value per
// call. Without resetting it first, a SECOND <container>
// reference in one invocation (e.g. SESSIONCTL.tag's own
// setenv definition: <eval name="_envvalue" scope="local">
// <container></eval> followed later by
// <eval name="#[name]"><container></eval>) parses an
// already-exhausted cursor and silently renders empty, even
// though the first reference worked correctly - confirmed via
// a real repro: setenv's own second <container> use wrote ""
// instead of the caller's actual value, so every
// $[_login_id]-style read after a successful login stayed
// empty. resolveKeyword() already resets its own equivalent
// cursor (keywords[keyword]) both before and after for the
// same reason - this mirrors that.
containerScope->container.reset();
parseContainer(containerScope->container, out, NULL, false);
} catch(...) {
resolvingContainerScopes.erase(containerScope);
throw;
}
resolvingContainerScopes.erase(containerScope);
} else {
container2.reset();
parseContainer(container2, out, NULL, false);
}
}
namespace {
struct CachedTagDef {
coreutils::MString name;
coreutils::MString body;
};
// Recognizes the exact pattern jetc's own codegen emits for every
// top-level <tag name="X">...</tag> definition it doesn't itself
// specially compile (everything except set/if/for/while - see
// JetCodegen.cpp): one interpretSpan(span, out) call per
// definition, re-run from scratch on every single request even
// though the definition text (SESSIONCTL.tag/barant.tag/
// project.tag, spliced in at compile time via <include>) never
// changes between requests once compiled - confirmed live, a real
// page's compiled main.compiled.cpp calls this 15+ times per
// request, one of them (the whole <tag name='sessionctl'> block,
// every nested tag definition inside it included) close to 5000
// characters, all fully re-scanned through the generic runtime Tag
// dispatch every time. Keyed by the span's own raw data pointer,
// not its content - safe because jetc emits these spans as C
// string literals (static storage duration, the same address for
// the whole life of the process), so pointer identity alone means
// "the exact same compiled span, already seen once on this
// thread" with no need to hash or compare bytes.
thread_local std::unordered_map<const char*, CachedTagDef> tagDefCache;
}
void Tag::interpretSpan(coreutils::ZString span, coreutils::MString &out) {
const char *key = span.getData();
auto cached = tagDefCache.find(key);
if(cached != tagDefCache.end()) {
global.tags[cached->second.name] = cached->second.body;
return;
}
// Only the fast path above is new behavior - everything below
// this point, for a cache MISS, is the exact same real interpreter
// call as before. The snapshot/diff afterward is purely for
// deciding whether THIS span is safe to cache for next time - it
// never changes what actually happens on this (first, per-thread)
// call.
std::set<coreutils::MString> tagKeysBefore;
for(auto &entry : global.tags)
tagKeysBefore.insert(entry.first);
size_t outLenBefore = out.getLength();
parseContainer(span, out);
// Only cache spans whose entire observable effect was registering
// EXACTLY one new top-level tag definition, with nothing written
// to `out` - the precise signature of a bare <tag name="X">...
// </tag> definition block (evaluate=false/output=false in
// __tag.cpp - see its own doc comment). Real page content,
// multiple registrations in one span, or a registration that
// landed in some scope's own localTags instead of global.tags
// (nested inside another custom tag, not the top-level case this
// targets) are all left running the real interpreter every time -
// the safe default, never caching something that isn't provably
// pure and static.
if(out.getLength() == outLenBefore && global.tags.size() == tagKeysBefore.size() + 1) {
for(auto &entry : global.tags) {
if(tagKeysBefore.find(entry.first) == tagKeysBefore.end()) {
tagDefCache[key] = CachedTagDef{entry.first, entry.second};
break;
}
}
}
}
void Tag::parseContainer(coreutils::ZString &in, coreutils::MString &out, coreutils::ZString container2, bool topLevel) {
coreutils::ZString tag;
char *start = in.getCursor();
while(!in.eod()) {
if(in.ifNext("|>")) {
if(!topLevel)
out.write("|>");
char ch = in.nextChar();
while(!in.ifNext("<|")) {
out.write(ch);
ch = in.nextChar();
}
out.write(ch);
if(!topLevel)
out.write("<|");
continue;
} else if(in.startsWith("<")) {
if(ifTagName(in, "mysql") || ifTagName(in, "database")) {
// <database> is jet-1.4's name for this same tag (real 1.4
// content - SESSIONCTL.tag's own <sessionctl> definition,
// index.cgi itself - uses <database name="..."> throughout,
// never <mysql>) - recognized as a real alias rather than
// requiring that content to be rewritten.
__mysql _mysql(in, out, global, this, local);
continue;
} else if(ifTagName(in, "comment")) {
__comment _comment(in, out, global, this, local);
continue;
} else if(ifTagName(in, "sql")) {
__sql _sql(in, out, global, this, local);
continue;
} else if(ifTagName(in, "imap")) {
__imap _imap(in, out, global, this, local);
continue;
} else if(ifTagName(in, "imaplist")) {
__imaplist _imaplist(in, out, global, this, local);
continue;
} else if(ifTagName(in, "imapmessage")) {
__imapmessage _imapmessage(in, out, global, this, local);
continue;
} else if(ifTagName(in, "imapflag")) {
__imapflag _imapflag(in, out, global, this, local);
continue;
} else if(ifTagName(in, "imapdelete")) {
__imapdelete _imapdelete(in, out, global, this, local);
continue;
} else if(ifTagName(in, "imapemptyfolder")) {
__imapemptyfolder _imapemptyfolder(in, out, global, this, local);
continue;
} else if(ifTagName(in, "imapmove")) {
__imapmove _imapmove(in, out, global, this, local);
continue;
} else if(ifTagName(in, "imapfolders")) {
__imapfolders _imapfolders(in, out, global, this, local);
continue;
} else if(ifTagName(in, "imapsearch")) {
__imapsearch _imapsearch(in, out, global, this, local);
continue;
} else if(ifTagName(in, "smtpsend")) {
__smtpsend _smtpsend(in, out, global, this, local);
continue;
} else if(ifTagName(in, "imapaccounts")) {
__imapaccounts _imapaccounts(in, out, global, this, local);
continue;
} else if(ifTagName(in, "whilerow")) {
__whilerow _whilerow(in, out, global, this, local);
continue;
} else if(ifTagName(in, "for")) {
__for _for(in, out, global, this, local);
continue;
} else if(ifTagName(in, "if")) {
__if _if(in, out, global, this, local);
continue;
} else if(ifTagName(in, "ifrow")) {
__ifrow _ifrow(in, out, global, this, local);
continue;
} else if(ifTagName(in, "include")) {
__include _include(in, out, global, this, local);
continue;
} else if(ifTagName(in, "exclude")) {
__exclude _exclude(in, out, global, this, local);
continue;
} else if(ifTagName(in, "jet")) {
__jet _jet(in, out, global, this, local);
continue;
} else if(ifTagName(in, "read")) {
__read _read(in, out, global, this, local);
continue;
} else if(ifTagName(in, "write")) {
__write _write(in, out, global, this, local);
continue;
} else if(ifTagName(in, "set")) {
__set _set(in, out, global, this, local);
continue;
} else if(ifTagName(in, "eval")) {
__eval _eval(in, out, global, this, local);
continue;
} else if(ifTagName(in, "call")) {
__call _call(in, out, global, this, local);
continue;
} else if(ifTagName(in, "system")) {
__system _system(in, out, global, this, local);
continue;
} else if(ifTagName(in, "while")) {
__while _while(in, out, global, this, local);
continue;
} else if(ifTagName(in, "until")) {
__until _until(in, out, global, this, local);
continue;
} else if(ifTagName(in, "try")) {
__trytag _trytag(in, out, global, this, local);
continue;
} else if(ifTagName(in, "header")) {
__header _header(in, out, global, this, local);
continue;
} else if(ifTagName(in, "cookie")) {
__cookie _cookie(in, out, global, this, local);
continue;
} else if(ifTagName(in, "whiledir")) {
__whiledir _whiledir(in, out, global, this, local);
continue;
} else if(ifTagName(in, "stream")) {
__stream _stream(in, out, global, this, local);
continue;
} else if(ifTagName(in, "dump")) {
__dump _dump(in, out, global, this, local);
continue;
} else if(ifTagName(in, "tag")) {
__tag _tag(in, out, global, this, local);
continue;
} else if(ifTagDefined(in, tag)) {
__dotag _dotag(in, out, global, this, local);
continue;
} else if(ifTagName(in, "container")) {
// Rendering logic lives in renderContainer (see Tag.h/below) -
// extracted, unchanged, so generated code for a compiled
// <tag name="X"> definition body (see jetc's TAGDEF handling)
// can call it directly too, without re-deriving the same
// scope-walking/recursion-guard logic.
renderContainer(out, container2);
// The old consumption here - in.ifNext("<container");
// in.skipWhitespace(); in.ifNext("/>"); - only ever handled
// a bare, lowercase, attribute-free "<container/>". Real
// 1.4 content writes this several other ways: uppercase
// (SESSIONCTL.tag's own <CONTAINER EVAL="NO">), with
// attributes, and closed with a bare ">" rather than "/>" -
// ifTagName(in, "container") above already matches all of
// these case-insensitively for DISPATCH, but the hardcoded
// lowercase "<container" literal consumption step then
// failed outright on any of them, consuming nothing at
// all and leaving the cursor exactly where it started -
// the dispatch loop re-entered this same branch forever,
// re-running processContainer(container2) with zero
// forward progress. Confirmed live via a loop-iteration
// guard showing "preview=[<CONTAINER EVAL=\"NO\">]"
// unchanged across tens of thousands of iterations.
// Consume properly instead: skip '<', the tag name itself
// (whatever case it was written in), then scan to the
// closing '>' - respecting quoted attribute values so a
// '>' inside one doesn't end the tag early - regardless of
// whether it was self-closed with '/>' or left as a bare
// '>' (a self-closing '/' is just consumed as an ordinary
// character by the scan below either way).
in.ifNext("<");
in.getTokenInclude("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_");
while(!in.eod() && !in.ifNext(">")) {
if(in.ifNext("\"")) {
while(!in.eod() && !in.ifNext("\"")) in.nextChar();
} else if(in.ifNext("'")) {
while(!in.eod() && !in.ifNext("'")) in.nextChar();
} else {
in.nextChar();
}
}
continue;
} else {
out.write(in.nextChar());
continue;
}
} else if(in.startsWith("$[") || in.startsWith("#[")) {
global.errorCursor = in.getCursor();
out.write(getVariable(in, true));
} else {
out.write(in.nextChar());
}
}
}
void Tag::scanContainer(coreutils::ZString &in) {
while(!in.eod()) {
if(ifEndTagName(in))
return;
else if(ifNested(in)) {}
else in.nextChar();
}
}
bool Tag::ifTagName(coreutils::ZString &in, const char *tag) {
// Case-insensitive - real 1.4 content invokes built-ins in every
// case (<MYSQL>, <Sql>, <DATABASE>, ...), and this is the dispatch
// that decides which __xxx class handles a tag at all, so a
// case-sensitive miss here doesn't throw, it just silently treats
// the tag as unrecognized fallback content instead.
in.push();
if(in.ifNext("<")) {
coreutils::MString token = in.getTokenInclude("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_");
if(token.toLower() == coreutils::MString(tag).toLower()) {
if(in.ifNext(" ")) {
in.pop();
return true;
} else if(in.ifNext("/>")) {
in.pop();
return true;
} else if(in.ifNext(">")) {
in.pop();
return true;
}
}
}
in.pop();
return false;
}
bool Tag::ifTagName(coreutils::ZString &in) {
// Case-insensitive - same reasoning as ifEndTagName above.
in.push();
if(in.ifNext("<")) {
coreutils::MString token = in.getTokenInclude("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_");
if(token.toLower() == coreutils::MString(name).toLower()) {
in.push();
if(in.ifNext(" ")) {
in.pop();
return true;
} else if(in.ifNext("/>")) {
in.pop();
return true;
} else if(in.ifNext(">")) {
in.pop();
return true;
}
in.pop();
}
}
in.pop();
return false;
}
bool Tag::findTagDefinition(coreutils::MString name, coreutils::ZString &result) {
// Case-insensitive, matching __tag.cpp's own registration fix -
// real 1.4 content declares and invokes a custom tag in different
// case at different sites (SESSIONCTL.tag's <TAG NAME='TEMPLATE'>
// vs mainpagetemplate.temp's <template>...</template>).
name = name.toLower();
Tag *scope = this;
while(scope) {
if(scope->isCustomTagBoundary && scope->localTags.count(name)) {
result = scope->localTags[name];
return true;
}
scope = scope->parent;
}
if(global.tags.count(name)) {
result = global.tags[name];
return true;
}
return false;
}
bool Tag::ifTagDefined(coreutils::ZString &in, coreutils::ZString &tag) {
in.push();
if(in.ifNext("<")) {
tag = in.getTokenInclude("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_");
coreutils::ZString definition;
if(findTagDefinition(tag, definition)) {
if(in.ifNext(" ")) {
in.pop();
return true;
} else if(in.ifNext("/>")) {
in.pop();
return true;
} else if(in.ifNext(">")) {
in.pop();
return true;
}
in.pop();
}
}
in.pop();
return false;
}
bool Tag::ifEndTagName(coreutils::ZString &in) {
// Case-insensitive, matching jetc's own compile-time matchTagClose
// fix - real 1.4 content closes tags in whatever case it opened
// them with (e.g. SESSIONCTL.tag's <tag name="linkbutton"> ... </TAG>).
in.push();
if(in.ifNext("</")) {
coreutils::MString token = in.getTokenInclude("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_");
if(token.toLower() == coreutils::MString(name).toLower()) {
if(in.ifNext(">"))
return true;
}
}
in.pop();
return false;
}
bool Tag::ifSplitTagName(coreutils::ZString &in) {
in.push();
if(in.ifNext("<")) {
if(coreutils::MString(in.getTokenInclude("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_")).toLower() == coreutils::MString(splitTagName).toLower()) {
// Tolerate attributes on the split-tag marker itself (e.g.
// <try>'s own <catch name="_imaperr">) rather than requiring
// '>' to land immediately after the tag name - every
// splitTagName="else" caller writes a bare <else> so this
// never mattered for them, but <catch name="..."> is the
// universal convention everywhere it's used. Previously this
// whole check was a single unbraced
// if(...){in.pop();return true;} where the missing braces
// meant "return true" executed unconditionally, leaving the
// cursor in a half-advanced, never-popped state on the
// attributed-tag path - confirmed live via a real /email/list
// failure whose caught error text leaked
// "name=\"_imaperr\">" into the JSON response.
while(!in.eod()) {
in.skipWhitespace();
if(in.ifNext(">")) {
in.pop();
return true;
} else if(in.getTokenExclude("=").getLength() != 0) {
bool dq = in.ifNext("=\"");
bool sq = !dq && in.ifNext("='");
if(dq || sq) {
while(1) {
if(in.ifNext(dq ? "\"" : "'"))
break;
in.nextChar();
}
} else {
in.nextChar();
while(!in.eod()) {
char c = in.charAt(0);
if(c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '>' || c == '/')
break;
in.nextChar();
}
}
} else
break;
}
}
}
in.pop();
return false;
}
int Tag::skipBlankLine(coreutils::ZString in) {
ZString temp = in.getTokenInclude(" \t");
if(ifNext("\n"))
return temp.getLength() + 1;
return 0;
}
void Tag::copyContainer(coreutils::ZString &in, coreutils::MString &out) {
while(!in.eod()) {
if(filterBlankLines) {
if(!in.lineIsWhitespace()) {
if(trimLines)
out.write(in.goeol().trim());
else
out.write(in.goeol());
out.write('\n');
}
else {
in.goeol();
}
}
else {
out.write(in.charAt(0));
in.nextChar();
}
}
}
bool Tag::keywordDefined(coreutils::ZString keyword) {
return keywords.find(keyword) != keywords.end();
}
namespace {
// Every built-in tag that uses splitTagName "else" - shared by
// ifNested(in)'s own cross-name fallback below and the new
// ifNested(in,tagName)/scanContainerNamed overloads. <try>'s own
// splitTagName is "catch", a different marker - deliberately not
// folded into this fix (no repro of the same bug shape there, and
// guessing its exact semantics without one risks getting it wrong).
const char *elseSplitTagNames[] = { "if", "while", "until", "ifrow" };
const int elseSplitTagNameCount = 4;
}
bool Tag::ifNested(coreutils::ZString &in) {
bool hasContainer = false;
if(ifTagName(in)) {
while(!in.eod()) {
in.skipWhitespace();
if(in.ifNext(">")) {
hasContainer = true;
break;
} else if(in.ifNext("/>")) {
hasContainer = false;
return true;
} else if(in.getTokenExclude("=").getLength() != 0) {
// Real 1.4 content quotes attribute values with either " or
// ' (e.g. <TAG NAME='TEMPLATE' SCOPE=LOCAL> nested inside
// SESSIONCTL.tag's own <sessionctl> definition) - accept
// either, closing with whichever character opened it.
bool dq = in.ifNext("=\"");
bool sq = !dq && in.ifNext("='");
if(dq || sq) {
while(1) {
if(in.ifNext(dq ? "\"" : "'")) {
break;
}
in.nextChar();
}
} else {
// Unquoted attribute value (e.g. TYPE=NE, SCOPE=LOCAL -
// real 1.4 content throughout, including SESSIONCTL.tag's
// own <TAG NAME='TEMPLATE' SCOPE=LOCAL>). Neither quote
// style matched, but the getTokenExclude("=") above
// already consumed the attribute NAME and left the cursor
// sitting exactly on '=' - without also consuming '=' and
// the unquoted value here, the next iteration's
// getTokenExclude("=") returns empty (cursor is already
// AT '=') and this loops forever with zero forward
// progress. Confirmed live via gdb: three snapshots over
// 15s showed IDENTICAL stack depth and cursor position,
// not a slow-but-progressing recursion.
in.nextChar(); // consume '='
while(!in.eod()) {
char c = in.charAt(0);
if(c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '>' || c == '/')
break;
in.nextChar();
}
}
}
}
if(hasContainer)
scanContainer(in);
return false;
}
// Same-name match failed - if THIS tag itself is one of the
// splitTagName="else" conditionals (if/while/until/ifrow), a
// DIFFERENTLY-named one of that same set nested here (e.g. an
// <if> nested directly inside an <ifrow>'s own body) needs to be
// recognized and skipped too, exactly like a same-name nested
// occurrence already is above - otherwise the inner tag's own
// <else>/</...> markers get read as if they belonged to THIS
// (outer) tag's own boundary scan. Confirmed via a real, minimal
// repro: <ifrow>...<if expr="..."><else>...</if>...<else>...
// </ifrow> - the outer <ifrow> incorrectly split on the INNER
// <if>'s own <else>, and the inner <if>'s real closing </if> then
// leaked into the rendered output as literal text (found while
// investigating a real "successful login silently doesn't
// proceed" report - login.method's own <ifrow><if expr=...>...
// </if></ifrow> structure hits this exactly).
if(splitTagName == "else") {
for(int i = 0; i < elseSplitTagNameCount; i++) {
if(ifNested(in, elseSplitTagNames[i]))
break;
}
}
return false;
}
// See Tag.h's own doc comment on this overload set. Mirrors
// ifNested(in) above exactly, but checks an explicit tagName (via
// ifTagName(in,tagName)) instead of this->name, and skips the
// nested tag's own body (if any) via scanContainerNamed(in,tagName)
// instead of scanContainer(in) - so it correctly stops at THAT
// tag's own close, not this outer tag's.
bool Tag::ifNested(coreutils::ZString &in, const char *tagName) {
bool hasContainer = false;
if(ifTagName(in, tagName)) {
while(!in.eod()) {
in.skipWhitespace();
if(in.ifNext(">")) {
hasContainer = true;
break;
} else if(in.ifNext("/>")) {
hasContainer = false;
return true;
} else if(in.getTokenExclude("=").getLength() != 0) {
bool dq = in.ifNext("=\"");
bool sq = !dq && in.ifNext("='");
if(dq || sq) {
while(1) {
if(in.ifNext(dq ? "\"" : "'")) {
break;
}
in.nextChar();
}
} else {
in.nextChar(); // consume '=' - see ifNested(in)'s own comment on why
while(!in.eod()) {
char c = in.charAt(0);
if(c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '>' || c == '/')
break;
in.nextChar();
}
}
}
}
if(hasContainer)
scanContainerNamed(in, tagName);
return true;
}
return false;
}
bool Tag::ifEndTagName(coreutils::ZString &in, const char *tagName) {
in.push();
if(in.ifNext("</")) {
coreutils::MString token = in.getTokenInclude("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_");
if(token.toLower() == coreutils::MString(tagName).toLower()) {
if(in.ifNext(">"))
return true;
}
}
in.pop();
return false;
}
// Like scanContainer(in) above, but scans for tagName's own close
// rather than this->name's - and, since whatever's nested INSIDE
// tagName's own body could itself contain any mix of the four
// splitTagName="else" conditionals (not just tagName repeated), tries
// all four at each position rather than only tagName itself. This is
// what actually skips PAST an inner conditional's entire span
// (attributes, body, close tag) when ifNested(in)'s own cross-name
// fallback recognizes one nested in a DIFFERENTLY-named outer tag.
void Tag::scanContainerNamed(coreutils::ZString &in, const char *tagName) {
while(!in.eod()) {
if(ifEndTagName(in, tagName))
return;
bool matchedNested = false;
for(int i = 0; i < elseSplitTagNameCount; i++) {
if(ifNested(in, elseSplitTagNames[i])) {
matchedNested = true;
break;
}
}
if(!matchedNested)
in.nextChar();
}
}
coreutils::MString Tag::getVariable(coreutils::ZString &variable, bool inContainer) {
if(variable.ifNext("$[")) {
coreutils::MString name;
coreutils::MString modifier;
if(variable.ifNext("!")) {
renderVariableName(variable, name, modifier);
return global.variables[name];
} else if(variable.ifNext("%")) {
renderVariableName(variable, name, modifier);
if(inContainer)
return keywords[name];
else
return parent->keywords[name];
} else if(variable.ifNext(":")) {
if(global.cgi) {
renderVariableName(variable, name, modifier);
if(name.find(":") == -1) {
name << ":0";
}
if(global.cgiData == NULL)
throw coreutils::Exception("cgi variable requested but no request body was available (not a POST, or an unrecognized Content-Type).");
coreutils::MString cgiValue = (*global.cgiData)[name];
return processModifier(cgiValue, modifier);
} else
throw coreutils::Exception("cgi variable only allowed in cgi mode.");
} else if(variable.ifNext("@")) {
renderVariableName(variable, name, modifier);
if(global.sessionFile == NULL)
throw coreutils::Exception("session variable requested but no session is active (missing sessiondir keyword, or cgi mode is off).");
coreutils::MString sessionValue = (*global.sessionFile)[name];
return processModifier(sessionValue, modifier);
} else if(variable.ifNext("&")) {
renderVariableName(variable, name, modifier);
const char *envValue = getenv(name.c_str());
if(envValue == NULL)
throw coreutils::Exception("environment variable is not set.");
coreutils::MString envValueStr(envValue);
return processModifier(envValueStr, modifier);
} else if(variable.ifNext("^")) {
renderVariableName(variable, name, modifier);
return global.cookies.data[name];
} else {
renderVariableName(variable, name, modifier);
name.split(".");
if(name.getList().size() == 1) {
if(global.variables.find(name[0]) == global.variables.end()) {
// jet-1.4 fallback: a bare $[name] that isn't a real global
// also checks the current default query (sessionid="")
// before failing - real 1.4 source depends on this, e.g.
// <sql>select ...</sql> immediately followed by a bare
// $[description] with no explicit $[.description] dot.
// 2.0 originally required the dot; this restores 1.4's
// more forgiving behavior without requiring the real
// source to be rewritten.
coreutils::MString defaultSession("");
if(global.sessionExists(defaultSession)) {
try {
coreutils::MString columnValue = global.getSession(defaultSession)->getColumnValue(name[0]);
return processModifier(columnValue, modifier);
} catch(coreutils::Exception &) {
// No such column in whatever's currently in the default
// session (or no query has run on it yet) - fall through
// to the empty-string default below rather than propagate.
}
}
// jet-1.4 fallback #2: a genuinely never-initialized bare $[name]
// (no global, no session/row match either) reads as an empty
// string, not a hard error - real 1.4 source depends on this too
// (e.g. SESSIONCTL.tag's own
// <if value1="$[_session_id]" value2="" type="ne"> for a fresh,
// no-cookie visitor - $[_session_id] was never set by anything
// at that point). 2.0 originally threw "global variable is not
// initialized" for this - matches ordinary template-language
// semantics (undefined reads as empty) far better than erroring
// on every fresh page hit.
coreutils::MString empty("");
return processModifier(empty, modifier);
}
return processModifier(global.variables[name[0]], modifier);
}
// Same jet-1.4 fallback as the bare (undotted) case just above,
// extended to the explicit $[session.column] form: real content
// (invoice.method's own $[.amount]/$[.invnumber]/etc., read
// right after a <sql>...where i.id=$[_invoice_id]</sql> that
// legitimately has no matching row when no invoice id was ever
// passed in - e.g. thankyou.page's unconditional <include
// file="invoice.method">) depends on a missing column/session
// reading as empty, not a hard error. This call previously threw
// straight through with no catch at all here - confirmed live,
// this exact page ("column does not exist in session result.")
// was an uncaught propagation from here, not the already-guarded
// 1-part path above.
try {
coreutils::MString sessionValue = global.getSessionVariable(name);
return processModifier(sessionValue, modifier);
} catch(coreutils::Exception &) {
coreutils::MString empty("");
return processModifier(empty, modifier);
}
}
throw coreutils::Exception("expected variable name or type designator.");
} else if(variable.ifNext("#[")) {
coreutils::MString name;
coreutils::MString modifier;
renderVariableName(variable, name, modifier);
// local is NULL at the true top level (jet-2.0.cpp's own
// new jet::__jet(data, out, global, NULL, NULL)) and stays NULL
// through any tag that doesn't establish its own local scope (most
// don't - <if>/<while>/<until>/<until>'s splitTagName constructor
// form is the exception, passing `this` as local) - dereferencing
// it unconditionally here crashes (SIGABRT/segfault, not a clean
// catchable exception) rather than reporting a normal error.
// Confirmed via a real crash while testing #[name] inside a custom
// tag invocation with no enclosing local-scope-owning tag.
if(local == NULL)
throw coreutils::Exception("local variable requested but no local scope is active.");
// #[name] most commonly refers to some ENCLOSING custom tag's own
// declared/passed attribute value - e.g. setpage's own body reads
// #[NAME]/#[DIR] (its own keywords, found at the first scope
// checked below), but sessionctl's body invokes
// <setpage name="#[PAGE]">, where "#[PAGE]" must resolve against
// SESSIONCTL's own "page" keyword, not setpage's (setpage never
// declares "page" - only "NAME DIR"). Since __dotag binds each
// custom tag invocation's own local=this (so a tag's body sees
// its OWN attributes first), reaching an ancestor's attributes
// requires walking the lexical containment chain via `parent`
// (the same chain findTagDefinition() already walks for tag
// DEFINITION lookups) rather than checking a single scope.
// local->variables (explicit <set scope="local"> only) is checked
// at each level too, ahead of that level's keywords, so a local
// <set> can shadow an attribute of the same name at that scope.
for(Tag *scope = local; scope; scope = scope->parent) {
if(scope->variables.find(name) != scope->variables.end())
return scope->variables[name];
// Only consult a scope's own keywords when it's a real custom
// tag invocation (isCustomTagBoundary - see __tag.cpp/Tag.h),
// not a control-flow construct like <if>/<while>/<until> that
// also binds local=this for ITS OWN internal value1/value2/
// type comparison keywords. Those are never meant to be
// visible to #[...] reads from nested content - they collide
// with real, unrelated attribute names on the ENCLOSING custom
// tag constantly (barant.tag's own <field> declares its own
// "type" keyword - the input's type="text" - and its
// definition immediately nests
// <if value1="#[type]" value2="multiline" type="ne">, whose
// OWN "type" keyword is the comparison operator "ne" - #[type]
// read from further inside that <if> must reach field's "type"
// two scopes up, not the <if>'s own "ne" one scope up).
// Confirmed via real rendered output: without this,
// <input type="#[type]"> rendered type="eq" (the nearest <if>'s
// own comparison type) instead of type="text" (the field's).
if(scope->isCustomTagBoundary) {
// Attribute names are stored lowercase (see the main
// constructor's attribute-parsing loop); the #[name]
// designator itself stays case-sensitive as written, only
// the keywords-map lookup key is lowered to match that
// storage.
coreutils::MString lname = coreutils::MString(name).toLower();
if((scope->keywords.find(lname) != scope->keywords.end()) &&
(resolvingKeywords.count(std::pair<Tag*, coreutils::MString>(scope, lname)) == 0))
return scope->resolveKeyword(lname);
}
}
// jet-1.4 fallback: a bare #[name] that was never passed as an
// attribute anywhere in the enclosing scope chain and never
// locally <set> reads as an empty string, not a hard error - real
// 1.4 content depends on this throughout (e.g. SESSIONCTL.tag's
// <page> definition checks #[secure]/#[admin]/#[loggedin]
// unconditionally, but most real .page files - including
// login.page's own <page template="mainpagetemplate">, no other
// attributes - never pass them at all).
coreutils::MString empty("");
return processModifier(empty, modifier);
}
throw coreutils::Exception("Expecting a variable initializer ('$[' or '#[').");
}
void Tag::renderVariableName(coreutils::ZString &variable, coreutils::MString &name, coreutils::MString &modifier) {
// Consumes everything between '[' (already eaten by the caller) and the
// matching ']' as the variable name, stopping early only for the
// genuinely structural bits: the ';' modifier separator and a nested
// $[...]/#[...] substitution. Real-world CGI field names are not
// restricted to identifier characters (an HTML form field can be named
// "first name", "cost$", etc.) - excluding only the structural
// characters (rather than whitelisting an identifier charset and
// throwing on anything else) means the full bracket contents are
// always consumed before a lookup happens, matching how a caller
// actually writing $[:field name] expects it to behave.
while(!variable.ifNext("]")) {
name << variable.getTokenExclude("];$#");
if(variable.ifNext(";")) {
renderVariableName(variable, modifier, modifier);
return;
} else if(variable.startsWith("$[") || variable.startsWith("#[")) {
name << getVariable(variable);
} else if(variable.ifNext("]")) {
return;
} else if(variable.eod()) {
throw coreutils::Exception("unterminated variable reference - missing ']'.");
} else {
// A literal '$' or '#' that isn't the start of a nested
// substitution (getTokenExclude stopped on it defensively, since
// it can't look ahead past a single character) - keep it as
// ordinary name text and continue.
name << variable.nextChar();
}
}
return;
}
void Tag::assignVariable(coreutils::ZString variable, coreutils::MString value, coreutils::ZString scope) {
if(variable.startsWith("@")) {
// NOT sessionName.ifNext("@") - that only advances sessionName's
// own read cursor past the "@", it doesn't produce a string whose
// OWN logical start is there. JString::locate() (used internally
// by JFile's operator[] to find an EXISTING key to replace, not
// just append a new one) resets whatever ZString it's given back
// to ITS OWN position 0 partway through searching - for a
// cursor-advanced view over the ORIGINAL "@name" buffer, position
// 0 is still '@', so the search silently looks for "@name" instead
// of "name". That only matters once the session file already has
// real content loaded from a PRIOR request to search through - a
// brand new/empty file has nothing to find either way, so this
// looked fine on a first write and only broke on session vars that
// outlive one request (login state read back on a later page,
// exactly what this mechanism exists for). Confirmed via a real
// corrupted session file: <clearenv>'s own <set name="@#[name]"
// value=""> calls (see SESSIONCTL.tag) never found the existing
// "_login_id" key that a PRIOR request's <setenv> had written, so
// each one appended a brand new "_login_id":"" pair instead of
// replacing it - duplicate keys, with whichever occurrence a given
// JSON reader picks (first or last) an unreliable coin flip, not a
// deliberate "cleared" state. substring(1) - not ifNext(), not
// reset() - is what actually produces an independent copy starting
// AT that position, immune to being reset back past it.
coreutils::MString sessionName = variable.substring(1);
if(global.sessionFile == NULL)
throw coreutils::Exception("session variable assignment requested but no session is active (missing sessiondir keyword, or cgi mode is off).");
(*global.sessionFile)[sessionName] = value;
return;
}
if((scope == "global") || (scope == ""))
global.variables[variable] = value;
else if(scope == "local") {
if(local == NULL)
throw coreutils::Exception("scope=\"local\" requested but no local scope is active.");
// Same reasoning as scope="parent" just below, one scope closer:
// `local` itself isn't necessarily a real custom tag invocation -
// <if>/<while>/<until> also bind local=this. A <set scope="local">
// written inside one of THEIR branches (barant.tag's own <field>
// definition: <if expr="..."><set name="class" value="..."
// scope="local"><else>...</if>) stores onto that transient <if>
// instance, which is destructed the moment </if> closes - so by
// the time <field>'s own #[class] read runs later in the SAME
// definition (outside the <if>), the value is already gone,
// falling to the empty-string fallback. Confirmed via real
// rendered output: class="" instead of class="fieldinput". Walk
// up to the nearest real scope boundary first, same as
// scope="parent"/__tag.cpp/the bare <container> fix.
Tag *localScope = local;
while(localScope->parent && !localScope->isCustomTagBoundary)
localScope = localScope->parent;
localScope->variables[variable] = value;
} else if(scope == "parent") {
if((local == NULL) || (local->parent == NULL))
throw coreutils::Exception("scope=\"parent\" requested but no local scope (or its parent) is active.");
// Walk up from local->parent to the nearest real scope boundary
// (isCustomTagBoundary), the same way __tag.cpp's own tag-
// DEFINITION registration already does - a bare parent hop lands
// on whatever C++ object happens to be the immediate caller in
// the dispatch chain, which for content reached through
// transparent wrapper constructs (<eval>, <include>) is that
// wrapper itself, not the custom tag it's lexically nested
// inside. SESSIONCTL.tag's own <TAG NAME='TEMPLATE'> definition
// depends on this: its
// <EVAL NAME=TEMPLATEDATA SCOPE=PARENT><CONTAINER EVAL="NO"></EVAL>
// is reached via <page>'s own
// <EVAL><INCLUDE FILE="...#[TEMPLATE].temp"></EVAL> - without
// this walk, TEMPLATEDATA landed on the transient __include
// instance's own scope (one hop from TEMPLATE) rather than
// <page>'s (two hops away, past the wrapper), so <page>'s own
// later #[TEMPLATEDATA] read - itself walking the real scope-
// boundary chain via getVariable's own parent-chain fix - never
// found it.
Tag *scope2 = local->parent;
while(scope2->parent && !scope2->isCustomTagBoundary)
scope2 = scope2->parent;
scope2->variables[variable] = value;
}
}
void Tag::storeVariable(coreutils::ZString variable, coreutils::MString value, coreutils::ZString scope) {
assignVariable(variable, value, scope);
}
void Tag::storeVariable(coreutils::ZString variable) {
if(keywordDefined("expr")) {
if(!keywordDefined("scope") || (resolveKeyword("scope").toLower() == "global"))
assignVariable(variable, Operand(keywords["expr"], *this).string, "global");
else if(resolveKeyword("scope").toLower() == "local")
assignVariable(variable, Operand(keywords["expr"], *this).string, "local");
else if(resolveKeyword("scope").toLower() == "parent")
assignVariable(variable, Operand(keywords["expr"], *this).string, "parent");
} else if(hasContainer) {
processContainer(container);
if(evaluate) {
if(!keywordDefined("scope") || (resolveKeyword("scope").toLower() == "global"))
assignVariable(variable, out, "global");
else if(resolveKeyword("scope").toLower() == "local")
assignVariable(variable, out, "local");
else if(resolveKeyword("scope").toLower() == "parent")
assignVariable(variable, out, "parent");
} else {
if(!keywordDefined("scope") || (resolveKeyword("scope").toLower() == "global"))
assignVariable(variable, container, "global");
else if(resolveKeyword("scope").toLower() == "local")
assignVariable(variable, container, "local");
else if(resolveKeyword("scope").toLower() == "parent")
assignVariable(variable, container, "parent");
}
} else {
if(!keywordDefined("scope") || (resolveKeyword("scope").toLower() == "global"))
assignVariable(variable, resolveKeyword("value"), "global");
else if(resolveKeyword("scope").toLower() == "local")
assignVariable(variable, resolveKeyword("value"), "local");
else if(resolveKeyword("scope").toLower() == "parent")
assignVariable(variable, resolveKeyword("value"), "parent");
}
}
coreutils::MString Tag::processModifier(coreutils::MString &value, coreutils::MString &modifier) {
if(modifier == "")
return value;
if(modifier == "tobinary")
return value.toBinary();
else if(modifier == "frombinary")
return value.fromBinary();
else if(modifier == "tohex")
return value.toHex();
else if(modifier == "fromhex")
return value.fromHex();
else if(modifier == "tobase64")
return value.toBase64();
else if(modifier == "frombase64")
return value.fromBase64();
else if(modifier == "toupper")
return value.toUpper();
else if(modifier == "tolower")
return value.toLower();
else if(modifier == "tocgi")
return value.toCGI();
else if(modifier == "fromcgi")
return value.fromCGI();
throw coreutils::Exception("modifier not valid.");
}
}