Compare commits

...
84 Commits
Author SHA1 Message Date
github-actions[bot] 9ab41c8003 Bump versions for v9.97 2026-07-17 01:42:35 +00:00
Lauri Ojansivu b2284f577e Updated ChangeLog. 2026-07-17 04:41:13 +03:00
Lauri Ojansivu 15adf1bb2d Fix #1289: deleting a user no longer leaves ghost users behind.
Every deletion path (admin removeUser method, self-service account
delete, DELETE /api/users/:userId) removed only the users document,
leaving dangling references everywhere: empty-avatar board members that
could not be removed, stale card members/assignees/watchers, orphaned
avatar files - reproducible for 8 years and reopened in 2025. A
server-only Users.after.remove collection hook now prunes
boards.members/watchers (object-shaped, $pull by userId),
cards.members/assignees/watchers and lists.watchers (string arrays), and
the user's Avatars files, on EVERY path that removes a user; a cleanup
failure can never break the deletion itself. Activities and comments are
deliberately preserved for history - their rendering is already
null-guarded (270eacb20, Playwright-verified).

Tests: tests/userDeletionCleanup.test.cjs (6, positive and negative,
end-to-end against a fake database).

Thanks to chotaire and xet7.
2026-07-17 03:53:09 +03:00
Lauri Ojansivu 17161a8355 Fix #2877: swimlanes no longer jump when starting/ending a card drag.
Drag start hid every list's "+ Add Card" composer link with
display: none, collapsing its row: lists shrank, auto-height swimlanes
shrank, and every swimlane below jumped up about one row (and back down
on drop), moving the drop target under the cursor mid-drag. The root
cause was proven by frame-diffing the issue's own GIF: the three largest
frame discontinuities are exactly drag start and drop, showing the
composer row vanish and the next swimlane header shift ~23px. The
composer now hides with visibility: hidden, preserving its layout box;
checked multi-selection cards keep display: none intentionally (the drag
payload previews the post-drop list).

Tests: tests/swimlaneDragJump.test.cjs (8, positive and negative,
including a guard that flags any return of the layout-collapsing rule).

Thanks to gerroon and xet7.
2026-07-17 03:44:38 +03:00
Lauri Ojansivu 2c23273c11 Fix #443: auto-scroll the board while dragging a card to an
off-screen list.

The horizontal auto-scroll in the card sortable targeted .board-canvas,
which stopped overflowing horizontally when the swimlane layout made the
.js-lists lane the horizontal scroller - scrollLeftMax was always 0, the
guard compared 0 < 0 and never fired, and ui.helper[0].offsetLeft -= 15
assigned a read-only property. Edge-proximity auto-scroll now drives the
lane actually under the pointer (axis-agnostic, clamped, overshoot-safe
helpers in imports/lib/boardAutoScroll.js), with vertical scrolling kept
on the board canvas.

Tests: tests/boardAutoScroll.test.cjs (15, positive and negative,
including a reproduction that the old no-overflow target can never
scroll).

Closes #603: obsolete - the stale-drop-target cause was removed by
d887e553c (perfect-scrollbar removal, native list scrolling),
ed8471be9 (sortable auto-scroll re-enabled) and jQuery UI 1.14.2, whose
sortable resolves insertion neighbours with live offsets on every
mousemove, so a scrolled target list cannot desynchronize drop targets.

Thanks to anhenghuang, AlexanderS and xet7.
2026-07-17 03:41:20 +03:00
Lauri Ojansivu 25d33cec36 Fix #2345 #2674 #574: rules card title filter, rules REST API, api docs;
Sandstorm username races.

- #2345: the Card Title Filter is now SAVED by every board trigger
  builder (a trigger doc missing the field could never satisfy the
  matcher's $in - those rules fired for nothing), SHOWN in the rule
  details, and ENFORCED for archive/restore triggers by resolving the
  title from the card when the activity lacks it; legacy field-less
  triggers keep matching; the filter popup prefills its current value.
- #2674: rules created via POST/PUT /api/boards/:boardId/rules never
  fired - missing matching fields are now normalized to '*' wildcards
  and trigger/action types validated; the addMember/removeMember rule
  actions no longer crash on unresolvable usernames or member-less
  cards and their writes are awaited. New docs/API/Rules.md (endpoints,
  matching fields, wildcard semantics, the exact two-rule
  add-on-move-to/remove-on-move-from workflow), linked from REST-API.md;
  api.py help now lists the rule commands with the same example.
- #574: Sandstorm unique-username generation probes case-insensitively
  (anchored, regex-escaped) and retries the next number when a
  concurrent insert wins the unique-index race, instead of aborting the
  login hook with E11000.

Tests: tests/rulesCardTitleFilter.test.cjs (12),
tests/rulesApiTriggerNormalize.test.cjs (19),
tests/sandstormUsername.test.cjs (11) - positive and negative cases.

Thanks to InfoSec812, sfahrenholz, mitar and xet7.
2026-07-17 03:36:50 +03:00
Lauri Ojansivu 0f2179988b Fix #619: invitee username collisions no longer fail with a raw 403.
Inviting by email derives the new user's username from the email local
part; a collision with an existing user (cats@foo.com then
cats@facebook.com) made Accounts.createUser throw Meteor's raw
"403 Username already exists", shown to the inviter as just "403". The
username now probes cats, cats1, cats2, ... to the first free variant
(bounded), and exhaustion raises the translated error-username-taken.

Tests: tests/inviteeUsername.test.cjs (11, positive and negative,
including the literal reported scenario).

Closes #804: already fixed - every popup is viewport-clamped with
internal scrolling since ac368de06 (#5667 geometry rewrite: maxHeight
from live viewport space, bounded flex layout) plus the 04eb8a8fb
(#6221) global 90vh clamp; the member picker inherits the shell, so
neither standalone nor the Sandstorm iframe can grow past the viewport.

Thanks to lemoer, ocdtrekkie and xet7.
2026-07-17 03:36:07 +03:00
Lauri Ojansivu d5937f6d38 Fix #1502: date pickers honor the configured default time.
The due-date picker configures defaultTime 17:00 (received/start/end use
now()), but an inverted guard in datePickerRendered applied it only when
the card ALREADY had a date - the one case where it is unnecessary - so
for dateless cards the time input stayed empty and submit stored a
hard-coded 12:00. Empty pickers now pre-fill with the configured
default, submit falls back to it, and existing dates keep their own
time. The 2018 AM/PM display/parse mismatch was already fixed by the
native HTML date/time inputs (79b94824e); week start already honors the
user preference.

Tests: tests/datePickerDefaultTime.test.cjs (10, positive and negative).

Thanks to Vlasterx, saschafoerster, suncobran and xet7.
2026-07-17 03:34:52 +03:00
Lauri Ojansivu 7c0ae509ac Fix #2769 #1992 #2292 #2494 #1853 #1554 #2306 #1437.
- #2769: refresh drag geometry when the DOM changes mid-drag - cards no
  longer drop into the wrong swimlane while someone adds a card.
- #1992: board import restores all five card date fields (and creator)
  with fallbacks; receivedAt/endAt were never imported at all.
- #2292: archiving a swimlane archives its cards (mirroring lists);
  restore brings back exactly the cards archived with it.
- #2494: client noCache card lookup returned a Promise since the
  Meteor 3 port - multi-select board moves wrote sort: NaN everywhere.
- #1853: subtask "View it" falls back to the subtask's boardId when the
  deposit board is not loaded, instead of silently doing nothing.
- #1554: restore the reactive dependency lost in 7673c77c5 so cards
  added after board render accept sidebar label/member drops.
- #2306: "filter to selection" and every bulk action are board-scoped;
  foreign-board cards can no longer be silently archived.
- #1437: new POST /users/logout API endpoint revokes the presented
  resume token, or all tokens with {"all": true}.

All with positive+negative regression tests (see tests/*.test.cjs).

Closes #1389: already fixed - the standalone pencil edit button
(0cc63b810) plus the wrapped viewer (bf2b3b40c) guarantee an edit target
even when a full-width link fills the description.

Thanks to hever, Cactusbone, Vermeille, Vanclief, Miffe, IcedQuinn,
ppouliot, GhassenRjab and xet7.
2026-07-17 03:34:23 +03:00
Lauri Ojansivu 42b4e51f85 Fix #2418: one inlined edit form at a time; no cross-item overwrite.
Since 8c3ce4bb7 (2021) the "close the previous inlined form" call was a
silent no-op: the inlinedForm escape action registers with
enabledOnClick: false and EscapeActions.clickExecute skips such actions,
so clicking another checklist item left both edit forms open - and the
submit handlers find the template's FIRST textarea, so the wrong form's
text was saved over the submitted item. Subtasks reproduced the full
bug; the checklists workaround corrupted the shared open-form tracker so
Escape fell through and closed the whole card details pane. A pure state
manager (client/lib/inlinedFormManager.js) now enforces the single-open
invariant: opening a form closes the tracked previous one (popups
untouched, preserving the 2021 intent); close/destroy only reset the
tracker for the form they own.

Tests: tests/inlinedFormSingleOpen.test.cjs (9, positive and negative,
including the exact reported A->B->C repro).

Thanks to Beebo89 and xet7.
2026-07-17 03:30:07 +03:00
Lauri Ojansivu 66a19c4bd4 Fix #2989: Advanced Filter matches date custom fields.
Two defects: the tokenizer flipped into regex mode on every '/' even
inside quoted strings, so a quoted date like '06/04/2020' broke
tokenizing and the whole filter silently no-opped; and date custom
fields store Date objects while the comparison selectors used strings
and parseInt - equality and ranges could never match, != matched every
card. Dates now parse per the user's date format (day-first formats
respected) into half-open Date-range selectors; non-date fields keep the
legacy selectors unchanged.

Tests: tests/advancedFilterDate.test.cjs (14, positive and negative).

Closes #2521: already fixed since v3.88 (9819c9f80) - the checklist
completed/uncompleted activity text was missing due to an activityType
name mismatch between model and template; the current unified activity
template, i18n keys and helpers render it correctly.

Thanks to k1ng440, ott29 and xet7.
2026-07-17 03:27:33 +03:00
Lauri Ojansivu 5e036dc544 Fix #3826: card drag reorder in lists full of subtask cards.
addSubtaskCard inserted every subtask card with the constant sort -1,
leaving the whole list tied: a drop between two equal sorts computes a
zero increment, the move modifier is empty and Card.move() silently
discards it - the card snapped back, and a multi-selection drop wrote
the SAME sort to every selected card, permanently destroying their
relative order (the data-loss risk in the issue triage). Subtask cards
now append with a unique sort (max+1), and the sortable stop handler
detects degenerate gaps (ties/inversions) and repairs the siblings'
sorts to a strictly increasing order before recomputing the drop index;
healthy lists take the unchanged fast path.

Tests: tests/subtaskCardReorder.test.cjs (14, positive and negative,
including the exact issue scenario and a guard that the old
{base:-1, increment:0} result can never be produced again).

Thanks to jayki and xet7.
2026-07-17 03:21:28 +03:00
Lauri Ojansivu 973c2ad901 Fix #3453 #3199; linked-card custom field crash; pin #3843.
- #3453: publish the FULL subtask ancestor chain, not only direct
  parents - the cross-board full-path label vanished after refresh.
- #3748 (defect half): skip unresolvable custom-field definitions on
  linked cards - phantom empty rows and a template TypeError on every
  card details render. The mirroring itself is by design: linked cards
  are pointers; label/custom-field ids are board-scoped; name-based
  inheritance is the copy feature, not the link feature.
- #3199: group each archived card with its own Restore/Delete links and
  add a clear separator below the group (RTL-safe, theme-neutral).
- #3843: comment-editor uploads and the attachments popup now share one
  null-safe meta builder, and tests pin that comment attachments list in
  the card's Attachments section.

Closes #3748: mirroring is by design (see above); the only actionable
defect is fixed in this commit.
Closes #3378: already fixed - notification_cleanup moved off SyncedCron
to a guarded Meteor.setInterval singleton, and quave:synced-cron 2.4.0
handles the E11000 history collision that percolate 1.5.x missed.
Closes #3276: already fixed by d3625db75 - the spent-time badge helpers
now read the live Cards document reactively, so the overtime color flips
immediately; verified behaviorally against the real component.
Closes #3843: behavior verified present and now regression-locked.

Thanks to MPeti1, peterbecich, fxkr, jghaanstra and xet7.
2026-07-17 03:21:02 +03:00
Lauri Ojansivu dd3f71c951 Fix #4822: maximized card position in Swimlanes view.
The maximized card pane had no position of its own, so it remained an
in-flow item inside the scrolled board canvas and rendered off-screen
after scrolling down; desktop-mode floating-window rules also overrode
every maximize geometry rule, and inline drag offsets survived
maximizing. The pane is now viewport-fixed with insets that win over
both (drag position restores on minimize), RTL-safe. Regression test
with a CSS cascade resolver that fails on the pre-fix stylesheet:
tests/maximizedCardPosition.test.cjs.

Closes #3566: mobile shows one list at a time by design (xet7's own
comments in the issue); Move Card popup is the supported flow, and the
2021-era touch drag glitches were since fixed with drag handles.
Closes #3252: already fixed - comment deletes are guarded in
client/components/activities/comments.js (tagged #3252), checklists in
checklists.js, attachments via #5282.
Closes #3542: no code bug - redirect_uri is the same expression on the
client and server (mismatches come from ROOT_URL/proxy configuration,
per the Bug:Environment-specific label), and the login-style half was
fixed via #5695.

Thanks to pravdomil, 1ubuntuuser, gastoncollaud and xet7.
2026-07-17 03:15:52 +03:00
Lauri Ojansivu 6b9086d2a8 Changelog for #4036 #4043 #4023 #4593; finish #4043 hardening.
- CHANGELOG.md: Upcoming entries for the LDAP group filter fix (#4036),
  invitation code regeneration (#4043), CJK add-card footer wrapping
  (#4023) and team-to-board member sync (#4593), whose code shipped in
  the previous commit.
- server/models/users.js: do not delete the invitation code in
  onCreateUser before the account insert is committed - a failed insert
  (duplicate username/email) burned the code for every retry (#4043).
  Consumption happens after a successful insert; re-invites regenerate
  stale codes.
- tests/teamBoardMemberSync.test.cjs: the #4593 regression tests (13,
  positive and negative) for the team board-member sync helpers.

Thanks to zeisss-mercedes, jkoenig134, yuki-snow1823, Sylvain2703,
szymonsztuka and xet7.
2026-07-17 03:12:43 +03:00
Lauri Ojansivu 9ddbc777dd Startup schema upgrade, self-healing attachments, migration speed; fix
#5695 #4897 #4654 #5174 #4825 #5659 #4730 #4419 #4158 #4560 #4036
#1959 #1971.

- Startup schema upgrade (server/lib/schemaUpgradeSteps.js): on start,
  check that data from EVERY old WeKan version is migrated to the newest
  structure and migrate only what is missing - all platforms, MongoDB and
  FerretDB. Version-gated (marker stores WeKan version + datetime of the
  last re-check; one findOne per boot until a new release), non-blocking,
  live dashboard at /schema-upgrade-status showing the product name, fast
  on big databases (distinct() set-joins, updateMany batches). Steps:
  archived-flag backfill, swimlane structure + visibility rescue
  (#1959 #1971: cards under deleted/archived/foreign swimlanes reassigned
  to a visible swimlane; card-insert hook validates supplied swimlaneIds),
  merge-per-swimlane-lists (v7.98/v8.0x list copies merged back into
  shared lists: no duplicate columns in Lists view, everything visible in
  Swimlanes view, cards keep their swimlane), embedded checklist items,
  customFields boardIds, allows* backfills, members isActive, permission
  lowercase, filesystem path healing.
- Migration speed (5-hour reports): insertMany batches in the text phase,
  preloaded target-record maps in the file phases.
- Snap attachment-repair + FILES_ONLY importer mode (see prior commit
  wiring) extended with CFS FileSystem-store coverage
  (ATTACHMENTS_STORE_PATH era), missing-binary reporting, and
  migrate-gridfs-to-fs.mjs bucket fixes.
- OAuth2/OIDC: OAUTH2_LOGIN_STYLE=redirect honored (#5695); concurrent
  logins no longer contaminate each other's user data (#4897); account
  merge no longer wipes avatars/templates (#4560).
- LDAP: background sync fixed (#4654), password login rejected after LDAP
  migration (#4419), LDAP_ENCRYPTION=true actually encrypts (#4158),
  group filter accepts multiple groups and admits admin-sync groups
  (#4036).
- All Boards tiles: per-list card counts + member avatars restored
  non-reactively (#5174 #4825). Uniform default list widths (#5659).
  Declined invitations no longer resurrect membership (#4730).
- Tests with negative cases for every fix (tests/*.test.cjs; suite green
  except the pre-existing environment-only htmljs failure).

Closes #5600: OAUTH2_CA_CERT already works - the fetch migration
(49a272d6c) applies the CA to all OIDC calls via https.Agent.
Closes #3828: board members seeing all board cards is by design (no
per-card visibility model), and organizations/teams now exist.

Thanks to mueschel, ArturRuta, gerardo-junior, fabianrbz, Miuler,
butteredCat-2021, Griiimm, preciousamorc, farwayer, LeoLu-eng, hnb1,
rangersdo and xet7.
2026-07-17 03:07:59 +03:00
Lauri Ojansivu 65bf215cbe Fix #6473: attachments missing after the MongoDB -> FerretDB migration.
- Migration importers: resolve the CollectionFS GridFS id from
  copies.<bucket>.key too (the REAL old-WeKan layout; only
  original.gridFsFileId / gridFsFileId / copies.gridfs.key were tried,
  none of which exist there) via a shared resolveCfsGridFsId() in
  releases/migrate-mongodb-to-ferretdb.mjs,
  snap-src/bin/migrate-mongo3-to-ferretdb.mjs and
  snap-src/bin/migrate-gridfs-to-fs.mjs. The modern importer now drives
  CollectionFS extraction from cfs_gridfs.<bucket>.files itself, so a
  missing/empty cfs.<bucket>.filerecord no longer silently skips every
  file; binaries without a filerecord are still extracted to disk, and
  filerecords whose binary cannot be located are reported on the
  dashboard instead of dropped.
- Meteor-Files phase: match versions.*.meta.gridFsFileId without a
  storage flag (WeKan's own getFileStrategy rule), handle every version
  (not just 'original'), and add a bucket-driven sweep of <bucket>.files
  by metadata.fileId so binaries are recovered even when the record's
  flags say nothing about GridFS. GridFS-flagged versions with no
  locatable binary are reported.
- mongo3 importer: copy the CollectionFS top-level boardId/cardId/
  listId/swimlaneId/userId into meta on the created records - an
  attachment without meta.cardId shows on no card.
- Admin Panel > Attachments: the Filesystem Storage paths were computed
  from process.env.WRITABLE_PATH IN THE BROWSER, so they always showed
  "/data". New admin-only getAttachmentStoragePaths method returns the
  real Snap-aware paths (shared models/lib/attachmentStoragePath.js),
  also used for the settings document default (was /data/attachments,
  actual Docker path is /data/files/attachments).
- Snap: `snap run wekan.database ferretdb` now says it does NOT migrate
  data, says when nothing was switched, and points at
  `snap run wekan.migrate` for re-running the full migration.
- Tests with negative cases: tests/migrationAttachmentExtraction.test.cjs
  (behavioral resolveCfsGridFsId from all three importers + wiring
  guards) and tests/attachmentStoragePath.test.cjs, wired into
  test:unit:node.
- Companion fix in wekan/FerretDB: accept documents with literal dotted
  field names like MongoDB 3.6+, so migrated documents containing them
  are no longer silently dropped.
- CHANGELOG.md: new Upcoming section with these changes.

If attachments are already missing after an earlier migration, run
`snap run wekan.migrate` - the source MongoDB data was never modified,
and the fixed importers re-create the attachment records and files.

Thanks to mueschel and xet7.
2026-07-17 01:43:53 +03:00
github-actions[bot] e4e73e8b80 Bump versions for v9.96 2026-07-16 17:40:41 +00:00
Lauri Ojansivu c83284811c Updated ChangeLog. 2026-07-16 20:39:07 +03:00
Lauri Ojansivu 643a296595 Fix #6465 follow-ups found by test run 2026-07-16_19-21-02.
The right-docked card details window exposed two real issues in the
Playwright run (03-cards-operations failing in all three browsers):

- Archiving or deleting a card left its id in the openCards session
  list, so the floating details window kept rendering above the board —
  and, docked to the right edge, exactly over the archives sidebar,
  intercepting its Restore/Delete clicks. Both handlers now drop the
  card from openCards and clear currentCard.
- An OPEN board sidebar now stacks above the card window (z-index 2002
  vs 2001), so the sidebar is always usable while a card is open.

Also from the same run: the new one-click cog spec closed its popup with
a keyboard Escape that proved unreliable across engines — it now uses
the popup's own X button (.js-close-pop-over) like 19-accessibility
does. The chromium-only 33-board-domains failure is an unrelated
token-login race in the auth helper (userId mismatch), not caused by
these changes.

tests/uiDensity.test.cjs got guards for both follow-ups (openCards
cleanup in archive+delete, sidebar z-index above the card window).
Updated ChangeLog.

Thanks to xet7.
2026-07-16 20:01:10 +03:00
Lauri Ojansivu 2d76e1cb92 Behavioral tests for the ferretdb-has-data guard.
tests/ferretdbHasData.test.cjs runs the real snap-src/bin/ferretdb-has-data
against crafted directories. This guard gates two critical switches
(migration-control's finish_success and mongodb-control's #6458/#6466
failure handler), so its semantics must never drift. Positive: non-empty
.sqlite, no -wal sidecar required (clean shutdown checkpoints it away),
one good file among empties. Negative: 0-byte .sqlite from a failed
migration, empty/missing directories, -wal/-shm-only leftovers, and a
DIRECTORY named *.sqlite. All eight behaviors verified against the
actual script. Wired into test:unit:node; ChangeLog updated.

Thanks to xet7.
2026-07-16 19:12:59 +03:00
Lauri Ojansivu 4fc918c245 Playwright: fix strict-mode violation from the #6465 header cog; test it.
The 2026-07-16_18-33-28 test run failed one spec in all three browsers:
the #6465 one-click board-settings cog added a second .js-open-board-menu
element, so 03-cards-operations' bare class locator resolved to 2
elements and tripped Playwright's strict mode. The archives test now
scopes the click to the sidebar's instance (.board-sidebar
.js-open-board-menu), keeping its 'from inside the sidebar' intent.

Also added a spec for the new cog itself to 15-board-actions: visible in
#header-main-bar, popup not open before the click (negative), ONE click
opens the real boardMenu popup (.js-open-archives inside), Escape closes
it again.

Thanks to xet7.
2026-07-16 19:09:36 +03:00
Lauri Ojansivu d7ca7360ff Tests for the cpu-exec delivery pipeline; changelog upcoming updates.
tests/cpuExecWiring.test.cjs, with negative cases: every Linux bundle in
release-all.yml embeds cpu-exec + its own arch's static qemu-user (arm64
and the QEMU-built extra arches replace the inherited amd64 one, extra
arches tolerantly), the Windows/macOS bundles strip both Linux-only
files, qemu-user-static is installed in every bundle-building job and
both sandstorm jobs, the Sandstorm .spk ships cpu-exec + qemu via
build-deps.sh (tolerant when qemu is not installed), the Docker
entrypoint and the bundle launcher route ferretdb/node through cpu-exec
while keeping direct-exec fallbacks for bundles that lack it, and the
snap ships cpu-exec via the snap-src helpers part. Wired into
test:unit:node; complements tests/cpuExec.test.cjs (the script's own
behavior).

ChangeLog Upcoming: the regression-tests entry now lists the cpu-exec
wiring test, the subtasks default-board test (#6456) and the FerretDB
fork's integration-test fixes.

Thanks to xet7.
2026-07-16 18:54:28 +03:00
Lauri Ojansivu fcce2e1cea Subtasks: fix addSubtaskCard crash on Meteor 3 server.
Fixes #6456.

The lazily-creating getters for the default subtasks helper board and
its landing list still used the sync Boards.insert / Swimlanes.insert /
Lists.insert / Boards.update APIs that Meteor 3 removed from the server,
so creating a subtask crashed with 'insert is not available on the
server. Please use insertAsync() instead' whenever the ^Board^ helper
board had to be created. The list creator additionally read
getDefaultSwimline()._id, which is a Promise on the Meteor 3 server.

- getDefaultSubtasksBoardId / getDefaultSubtasksListId are now PURE
  getters (no creation), matching the #3868/#2256 rule that only the
  server may create these.
- The server-side lazy creation moved into getDefaultSubtasksBoardAsync
  and getDefaultSubtasksListAsync using insertAsync/updateAsync and
  getDefaultSwimlineAsync — the exact path addSubtaskCard uses.
- The never-called date-settings twins had the same sync calls and no
  server-only guard at all; they are pure getters now too.
- tests/subtasksDefaultBoard.test.cjs guards the async creators and that
  no sync collection writes come back to models/boards.js, wired into
  test:unit:node.
- Updated ChangeLog.

Thanks to sjohnen and xet7.
2026-07-16 18:46:09 +03:00
Lauri Ojansivu a91203b158 Close the issues fixed by ed19445d3 and 794346e39.
That commit's message listed all ten issues after a single Fix keyword,
but GitHub only auto-closes a reference that directly follows its own
closing keyword, so only the first issue was closed on push. Closing
the rest here; the fixes themselves are already on main.

Fixes #6455. Fixes #6458. Fixes #6466. Fixes #6467. Fixes #6468.
Fixes #6472. Fixes #6465. Fixes #5547. Fixes #5282.

Thanks to xet7.
2026-07-16 17:55:44 +03:00
Lauri Ojansivu 794346e396 cpu-exec qemu-user fallback everywhere; tests for all newest fixes.
Fix #6458 completely: the reporter's host runs inside a hypervisor that
masks AVX, and the old per-tool AVX wrappers (amd64-only, PATH-based)
were bypassed by absolute-path mongod invocations.

- New general snap-src/bin/cpu-exec: runs any binary directly when the
  CPU has the features it declares (--features x86_64=avx,aarch64=atomics
  or WEKAN_REQUIRED_CPU_FEATURES) and through same-arch qemu-user when
  not; plain zero-overhead exec with no declared features. Lookup order:
  WEKAN_QEMU_USER, qemu-<arch> next to the script (bundle/Docker),
  $SNAP/qemu-<arch>, the snap's migratemongo/avx one, then system
  qemu-user(-static). Clear error + direct run when no qemu exists, so
  the real SIGILL surfaces instead of hiding.
- Snap: mongodb-control and migration-control run every mongod 7 through
  cpu-exec, so MongoDB works without AVX (slower) and migration can READ
  modern MongoDB data on such CPUs; completed-FerretDB switch and
  migration fallbacks unchanged (switch_to_completed_ferretdb extracted).
- release-all.yml: every Linux bundle .zip ships cpu-exec + this-arch's
  static qemu-user (amd64/arm64/ppc64le/s390x/riscv64; stripped from
  win64/mac bundles), flowing into Docker and Snap automatically;
  Sandstorm .spk gets both via build-deps.sh. Bundle launcher and Docker
  entrypoint route node/ferretdb through cpu-exec.
- Docs: mongodb-avx-qemu.md and mongodb-raspi4-qemu.md document the
  built-in mechanism.

Tests, with negative cases, for the newest features and fixes at
changelog: htmljs array-vs-attributes (#6459), description draft
normalize/reset (#6455), comment draft lifecycle (#5547), attachment
delete guard (#5282), rules move actions + import normalization (#6472),
snap mongod-failure/migration recovery (#6458 #6466), FerretDB polling
defaults (#6467 #6468), UI density guards for every #6465 fix, and a
behavioral cpu-exec test against fake cpuinfo + fake qemu. All wired
into test:unit:node. Go table tests for the FerretDB SQLite filter
pushdown are in the wekan/FerretDB repo.

Updated ChangeLog.

Thanks to xet7.
2026-07-16 17:40:24 +03:00
Lauri Ojansivu ed19445d30 Fix #6459 #6455 #6458 #6466 #6467 #6468 #6472 #6465 #5547 #5282.
- #6459: card More menu rendered empty (no Delete): the vendored jade
  compiler's htmljs patch made isConstructedObject(Array) false, so
  'label {{_ ...}}:' lines got their content array mis-assigned as tag
  attributes and Blaze threw 'foreign objects in attributes' killing the
  whole cardMorePopup. Also fixed the list More link input (nonexistent
  rootUrl helper -> absoluteUrl).
- #6455: saving a card description never removed a pre-existing unsaved-
  edits record, and the draft/description comparison mismatched on Markdown
  hard-breaks and empty descriptions, re-creating a phantom draft on every
  save. Save now clears the draft; both sides normalized the same way.
- #5547: comment drafts: the draft-saving escape handler had been disarmed
  since 2019 (flag with no setter), so a comment being written was lost
  when the card closed. Drafts are now saved continuously (debounced),
  flushed on teardown, cleared on submit; text no longer visually vanishes
  on outside clicks.
- #5282: attachment delete: guard against the doc being already evicted
  from Minimongo ('Removed nonexistent document'), like the existing
  comment/checklist guards.
- #6472: rules move card to top/bottom: fall back to the card's current
  list when listName does not resolve (was a swallowed TypeError = rule
  silently did nothing); wizard stored listTitle which the engine never
  reads (listName); empty destination wrote sort +-Infinity; rules JSON/CSV
  import now uses the rules.createRule method instead of client inserts
  rejected into minimongo limbo, and defaults missing trigger matching
  fields to '*'; empty boardId no longer overrides the real board; the
  server-side orphaned-cards fallback in List.cards()/cardsUnfiltered()
  now actually resolves its async swimlane lookup.
- #6465: desktop density back to WeKan 6.09: base font 14px and headings
  22/18/16px (vw clamps resolved to 18/24px on desktop), All Boards
  wrapper padding 10px/15px, card details docks to the right edge instead
  of floating on top of its own card (still draggable), 20px canvas
  padding instead of ~48px white borders, removed the force-all-card-text-
  to-title-size rule, admin org/team table Select/Unselect-all header
  links are compact icons and header cells may wrap, zoom pill no longer
  cut off, one-click board settings cog in the board header.
- #6458 #6466: snap: mongodb-control now checks mongod's exit status and
  does an AVX pre-flight (MongoDB 5+ needs AVX; without it mongod SIGILLs)
  instead of pinging a dead port forever behind a 502: it switches to a
  completed FerretDB migration, or (re)runs the migration (AVX-free) with
  a 3-attempt guard. Migration importers no longer fail the whole run on
  >=10 per-item errors ('Avatars Errors' etc.), and a failed 3.x-source
  migration keeps the copied FerretDB data + checkpoint and resumes next
  start instead of deleting it and 'falling back' to a mongod 7 that
  cannot open 3.x data files.
- #6467 #6468: with FerretDB, calm Meteor's no-oplog polling storm
  (METEOR_POLLING_THROTTLE_MS=2000, METEOR_POLLING_INTERVAL_MS=30000
  defaults in the snap and bundle launcher; overridable). The FerretDB
  fork gets filter pushdown, a sane pool size and less locking in its own
  repo.
- Updated ChangeLog.

Thanks to xet7.
2026-07-16 17:08:31 +03:00
Lauri Ojansivu 1193f3a4b5 LDAP: cleaner server-context org/team sync call, fix indentation.
Follow-up to PRs #6469 and #6470:

- The login-time org/team sync now clears the inherited method invocation
  context (DDP._CurrentMethodInvocation.withValue) around a normal
  Meteor.callAsync, instead of invoking the raw method handler with a
  hand-made invocation object. This goes through Meteor's normal method
  dispatch (check() argument audits, EJSON argument cloning) while still
  being the server-to-server path (connection null) that the admin guard
  in setUserOrgsTeamsFromLdap allows.
- Added the ddp package dependency to wekan-ldap for the DDP symbol.
- Fixed indentation in localizeAvatarFromBuffer and restored the comment
  explaining the proceedAfterUpload argument.
- Removed a stray double blank line in the LDAP login handler.
- Updated ChangeLog about the merged LDAP fixes.

Thanks to xet7.
2026-07-16 15:47:52 +03:00
Lauri Ojansivu 98ba5fcc9d Merge pull request #6470 from ChristianMa97/feature-ldap-hardening-and-wildcard-group-filter
LDAP: harden org/team sync during login and add wildcard group allowlists
2026-07-16 15:39:54 +03:00
Lauri Ojansivu b735f23045 Merge pull request #6469 from ChristianMa97/bugfix-ldap-double-escaping
Fix LDAP group filters by removing redundant backslash escaping
2026-07-16 15:38:42 +03:00
Lauri Ojansivu 7491c37feb release-all.yml: also build the Sandstorm .spk and attach it to the release.
Added a build-sandstorm job that runs after the GitHub Release is created,
with the same steps as the standalone sandstorm.yml workflow (which still
exists for testing the .spk build on its own), attaching
wekan-<version>-sandstorm.spk to the Release. Non-blocking, so the
experimental Sandstorm build never fails or delays the release.

Thanks to xet7.
2026-07-16 13:27:32 +03:00
Lauri Ojansivu 503601515a Updated ChangeLog. 2026-07-16 13:18:59 +03:00
Lauri Ojansivu 10d5006d2e Merge pull request #6462 from wekan/dependabot/npm_and_yarn/websocket-driver-0.7.5
Bump websocket-driver from 0.7.4 to 0.7.5
2026-07-16 13:12:18 +03:00
cmartin 2513c782f7 feat(ldap): implement LDAP group allowlist parsing and filtering with wildcards support 2026-07-16 10:17:13 +02:00
cmartin c1cae29544 fix(ldap): keep login successful when optional sync fails and fix avatar localization write path 2026-07-16 10:16:59 +02:00
cmartin 98dae04c2d Remove redundant backslash escaping in LDAP filter construction 2026-07-16 09:53:37 +02:00
dependabot[bot] 4e15057277 Bump websocket-driver from 0.7.4 to 0.7.5
Bumps [websocket-driver](https://github.com/faye/websocket-driver-node) from 0.7.4 to 0.7.5.
- [Changelog](https://github.com/faye/websocket-driver-node/blob/main/CHANGELOG.md)
- [Commits](https://github.com/faye/websocket-driver-node/compare/0.7.4...0.7.5)

---
updated-dependencies:
- dependency-name: websocket-driver
  dependency-version: 0.7.5
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-07-15 22:09:17 +00:00
github-actions[bot] f602b9459f Bump versions for v9.95 2026-07-15 12:58:19 +00:00
Lauri Ojansivu b3a9b90f22 Updated ChangeLog. 2026-07-15 15:57:04 +03:00
Lauri Ojansivu 14e6851f01 release-all.yml: publish the snap to the stable channel too
Both snap jobs (snap-native and snap-launchpad) pushed only to candidate, beta
and edge, and stable had to be released by hand afterwards. Publish to
stable,candidate,beta,edge instead. base: core24 allows stable and candidate.

Thanks to xet7.
2026-07-15 15:57:04 +03:00
Lauri Ojansivu ab1c636e71 Snap: resume an interrupted MongoDB to FerretDB migration instead of redoing it
A big migration can run for 5 hours, so being interrupted by a snap refresh,
`snap stop` or a reboot is normal - but it was treated as a failure, and every
interruption threw away all of the work.

Distinguish interrupted from failed. snapd's SIGTERM killed the importer, bash
resumed at the line after the importer call, read the signal exit code (143) as
"the migration failed", and fail_and_run_mongodb deleted the partial FerretDB
SQLite and set migrate=off. Now a SIGTERM/SIGINT trap (and an importer exit code
>= 128, since snapd signals every process in the service cgroup) keeps the
partial database and the checkpoint, leaves auto-migration on, and hands back to
mongodb-control so WeKan keeps serving from MongoDB until the next start resumes.
Both importers flush their checkpoint on the signal and exit 128+signo.

Checkpoint files, not just collections. Only fully-copied collections were
checkpointed; the file phase started over. Worse, the destination path was picked
with an "append _1, _2, ... while the file exists" loop, so every already-
extracted attachment was written a second time under a new name, orphaning the
first copy - a resumed migration silently needed twice the disk the up-front
space check budgeted for. Files are now checkpointed individually (recorded only
once the bytes are on disk AND the record points at them, and re-verified by size
on resume, so a half-written file is never mistaken for a finished one) and
skipped when resuming. The path is now deterministic: idHex is the record's _id,
so two records never collide and an existing file there can only be this record's
own partial extraction, which is meant to be overwritten.

Discard the checkpoint together with the SQLite it describes. The checkpoint
lives in $SNAP_COMMON, not in the SQLite dir that discard_partial_ferretdb wipes,
so it survived. The next migration then trusted it, skipped every "already
migrated" collection, copied only the rest into the now-empty database, and
reported success - leaving the snap serving a FerretDB missing most of its data.

The MongoDB 3 importer had no checkpoint at all and now resumes collections and
files the same way. The source MongoDB data is never touched on any of these
paths.

Thanks to markusst1982 and xet7.
2026-07-15 15:57:04 +03:00
Lauri Ojansivu 4e1e661d99 Fix WeKan not working after FerretDB migration: resume login used a positional projection
Meteor's accounts-base "resume" login handler projects a single array element
with the positional operator:

  Meteor.users.findOneAsync(
    { 'services.resume.loginTokens.hashedToken': hashedToken },
    { fields: { 'services.resume.loginTokens.$': 1 } })

FerretDB rejects that find with "Executor error during find command :: caused
by :: positional operator '.$' couldn't find a matching element in the array"
(code 51246).

Resume is how every already-logged-in browser re-authenticates on page load and
on every DDP reconnect, so the throw logged users out, the client retried the
connection, and the retry loop pinned the FerretDB CPU - the board looked broken
right after a migration that had just taken hours.

Replace the handler with one that projects the whole loginTokens array and picks
the matching token in JS. Upstream already does exactly this in its own $or
fallback query ("Cannot use ...loginTokens.$ positional operator with $or
query"), so the array is known to be small enough to fetch, and behaviour is
otherwise unchanged - including looking up the hashed token on its own first so
the unhashed token is not sent to the database unless it has to be.

Closes #6457

Thanks to markusst1982 and xet7.
2026-07-15 15:57:04 +03:00
github-actions[bot] a84a88794f Bump versions for v9.94 2026-07-15 06:09:00 +00:00
Lauri Ojansivu a5d206e23d Updated ChangeLog. 2026-07-15 09:07:36 +03:00
Lauri Ojansivu aadd653b15 CHANGELOG: new Upcoming section above v9.93 with the post-9.93 fixes
9.93 is released, so move the two commits made after it into a fresh
"# Upcoming WeKan ® release" section above v9.93, organized like the previous releases:

  Features: database setting authoritative + snap run wekan.database mongodb|ferretdb +
            no-downtime handling of a failed migration.
  Bugs:     migration skips dotted (GridFS/CollectionFS/system) collections that FerretDB
            rejects, and cleans up a partial SQLite from a failed migration.

No entry text changed; only relocated.
2026-07-15 09:01:37 +03:00
Lauri Ojansivu 7d271413bf Snap: make database setting authoritative + wekan.database command + no-downtime on failure
Problem: the control scripts force-switched to FerretDB whenever a *.sqlite file existed, so
`snap set wekan database=mongodb` did not stick and a failed migration caused downtime with no
way to keep WeKan running on MongoDB while fixing it.

- The `database` snap setting is now AUTHORITATIVE. Removed the "FerretDB SQLite present ->
  force ferretdb / disable mongodb" overrides from wekan-control, ferretdb-control and
  mongodb-control. wekan-control keeps only the safety guard (never start an EMPTY FerretDB
  while MongoDB has data).

- New `snap run wekan.database mongodb|ferretdb` command (bin/wekan-database): switch which
  database WeKan runs on. `mongodb` also pauses auto-migration (migrate=off) so it does not
  switch back; `ferretdb` requires a non-empty SQLite first.

- Auto-migration can be paused: migration-pending now also returns "not pending" when
  `snap get migrate` == off. A migration that FAILS now runs fail_and_run_mongodb: delete the
  partial SQLite, set migrate=off, and exec mongodb-control so WeKan keeps working on MongoDB
  (no downtime, no retry loop). fall_back_to_mongodb likewise sets migrate=off instead of the
  done marker. `snap run wekan.migrate` re-enables migrate and retries.

- finish_success now restarts wekan.wekan so it reconnects to FerretDB after a successful
  migration instead of waiting for the now-stopped MongoDB.

Registered the `database` app in snapcraft.yaml and snapcraft-core26.yaml (also added the
previously-missing migrate/maintenance apps to core26).

Thanks to xet7.
2026-07-15 08:58:36 +03:00
Lauri Ojansivu 73ad55f696 Snap migration: skip dotted collections (FerretDB rejects them) + clean partial SQLite
Two bugs surfaced when the MongoDB 7 -> FerretDB migration finally connected (after the
db-eval fix):

1. FerretDB v1 rejects collection names containing a dot:
     invalid key: "attachments.chunks" (key must not contain '.' sign)
   Both importers tried to copy GridFS internals (attachments.chunks/.files, avatars.*,
   cfs_gridfs.*) and CollectionFS cfs.<bucket>.filerecord collections as TEXT, aborting the
   migration. Now the text phase skips ANY dotted collection: none of WeKan's real data
   collections contain a dot, and the dotted ones are GridFS internals (extracted in the file
   phase), CollectionFS filerecords (now turned into bare attachments/avatars records in the
   file phase via replaceOne upsert:true) or system.* collections.

2. The failed migration had already copied some text collections, leaving a NON-EMPTY but
   incomplete files/db/wekan.sqlite. ferretdb-has-data then saw it as "migrated", so
   mongodb-control disabled MongoDB and the snap tried to serve a half-migrated FerretDB. On
   any failure migration-control now runs discard_partial_ferretdb: stop the temp target
   FerretDB and delete the partial SQLite, so the snap cleanly keeps MongoDB and retries. The
   finish_success switch is also gated on it (`rc -eq 0 && finish_success`).

Source MongoDB data is never modified or deleted.

Thanks to xet7.
2026-07-15 08:58:36 +03:00
github-actions[bot] 1a4283e598 Bump versions for v9.93 2026-07-15 04:47:18 +00:00
Lauri Ojansivu 8ec4855d6c Updated ChangeLog. 2026-07-15 07:46:12 +03:00
Lauri Ojansivu 1088f31a0d Updated translations 2026-07-15 07:44:47 +03:00
Lauri Ojansivu c032c24065 CHANGELOG: new Upcoming section above v9.92 with the post-9.92 fixes
9.92 is released, so move everything committed after it into a fresh
"# Upcoming WeKan ® release" section above v9.92, organized by topic like the
previous releases (features, then bugs):

  Features: wekan.migrate command; maintenance mode + maintenance page.
  Bugs: db-eval driver resolution (ESM ignores NODE_PATH); decide FerretDB vs
        MongoDB from a non-empty SQLite database (not the marker); mongod-7
        readiness probe fast-fail.

v9.92 is restored to what it shipped, including its "migration-success marker is
now authoritative" bug entry (which the Upcoming "presence of a FerretDB SQLite
database" entry supersedes). No entry text changed; only relocated.
2026-07-15 07:41:11 +03:00
Lauri Ojansivu 88e692ef43 Snap migration: fast-fail the mongod-7 readiness probe when the temp mongod has died
ready_via_node waits up to 45s for the temporary source mongod to accept connections, to
allow a large MongoDB 6/7 database time to replay its journal (#6454). Add a liveness check:
if the mongod process (SRC_PIDFILE) has already exited - e.g. mongod 7 cannot open old
MongoDB 3.x data - stop waiting immediately and drop to the MongoDB 3.2 reader, instead of
pinging a dead process for the full timeout. Matters across many unattended 6.09 -> 9.x
upgrades. (With --fork, start_mongod usually already returns non-zero when mongod cannot open
the data; this also covers a mongod that started then died mid-probe.)

Thanks to xet7.
2026-07-15 07:32:58 +03:00
Lauri Ojansivu b9a9bf1593 Snap: require a NON-EMPTY FerretDB SQLite before treating the migration as done
For unattended upgrades at scale (6.09/MongoDB 3.2 -> 9.x/FerretDB across many servers), the
"did the migration succeed?" test must not be fooled by a 0-byte stub file.

- New shared helper snap-src/bin/ferretdb-has-data: exit 0 only if a *.sqlite file bigger than
  0 bytes exists in files/db. Used by mongodb-control, ferretdb-control and wekan-control in
  place of the previous "*.sqlite exists" glob, so the DB decision is based on a real,
  non-empty FerretDB database. (Deliberately does NOT require the -wal file, which SQLite may
  checkpoint away when FerretDB is stopped - that would cause false negatives at startup.)

- migration-control finish_success now verifies the non-empty SQLite database exists (and logs
  the WAL/shm sidecars) BEFORE switching the snap to FerretDB. If the importer returns success
  but wrote no data, it does not switch or set the done marker - MongoDB data is kept and the
  migration retries on the next start.

Thanks to xet7.
2026-07-15 07:32:58 +03:00
Lauri Ojansivu 8db071f94c Snap: fix db-eval driver resolution (ESM ignores NODE_PATH) - the root cause
db-eval is the Node helper the snap uses instead of mongosh to check whether MongoDB/FerretDB
is up, elect the replica-set primary, and probe mongod-7 readiness during migration. It did
`import { MongoClient } from 'mongodb'` while the wrapper set NODE_PATH to the bundled driver
-- but Node's ESM loader IGNORES NODE_PATH (only the CommonJS loader honors it). So the import
resolved nothing and db-eval exited BEFORE opening any connection, making every
ping/primary/rs-* check fail.

This single bug explains the whole family of failures seen this week:
  - WeKan looping "MongoDB not ready yet, retrying..." / "FerretDB not ready yet..." forever
    even though the database was running and listening;
  - replica-set initialisation failing;
  - the MongoDB -> FerretDB migration falling back to MongoDB 3.2 because the mongod-7
    readiness probe never connected (mongod 7 opened the data fine, but db-eval couldn't reach
    it), and 3.2 cannot read WiredTiger-7 files -> no FerretDB SQLite produced.

Proof from the migration source mongod log: mongod 7 reached "Waiting for connections" with
ZERO "Connection accepted" before the readiness timeout killed it; the only connection in the
file was the native `mongo` shell to mongod 3.2.

Fix: resolve the driver with createRequire (CommonJS resolution honors NODE_PATH and the
bundle layout), anchored inside the modern bundle (npm-mongo v6 first). Applied the same fix
to the standalone migrate-schema-v843.mjs and migrate-gridfs-to-fs.mjs tools.

Thanks to xet7.
2026-07-15 07:32:58 +03:00
Lauri Ojansivu 0ebf34aedc Snap: add wekan.migrate + wekan.maintenance commands and a maintenance page
wekan.migrate (bin/wekan-force-migrate): force a fresh MongoDB -> FerretDB migration,
ignoring the database setting and the migration marker. Removes any partial FerretDB SQLite +
resume checkpoint, sets database=mongodb, and starts wekan.mongodb so migration-control
re-reads the existing MongoDB (3 or 7) data and migrates again. Source MongoDB data untouched.

wekan.maintenance on|off (bin/wekan-maintenance): toggles a $SNAP_COMMON/.wekan-maintenance
marker. While present, mongodb-control / ferretdb-control do NOT auto-migrate or auto-disable,
so `snap start wekan.mongodb` or `snap start wekan.ferretdb` stays up and you can reach the
data over the MongoDB wire protocol on port 27019 (one at a time - they share the port).

Maintenance page (bin/wekan-maintenance-page.mjs): in maintenance mode wekan-control execs
this instead of WeKan; it serves an "under maintenance" page (HTTP 503) on the web port for
ALL URLs. It shows the Admin Panel product name if set (not "WeKan"), read from
$SNAP_COMMON/.productname.txt, which is cached while a database is running by wekan-control
(new db-eval `product-name` command) and by both migration importers - so it is available even
when both databases are stopped.

Registered `migrate` and `maintenance` apps in snapcraft.yaml.

Thanks to xet7.
2026-07-15 07:32:58 +03:00
Lauri Ojansivu 3f42d4d3f0 Snap: decide FerretDB vs MongoDB from SQLite data, not the migration marker
Regression fix. An earlier change made mongodb-control/ferretdb-control/wekan-control key
the "use FerretDB / disable MongoDB" decision off the .migration-to-ferretdb-done marker.
But migration-control ALSO writes that marker when the migration falls back (data
unreadable, tools missing) or when there is nothing to migrate - producing NO FerretDB
data. So on a server whose MongoDB 7 -> FerretDB migration failed:
  - mongodb-control saw the marker -> "migration already finished; disabling mongodb
    service" -> disabled MongoDB;
  - FerretDB SQLite (files/db) was EMPTY;
  - database=mongodb, so wekan-control waited on MongoDB -> "MongoDB not ready yet,
    retrying in 5 seconds..." forever, and wekan.mongodb refused to stay up.

Now all three scripts decide from ACTUAL DATA ON DISK: MongoDB is disabled / FerretDB is
forced ONLY when a *.sqlite database exists in files/db. An empty files/db means the
migration did not succeed, so mongod starts normally and WeKan keeps working (and the
migration can be retried). The marker still prevents re-running a finished migration.

Thanks to xet7.
2026-07-15 07:32:57 +03:00
github-actions[bot] 3e6a11d7f0 Bump versions for v9.92 2026-07-15 02:51:17 +00:00
Lauri Ojansivu 3bd9da70d4 Updated ChangeLog. 2026-07-15 05:50:09 +03:00
Lauri Ojansivu 8e47eca72e CHANGELOG: note disk-space guard is verified to work in snap confinement
Upcoming section: document that statfs is in snapd's default seccomp allow-list, so the
MongoDB -> FerretDB migration's free-space guard is active on Snap; quotactl is not used and
its absence is covered by the ENOSPC/EDQUOT write-failure fallback.
2026-07-15 05:46:05 +03:00
Lauri Ojansivu 2c895107a0 Snap migration: cite snapd seccomp allow-list in the disk-space guard comments
Document that statfs (and statfs64/fstatfs/fstatfs64/statvfs/fstatvfs) are in snapd's
default seccomp allow-list (snapcore/snapd interfaces/seccomp/template.go), so free-space
checks WORK inside a snap (which also has no per-snap disk quota by default, so statfs shows
real usable space). quotactl is NOT in the allow-list, but it is never called; a snapd
storage-quota group is still caught by the ENOSPC/EDQUOT write-failure path. Only Sandstorm
grains genuinely lack statfs (FUSE unimplemented, quotactl blocked). No behaviour change.
2026-07-15 05:44:32 +03:00
Lauri Ojansivu 22a4f419ce Snap: harden MongoDB 6/7 -> FerretDB importer + never start an empty FerretDB
migrate-mongodb-to-ferretdb.mjs (the modern MongoDB 6/7 driver importer that
migration-control runs, packaged from releases/):
  - Resolve the mongodb driver by probing the WeKan bundle with createRequire anchors and
    USE WHAT WORKS: prefer a v6+ driver that exposes GridFSBucket and speaks OP_MSG, since
    an older bundled v2 driver's OP_QUERY is rejected by FerretDB ("Unsupported OP_QUERY
    command: update"). A plain `import from 'mongodb'` could pick up that v2 driver. Fail
    fast with a clear message if no usable driver is found.
  - Bring it to parity with migrate-mongo3-to-ferretdb.mjs's data-safety and UX: measure
    total attachment/avatar bytes up front and STOP before extracting if they will not fit;
    if space runs out mid-run, stop + delete the partially migrated files + report how much
    more disk is needed (a full disk can corrupt the still-running source MongoDB);
    detect ENOSPC/EDQUOT where free space is not measurable (Sandstorm); show a live
    per-file progress bar; and translate the dashboard into the browser's language.
    Existing checkpoint/resume, schema upgrade, orphan fixing, compaction and index
    creation are unchanged.

wekan-control:
  - On startup, decide the database from what data actually exists on disk (FerretDB SQLite
    at $SNAP_COMMON/files/db, MongoDB WiredTiger at $SNAP_COMMON), not the `database` setting
    alone. If ferretdb is selected but its SQLite is empty while MongoDB still has data,
    revert to database=mongodb instead of starting an EMPTY FerretDB that would look like all
    data was lost, and tell the user to run the migration first.

Thanks to xet7.
2026-07-15 05:35:33 +03:00
Lauri Ojansivu f2a417047b Updated ChangeLog. 2026-07-15 05:30:08 +03:00
Lauri Ojansivu 48e47e6687 Snap: RAM-aware WiredTiger cache so MongoDB starts on < 34 GB RAM boxes (#6454)
Symptom: WeKan never started, looping "MongoDB not ready yet, retrying in 5 seconds..."
forever, even though mongod appeared to be running.

Cause: mongodb-control started mongod with a HARDCODED --wiredTigerCacheSizeGB 32. On any
server with less than ~34 GB RAM, mongod was OOM-killed seconds after startup. That
included the temporary mongod started to initialise the replica set: it died before
db-eval could reach it (log showed "child process started successfully" then 30 s of
failed pings), so the replica set was never initiated. The final mongod then ran with
--replSet rs0 but no config, no PRIMARY was elected, and wekan-control (which needs the
replica-set primary for Meteor change streams) waited forever.

Fixes in mongodb-control:
  - WiredTiger cache is now RAM-aware: ~50% of (MemTotal - 1 GB), the same formula mongod
    uses for its own default, capped at 32 GB, min 1 GB. Override with
    MONGODB_WIREDTIGER_CACHE_GB. Applied to both the temp replica-set-check mongod and the
    final mongod.
  - Temporary-mongod readiness wait raised 30 s -> 90 s so a large database that needs
    longer to replay its journal still gets its replica set initialised/reconfigured.

Fix in migration-control:
  - The temporary source mongod started to READ the data during a MongoDB -> FerretDB
    migration now uses a conservative RAM-aware cache (1/4 of (MemTotal - 1 GB), cap 8 GB,
    override MIGRATION_MONGOD_CACHE_GB), leaving room for the target FerretDB and the Node
    importer that run alongside it. Applied only to the mongod 7 (WiredTiger-only) read so
    the flag can never clash with a legacy MMAPv1 MongoDB 3.x dbpath.

Thanks to xet7.
2026-07-15 05:23:16 +03:00
Lauri Ojansivu 22804fdf38 Snap: make the MongoDB->FerretDB migration-done marker authoritative
Symptom: on an already-migrated install, `sudo snap start --enable wekan.ferretdb`
started FerretDB and then it immediately stopped itself, logging:
  "database is 'mongodb', not 'ferretdb'. Disabling ferretdb service."

Cause: every DB service keyed its behaviour off the `database` snap setting alone. If
that setting was never flipped to ferretdb (e.g. the migration's INTERNAL `snapctl set`
did not re-run the configure hook), ferretdb-control read `database=mongodb` and disabled
itself, so FerretDB could not be started by hand without first running
`snap set wekan database=ferretdb`.

Fix: the marker $SNAP_COMMON/.migration-to-ferretdb-done is now authoritative.
  - ferretdb-control: if the marker exists, repair database=ferretdb and keep running
    instead of self-disabling.
  - mongodb-control: if the marker exists, repair database=ferretdb and disable mongodb,
    BEFORE the migration-pending check so a finished migration is never re-attempted.
  - wekan-control: already forces ferretdb on the marker (previous commit).

Immediate recovery on an already-migrated install running an older release:
  sudo snap set wekan database=ferretdb

Thanks to xet7.
2026-07-15 04:58:44 +03:00
Lauri Ojansivu 87783b6f15 Snap: on startup, start the configured database instead of waiting forever
wekan-control (the wekan.wekan service) only WAITED for the database DATABASE points at
and never started a DB service, so if both wekan.ferretdb and wekan.mongodb were
stopped/disabled WeKan hung on "MongoDB not ready yet, retrying..." forever.

Now, on start, wekan-control:
  1. If the migration-success marker $SNAP_COMMON/.migration-to-ferretdb-done exists,
     forces database=ferretdb, then enables + starts wekan.ferretdb and stops + disables
     wekan.mongodb. This self-heals the case where the migration's INTERNAL `snapctl set`
     never re-ran the configure hook that flips the services.
  2. Before waiting, enables + starts whichever DB service is configured
     (snapctl start --enable = snap enable + snap start), so a merely-stopped DB is
     brought back up instead of WeKan waiting forever.

Uses the snap instance name so parallel installs target their own services.

Thanks to xet7.
2026-07-15 04:49:16 +03:00
Lauri Ojansivu 856743baef Updated ChangeLog. 2026-07-15 04:40:55 +03:00
Lauri Ojansivu 8a958650be CHANGELOG: new Upcoming section above v9.91 with the FerretDB post-migration fix
v9.91 was cut as a release, so move the Snap FerretDB service-flip fix out of it into a
fresh "# Upcoming WeKan ® release" section above v9.91. No entry text changed; only
relocated.
2026-07-15 04:39:29 +03:00
Lauri Ojansivu 3cc9dccb3c Snap: start FerretDB after migration (internal snapctl set skips the configure hook)
After a MongoDB -> FerretDB migration, WeKan hung on "MongoDB not ready yet, retrying..."
because no database was running: wekan.ferretdb stayed disabled and wekan.mongodb stayed
enabled-but-stopped.

Root cause: the wekan.ferretdb service disables itself while database=mongodb, and the
service flip that re-enables it lives in snap/hooks/configure. migration-control switches
the backend with an INTERNAL `snapctl set database=ferretdb`, but an internal snapctl set
does not re-run the configure hook, so the flip never happened.

Fix: finish_success now does the flip itself (mirroring the configure hook's ferretdb
branch): enable+start+restart wekan.ferretdb, then stop+disable wekan.mongodb, using the
snap instance name so parallel installs target their own services. FerretDB is started
before MongoDB is disabled so a DB is up first.

Immediate recovery on an already-migrated install:
  sudo snap start --enable wekan.ferretdb && sudo snap stop --disable wekan.mongodb
2026-07-15 04:38:52 +03:00
github-actions[bot] 6744fca2b3 Bump versions for v9.91 2026-07-15 00:25:43 +00:00
Lauri Ojansivu b9b6a55be6 Updated translations. 2026-07-15 03:24:36 +03:00
Lauri Ojansivu e7ec28b7a6 Updated ChangeLog. 2026-07-15 03:23:21 +03:00
Lauri Ojansivu db41dad70f CHANGELOG: add Upcoming section above v9.90; move post-release entries into it
v9.90 (2026-07-15) was already cut, but later work had been appended to it. Create a new
"# Upcoming WeKan ® release" section above v9.90 and move into it everything committed
after the v9.90 cut:
  - new features: Snap/Sandstorm migration dashboard (per-file progress + disk guard)
  - updates: i18n 10 more languages, native-name fixes, pull English-regression report
  - tests: dev server also frees the MongoDB port
  - bugs: MongoDB 3->FerretDB EJSON + stay-on-page; "Always show all code as plain text"
          reactivity race; i18n browser-language -> file mapping fixes
v9.90 is restored to its cut contents (MimeBleed CRITICAL + the original features/updates/
tests/bugs). No entry text changed; only relocated.
2026-07-15 03:20:51 +03:00
Lauri Ojansivu dc6839aef6 CHANGELOG: record the i18n language-detection fixes and additions
Document the Upcoming i18n work: the ja_JP->ja clobber fix, case/underscore-insensitive
language matching, Chinese subtag fallback + zh alias, the cmn tag typo fix (bugs), and
the 10 new selectable languages, native-name corrections, and the pull-translations
English-regression report (updates).
2026-07-15 03:14:08 +03:00
Lauri Ojansivu 2e39d80cf5 i18n: add 10 distinct language picker entries; fix English names to native
Add languages.js entries for translation files that had none (so they were pulled from
Transifex but never selectable): ca-valencia (Català (Valencià)), en_ID/en_SG/en_TR
(English (Indonesia/Singapore/Turkey)), es_CO (Español (Colombia)), fr-FR (Français
(France)), pt_PT (Português (Portugal)), ru-UA (Русский (Украина)), tk_TM (Türkmençe
(Türkmenistan)), wuu-Hans (吴语(简体)). Skipped km_KH and ru_RU (duplicate the existing
km-KH / ru-RU entries) and zh (already aliased to zh-Hans).

Fix language names that used the English name instead of the native one:
  ace  "Acehnese"            -> "Bahsa Acèh"
  cy   "Welsh"               -> "Cymraeg"
  cy-GB"Welsh (UK)"          -> "Cymraeg (Y Deyrnas Unedig)"
  af_ZA"Afrikaans (South Africa)" -> "Afrikaans (Suid-Afrika)"
2026-07-15 03:14:08 +03:00
Lauri Ojansivu 220d04e50d i18n: robust browser-language -> file matching (case/underscore-insensitive, subtag fallback)
Fix several browser-language -> translation-file mapping gaps:

- isLanguageSupported is now case-insensitive (requested) via a new TAPi18n.resolveTag()
  that maps any input to the canonical languages.js tag case-insensitively AND
  underscore<->hyphen-insensitively (so 'zh-hant'->'zh-Hant', 'JA-JP'->'ja-JP', browser
  'af-ZA'->legacy key 'af_ZA'). loadLanguage/setLanguage/ensureLanguageLoaded resolve
  through it, so the loaded file, the i18next code and the stored current tag all agree.
- Bare base codes with no plain-code file resolve via an alias map: 'zh' -> 'zh-Hans'
  (Chinese has only script/region files), so plain 'zh' gives Simplified, not English.
- Browser detection (client/lib/i18n.js) now strips trailing subtags progressively
  instead of jumping to the first segment: 'zh-Hans-CN' -> 'zh-Hans', 'zh-Hant-TW' ->
  'zh-Hant' (Chrome sends these), rather than -> 'zh' -> English.
- languages.js: fix the 'cmn' entry whose tag was the typo 'cnm' (and code 'cn'), which
  mismatched supportedLngs and broke selecting Mandarin; now tag/code = 'cmn'.

Adds i18n.test.js coverage for resolveTag, case-insensitive isLanguageSupported, the zh
alias, the underscore/hyphen match, and each Japanese variant loading its own file.
2026-07-15 03:14:08 +03:00
Lauri Ojansivu 4ab6b8561f i18n: give Japanese ja_JP its own file; report English regressions after pull
Two Transifex languages were writing to the same local file: .tx/config lang_map had
`ja_JP: ja`, which sent Transifex's ja_JP INTO imports/i18n/data/ja.i18n.json — the same
file the real Japanese (`ja`) uses. On `tx pull -a -f`, the emptier/untranslated ja_JP
overwrote ja.i18n.json, reverting Japanese strings to the English source. Map it to its
own file instead: `ja_JP: ja-JP` (-> ja-JP.i18n.json), matching languages.js which already
has three separate Japanese entries (ja -> ja.i18n.json, ja-JP -> ja-JP.i18n.json,
ja-Hira -> ja-HI.i18n.json). No other lang_map target collides. languages.js already loads
each to its own file, so no change needed there.

Also add releases/translations/report-english-regressions.mjs and call it from
pull-translations.sh: after pulling, it lists the language files where a previously
translated string reverted to exactly the English source (i.e. untranslated on Transifex),
so the regression is visible instead of being committed silently.
2026-07-15 03:14:08 +03:00
Lauri Ojansivu 97911f3e3e CHANGELOG: split migration dashboard features into "new features"
The MongoDB 3 -> FerretDB migration work had grown into one large bug bullet that
actually contained major features (live per-file progress bar, chunk-by-chunk streaming,
disk-space safety guard + rollback, Snap/Sandstorm/availability detection). Move those to
the "new features" section as their own bullet, and keep the EJSON-resolution fix +
stay-on-page hand-off as the bug entry (with a pointer to the feature bullet).
2026-07-15 03:14:08 +03:00
Lauri Ojansivu c3e36d4a2e Snap mongo3->FerretDB: disk guard keys off free-space availability, not platform
Previously the statfs free-space guards were gated on IS_SNAP. But a Snap container may
also be unable to report free space (statfs fails). Drive the behaviour off whether free
space is actually MEASURABLE instead:

- updateDiskFree: skip statfs only on Sandstorm (where it is known-unreliable — reports the
  host disk, not the grain quota); everywhere else ATTEMPT statfs, and on failure leave
  state.diskFree < 0 (unknown).
- ensureDiskForFile / the up-front total-size pre-check: run only when state.diskFree >= 0
  (measurable); otherwise skip and rely on an ENOSPC/EDQUOT write failure.
- Dashboard already hides the free-space figure and switches to "free space required for
  all files" whenever diskFree < 0, so a Snap-with-no-statfs degrades exactly like
  Sandstorm: try, and stop + delete + report on a write failure.

IS_SNAP is now only used for the platform log line. CHANGELOG updated.
2026-07-15 03:14:08 +03:00
Lauri Ojansivu 2676e8d434 Snap mongo3->FerretDB: Snap/Sandstorm-aware disk-space guard
The statfs free-space checks only make sense on the Snap (a real filesystem whose size we
can read). A Sandstorm grain cannot see its free space or quota — its FUSE layer does not
implement statfs and quotactl is blocked (confirmed in the Sandstorm source), and statfs
on the writable /var reports the host disk, not the grain quota. So:

- Detect Snap via $SNAP (IS_SNAP) and Sandstorm via SANDSTORM / SANDSTORM_RAW_MONGO_PATH /
  METEOR_SETTINGS.public.sandstorm (IS_SANDSTORM).
- Run the statfs up-front + mid-run free-space guards ONLY on Snap.
- On Sandstorm (and anything else), just try to migrate and detect "out of space" from an
  actual ENOSPC/EDQUOT write failure (in the streaming writer and in the file-loop catches),
  which triggers the same stop + delete-migrated-files + report rollback (onDiskAbort).
- Dashboard shows the free-space figure only when known (Snap); on Sandstorm it says free
  space is unknown and phrases the requirement as "free space required for all files".

Sandstorm source used only for research (grain cannot query disk/quota); not committed.
CHANGELOG updated.
2026-07-15 03:14:08 +03:00
Lauri Ojansivu e5e9f83650 CHANGELOG: document the "Always show all code as plain text" reactivity fix
Add the missing Upcoming bug entry for the alwaysShowCodeAsText fix (the viewer read a
stale ReactiveVar and never re-rendered, so the toggle did nothing; now set inside the
mentions helper from the same reactive setting it already reads). The MongoDB 3 ->
FerretDB migration progress/disk-guard improvements were already recorded in the mongo3
migration entry.
2026-07-15 03:14:08 +03:00
Lauri Ojansivu 96428115f4 Snap mongo3->FerretDB: per-file progress, streaming, and disk-space guard
Migration dashboard + migrator improvements for the MongoDB 3 -> FerretDB path:

- Live per-file progress: the file currently being extracted shows its name, size,
  "file N of TOTAL", a percent progress bar, and whether it is an attachment or an
  avatar. File-type words use WeKan's existing translations in the viewer's browser
  language (Accept-Language), read best-effort from the bundle with an English fallback.

- RAM-safe streaming: each GridFS file is streamed chunk-by-chunk (sorted by n) straight
  to disk via a spawned mongoexport + readline, with natural back-pressure, so a multi-GB
  attachment never lands in memory. The old approach buffered the whole file through
  mongoexport's 512 MB stdout maxBuffer and failed on big files.

- Disk-space guard (a full disk can corrupt the still-running source MongoDB): the
  dashboard shows remaining free space; the migrator measures the total size of all
  attachments+avatars up front and stops immediately if the volume cannot hold them; it
  also stops mid-run if free space drops below a safety margin (default 1 GB,
  MIGRATION_MIN_FREE_BYTES). On such a stop it deletes the partially-migrated files to
  free the space back, reports how many files were migrated before stopping, and shows how
  much more disk space is required to migrate all files.

Cannot run the snap here, so this is reviewed but not executed; needs a snap migration run
to verify. CHANGELOG updated.
2026-07-15 03:14:08 +03:00
Lauri Ojansivu c6a75de076 Snap mongo3->FerretDB: fix "EJSON.parse unavailable" (wrong anchor roots)
The MongoDB 3 migrator resolves WeKan's modern bson (with EJSON) and mongodb v6 by
anchoring require() inside the Meteor bundle. It anchored the sub-paths relative to the
script, but in the snap the script runs from $SNAP/bin/ while the bundle is at
$SNAP/programs/server/... (one level up) — so every anchor resolved
$SNAP/bin/programs/server/... (nonexistent) and fell through to the ancient meteor-spk
base bson 1.x with no EJSON, giving "FATAL: EJSON.parse unavailable" and aborting the
migration.

Build candidate bundle roots from $SNAP (env) and the script's parent dirs, then try the
known modern-bundle sub-paths under each (npm-mongo's nested v6 driver first, so the
ancient v2 that FerretDB rejects with OP_QUERY is never chosen). Node's module resolution
walks up from the '_.cjs' anchor to programs/server/npm/node_modules/bson.

Also: on successful hand-off the dashboard now reloads the SAME page the user was on
(the board URL) instead of forcing All Boards, so a reload during migration keeps you in
place. The dashboard already serves the progress page for every URL. CHANGELOG updated.
2026-07-15 03:14:08 +03:00
Lauri Ojansivu 1a9263326c Fix "Always show all code as plain text" not taking effect (reactivity race)
The viewer (mentions -> markdown) applies alwaysShowCodeAsText via a ReactiveVar
(Markdown.alwaysShowCodeAsText) that only a separate startup Tracker.autorun kept in
sync with the setting. But the mentions helper re-renders whenever the settings doc
changes (it reads getCurrentSetting for renderLinksAsPlainText/stripLinks), and that
re-render often runs BEFORE the bridge autorun updated the ReactiveVar — so the inner
markdown helper read the stale flag and rendered links/markdown normally (clickable),
and since mentions does not depend on that ReactiveVar it never re-rendered again.
Net effect: toggling "Always show all code as plain text" did nothing (links stayed
clickable, code stayed rendered), even after reload (same race on load).

Fix: set Markdown.alwaysShowCodeAsText inside the mentions helper, from the same
reactive getCurrentSetting() it already reads, BEFORE rendering the inner markdown
via Blaze.toHTML. The markdown helper now always reads the up-to-date flag in the same
synchronous render, so the toggle takes effect immediately in every rich-text field
(card titles, descriptions, comments, checklists). The startup autorun stays for any
direct +markdown use outside a viewer.
2026-07-15 03:14:08 +03:00
Lauri Ojansivu d923166a96 rebuild-wekan.sh: free the MongoDB port too when stopping a dev server
kill_meteor_on_port freed the app port (3000) and rspack dev-server port (8080) but not
Meteor's bundled MongoDB on app-port+1 (3001). When the meteor parent is SIGKILLed its
mongo child is often orphaned and keeps holding 3001, so the next `meteor run` failed
with "Unexpected mongo exit code 48 ... port was closed, or was already taken". Also
free app-port+1 (which additionally clears a leftover standalone test mongod on :3001),
include it in the readiness guard/wait, and in the SIGKILL escalation. CHANGELOG noted.
2026-07-15 03:14:08 +03:00
206 changed files with 20057 additions and 1139 deletions

No files matched your search

+179 -13
View File
@@ -45,13 +45,19 @@ name: Release All Platforms
# its .zip to the Release. Windows/macOS strip the Linux FerretDB back
# out (MongoDB-only). Decoupled from `release` so a slow/flaky build
# never blocks it
# - build-sandstorm: built AFTER release, builds the Sandstorm .spk package
# (same steps as the standalone sandstorm.yml workflow, which still
# exists for testing the .spk build on its own) and attaches
# wekan-<version>-sandstorm.spk to the Release. Non-blocking: the
# Sandstorm build is the experimental/fragile part of CI, so it
# never fails the release
# - docker: builds and pushes the multi-arch image (amd64, arm64, ppc64le, s390x,
# riscv64) to Docker Hub, Quay.io, GHCR
# - snap: builds the snap on Launchpad from the default core24 snapcraft.yaml
# (platforms: amd64, arm64, s390x, ppc64el, riscv64), pushes it to the
# Snap Store candidate + beta + edge channels and attaches the .snap
# files to the GitHub Release. core24 allows candidate (core26 does
# not); the stable channel is published MANUALLY later, not here.
# Snap Store stable + candidate + beta + edge channels and attaches
# the .snap files to the GitHub Release. core24 allows stable and
# candidate (core26 does not).
# `snap set wekan database=ferretdb` switches the running backend to
# FerretDB v1 (snapcraft-core26.yaml is the core26 variant)
#
@@ -62,6 +68,8 @@ name: Release All Platforms
# SNAP_AUTH - Snap Store credentials (output of `snapcraft export-login`)
# LP_CREDENTIALS - base64 of the Launchpad credentials file used by
# `snapcraft remote-build` (see releases/snap-build.sh notes)
# SANDSTORM_KEYRING - base64 of ~/.sandstorm-keyring; meteor-spk signs the .spk
# with the WeKan Sandstorm app's private key from this keyring
# WEKAN_REPO_TOKEN - Personal Access Token with write access to wekan/wekan.fi
# and wekan/charts, used by the website + charts jobs to push
# to those repos (the built-in GITHUB_TOKEN only covers
@@ -301,7 +309,7 @@ jobs:
- name: Install system dependencies
run: |
sudo apt-get update
sudo apt-get install -y build-essential g++ make python3 curl wget zip unzip
sudo apt-get install -y build-essential g++ make python3 curl wget zip unzip qemu-user-static
- uses: actions/setup-node@v6
with:
@@ -353,6 +361,16 @@ jobs:
# Self-contained launcher (defaults to FerretDB SQLite + WRITABLE_PATH).
cp releases/ferretdb/start-wekan.sh .build/bundle/
chmod +x .build/bundle/start-wekan.sh
# #6458: cpu-exec + same-arch qemu-user. cpu-exec runs any bundled
# binary that declares required CPU features (e.g. an external
# MongoDB 5+: AVX on x86_64) through qemu-user emulation on CPUs
# that lack them — including hypervisors that mask AVX. Every Linux
# bundle ships its own arch's qemu-user; other arches overwrite
# these below.
cp snap-src/bin/cpu-exec .build/bundle/cpu-exec
chmod +x .build/bundle/cpu-exec
cp /usr/bin/qemu-x86_64-static .build/bundle/qemu-x86_64
chmod +x .build/bundle/qemu-x86_64
- name: Create amd64 zip
run: |
@@ -376,7 +394,7 @@ jobs:
- name: Install dependencies
run: |
sudo apt-get update
sudo apt-get install -y build-essential g++ make python3 curl unzip zip
sudo apt-get install -y build-essential g++ make python3 curl unzip zip qemu-user-static
- name: Download amd64 bundle
uses: actions/download-artifact@v8
@@ -422,6 +440,13 @@ jobs:
curl -fSL --retry 5 --retry-delay 10 -o "bundle/$t" "$MT/$t-arm64"
chmod +x "bundle/$t"
done
# #6458: replace the inherited amd64 qemu-user with this arch's own
# (cpu-exec is a shell script and stays as inherited). qemu-aarch64
# lets ARMv8.0 hosts (Raspberry Pi 4 and older) run binaries that
# need ARMv8.2-A, like MongoDB 5+.
rm -f bundle/qemu-x86_64
cp /usr/bin/qemu-aarch64-static bundle/qemu-aarch64
chmod +x bundle/qemu-aarch64
- name: Create arm64 zip
run: |
@@ -510,6 +535,8 @@ jobs:
rm -f bundle/node bundle/ferretdb bundle/.ferretdb-default bundle/start-wekan.sh
rm -f bundle/bsondump bundle/mongodump bundle/mongoexport bundle/mongofiles \
bundle/mongoimport bundle/mongorestore bundle/mongostat bundle/mongotop
# Linux-only cpu-exec + qemu-user (#6458) make no sense on Windows.
rm -f bundle/cpu-exec bundle/qemu-x86_64
# Fix: bcrypt 5.0.1 (Meteor accounts-password) ships node-addon-api@3
# which fails to compile on Node.js 24. Replace with bcrypt 6.0.0.
BCRYPT_DIR="$(pwd)/bundle/programs/server/npm/node_modules/meteor/accounts-password/node_modules/bcrypt"
@@ -617,6 +644,9 @@ jobs:
# inherited from the amd64 base bundle with the macOS builds (added in a
# later step). The POSIX launcher start-wekan.sh works on macOS, so keep it.
rm -f bundle/node bundle/ferretdb bundle/.ferretdb-default
# Linux-only cpu-exec + qemu-user (#6458): qemu-user does not exist for
# macOS (Apple Silicon needs no AVX emulation anyway).
rm -f bundle/cpu-exec bundle/qemu-x86_64
rm -f bundle/bsondump bundle/mongodump bundle/mongoexport bundle/mongofiles \
bundle/mongoimport bundle/mongorestore bundle/mongostat bundle/mongotop
# Fix: bcrypt 5.0.1 (Meteor accounts-password) ships node-addon-api@3
@@ -777,6 +807,21 @@ jobs:
# launcher. /bundle is the host bundle/ dir (see -v mount above).
cp /opt/node/bin/node /bundle/node
chmod +x /bundle/node
# #6458: replace the inherited amd64 qemu-user with THIS arch own
# same-arch qemu-user (from the target-arch distro, so it runs on
# this arch), used by bundle/cpu-exec to emulate CPU features a
# binary needs but the host CPU lacks. Tolerant: if the package
# is unavailable on this arch, the bundle just ships without it
# (cpu-exec then falls back to a system qemu-user, or reports).
rm -f /bundle/qemu-x86_64
if apt-get install -y -q qemu-user-static >/dev/null 2>&1 && \
[ -x "/usr/bin/qemu-$(uname -m)-static" ]; then
cp "/usr/bin/qemu-$(uname -m)-static" "/bundle/qemu-$(uname -m)"
chmod +x "/bundle/qemu-$(uname -m)"
echo "Bundled qemu-$(uname -m) for cpu-exec."
else
echo "qemu-user-static not available for $(uname -m); bundle ships without a bundled qemu-user."
fi
'
- name: Embed FerretDB (${{ matrix.arch }}) into the bundle
@@ -814,6 +859,128 @@ jobs:
GH_REPO: ${{ github.repository }}
run: gh release upload "v${VERSION}" "wekan-${VERSION}-${{ matrix.arch }}.zip" --clobber
# ─── 7c. Build the Sandstorm .spk and attach it to the Release ───────────────
# Same steps as the standalone sandstorm.yml workflow (kept for building/testing
# the .spk on its own without a full release); here it builds from the release
# tag and attaches wekan-<version>-sandstorm.spk to the GitHub Release.
#
# EXPERIMENTAL in CI (same caveats as sandstorm.yml):
# * Sandstorm needs unprivileged user namespaces; GitHub's Ubuntu runners are VMs
# that allow them, but this is the fragile part.
# * meteor-spk SIGNS the .spk with the app private key from the Sandstorm keyring;
# provide it as the SANDSTORM_KEYRING secret (base64 of ~/.sandstorm-keyring).
#
# continue-on-error: the experimental Sandstorm build must NOT fail the release;
# like the other post-`release` bundle jobs it only attaches its artifact.
build-sandstorm:
needs: [prepare, release]
continue-on-error: true
runs-on: ubuntu-24.04
timeout-minutes: 120
env:
VERSION: ${{ needs.prepare.outputs.version }}
steps:
- uses: actions/checkout@v7
with:
ref: refs/tags/v${{ needs.prepare.outputs.version }}
- uses: actions/setup-node@v6
with:
node-version: ${{ env.NODE_VERSION }}
- name: Enable unprivileged user namespaces (Ubuntu 24.04 restricts them)
# Ubuntu 24.04's AppArmor defaults kernel.apparmor_restrict_unprivileged_userns=1,
# which blocks the unprivileged user namespaces that the Sandstorm install and
# the spk supervisor rely on (the "fragile part" noted above). Relax it so
# `install.sandstorm.io` and meteor-spk can create sandboxes on the runner.
# `|| true`: on kernels/runners without these knobs, setting them is a no-op.
run: |
sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0 || true
sudo sysctl -w kernel.unprivileged_userns_clone=1 2>/dev/null || true
- name: Install system dependencies and Meteor
run: |
sudo apt-get update
sudo apt-get install -y p7zip-full wget curl build-essential g++ make python3 unzip xz-utils git qemu-user-static
if [ ! -f "$HOME/.meteor/meteor" ]; then curl https://install.meteor.com/ | sh; fi
echo "$HOME/.meteor" >> "$GITHUB_PATH"
- name: Install Sandstorm (dev, unattended)
# Installed BEFORE assembling the deps: build-deps.sh's [bridge] step copies
# the modern /opt/sandstorm/latest/bin/sandstorm-http-bridge over the ancient
# bundled one, so the Sandstorm install must be in place first.
run: curl https://install.sandstorm.io | sudo bash -s -- -d
- name: Assemble modern meteor-spk.deps (Node 24 + FerretDB + Mongo 3.x CLIs)
# Base = upstream meteor-spk 0.6.0 from dl.sandstorm.io (has mongod 3.0 +
# niscud). build-deps.sh swaps in Node 24, adds FerretDB + the Mongo 3.x
# CLIs + the migration launcher/importer, keeps niscud, and swaps in the
# modern sandstorm-http-bridge from the Sandstorm install above. No dependency
# on the retired releases.wekan.team or the old projects.7z.
run: |
bash sandstorm-src/build-deps.sh
echo "$HOME/projects/meteor-spk/meteor-spk-0.6.0" >> "$GITHUB_PATH"
- name: Restore the Sandstorm signing keyring
env:
SANDSTORM_KEYRING: ${{ secrets.SANDSTORM_KEYRING }}
run: |
if [ -n "${SANDSTORM_KEYRING:-}" ]; then
# meteor-spk / spk read the app signing key from ~/.sandstorm-keyring —
# a FILE directly in $HOME (see the pack crash path
# "/home/runner/.sandstorm-keyring"). Write it exactly there, NOT to
# ~/.sandstorm/sandstorm-keyring, or `meteor-spk pack` aborts with
# "open(~/.sandstorm-keyring): No such file or directory".
printf '%s' "$SANDSTORM_KEYRING" | base64 -d > "$HOME/.sandstorm-keyring"
chmod 600 "$HOME/.sandstorm-keyring"
echo "Restored ~/.sandstorm-keyring ($(wc -c < "$HOME/.sandstorm-keyring") bytes)."
else
echo "::error::SANDSTORM_KEYRING secret is not set. meteor-spk pack signs the .spk with the WeKan Sandstorm app's private key, which lives in this keyring, so packing cannot proceed without it. Add the base64 of your ~/.sandstorm-keyring file as the SANDSTORM_KEYRING repository secret (e.g. 'base64 -w0 ~/.sandstorm-keyring')."
exit 1
fi
- name: Install Meteor npm dependencies
# PUPPETEER_SKIP_DOWNLOAD: puppeteer is a devDependency used only by tests,
# not by the server, so it never belongs in the packed .spk. Skipping its
# Chromium download (~150 MB) avoids any risk of it bloating the build and
# speeds up CI.
env:
PUPPETEER_SKIP_DOWNLOAD: '1'
run: |
(meteor update --npm 2>/dev/null || true) && meteor npm install
- name: Build the Sandstorm .spk
id: build
env:
PUPPETEER_SKIP_DOWNLOAD: '1'
run: |
set -euo pipefail
# Version-named (not timestamped like sandstorm.yml): the release re-runs
# idempotently with --clobber replacing the same asset.
SPK="wekan-${VERSION}-sandstorm.spk"
meteor-spk pack "$SPK"
# Report the packed size and warn if it exceeds Cloudflare's 100 MB upload
# cap (a proxied browser upload to a Cloudflare-fronted Sandstorm 413s above
# this; install via a DNS-only host / SSH tunnel, or trim further).
SPK_BYTES=$(stat -c%s "$SPK")
echo "Packed $SPK: $((SPK_BYTES/1024/1024)) MiB ($SPK_BYTES bytes)"
if [ "$SPK_BYTES" -gt $((100*1024*1024)) ]; then
echo "::warning::$SPK is $((SPK_BYTES/1024/1024)) MiB — over Cloudflare's 100 MB upload limit. Upload via a DNS-only host / SSH tunnel to Sandstorm, or trim the bundle further."
fi
ls -la "$SPK"
echo "spk=$SPK" >> "$GITHUB_OUTPUT"
- uses: actions/upload-artifact@v7
with:
name: ${{ steps.build.outputs.spk }}
path: ${{ steps.build.outputs.spk }}
retention-days: 7
- name: Attach the .spk to the GitHub Release
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: gh release upload "v${VERSION}" "${{ steps.build.outputs.spk }}" --clobber
# ─── 8. Build and push the multi-arch Docker image to all registries ────────
# Mirrors releases/docker-build.sh step 3 (multi-arch buildx --push).
# Needs `release` because the Dockerfile downloads wekan-<version>-<arch>.zip
@@ -965,7 +1132,7 @@ jobs:
# GitHub runners and snapcraft cannot cross-build, so they stay on Launchpad but
# in a NON-BLOCKING, per-arch matrix so a slow/failed arch (riscv64 queues for
# hours) never holds up the release or the other arches. Each arch publishes to
# the Snap Store (candidate + beta + edge) and attaches to the Release the moment
# the Snap Store (stable + candidate + beta + edge) and attaches to the Release the moment
# it finishes — all 5 arches, published independently.
snap-native:
needs: [prepare, release]
@@ -1012,13 +1179,13 @@ jobs:
*) echo "::error::Built snap '$snap' is not ${{ matrix.arch }}."; exit 1 ;;
esac
- name: Push ${{ matrix.arch }} to the Snap Store (candidate + beta + edge)
- name: Push ${{ matrix.arch }} to the Snap Store (stable + candidate + beta + edge)
uses: snapcore/action-publish@v1
env:
SNAPCRAFT_STORE_CREDENTIALS: ${{ secrets.SNAP_AUTH }}
with:
snap: ${{ steps.build.outputs.snap }}
release: candidate,beta,edge
release: stable,candidate,beta,edge
- name: Attach the ${{ matrix.arch }} snap to the GitHub Release
env:
@@ -1109,7 +1276,7 @@ jobs:
echo "::error::Remote build ${{ matrix.arch }} failed after $attempts attempts (no wekan_${VERSION}_${{ matrix.arch }}.snap produced)." >&2
exit 1
- name: Push ${{ matrix.arch }} to the Snap Store (candidate + beta + edge)
- name: Push ${{ matrix.arch }} to the Snap Store (stable + candidate + beta + edge)
env:
SNAPCRAFT_STORE_CREDENTIALS: ${{ secrets.SNAP_AUTH }}
run: |
@@ -1120,11 +1287,10 @@ jobs:
echo "::error::No wekan_${VERSION}_${{ matrix.arch }}.snap to upload."
exit 1
fi
# base: core24 allows publishing to candidate (core26 does not). Stable is
# published MANUALLY later, once the build has proven stable enough.
# base: core24 allows publishing to stable and candidate (core26 does not).
for f in "${snaps[@]}"; do
echo "Uploading $f to the Snap Store (candidate,beta,edge)..."
snapcraft upload --release=candidate,beta,edge "$f"
echo "Uploading $f to the Snap Store (stable,candidate,beta,edge)..."
snapcraft upload --release=stable,candidate,beta,edge "$f"
done
- name: Attach the ${{ matrix.arch }} snap to the GitHub Release
+1 -1
View File
@@ -55,7 +55,7 @@ jobs:
- name: Install system dependencies and Meteor
run: |
sudo apt-get update
sudo apt-get install -y p7zip-full wget curl build-essential g++ make python3 unzip xz-utils git
sudo apt-get install -y p7zip-full wget curl build-essential g++ make python3 unzip xz-utils git qemu-user-static
if [ ! -f "$HOME/.meteor/meteor" ]; then curl https://install.meteor.com/ | sh; fi
echo "$HOME/.meteor" >> "$GITHUB_PATH"
+1 -1
View File
@@ -1,6 +1,6 @@
[main]
host = https://www.transifex.com
lang_map = te_IN: te-IN, es_AR: es-AR, es_419: es-LA, es_TX: es-TX, he_IL: he-IL, zh_CN: zh-CN, ar_EG: ar-EG, cs_CZ: cs-CZ, fa_IR: fa-IR, ms_MY: ms-MY, nl_NL: nl-NL, de_CH: de-CH, en_IT: en-IT, uz_UZ: uz-UZ, fr_CH: fr-CH, hi_IN: hi-IN, et_EE: et-EE, es_PE: es-PE, es_MX: es-MX, gl_ES: gl-ES, mn_MN: mn, zh_TW: zh-TW, ast_ES: ast-ES, es_CL: es-CL, ja_JP: ja, lv_LV: lv, ro_RO: ro-RO, az_AZ: az-AZ, cy_GB: cy-GB, gu_IN: gu-IN, pl_PL: pl-PL, vep: ve-PP, en_BR: en-BR, en@ysv: en-YS, hu_HU: hu, ko_KR: ko-KR, pt_BR: pt-BR, zh_HK: zh-HK, zu_ZA: zu-ZA, en_MY: en-MY, ja-Hira: ja-HI, fi_FI: fi, vec: ve-CC, vi_VN: vi-VN, fr_FR: fr-FR, id_ID: id, zh_Hans: zh-Hans, en_DE: en-DE, en_GB: en-GB, el_GR: el-GR, uk_UA: uk-UA, az@latin: az-LA, de_AT: de-AT, uz@Latn: uz-LA, vls: vl-SS, ar_DZ: ar-DZ, bg_BG: bg, es_PY: es-PY, fy_NL: fy-NL, uz@Arab: uz-AR, ru_UA: ru-UA, war: wa-RR, zh_CN.GB2312: zh-GB
lang_map = te_IN: te-IN, es_AR: es-AR, es_419: es-LA, es_TX: es-TX, he_IL: he-IL, zh_CN: zh-CN, ar_EG: ar-EG, cs_CZ: cs-CZ, fa_IR: fa-IR, ms_MY: ms-MY, nl_NL: nl-NL, de_CH: de-CH, en_IT: en-IT, uz_UZ: uz-UZ, fr_CH: fr-CH, hi_IN: hi-IN, et_EE: et-EE, es_PE: es-PE, es_MX: es-MX, gl_ES: gl-ES, mn_MN: mn, zh_TW: zh-TW, ast_ES: ast-ES, es_CL: es-CL, ja_JP: ja-JP, lv_LV: lv, ro_RO: ro-RO, az_AZ: az-AZ, cy_GB: cy-GB, gu_IN: gu-IN, pl_PL: pl-PL, vep: ve-PP, en_BR: en-BR, en@ysv: en-YS, hu_HU: hu, ko_KR: ko-KR, pt_BR: pt-BR, zh_HK: zh-HK, zu_ZA: zu-ZA, en_MY: en-MY, ja-Hira: ja-HI, fi_FI: fi, vec: ve-CC, vi_VN: vi-VN, fr_FR: fr-FR, id_ID: id, zh_Hans: zh-Hans, en_DE: en-DE, en_GB: en-GB, el_GR: el-GR, uk_UA: uk-UA, az@latin: az-LA, de_AT: de-AT, uz@Latn: uz-LA, vls: vl-SS, ar_DZ: ar-DZ, bg_BG: bg, es_PY: es-PY, fy_NL: fy-NL, uz@Arab: uz-AR, ru_UA: ru-UA, war: wa-RR, zh_CN.GB2312: zh-GB
[o:wekan:p:wekan:r:application]
file_filter = imports/i18n/data/<lang>.i18n.json
+1125
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -7,7 +7,7 @@ LABEL org.opencontainers.image.source="https://github.com/wekan/wekan"
# TARGETARCH and TARGETVARIANT are automatically provided by Docker Buildx
ARG TARGETARCH
ARG TARGETVARIANT
ARG VERSION=9.90
ARG VERSION=9.97
ARG DEBIAN_FRONTEND=noninteractive
ENV BUILD_DEPS="apt-utils gnupg wget bzip2 g++ curl libarchive-tools build-essential git ca-certificates python3 unzip"
+1 -1
View File
@@ -1,5 +1,5 @@
appId: wekan-public/apps/77b94f60-dec9-0136-304e-16ff53095928
appVersion: "v9.90.0"
appVersion: "v9.97.0"
files:
userUploads:
- README.md
+22
View File
@@ -132,6 +132,16 @@ If *nix: chmod +x api.py => ./api.py users
python3 api.py getcardsettings BOARDID # Get board-level card settings (allows* toggles, cardAging, cardAgingDays1/2/3)
python3 api.py setcardsetting BOARDID KEY VALUE # Set one board card setting, e.g. allowsDueDate true, cardAging true, cardAgingDays1 5
Board Automation Rules API (IFTTT, Issue #2674):
python3 api.py listrules BOARDID # List automation rules of a board
python3 api.py getrule BOARDID RULEID # Get one rule with its trigger and action
python3 api.py addrule BOARDID TITLE TRIGGER_JSON ACTION_JSON # Add rule. Missing trigger matching fields default to the '*' wildcard
python3 api.py editrule BOARDID RULEID PATCH_JSON # Edit rule: {"title":..,"trigger":{..},"action":{..}}
python3 api.py removerule BOARDID RULEID # Remove rule (and its trigger + action)
# Example (Issue #2674) - add member when card moved TO list, remove member when moved AWAY FROM list:
# python3 api.py addrule BOARDID 'Add on move to Doing' '{"activityType":"moveCard","listName":"Doing"}' '{"actionType":"addMember","username":"someuser"}'
# python3 api.py addrule BOARDID 'Remove on move from Doing' '{"activityType":"moveCard","oldListName":"Doing"}' '{"actionType":"removeMember","username":"someuser"}'
Admin API:
python3 api.py newuser USERNAME EMAIL PASSWORD
@@ -1773,6 +1783,18 @@ if arguments >= 1:
# python3 api.py addrule BOARDID 'Archive after 90 days' \
# '{"activityType":"scheduledTrigger","scheduleKind":"aging","listName":"Completed","days":90,"atTime":"03:00"}' \
# '{"actionType":"archive"}'
#
# Example (Issue #2674 - add a user to the card when it is moved TO a list, and
# remove the user again when the card is moved AWAY FROM that list). Trigger
# matching fields that are omitted (userId, swimlaneName, cardTitle, and the
# unused one of listName/oldListName) are stored as the '*' wildcard by the
# server, so the rules fire for any user/swimlane/card title:
# python3 api.py addrule BOARDID 'Add member on move to Doing' \
# '{"activityType":"moveCard","listName":"Doing"}' \
# '{"actionType":"addMember","username":"someuser"}'
# python3 api.py addrule BOARDID 'Remove member on move from Doing' \
# '{"activityType":"moveCard","oldListName":"Doing"}' \
# '{"actionType":"removeMember","username":"someuser"}'
if arguments >= 2 and sys.argv[1] == 'listrules':
boardid = sys.argv[2]
+79 -2
View File
@@ -10,7 +10,61 @@ const commentFormIsOpen = new ReactiveVar(false);
// Empty string means a new top-level comment.
const replyToCommentId = new ReactiveVar('');
// #5547: persist the comment draft (debounced) into UnsavedEdits while the user
// types, so a comment in progress survives closing the card, clicking outside
// it, or navigating away — the form prefills from {{getUnsavedValue
// 'cardComment' ...}} on the next open. Historical note: the click-open flag
// that armed the old escape-time draft save was removed in 2019 (3b3950369)
// because the escape handler CLEARED the visible text; since then nothing saved
// the draft at all, so any close of the card discarded the comment.
let commentDraftTimer = null;
let commentDraftPending = null; // { cardId, value }
function commentDraftWrite({ cardId, value }) {
if (!cardId) return;
const draftKey = { fieldName: 'cardComment', docId: cardId };
if ((value || '').trim()) {
UnsavedEdits.set(draftKey, value);
} else {
UnsavedEdits.reset(draftKey);
}
}
function scheduleCommentDraftSave(cardId, value) {
commentDraftPending = { cardId, value };
if (commentDraftTimer) clearTimeout(commentDraftTimer);
commentDraftTimer = setTimeout(() => {
commentDraftTimer = null;
const pending = commentDraftPending;
commentDraftPending = null;
if (pending) commentDraftWrite(pending);
}, 300);
}
// Run a pending (debounced) save immediately — e.g. the card is closing.
function flushCommentDraftSave() {
if (commentDraftTimer) {
clearTimeout(commentDraftTimer);
commentDraftTimer = null;
}
const pending = commentDraftPending;
commentDraftPending = null;
if (pending) commentDraftWrite(pending);
}
// Drop any pending save — the comment was submitted, so there is no draft.
function cancelCommentDraftSave() {
if (commentDraftTimer) {
clearTimeout(commentDraftTimer);
commentDraftTimer = null;
}
commentDraftPending = null;
}
Template.commentForm.onDestroyed(function () {
// #5547: the card can close without the escape handler ever running (the X
// button, a route change); make sure the last keystrokes reach the draft.
flushCommentDraftSave();
commentFormIsOpen.set(false);
$('.note-popover').hide();
});
@@ -28,6 +82,15 @@ Template.commentForm.helpers({
});
Template.commentForm.events({
// #5547: arm the escape handler below (it saves the draft and closes the
// form); this flag had no setter since 2019, so the handler never ran.
'focus .js-new-comment-input'() {
commentFormIsOpen.set(true);
},
// #5547: keep the draft continuously saved (debounced) while typing.
'input .js-new-comment-input'(evt) {
scheduleCommentDraftSave(Utils.getCurrentCardId(), evt.currentTarget.value);
},
'submit .js-new-comment-form'(evt, tpl) {
const input = tpl.$('.js-new-comment-input');
const text = input.val().trim();
@@ -48,6 +111,13 @@ Template.commentForm.events({
cardId,
parentId: parentId || '',
});
// #5547: the comment is saved — cancel any debounced draft save still in
// flight and remove the stored draft so it does not resurface next open.
cancelCommentDraftSave();
UnsavedEdits.reset({
fieldName: 'cardComment',
docId: Utils.getCurrentCardId(),
});
replyToCommentId.set('');
resetCommentInput(input);
Tracker.flush();
@@ -159,13 +229,20 @@ EscapeActions.register(
docId: Utils.getCurrentCardId(),
};
const commentInput = $('.js-new-comment-input');
const draft = commentInput.val().trim();
const draft = (commentInput.val() || '').trim();
cancelCommentDraftSave();
if (draft) {
UnsavedEdits.set(draftKey, draft);
} else {
UnsavedEdits.reset(draftKey);
}
resetCommentInput(commentInput);
// #5547: do NOT clear the input — clearing it on every click outside the
// comment box is exactly the "comment text disappearing" bug that got this
// handler disarmed in 2019 (3b3950369). The draft is saved above; if the
// card stays open, the text stays visible; if the card closes, the next
// open prefills the form from the draft.
commentInput.blur();
commentFormIsOpen.set(false);
},
() => {
return commentFormIsOpen.get();
+13 -1
View File
@@ -316,7 +316,19 @@ body.desktop-mode .board-wrapper .board-canvas .board-overlay {
display: none !important;
pointer-events: none !important;
}
.board-wrapper .board-canvas.is-dragging-active .open-minicard-composer,
/* #2877 "Wekan swimlane jumps when moving card": while a card is dragged the
"+ Add Card" composer link is hidden, but hiding it with `display: none`
collapsed the bottom row of EVERY list at drag start (and restored it on
drop). With auto-height swimlanes the whole swimlane shrank/grew by the
composer's height, so all swimlanes below visibly jumped up and back down.
`visibility: hidden` hides the link just the same but keeps its box in the
layout, so nothing moves when a drag starts or ends. */
.board-wrapper .board-canvas.is-dragging-active .open-minicard-composer {
visibility: hidden;
}
/* Checked cards of a multi-selection ARE the payload being dragged, so
removing them from the flow (showing the list as it will look after the
drop) is intentional — keep display: none here. */
.board-wrapper .board-canvas.is-dragging-active .minicard-wrapper.is-checked {
display: none;
}
@@ -159,6 +159,12 @@ template(name="boardHeaderBar")
i.fa.fa-times-thin
.separator
//- #6465: one-click board settings — the boardMenu popup used to need
//- two clicks (open sidebar, then Boardeinstellungen). The click
//- handler already exists in boardHeader.js ('click .js-open-board-menu').
if currentUser.isBoardMember
a.board-header-btn.js-open-board-menu(title="{{_ 'boardMenuPopup-title'}}")
i.fa.fa-cog
a.board-header-btn.js-toggle-sidebar(title="{{_ 'sidebar-open'}} {{_ 'or'}} {{_ 'sidebar-close'}}")
i.fa.fa-bars
+7 -2
View File
@@ -197,14 +197,19 @@ template(name="boardList")
span.board-list-item-name(title="{{boardOpenAndMoveHint}}")
+viewer
= title
//- #5174 / #4825: the per-board allows* flags are
//- resolved server-side into the one-shot tile data
//- (the raw fields are not even published to this
//- page), so the show* helpers below gate the whole
//- block consistently for every board.
unless currentSetting.hideBoardMemberList
if allowsBoardMemberList
if showBoardMemberList _id
.minicard-members
each member in boardMembers _id
a.name
+userAvatar(userId=member noRemove=true)
unless currentSetting.hideCardCounterList
if allowsCardCounterList
if showCardCounterList _id
.minicard-lists.flex.flex-wrap
each list in boardLists _id
.item
+31 -25
View File
@@ -132,16 +132,6 @@ function saveWorkspace(workspaceId, { name, icon }) {
}
Template.boardList.helpers({
hideCardCounterList() {
/* Bug Board icons random dance https://github.com/wekan/wekan/issues/4214
return Utils.isMiniScreen() && Session.get('currentBoard'); */
return true;
},
hideBoardMemberList() {
/* Bug Board icons random dance https://github.com/wekan/wekan/issues/4214
return Utils.isMiniScreen() && Session.get('currentBoard'); */
return true;
},
BoardMultiSelection() {
return BoardMultiSelection;
},
@@ -193,6 +183,15 @@ Template.boardList.onCreated(function () {
Meteor.call('getMyShareableGroups', (err, res) => {
if (!err && res) this.shareableGroups.set(res);
});
// #5174 / #4825: per-board tile data (per-list card counts + member ids) for
// the All Boards tiles, computed server-side and fetched exactly ONCE here —
// deliberately NOT inside an autorun and NOT from reactive getLists/getCards
// cursors, so the #4214 "icons random dance" (a reactive re-render loop on
// this page, which is why the old helpers were stubbed out) cannot return.
this.boardTileDataVar = new ReactiveVar({});
Meteor.call('getAllBoardsTileData', (err, res) => {
if (!err && res) this.boardTileDataVar.set(res);
});
let currUser = ReactiveCache.getCurrentUser();
let userLanguage;
if (currUser && currUser.profile) {
@@ -598,25 +597,32 @@ Template.boardList.helpers({
.slice()
.sort((a, b) => (a.title || '').localeCompare(b.title || ''));
},
// #5174 / #4825: the board tiles' per-list card-count line and member avatar
// row. Data comes from the one-shot getAllBoardsTileData method fetch in
// onCreated (see there) — NOT from reactive getLists/getCards cursors, which
// caused the #4214 "icons random dance" and got these helpers stubbed to []
// (hiding the counters/avatars for everyone). The show* helpers resolve the
// per-board opt-in flags (allowsCardCounterList / allowsBoardMemberList,
// board sidebar "Show at All Boards page"), strictly, server-side — so a
// board with the checkbox off (or never set) consistently shows nothing.
boardLists(boardId) {
/* Bug Board icons random dance https://github.com/wekan/wekan/issues/4214
const lists = ReactiveCache.getLists({ 'boardId': boardId, 'archived': false },{sort: ['sort','asc']});
const ret = lists.map(list => {
let cardCount = ReactiveCache.getCards({ 'boardId': boardId, 'listId': list._id }).length;
return `${list.title}: ${cardCount}`;
});
return ret;
*/
return [];
const tile = (Template.instance().boardTileDataVar.get() || {})[boardId];
return (tile && tile.showLists && tile.lists) || [];
},
boardMembers(boardId) {
/* Bug Board icons random dance https://github.com/wekan/wekan/issues/4214
const lists = ReactiveCache.getBoard(boardId)
const boardMembers = lists?.members.map(member => member.userId);
return boardMembers;
*/
return [];
const tile = (Template.instance().boardTileDataVar.get() || {})[boardId];
return (tile && tile.showMembers && tile.memberIds) || [];
},
showCardCounterList(boardId) {
const tile = (Template.instance().boardTileDataVar.get() || {})[boardId];
return !!(tile && tile.showLists && tile.lists && tile.lists.length);
},
showBoardMemberList(boardId) {
const tile = (Template.instance().boardTileDataVar.get() || {})[boardId];
return !!(tile && tile.showMembers && tile.memberIds && tile.memberIds.length);
},
isStarred() {
+8 -1
View File
@@ -49,7 +49,14 @@ Template.attachmentGallery.events({
if (card && card.coverId === this._id) {
await card.unsetCover();
}
await Attachments.removeAsync(this._id);
// #5282 (same class as #3252 for comments/checklists): only remove if the
// doc is still in the local cache. Under publication churn the attachment
// can already be evicted from Minimongo, and removing a missing _id
// throws "Removed nonexistent document" even though the delete itself
// succeeded on the server.
if (this._id && ReactiveCache.getAttachment(this._id)) {
await Attachments.removeAsync(this._id);
}
Popup.back();
}),
});
@@ -1,3 +1,5 @@
import { UnsavedEdits } from '/client/lib/unsavedEdits';
const descriptionFormIsOpen = new ReactiveVar(false);
Template.descriptionForm.onDestroyed(function () {
@@ -16,6 +18,10 @@ Template.descriptionForm.events({
event.preventDefault();
const description = tpl.currentComponent ? tpl.currentComponent().getValue() : tpl.$('textarea').val();
await this.setDescription(description);
// #6455: a successful save means there is no unsaved draft anymore; clear
// any pre-existing draft record so the "You have an unsaved description"
// warning does not stick around after saving.
UnsavedEdits.reset({ fieldName: 'cardDescription', docId: this._id });
},
// Pressing Ctrl+Enter should submit the form
'keydown form textarea'(evt, tpl) {
+59 -30
View File
@@ -129,50 +129,82 @@
box-sizing: border-box;
}
/* Desktop mode: position card below board header */
/* Desktop mode: position card below board header.
#6465: the floating window used to span nearly the whole board (insets
20px/20px from BOTH edges, top-left anchored) — right on top of the card it
belongs to, with big rounded borders. Dock it to the END edge (right in LTR)
like the classic 6.09 side panel instead: the board and the card stay
visible, and the drag handle still moves it anywhere. */
body.desktop-mode .card-details:not(.card-details-popup) {
position: fixed;
width: auto;
max-width: 800px;
flex-basis: auto;
border-radius: 8px;
border-radius: 3px;
z-index: 2001;
}
/* Default position for first card or when dragged */
body.desktop-mode .card-details:not(.card-details-popup):not([style*="left"]):not([style*="top"]) {
top: 8px;
inset-inline-start: 20px;
inset-inline-end: 20px;
bottom: 20px;
inset-inline-start: auto;
inset-inline-end: 8px;
width: min(650px, 90vw);
bottom: 8px;
}
/* Stagger positions for multiple cards using nth-of-type */
/* Stagger positions for multiple cards using nth-of-type (from the end edge) */
body.desktop-mode .card-details:not(.card-details-popup):nth-of-type(1) {
top: 8px;
inset-inline-start: 20px;
inset-inline-end: 8px;
}
body.desktop-mode .card-details:not(.card-details-popup):nth-of-type(2) {
top: 38px;
inset-inline-start: 50px;
inset-inline-end: 38px;
}
body.desktop-mode .card-details:not(.card-details-popup):nth-of-type(3) {
top: 68px;
inset-inline-start: 80px;
inset-inline-end: 68px;
}
body.desktop-mode .card-details:not(.card-details-popup):nth-of-type(4) {
top: 98px;
inset-inline-start: 110px;
inset-inline-end: 98px;
}
body.desktop-mode .card-details:not(.card-details-popup):nth-of-type(5) {
top: 128px;
inset-inline-start: 140px;
inset-inline-end: 128px;
}
/* For expanded cards, set dimensions */
body.desktop-mode .card-details:not(.card-details-popup):not(.card-details-collapsed) {
inset-inline-end: 20px;
bottom: 20px;
bottom: 8px;
}
/* #4822: the MAXIMIZED card must be anchored to the VIEWPORT (position: fixed
with viewport insets), never laid out inside — or measured from — the
scrolled swimlane/board container. Historically the maximized pane was an
in-flow flex/float item of its swimlane, so after scrolling down in the
swimlanes view it rendered at the swimlane's position in the tall scrolled
canvas (off-screen) instead of over the viewport.
All four insets are !important for two reasons:
1. The floating-window rules above (top: 8px / inset-inline-end: 8px /
width: min(650px, 90vw), specificity up to 0,5,1) otherwise override the
lower-specificity .card-details-maximized geometry entirely, leaving the
Maximize button a no-op.
2. The drag handle writes inline left/top styles onto the card; a card that
was dragged and then maximized must not keep the stale dragged offsets
(an off-viewport inline top is exactly the "wrong place" of #4822).
Only !important declarations beat inline styles. */
body.desktop-mode .card-details.card-details-maximized:not(.card-details-popup):not(.card-details-collapsed) {
position: fixed !important;
top: 8px !important;
inset-inline-start: 8px !important;
inset-inline-end: 8px !important;
bottom: 8px !important;
width: auto !important;
height: auto !important;
max-width: none !important;
resize: none;
}
/* Collapsed card state - hide content and set height to title row only */
@@ -192,7 +224,9 @@ body.desktop-mode .card-details.card-details-collapsed {
}
.card-details .card-details-canvas {
width: auto;
padding: 0 2.5vw;
/* #6465: fixed 20px as in 6.09 — 2.5vw was ~48px of white border per side
on a FullHD screen. */
padding: 0 20px;
}
.card-details .card-details-header {
margin: 0 -20px 5px;
@@ -300,25 +334,14 @@ body.desktop-mode .card-details.card-details-collapsed {
float: inline-end;
}
/* Unify all card text to match title size */
/* #6465: the "unify all card text to match title size" block (v8.18) forced
EVERY element in card details to the base font size with line-height 1.5,
flattening the 6.09 hierarchy where labels/metadata were smaller than body
text — a big part of the "card window is WAAAY too big" complaint. Removed:
components keep their own sizes again. */
.card-details {
font-size: 1em;
}
.card-details p,
.card-details span,
.card-details div,
.card-details a,
.card-details label,
.card-details input,
.card-details textarea,
.card-details select,
.card-details button,
.card-details .card-details-item-title,
.card-details .card-label,
.card-details .viewer {
font-size: inherit;
line-height: 1.5;
}
.card-details .card-details-header .card-details-watch {
font-size: 17px;
padding-inline-start: 7px;
@@ -446,6 +469,12 @@ body.desktop-mode .card-details.card-details-collapsed {
flex-shrink: 0;
flex-basis: calc(100% - 20px);
will-change: flex-basis;
/* #4822: declare the position strategy explicitly. The maximized pane must
be fixed to the viewport in its own right — never an in-flow flex/float
item of the scrolled swimlane container, and never dependent on the
sibling .card-details rule (or the body.desktop-mode rules) happening to
supply position: fixed. */
position: fixed;
overflow-y: auto;
overflow-x: auto;
background: #f7f7f7;
+37 -2
View File
@@ -867,6 +867,12 @@ Template.cardDetails.events({
// permission denial that otherwise vanished with no feedback.
try {
await card.setDescription(description);
// #6455: a successful save means there is no unsaved draft anymore.
// Clear the record explicitly instead of relying on the inlined form's
// close-time draft/description comparison, which can run before the
// updated description is visible and leave a stale "You have an unsaved
// description" warning behind.
UnsavedEdits.reset({ fieldName: 'cardDescription', docId: card._id });
} catch (error) {
alert(error?.reason || error?.message || 'Failed to save description');
}
@@ -1367,10 +1373,24 @@ Template.inlinedCardDescription.onCreated(function () {
this._close = (isReset = false) => {
if (this.isOpen.get() && !isReset) {
const draft = (this._getValue() || '').trim();
// #6455: normalize BOTH sides the same way before comparing. The textarea
// value has per-line trailing whitespace stripped (_getValue), while
// getDescription() returns the raw stored text — or null for an empty
// description. Comparing them raw made the comparison permanently unequal
// for descriptions containing Markdown " \n" hard breaks (or after
// emptying the description), re-creating the phantom draft on every save.
const normalize = (s) => (s || '').replaceAll(/[ \f\r\t\v]+$/gm, '').trim();
const draft = normalize(this._getValue());
const card = getCurrentCardFromContext();
if (card && draft !== card.getDescription()) {
if (card && draft !== normalize(card.getDescription())) {
UnsavedEdits.set(this._getUnsavedEditKey(), this._getValue());
} else {
// #6455: closing with the draft equal to the saved description must
// REMOVE any pre-existing unsaved-edits record. Previously this branch
// did nothing, so once a draft record existed, pressing Save ("View it"
// -> Save) could never clear the "You have an unsaved description"
// warning — only Discard could.
UnsavedEdits.reset(this._getUnsavedEditKey());
}
}
this.isOpen.set(false);
@@ -1467,6 +1487,15 @@ Template.cardDetailsActionsPopup.events({
Popup.close();
if (!card) return;
await card.archive();
// #6465 follow-up: archiving must also CLOSE the card's details window.
// The card id stayed in the openCards session list, so the floating window
// kept rendering above the board — and, docked to the right edge, exactly
// over the archives sidebar someone restoring the card would open next,
// intercepting its Restore/Delete clicks.
Session.set('openCards', (Session.get('openCards') || []).filter((id) => id !== card._id));
if (Session.get('currentCard') === card._id) {
Session.set('currentCard', null);
}
Utils.goBoardId(card.boardId);
}),
'click .js-more': Popup.open('cardMore'),
@@ -2217,6 +2246,12 @@ Template.cardMorePopup.events({
// verify that there are no linked cards
if (ReactiveCache.getCards({ linkedId: card._id }).length === 0) {
Cards.remove(card._id);
// #6465 follow-up: like archiving, deleting must close the card's
// details window (drop it from the openCards session list).
Session.set('openCards', (Session.get('openCards') || []).filter((id) => id !== card._id));
if (Session.get('currentCard') === card._id) {
Session.set('currentCard', null);
}
} else {
// TODO: Maybe later we can list where the linked cards are.
// Now here is popup with a hint that the card cannot be deleted
+58 -13
View File
@@ -17,24 +17,69 @@ export function canNavigateToSubtaskBoard(board) {
// the parent card again, and so the behaviour is unit-testable.
//
// Returns the FlowRouter 'card' route params taken from the subtask, or
// undefined when the subtask's board is not loaded yet (see #4762 guard).
// undefined for a malformed subtask (no usable card id / board id).
//
// #1853: "Subtask board id missing: cannot read property _id of undefined".
// The subtask often lives on ANOTHER board (the deposit/target board) whose
// document is not in minimongo while the parent card's board is open. In that
// case subtask.board() yields nothing; instead of crashing (the original
// TypeError) or silently doing nothing (the post-#4762 behaviour), fall back
// to the subtask's own boardId and the default 'board' slug — the 'card'
// route action only uses :boardId/:cardId (config/router.js) and its
// subscriptions load the board, so navigation succeeds without a reload.
// 'board' is the model's own default slug (models/boards.js).
export function subtaskNavTarget(subtask) {
if (!subtask) {
return undefined;
}
const board = typeof subtask.board === 'function' ? subtask.board() : undefined;
if (!canNavigateToSubtaskBoard(board)) {
return undefined;
}
// Prefer the real card id (resolves linked subtask cards to their source);
// fall back to the plain _id when getRealId is unavailable (e.g. in tests).
const cardId =
typeof subtask.getRealId === 'function' ? subtask.getRealId() : subtask._id;
return {
boardId: board._id,
slug: board.slug,
cardId,
swimlaneId: subtask.swimlaneId,
listId: subtask.listId,
};
(typeof subtask.getRealId === 'function' ? subtask.getRealId() : undefined) ||
subtask._id;
if (!cardId) {
// Malformed subtask document: nothing sane to navigate to.
return undefined;
}
const board = typeof subtask.board === 'function' ? subtask.board() : undefined;
if (canNavigateToSubtaskBoard(board)) {
return {
boardId: board._id,
slug: board.slug,
cardId,
swimlaneId: subtask.swimlaneId,
listId: subtask.listId,
};
}
if (subtask.boardId) {
// Board doc missing locally (#1853 / #4762): navigate by id and let the
// route load the board. The slug segment is cosmetic for the card route.
return {
boardId: subtask.boardId,
slug: 'board',
cardId,
swimlaneId: subtask.swimlaneId,
listId: subtask.listId,
};
}
// No board reference at all: broken subtask, don't navigate (and don't
// throw — the caller shows a warning instead).
return undefined;
}
// Same idea for the "Go to board" popup entry (js-go-to-subtask-board):
// prefer the loaded board's id/slug, fall back to the subtask's boardId so a
// not-yet-subscribed deposit board is still reachable (#1853).
export function subtaskBoardNavTarget(subtask) {
if (!subtask) {
return undefined;
}
const board = typeof subtask.board === 'function' ? subtask.board() : undefined;
if (canNavigateToSubtaskBoard(board)) {
return { id: board._id, slug: board.slug };
}
if (subtask.boardId) {
return { id: subtask.boardId, slug: 'board' };
}
return undefined;
}
+23 -6
View File
@@ -3,7 +3,10 @@ import { FlowRouter } from 'meteor/ostrio:flow-router-extra';
import Cards from '/models/cards';
import { Filter } from '/client/lib/filter';
import { subtaskStatusLabel } from './subtaskStatusHelpers';
import { subtaskNavTarget } from './subtaskViewHelpers';
import {
subtaskNavTarget,
subtaskBoardNavTarget,
} from './subtaskViewHelpers';
import { Utils } from '/client/lib/utils';
Template.subtasks.events({
@@ -125,20 +128,34 @@ Template.subtaskActionsPopup.events({
const subtask = Template.currentData().subtask;
// #3743: open the SUBTASK card itself, not the parent/current card.
// subtaskNavTarget derives boardId/slug/cardId from the subtask only.
// #4762: it also returns undefined while the subtask's board is not
// loaded yet (ReactiveCache miss), mirroring js-go-to-subtask-board.
// #1853 / #4762: when the subtask's board (often a DIFFERENT deposit
// board) is not in minimongo yet, it falls back to the subtask's own
// boardId so the route loads the board — no TypeError, no dead button.
// It only returns undefined for a truly broken subtask document.
const target = subtaskNavTarget(subtask);
if (target) {
FlowRouter.go('card', target);
} else {
// Broken subtask (no card id / board id): warn instead of throwing.
console.warn(
'Cannot view subtask: missing board/card id on subtask',
subtask && subtask._id,
);
}
}
},
'click .js-go-to-subtask-board'() {
const subtask = Template.currentData().subtask;
const board = subtask.board();
if (board) {
// #1853: fall back to subtask.boardId when the board doc is not loaded.
const target = subtaskBoardNavTarget(subtask);
if (target) {
Popup.close();
FlowRouter.go('board', { id: board._id, slug: board.slug });
FlowRouter.go('board', target);
} else {
console.warn(
'Cannot go to subtask board: missing board id on subtask',
subtask && subtask._id,
);
}
},
'click .js-delete-subtask' : Popup.afterConfirm('subtaskDelete', async function () {
+19
View File
@@ -298,6 +298,25 @@ textarea::-moz-placeholder {
font-size: clamp(20px, 4vw, 26px);
margin: 0.5vh 1.5vw;
}
/* CJK (Japanese/Chinese/Korean) labels contain no spaces, so browsers may
insert a line break between any two characters. In the narrow add-card /
edit footers this made short labels such as "追加" (Add) and "リンク"
(Link) wrap mid-word. `word-break: keep-all` forbids breaks inside CJK
words while leaving Latin wrapping behavior unchanged, and `flex-wrap`
lets the footer wrap between its links instead of inside them.
See https://github.com/wekan/wekan/issues/4023 */
.edit-controls,
.add-controls {
flex-wrap: wrap;
word-break: keep-all;
}
.edit-controls button[type=submit],
.add-controls button[type=submit] {
white-space: nowrap;
}
.add-controls .quiet {
white-space: nowrap;
}
[type="checkbox"]:not(:checked),
[type="checkbox"]:checked {
position: absolute;
+122 -50
View File
@@ -3,6 +3,11 @@ import { TAPi18n } from '/imports/i18n';
import { EscapeActions } from '/client/lib/escapeActions';
import { MultiSelection } from '/client/lib/multiSelection';
import { Utils } from '/client/lib/utils';
import Cards from '/models/cards';
import {
isDegenerateSortGap,
computeRepairedDropIndex,
} from '/models/lib/cardSortRepair';
require('/client/lib/jquery-ui.js')
const { calculateIndex } = Utils;
@@ -19,9 +24,17 @@ const { calculateIndex } = Utils;
//
// The old per-list "min width / max width / automatic" knobs are gone — the
// rendered width is now a single hard value (see list.jade).
//
// #5659: the default/minimum width and the resolution order live in ONE
// Meteor-free module shared with models/users.js, so every path (member,
// anonymous public-board visitor, fixed mode) falls back to the SAME default
// and all lists render the same width when nothing is customized.
// ---------------------------------------------------------------------------
const DEFAULT_LIST_WIDTH = 272;
const MIN_LIST_WIDTH = 270;
import {
DEFAULT_LIST_WIDTH,
MIN_LIST_WIDTH,
resolveListWidth,
} from '/models/lib/listWidth';
function isPersonalListWidth(boardId) {
const board = ReactiveCache.getBoard(boardId);
@@ -122,25 +135,28 @@ function saveAnonFixedListWidth(boardId, width) {
function effectiveListWidth(list) {
if (!list) return DEFAULT_LIST_WIDTH;
// #5729 In fixed width mode every list renders at the single shared value.
if (isFixedListWidth(list.boardId)) {
return fixedListWidthValue(list.boardId);
// #5659: all inputs are gathered here, but the fallback order and the ONE
// default width live in models/lib/listWidth.js (shared + unit tested).
const fixedEnabled = isFixedListWidth(list.boardId);
const personalMode = isPersonalListWidth(list.boardId);
let personalWidth = null;
if (personalMode) {
const user = ReactiveCache.getCurrentUser();
if (user) {
const widths = user.getListWidths();
personalWidth = widths[list.boardId] && widths[list.boardId][list._id];
} else {
personalWidth = readAnonListWidth(list.boardId, list._id);
}
}
const shared =
typeof list.width === 'number' && list.width >= MIN_LIST_WIDTH
? list.width
: DEFAULT_LIST_WIDTH;
if (!isPersonalListWidth(list.boardId)) {
return shared;
}
const user = ReactiveCache.getCurrentUser();
if (user) {
const widths = user.getListWidths();
const w = widths[list.boardId] && widths[list.boardId][list._id];
return typeof w === 'number' && w >= MIN_LIST_WIDTH ? w : shared;
}
const w = readAnonListWidth(list.boardId, list._id);
return w || shared;
return resolveListWidth({
// #5729 In fixed width mode every list renders at the single shared value.
fixedEnabled,
fixedWidth: fixedEnabled ? fixedListWidthValue(list.boardId) : null,
sharedWidth: list.width,
personalMode,
personalWidth,
});
}
// Can the current user change THIS list's width by dragging?
@@ -276,7 +292,35 @@ Template.list.onRendered(function () {
const prevCardDom = ui.item.prev('.js-minicard').get(0);
const nextCardDom = ui.item.next('.js-minicard').get(0);
const nCards = MultiSelection.isActive() ? MultiSelection.count() : 1;
const sortIndex = calculateIndex(prevCardDom, nextCardDom, nCards);
let sortIndex = calculateIndex(prevCardDom, nextCardDom, nCards);
// #3826: cards created by the "add subtask" flow were all inserted with
// a constant sort of -1, so a list full of subtask cards contains only
// ties. No number lies strictly between two equal sorts, so
// calculateIndex returns base === neighbour sort with increment 0: the
// write is then discarded by Card.move()'s no-op guard and the card
// snaps back (and a multi-selection drop would give every selected card
// the SAME sort, losing their relative order). When the drop landed in
// such a degenerate gap, capture the target list's sibling cards in
// their current visual order (before sortable('cancel') reshuffles the
// DOM) so their sorts can be repaired below.
const prevCardData = prevCardDom ? Blaze.getData(prevCardDom) : null;
const nextCardData = nextCardDom ? Blaze.getData(nextCardDom) : null;
let orderedSiblingCards = null;
if (
isDegenerateSortGap(
prevCardData ? prevCardData.sort : null,
nextCardData ? nextCardData.sort : null,
)
) {
orderedSiblingCards = ui.item
.parent()
.children(itemsSelector)
.not(ui.item)
.toArray()
.map(el => Blaze.getData(el))
.filter(Boolean);
}
const listData = Blaze.getData(ui.item.parents('.list').get(0));
const listId = listData._id;
const currentBoard = Utils.getCurrentBoard();
@@ -303,6 +347,25 @@ Template.list.onRendered(function () {
// Blaze with the below query.
$cards.sortable('cancel');
// #3826: the drop landed between two cards whose sorts do not strictly
// increase (duplicate -1 sorts from subtask creation, or legacy data).
// Repair the sibling sorts with the minimal bumps that make the visible
// order strictly increasing, then recompute the drop index from the
// repaired neighbours: base now falls strictly between them and the
// increment is strictly positive (distinct sorts for a multi-selection).
if (orderedSiblingCards && prevCardData && nextCardData) {
const repairedDrop = computeRepairedDropIndex(
orderedSiblingCards,
prevCardData,
nextCardData,
nCards,
);
repairedDrop.updates.forEach(u => {
Cards.update(u._id, { $set: { sort: u.sort } });
});
sortIndex = { base: repairedDrop.base, increment: repairedDrop.increment };
}
if (MultiSelection.isActive()) {
ReactiveCache.getCards(MultiSelection.getMongoSelector(), { sort: ['sort'] }).forEach((card, i) => {
const newSwimlaneId = targetSwimlaneId
@@ -326,37 +389,39 @@ Template.list.onRendered(function () {
if (boardComponent) boardComponent.setIsDragging(false);
},
sort(event, ui) {
const $boardCanvas = $('.board-canvas');
const boardCanvas = $boardCanvas[0];
if (event.pageX < 10) { // scroll to the left
boardCanvas.scrollLeft -= 15;
ui.helper[0].offsetLeft -= 15;
// #443: the HORIZONTAL scroller is the .js-lists lane (.swimlane has
// overflow: auto), NOT .board-canvas, which only overflows vertically —
// the old code compared against a scrollLeftMax of 0 and never fired, so
// dragging a card toward an off-screen list never auto-scrolled the board.
const { computeEdgeScroll, findLaneUnderPointer } = require('/imports/lib/boardAutoScroll');
const lanes = document.querySelectorAll('.js-lists');
const rects = Array.prototype.map.call(lanes, el => el.getBoundingClientRect());
const laneIndex = findLaneUnderPointer(rects, event.clientX, event.clientY);
if (laneIndex !== -1) {
const nextLeft = computeEdgeScroll({
pointer: event.clientX,
lowEdge: rects[laneIndex].left,
highEdge: rects[laneIndex].right,
scrollPos: lanes[laneIndex].scrollLeft,
scrollSize: lanes[laneIndex].scrollWidth,
clientSize: lanes[laneIndex].clientWidth,
});
if (nextLeft !== null) lanes[laneIndex].scrollLeft = nextLeft;
}
if (
event.pageX > boardCanvas.offsetWidth - 10 &&
boardCanvas.scrollLeft < $boardCanvas.data('scrollLeftMax') // don't scroll more than possible
) { // scroll to the right
boardCanvas.scrollLeft += 15;
// vertical auto-scroll stays on the board canvas
const canvas = document.querySelector('.board-canvas');
if (canvas) {
const crect = canvas.getBoundingClientRect();
const nextTop = computeEdgeScroll({
pointer: event.clientY,
lowEdge: crect.top,
highEdge: crect.bottom,
scrollPos: canvas.scrollTop,
scrollSize: canvas.scrollHeight,
clientSize: canvas.clientHeight,
});
if (nextTop !== null) canvas.scrollTop = nextTop;
}
if (
event.pageY > boardCanvas.offsetHeight - 10 &&
event.pageY + boardCanvas.scrollTop < $boardCanvas.data('scrollTopMax') // don't scroll more than possible
) { // scroll to the bottom
boardCanvas.scrollTop += 15;
}
if (event.pageY < 10) { // scroll to the top
boardCanvas.scrollTop -= 15;
}
},
activate(event, ui) {
const $boardCanvas = $('.board-canvas');
const boardCanvas = $boardCanvas[0];
// scrollTopMax and scrollLeftMax only available at Firefox (https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTopMax)
// https://www.it-swarm.com.de/de/javascript/so-erhalten-sie-den-maximalen-dokument-scrolltop-wert/1069126844/
$boardCanvas.data('scrollTopMax', boardCanvas.scrollHeight - boardCanvas.clientTop);
// https://stackoverflow.com/questions/5138373/how-do-i-get-the-max-value-of-scrollleft/5704386#5704386
$boardCanvas.data('scrollLeftMax', boardCanvas.scrollWidth - boardCanvas.clientWidth);
},
});
@@ -384,6 +449,13 @@ Template.list.onRendered(function () {
const currentBoardId = Tracker.nonreactive(() => {
return Session.get('currentBoard');
});
// #1554: reactive dependency so newly added / re-rendered minicards are
// (re)initialized as droppable for label/member drags. The dependency
// (Cards.find(...).fetch()) was dropped in 7673c77c5, so the autorun ran
// ONCE per list render and cards added afterwards silently rejected
// sidebar label/member drops until the board was re-entered. Re-running
// .droppable() on initialized elements is an idempotent option refresh.
ReactiveCache.getCards({ boardId: currentBoardId });
Tracker.afterFlush(() => {
$cards.find(itemsSelector).droppable({
hoverClass: 'draggable-hover-card',
+78
View File
@@ -13,6 +13,10 @@ import { isLinkableCardTarget } from '/models/lib/linkedCardTarget';
import { listCardsSelector } from '/models/lib/swimlaneFilter';
import { sortCardsByTitle } from '/models/lib/sortCardsByTitle';
import { isLazyCards, BoardListCardCounts, windowCountId } from '/client/lib/lazyCards';
import {
mutationsChangeDragGeometry,
findActiveCardDrag,
} from '/client/lib/cardDragGeometry';
import autosize from 'autosize';
// SubsManager removed for Meteor 3 migration
@@ -453,6 +457,80 @@ Template.listBody.events({
},
});
// #2769 Card lands in the WRONG swimlane when it is dropped while a connected
// list's layout changed mid-drag. jQuery UI sortable snapshots the geometry
// of every connected `.js-minicards` container once at drag start
// (_mouseStart runs refreshPositions() BEFORE the `start` callback) and only
// re-snapshots after its own placeholder moves — never when Blaze mutates the
// DOM. Two such mutations routinely happen during a drag: another user's
// newly added card is reactively inserted into the target list (the issue's
// "target column where a new card is being added"), and the dragging user's
// own open add-card composer is closed by the `start` callback's
// EscapeActions call, AFTER the snapshot. Every list/swimlane below the
// change then shifts vertically while the cached rectangles stay put, so the
// drop resolves against a stale map: the placeholder is parked in the
// neighbouring swimlane's copy of the list (hence the reporter's "no drop
// shadow in the target column") and the stop handler's
// ui.item.parents('.swimlane') (client/components/lists/list.js) faithfully
// persists that wrong swimlane.
// Fix: watch each list's minicards for REAL DOM changes (Blaze insertions and
// removals — not jQuery UI's own placeholder/helper churn, which the library
// already follows with its own refresh) and re-cache the active drag's
// geometry with sortable('refresh'). The decision helpers are pure and unit
// tested in tests/cardDragGeometry.test.cjs.
Template.listBody.onRendered(function () {
const minicardsEl = this.find('.js-minicards');
if (!minicardsEl || typeof MutationObserver === 'undefined') {
return;
}
this.dragGeometryRefreshQueued = false;
this.dragGeometryObserver = new MutationObserver(mutations => {
// Cheapest gate first: no drag helper on the page means no drag at all
// (this observer also fires on every ordinary reactive card update).
if (!document.getElementsByClassName('ui-sortable-helper').length) {
return;
}
if (!mutationsChangeDragGeometry(mutations)) {
return;
}
if (this.dragGeometryRefreshQueued) {
return;
}
this.dragGeometryRefreshQueued = true;
// Coalesce bursts (Blaze can insert several nodes per flush); by the time
// the timeout runs, this tick's layout is final and measurable.
setTimeout(() => {
this.dragGeometryRefreshQueued = false;
const active = findActiveCardDrag(
$('.js-minicards')
.toArray()
.map(el => $.data(el, 'ui-sortable')),
);
if (active) {
try {
// Re-collects the items of every connected container and re-measures
// all container rectangles, so the pointer is matched against the
// CURRENT layout for the rest of the drag.
active.refresh();
} catch (e) {
// A failed re-measure must never break the drag itself.
}
}
}, 0);
});
this.dragGeometryObserver.observe(minicardsEl, {
childList: true,
subtree: true,
});
});
Template.listBody.onDestroyed(function () {
if (this.dragGeometryObserver) {
this.dragGeometryObserver.disconnect();
this.dragGeometryObserver = null;
}
});
function toggleValueInReactiveArray(reactiveValue, value) {
const array = reactiveValue.get();
const valueIndex = array.indexOf(value);
+4 -1
View File
@@ -208,7 +208,10 @@ template(name="listMorePopup")
span {{_ 'link-list'}}
= ' '
i.fa(class="{{#if currentBoard.isPublic}}fa-globe{{else}}fa-lock{{/if}}")
input.inline-input(type="text" readonly value="{{ rootUrl }}")
//- #6459: was {{ rootUrl }}, a helper that does not exist anywhere, so the
//- link input was always empty. absoluteUrl resolves a URL via a card on
//- this list.
input.inline-input(type="text" readonly value="{{ absoluteUrl }}")
| {{_ 'added'}}
span.date(title=list.createdAt) {{ displayDate createdAt 'LLL' }}
//unless currentUser.isWorker
+12 -6
View File
@@ -9,6 +9,13 @@ import { isHexColor, toHex } from '/models/lib/contrastColor';
import { MultiSelection } from '/client/lib/multiSelection';
import { Utils } from '/client/lib/utils';
import { lazyListCardCount } from '/client/lib/lazyCards';
// #5659: single source of truth for the default/minimum list width, shared
// with client/components/lists/list.js and models/users.js.
import {
DEFAULT_LIST_WIDTH,
MIN_LIST_WIDTH,
normalizeListWidth,
} from '/models/lib/listWidth';
let listsColors;
Meteor.startup(() => {
@@ -562,12 +569,12 @@ function readAnonFixedListWidth(boardId) {
if (stored) {
const widths = JSON.parse(stored);
const w = widths[boardId];
if (typeof w === 'number' && w >= 270) return w;
if (typeof w === 'number' && w >= MIN_LIST_WIDTH) return w;
}
} catch (e) {
console.warn('Error reading fixed list width from localStorage:', e);
}
return 272;
return DEFAULT_LIST_WIDTH;
}
function isFixedListWidth(boardId) {
@@ -611,8 +618,7 @@ Template.setListWidthPopup.helpers({
if (isFixedListWidth(list.boardId)) {
return fixedListWidthValue(list.boardId);
}
const shared =
typeof list.width === 'number' && list.width >= 270 ? list.width : 272;
const shared = normalizeListWidth(list.width);
if (!isPersonalListWidth(list.boardId)) {
return shared;
}
@@ -620,7 +626,7 @@ Template.setListWidthPopup.helpers({
if (user) {
const widths = user.getListWidths();
const w = widths[list.boardId] && widths[list.boardId][list._id];
return typeof w === 'number' && w >= 270 ? w : shared;
return normalizeListWidth(w, shared);
}
return shared;
},
@@ -702,7 +708,7 @@ Template.setListWidthPopup.events({
const boardId = list.boardId;
const width = parseInt(tpl.$('.list-width-value').val(), 10);
if (!width || width < 270) {
if (!width || width < MIN_LIST_WIDTH) {
tpl.$('.list-width-error').click();
return;
}
+14 -1
View File
@@ -383,12 +383,25 @@ Blaze.Template.registerHelper(
'mentions',
new Template('mentions', function() {
const view = this;
// Admin Panel / Features / Security: read the setting FIRST (a reactive dependency
// of this viewer) and push the "always show all code as plain text" flag into the
// wekan-markdown package BEFORE rendering the inner markdown below. Doing it here —
// not only in the separate startup autorun — removes a re-render race: this viewer
// already re-renders whenever the setting doc changes (it reads it for stripLinks),
// and the inner markdown helper then reads the up-to-date flag in the SAME
// synchronous render, so toggling "always show all code as plain text" takes effect
// immediately. Without this the viewer could re-render (setting changed) BEFORE the
// startup autorun updated the flag, read the stale value, and never re-render again
// since it does not itself depend on that ReactiveVar.
const setting = ReactiveCache.getCurrentSetting();
if (typeof Markdown !== 'undefined' && Markdown.alwaysShowCodeAsText) {
Markdown.alwaysShowCodeAsText.set(!!(setting && setting.alwaysShowCodeAsText));
}
let content = Blaze.toHTML(view.templateContentBlock);
// Admin Panel / Features: when "render links as plain text" is enabled, every
// link (markdown [label](url) and raw HTML <a href>) is stripped to plain,
// non-clickable text everywhere rich text is shown. Reactive: toggling the
// setting re-renders viewers.
const setting = ReactiveCache.getCurrentSetting();
const stripLinks = !!(setting && setting.renderLinksAsPlainText);
const currentBoard = Utils.getCurrentBoard();
if (!currentBoard)
+9 -5
View File
@@ -290,15 +290,19 @@ body:not(.board-view) #header #header-main-bar h1 {
}
/* Zoom Controls in Header */
/* #6465: compact fixed-pixel pill. The vh/vw padding+shadow made the pill
taller than the 28px overflow-hidden quick-access row, so it rendered cut
off at every window size. */
#header-quick-access .zoom-controls {
display: flex;
align-items: center;
gap: 0.5vw;
gap: 4px;
background: rgba(255, 255, 255, 0.9);
padding: 0.5vh 1vw;
border-radius: 0.5vw;
box-shadow: 0 0.2vh 0.5vh rgba(0,0,0,0.1);
margin: 0 1vw;
padding: 2px 8px;
border-radius: 10px;
box-shadow: 0 1px 2px rgba(0,0,0,0.1);
margin: 0 8px;
max-height: 24px;
float: inline-start;
}
+17 -7
View File
@@ -157,8 +157,14 @@ input,
select,
textarea,
button {
font: clamp(14px, 2.5vw, 18px) Roboto, Poppins, "Helvetica Neue", Arial, Helvetica, sans-serif;
line-height: 1.4;
/* #6465: back to the WeKan 6.09 desktop density. The clamp() introduced in
v7.98 (20e9cf114) and raised in v8.02 (67b078b80) resolved to 18px on any
window wider than 720px — +28.5% on EVERY font, input and button versus
6.09's 14px — which is the "everything is way too big" regression. Mobile
readability is handled by the mobile media queries, not by inflating the
desktop base font. */
font: 14px Roboto, Poppins, "Helvetica Neue", Arial, Helvetica, sans-serif;
line-height: 18px;
color: #4d4d4d;
/* Improve text rendering */
-webkit-font-smoothing: antialiased;
@@ -217,8 +223,10 @@ body.mobile-mode #content {
margin-top: 30vh;
}
#content > .wrapper {
margin-top: 1vh;
padding: 2vh 2vw;
/* #6465: 6.09 values; 2vh/2vw padding was ~21x38px on FullHD — the huge
empty header band on the All Boards page. */
margin-top: 10px;
padding: 15px;
}
#modal {
position: absolute;
@@ -264,13 +272,15 @@ body.mobile-mode #content {
float: inline-end;
font-size: clamp(18px, 4vw, 24px);
}
/* #6465: heading sizes back to the 6.09 values (22/18/16px) — the vw clamps
resolved to 24/20/18px on desktop and compounded the density regression. */
h1 {
font-size: clamp(18px, 4vw, 24px);
font-size: 22px;
line-height: 1.2em;
margin: 0 0 1vh;
}
h2 {
font-size: clamp(16px, 3.5vw, 20px);
font-size: 18px;
line-height: 1.2em;
margin: 0 0 0.8vh;
}
@@ -278,7 +288,7 @@ h3,
h4,
h5,
h6 {
font-size: clamp(14px, 3vw, 18px);
font-size: 16px;
line-height: 1.25em;
margin: 0 0 0.6vh;
}
+4 -1
View File
@@ -31,7 +31,10 @@ Template.userFormsLayout.onCreated(function () {
Meteor.call('isOidcRedirectionEnabled', (_, result) => {
if (result) {
AccountsTemplates.options.socialLoginStyle = 'redirect';
options = {
// #5695: this is an ES module, so the body runs in strict mode and
// the previous undeclared `options = {...}` assignment threw a
// ReferenceError, breaking the OIDC_REDIRECTION_ENABLED auto-login.
const options = {
loginStyle: AccountsTemplates.options.socialLoginStyle,
};
Meteor.loginWithOidc(options);
@@ -134,7 +134,11 @@ Template.boardActions.events({
// documents land in minimongo limbo when the wizard subscription stops.
Meteor.call('rules.createRule', boardId, ruleName, trigger, {
actionType,
listTitle: '*',
// #6472: was `listTitle: '*'` since the original rules implementation,
// but performAction reads action.listName/action.swimlaneName — so every
// generic "move to top/bottom" rule created by this wizard did nothing.
listName: '*',
swimlaneName: '*',
boardId,
desc,
});
+32 -6
View File
@@ -1,9 +1,6 @@
import { ReactiveCache } from '/imports/reactiveCache';
import { TAPi18n } from '/imports/i18n';
import Papa from 'papaparse';
import Actions from '/models/actions';
import Rules from '/models/rules';
import Triggers from '/models/triggers';
const RULES_FORMAT = 'wekan-rules-1.0.0';
const STRIP_FIELDS = ['_id', 'boardId', 'createdAt', 'modifiedAt', 'updatedAt'];
@@ -33,14 +30,43 @@ function collectBoardRules(boardId) {
.filter(Boolean);
}
// #6472: the trigger matcher (server/rulesHelper.js buildMatchingFieldsMap)
// queries every matching field of the trigger type with {$in: [value, '*']} —
// a trigger DOCUMENT that lacks one of those fields can never match. Hand-
// written or third-party JSON often omits fields like userId, so default every
// known matching field to the '*' wildcard when absent. Extra fields on
// trigger types that do not use them are harmless (never queried).
const TRIGGER_MATCHING_FIELDS = [
'userId', 'username', 'cardTitle', 'listName', 'oldListName',
'swimlaneName', 'checklistName', 'checklistItemName', 'labelId',
'attachmentName',
];
function normalizeTrigger(trigger) {
const out = { ...trigger };
TRIGGER_MATCHING_FIELDS.forEach(f => {
if (out[f] === undefined || out[f] === null || out[f] === '') out[f] = '*';
});
return out;
}
// Insert an array of {title, trigger, action} onto the given target board.
function importRules(rulesArray, boardId) {
let count = 0;
(rulesArray || []).forEach(entry => {
if (!entry || !entry.trigger || !entry.action) return;
const triggerId = Triggers.insert({ ...stripDoc(entry.trigger), boardId });
const actionId = Actions.insert({ ...stripDoc(entry.action), boardId });
Rules.insert({ title: entry.title || 'Imported rule', triggerId, actionId, boardId });
// #6472: create via the rules.createRule server method (like the rules
// wizard since #5536) instead of three optimistic client inserts — those
// are rejected by the board-admin-only allow() rules for non-admins and
// land in minimongo limbo: the imported rule LOOKS created but never
// exists on the server, so it silently does nothing until it vanishes.
Meteor.call(
'rules.createRule',
boardId,
entry.title || 'Imported rule',
normalizeTrigger(stripDoc(entry.trigger)),
stripDoc(entry.action),
);
count += 1;
});
return count;
@@ -106,6 +106,9 @@ template(name="boardCardTitlePopup")
form
label
| {{_ 'boardCardTitlePopup-title'}}
input.js-card-filter-name(type="text" value=title autofocus)
//- #2345: cardTitleFilter is passed as the popup's data context by the
//- js-open-card-title-popup handler so reopening the popup shows the
//- filter that is already set (it used to always render empty).
input.js-card-filter-name(type="text" value=cardTitleFilter autofocus)
input.js-card-filter-button.primary.wide(type="submit" value="{{_ 'set-filter'}}")
@@ -1,4 +1,31 @@
import { TAPi18n } from '/imports/i18n';
import { Utils } from '/client/lib/utils';
import {
cardTitleFilterOrWildcard,
appendCardTitleFilterToDesc,
} from '/models/lib/ruleCardTitleFilter';
// #2345: fallback reference to the live boardTriggers template instance, so the
// card-title-filter popup can still store its value even if the Blaze
// data-context walk in Popup.getOpenerComponent() does not resolve (same
// module-level pattern as cardActions.js' sharedCardColorButtonValue).
let activeBoardTriggersTemplate = null;
// #2345: the trigger description is assembled from the wizard's DOM text, which
// never includes the card-title filter (it lives in a popup). Append it so the
// created rule's details actually show the filter.
function descWithCardTitleFilter(desc, cardTitle) {
let label = 'card title filter';
try {
const translated = TAPi18n.__('boardCardTitlePopup-title');
if (translated && translated !== 'boardCardTitlePopup-title') {
label = translated.toLowerCase();
}
} catch (e) {
// keep the English fallback label
}
return appendCardTitleFilterToDesc(desc, cardTitle, label);
}
Template.boardTriggers.onCreated(function () {
this.provaVar = new ReactiveVar('');
@@ -7,6 +34,13 @@ Template.boardTriggers.onCreated(function () {
this.setNameFilter = (name) => {
this.cardTitleFilters[this.currentPopupTriggerId] = name;
};
activeBoardTriggersTemplate = this;
});
Template.boardTriggers.onDestroyed(function () {
if (activeBoardTriggersTemplate === this) {
activeBoardTriggersTemplate = null;
}
});
Template.boardTriggers.events({
@@ -14,16 +48,24 @@ Template.boardTriggers.events({
const funct = Popup.open('boardCardTitle');
const divId = $(event.currentTarget.parentNode.parentNode).attr('id');
tpl.currentPopupTriggerId = divId;
funct.call(this, event);
// #2345: hand the already-stored filter to the popup as its data context so
// reopening it shows the current value instead of an empty input.
funct.call({ cardTitleFilter: tpl.cardTitleFilters[divId] || '' }, event);
},
'click .js-add-create-trigger'(event, tpl) {
const desc = Utils.getTriggerActionDesc(event, tpl);
const datas = Template.currentData();
const listName = tpl.find('#create-list-name').value;
const swimlaneName = tpl.find('#create-swimlane-name').value;
const boardId = Session.get('currentBoard');
const divId = $(event.currentTarget.parentNode).attr('id');
const cardTitle = tpl.cardTitleFilters[divId];
// #2345: an unset/empty filter is stored as the '*' wildcard so the trigger
// document always carries a cardTitle field (the server matches with
// cardTitle: { $in: [...] }, which a document missing the field never satisfies).
const cardTitle = cardTitleFilterOrWildcard(tpl.cardTitleFilters[divId]);
const desc = descWithCardTitleFilter(
Utils.getTriggerActionDesc(event, tpl),
cardTitle,
);
// move to generic funciont
datas.triggerVar.set({
activityType: 'createCard',
@@ -36,13 +78,16 @@ Template.boardTriggers.events({
},
'click .js-add-moved-trigger'(event, tpl) {
const datas = Template.currentData();
const desc = Utils.getTriggerActionDesc(event, tpl);
const swimlaneName = tpl.find('#create-swimlane-name-2').value;
const actionSelected = tpl.find('#move-action').value;
const listName = tpl.find('#move-list-name').value;
const boardId = Session.get('currentBoard');
const divId = $(event.currentTarget.parentNode).attr('id');
const cardTitle = tpl.cardTitleFilters[divId];
const cardTitle = cardTitleFilterOrWildcard(tpl.cardTitleFilters[divId]);
const desc = descWithCardTitleFilter(
Utils.getTriggerActionDesc(event, tpl),
cardTitle,
);
if (actionSelected === 'moved-to') {
datas.triggerVar.set({
activityType: 'moveCard',
@@ -68,12 +113,22 @@ Template.boardTriggers.events({
},
'click .js-add-gen-moved-trigger'(event, tpl) {
const datas = Template.currentData();
const desc = Utils.getTriggerActionDesc(event, tpl);
const boardId = Session.get('currentBoard');
const divId = $(event.currentTarget.parentNode).attr('id');
// #2345: this trigger ignored the card-title-filter popup entirely AND
// stored no cardTitle field at all — and since the server matches triggers
// with cardTitle: { $in: [...] }, a moveCard trigger without the field
// never fired for any card. Store the filter (or the '*' wildcard).
const cardTitle = cardTitleFilterOrWildcard(tpl.cardTitleFilters[divId]);
const desc = descWithCardTitleFilter(
Utils.getTriggerActionDesc(event, tpl),
cardTitle,
);
datas.triggerVar.set({
activityType: 'moveCard',
boardId,
cardTitle,
swimlaneName: '*',
listName: '*',
oldListName: '*',
@@ -82,13 +137,20 @@ Template.boardTriggers.events({
},
'click .js-add-arch-trigger'(event, tpl) {
const datas = Template.currentData();
const desc = Utils.getTriggerActionDesc(event, tpl);
const actionSelected = tpl.find('#arch-action').value;
const boardId = Session.get('currentBoard');
const divId = $(event.currentTarget.parentNode).attr('id');
// #2345: the archive/unarchive trigger also dropped the card-title filter.
const cardTitle = cardTitleFilterOrWildcard(tpl.cardTitleFilters[divId]);
const desc = descWithCardTitleFilter(
Utils.getTriggerActionDesc(event, tpl),
cardTitle,
);
if (actionSelected === 'archived') {
datas.triggerVar.set({
activityType: 'archivedCard',
boardId,
cardTitle,
desc,
});
}
@@ -96,6 +158,7 @@ Template.boardTriggers.events({
datas.triggerVar.set({
activityType: 'restoredCard',
boardId,
cardTitle,
desc,
});
}
@@ -104,15 +167,27 @@ Template.boardTriggers.events({
Template.boardCardTitlePopup.events({
submit(event) {
// #2345: preventDefault FIRST — if anything below throws, a real form
// submit would reload the page and silently drop the filter.
event.preventDefault();
const title = $(event.target)
.find('.js-card-filter-name')
.val()
.trim();
const opener = Popup.getOpenerComponent();
if (opener?.setNameFilter) {
let opener = null;
try {
opener = Popup.getOpenerComponent();
} catch (e) {
opener = null;
}
if (!opener || typeof opener.setNameFilter !== 'function') {
// #2345: fall back to the live boardTriggers instance when the Blaze
// data-context walk cannot resolve the opener.
opener = activeBoardTriggersTemplate;
}
if (opener && typeof opener.setNameFilter === 'function') {
opener.setNameFilter(title);
}
event.preventDefault();
Popup.back();
},
});
+18 -5
View File
@@ -234,6 +234,15 @@ Template.attachments.onCreated(function () {
this.activeSection = new ReactiveVar('move');
this.storageSettingsSubscription = Meteor.subscribe('attachmentStorageSettings');
this.attachmentStorageSettings = new ReactiveVar(null);
// #6473: the real storage paths only exist on the SERVER (WRITABLE_PATH is a
// server environment variable — process.env in the browser never has it, so
// computing the path client-side always showed the misleading "/data").
this.storagePaths = new ReactiveVar(null);
Meteor.call('getAttachmentStoragePaths', (err, paths) => {
if (!err && paths) {
this.storagePaths.set(paths);
}
});
this.attachmentLimitUnits = new ReactiveVar({
attachmentsUploadMaxBytes: 'mb',
attachmentsDownloadMaxBytes: 'mb',
@@ -537,16 +546,20 @@ Template.attachments.helpers({
isS3Active() {
return Template.instance().activeSection.get() === 's3';
},
// #6473: these paths come from the getAttachmentStoragePaths server method —
// WRITABLE_PATH is a server-side environment variable, so reading
// process.env here in the browser always produced the misleading "/data".
filesystemPath() {
return process.env.WRITABLE_PATH || '/data';
const paths = Template.instance().storagePaths.get();
return paths ? paths.writablePath : '';
},
attachmentsPath() {
const writablePath = process.env.WRITABLE_PATH || '/data';
return `${writablePath}/attachments`;
const paths = Template.instance().storagePaths.get();
return paths ? paths.attachments : '';
},
avatarsPath() {
const writablePath = process.env.WRITABLE_PATH || '/data';
return `${writablePath}/avatars`;
const paths = Template.instance().storagePaths.get();
return paths ? paths.avatars : '';
},
filesystemEnabled() {
const tpl = Template.instance();
+30 -18
View File
@@ -146,21 +146,27 @@ template(name="orgGeneral")
th
| {{_ 'org-shared-templates'}}
br
a.js-org-feature-all(href="#", data-feature="orgSharedTemplates", data-value="true") {{_ 'select-all'}}
| /
a.js-org-feature-all(href="#", data-feature="orgSharedTemplates", data-value="false") {{_ 'unselect-all'}}
a.js-org-feature-all(href="#", data-feature="orgSharedTemplates", data-value="true", title="{{_ 'select-all'}}")
i.fa.fa-check-square-o
|
a.js-org-feature-all(href="#", data-feature="orgSharedTemplates", data-value="false", title="{{_ 'unselect-all'}}")
i.fa.fa-square-o
th
| {{_ 'org-propagate-members-to-boards'}}
br
a.js-org-feature-all(href="#", data-feature="orgPropagateMembersToBoards", data-value="true") {{_ 'select-all'}}
| /
a.js-org-feature-all(href="#", data-feature="orgPropagateMembersToBoards", data-value="false") {{_ 'unselect-all'}}
a.js-org-feature-all(href="#", data-feature="orgPropagateMembersToBoards", data-value="true", title="{{_ 'select-all'}}")
i.fa.fa-check-square-o
|
a.js-org-feature-all(href="#", data-feature="orgPropagateMembersToBoards", data-value="false", title="{{_ 'unselect-all'}}")
i.fa.fa-square-o
th
| {{_ 'org-sync-members-from-auth'}}
br
a.js-org-feature-all(href="#", data-feature="orgSyncMembersFromAuth", data-value="true") {{_ 'select-all'}}
| /
a.js-org-feature-all(href="#", data-feature="orgSyncMembersFromAuth", data-value="false") {{_ 'unselect-all'}}
a.js-org-feature-all(href="#", data-feature="orgSyncMembersFromAuth", data-value="true", title="{{_ 'select-all'}}")
i.fa.fa-check-square-o
|
a.js-org-feature-all(href="#", data-feature="orgSyncMembersFromAuth", data-value="false", title="{{_ 'unselect-all'}}")
i.fa.fa-square-o
tbody
tr
each org in orgList
@@ -187,21 +193,27 @@ template(name="teamGeneral")
th
| {{_ 'team-shared-templates'}}
br
a.js-team-feature-all(href="#", data-feature="teamSharedTemplates", data-value="true") {{_ 'select-all'}}
| /
a.js-team-feature-all(href="#", data-feature="teamSharedTemplates", data-value="false") {{_ 'unselect-all'}}
a.js-team-feature-all(href="#", data-feature="teamSharedTemplates", data-value="true", title="{{_ 'select-all'}}")
i.fa.fa-check-square-o
|
a.js-team-feature-all(href="#", data-feature="teamSharedTemplates", data-value="false", title="{{_ 'unselect-all'}}")
i.fa.fa-square-o
th
| {{_ 'team-propagate-members-to-boards'}}
br
a.js-team-feature-all(href="#", data-feature="teamPropagateMembersToBoards", data-value="true") {{_ 'select-all'}}
| /
a.js-team-feature-all(href="#", data-feature="teamPropagateMembersToBoards", data-value="false") {{_ 'unselect-all'}}
a.js-team-feature-all(href="#", data-feature="teamPropagateMembersToBoards", data-value="true", title="{{_ 'select-all'}}")
i.fa.fa-check-square-o
|
a.js-team-feature-all(href="#", data-feature="teamPropagateMembersToBoards", data-value="false", title="{{_ 'unselect-all'}}")
i.fa.fa-square-o
th
| {{_ 'team-sync-members-from-auth'}}
br
a.js-team-feature-all(href="#", data-feature="teamSyncMembersFromAuth", data-value="true") {{_ 'select-all'}}
| /
a.js-team-feature-all(href="#", data-feature="teamSyncMembersFromAuth", data-value="false") {{_ 'unselect-all'}}
a.js-team-feature-all(href="#", data-feature="teamSyncMembersFromAuth", data-value="true", title="{{_ 'select-all'}}")
i.fa.fa-check-square-o
|
a.js-team-feature-all(href="#", data-feature="teamSyncMembersFromAuth", data-value="false", title="{{_ 'unselect-all'}}")
i.fa.fa-square-o
tbody
tr
each team in teamList
+23 -27
View File
@@ -1171,31 +1171,30 @@ Template.modifyTeamsUsers.events({
selectedEltValue = selectedElt.options[selectedElt.selectedIndex].text;
selectedEltValueId = selectedElt.options[selectedElt.selectedIndex].value;
// #4593: `teams` is a forbidden field for direct client-side Users.update
// (see server/permissions/users.js: only the owner may update, and never
// `teams`), so the previous Users.update() calls here were silently denied
// by the server and the bulk team assignment never persisted — a user
// "added" to a team this way never saw the boards that team is assigned
// to. Use the admin-only `editUser` method instead, which persists the
// change and also grants the user membership of the boards the gained
// team is assigned to.
if(document.getElementById('addAction').checked){
for(let i = 0; i < selectedUserChkBoxUserIds.length; i++){
currentUser = ReactiveCache.getUser(selectedUserChkBoxUserIds[i]);
userTms = currentUser.teams;
if(userTms == undefined || userTms.length == 0){
userTms = [];
// Copy, so the cached minimongo document is not mutated in place.
userTms = (currentUser.teams || []).slice();
currUserTeamIndex = userTms.findIndex(function(t){ return t.teamId == selectedEltValueId});
if(currUserTeamIndex == -1){
userTms.push({
"teamId": selectedEltValueId,
"teamDisplayName": selectedEltValue,
})
}
else if(userTms.length > 0)
{
currUserTeamIndex = userTms.findIndex(function(t){ return t.teamId == selectedEltValueId});
if(currUserTeamIndex == -1){
userTms.push({
"teamId": selectedEltValueId,
"teamDisplayName": selectedEltValue,
});
}
});
}
Users.update(selectedUserChkBoxUserIds[i], {
$set:{
teams: userTms
Meteor.call('editUser', selectedUserChkBoxUserIds[i], { teams: userTms }, (error) => {
if (error) {
console.error('Error updating user teams:', error);
}
});
}
@@ -1203,18 +1202,15 @@ Template.modifyTeamsUsers.events({
else{
for(let i = 0; i < selectedUserChkBoxUserIds.length; i++){
currentUser = ReactiveCache.getUser(selectedUserChkBoxUserIds[i]);
userTms = currentUser.teams;
if(userTms !== undefined || userTms.length > 0)
{
currUserTeamIndex = userTms.findIndex(function(t){ return t.teamId == selectedEltValueId});
if(currUserTeamIndex != -1){
userTms.splice(currUserTeamIndex, 1);
}
userTms = (currentUser.teams || []).slice();
currUserTeamIndex = userTms.findIndex(function(t){ return t.teamId == selectedEltValueId});
if(currUserTeamIndex != -1){
userTms.splice(currUserTeamIndex, 1);
}
Users.update(selectedUserChkBoxUserIds[i], {
$set:{
teams: userTms
Meteor.call('editUser', selectedUserChkBoxUserIds[i], { teams: userTms }, (error) => {
if (error) {
console.error('Error updating user teams:', error);
}
});
}
+8 -2
View File
@@ -117,11 +117,17 @@
}
/* Force tables to always trigger horizontal scrolling */
.setting-content .content-body .main-body table td,
.setting-content .content-body .main-body table th {
.setting-content .content-body .main-body table td {
white-space: nowrap;
min-width: 120px;
}
/* #6465: headers may wrap — nowrap on long header labels (e.g. the org/team
feature columns) blew the column widths up to the whole label length. */
.setting-content .content-body .main-body table th {
white-space: normal;
min-width: 120px;
max-width: 240px;
}
/* Ensure there's enough content to trigger vertical scrolling */
.setting-content .content-body .main-body {
+17 -5
View File
@@ -255,6 +255,14 @@ Template.setting.onCreated(function () {
this.webhookSetting = new ReactiveVar(false);
this.attachmentSettings = new ReactiveVar(false);
this.attachmentStorageSettings = new ReactiveVar(null);
// #6473: real storage paths come from the server (WRITABLE_PATH does not
// exist in the browser's process.env, which always showed "/data").
this.storagePaths = new ReactiveVar(null);
Meteor.call('getAttachmentStoragePaths', (err, paths) => {
if (!err && paths) {
this.storagePaths.set(paths);
}
});
this.attachmentLimitUnits = new ReactiveVar({
attachmentsUploadMaxBytes: 'mb',
attachmentsDownloadMaxBytes: 'mb',
@@ -393,18 +401,22 @@ Template.setting.helpers({
},
// Attachment settings helpers
// #6473: these come from the getAttachmentStoragePaths server method —
// WRITABLE_PATH is a server-side environment variable, so reading
// process.env here in the browser always produced the misleading "/data".
filesystemPath() {
return process.env.WRITABLE_PATH || '/data';
const paths = Template.instance().storagePaths.get();
return paths ? paths.writablePath : '';
},
attachmentsPath() {
const writablePath = process.env.WRITABLE_PATH || '/data';
return `${writablePath}/attachments`;
const paths = Template.instance().storagePaths.get();
return paths ? paths.attachments : '';
},
avatarsPath() {
const writablePath = process.env.WRITABLE_PATH || '/data';
return `${writablePath}/avatars`;
const paths = Template.instance().storagePaths.get();
return paths ? paths.avatars : '';
},
gridfsEnabled() {
+22
View File
@@ -197,6 +197,11 @@ body.grey-icons-enabled .sidebar .sidebar-content ul.sidebar-list li > a .fa.fa-
}
.board-sidebar.is-open {
display: block;
/* #6465 follow-up: the card details window docks to the right edge with
z-index 2001 — the same place this sidebar opens. When the user opens the
sidebar, the sidebar must win, or its content (e.g. the archives
Restore/Delete links) sits unreachable UNDER the card window. */
z-index: 2002;
}
.board-widget h4 {
margin: 5px 0;
@@ -254,6 +259,23 @@ body.grey-icons-enabled .sidebar .sidebar-content ul.sidebar-list li > a .fa.fa-
z-index: 0;
inset-inline-start: 5px;
}
/* #3199: In the Archive sidebar's Cards tab each card's Restore/Delete links
used to sit BETWEEN two archived cards with near-equal spacing, so users
could not tell which card they belonged to. Group each card with its own
links: no gap between the card and its links, and a clear separator gap
below the whole group before the next card. Spacing-only, so it works in
every board color/theme; logical properties keep it RTL-safe. */
.archived-card-item {
margin-block-end: 1.6em;
}
.archived-card-item .minicard-wrapper {
margin-bottom: 0;
}
.archived-card-item p.quiet {
margin-block-start: 2px;
margin-block-end: 0;
padding-inline-start: 4px;
}
.archived-lists .archived-lists-item {
border-top: 1px solid #ccc;
clear: both;
+21 -17
View File
@@ -16,23 +16,27 @@ template(name="archivesSidebar")
| -
a.js-delete-all-cards {{_ 'delete-all'}}
each archivedCards
.minicard-wrapper.js-minicard
+minicard(this)
if currentUser.isBoardMember
unless isWorker
unless currentUser.isReadOnly
unless currentUser.isReadAssignedOnly
p.quiet
if this.archivedAt
| {{_ 'archived-at' }}
| | {{ displayDate this.archivedAt 'LLL' }}
br
a.js-restore-card {{_ 'restore'}}
if currentUser.isBoardAdmin
| -
a.js-delete-card {{_ 'delete'}}
if cardIsInArchivedList
p.quiet.small ({{_ 'warn-list-archived'}})
//- #3199: keep each archived card and ITS Restore/Delete links in
//- one wrapper so the links visually group with the card above
//- them instead of floating ambiguously between two cards.
.archived-card-item
.minicard-wrapper.js-minicard
+minicard(this)
if currentUser.isBoardMember
unless isWorker
unless currentUser.isReadOnly
unless currentUser.isReadAssignedOnly
p.quiet
if this.archivedAt
| {{_ 'archived-at' }}
| | {{ displayDate this.archivedAt 'LLL' }}
br
a.js-restore-card {{_ 'restore'}}
if currentUser.isBoardAdmin
| -
a.js-delete-card {{_ 'delete'}}
if cardIsInArchivedList
p.quiet.small ({{_ 'warn-list-archived'}})
else
p.no-items-message {{_ 'no-archived-cards'}}
+103
View File
@@ -0,0 +1,103 @@
'use strict';
// Pure helpers for keeping jQuery UI sortable's cached drag geometry in sync
// with the real card layout. Extracted so the decision logic is unit-testable
// in plain Node without Meteor (mirrors models/lib/cardSortRepair.js).
//
// #2769 "Card moves to wrong swimlane when moving to target column where a
// new card is being added": jQuery UI sortable snapshots the geometry of
// every connected `.js-minicards` container ONCE at drag start
// (sortable._mouseStart calls refreshPositions() BEFORE it fires the `start`
// callback) and only re-snapshots after its OWN placeholder rearranges. It
// never notices DOM changes made by anyone else. Two such changes routinely
// happen DURING a card drag:
//
// * another user submits the open add-card composer, so Blaze reactively
// inserts the new minicard into a connected list (the issue's "target
// column where a new card is being added"), and
// * the dragging user's own open composer is closed by the `start`
// callback's EscapeActions.executeUpTo('popup-close')
// (client/components/lists/list.js) — i.e. AFTER the snapshot was taken.
//
// Either way, every list and swimlane below the change shifts vertically
// while the cached rectangles stay where they were, so the pointer is matched
// against a stale map: the placeholder is parked in the NEIGHBOURING
// swimlane's copy of the list (which is why the reporter saw no drop shadow
// in the column they were aiming at), and the `stop` handler's
// ui.item.parents('.swimlane') then faithfully reports that wrong swimlane —
// the card "disappears and reappears in the swimlane below".
//
// The wiring lives in client/components/lists/listBody.js (a MutationObserver
// per list body that calls sortable('refresh') on the active drag). The
// decisions worth testing in isolation are below:
// 1. whether a mutation batch represents a REAL layout change (a Blaze
// insertion/removal) as opposed to jQuery UI's own placeholder/helper
// churn, which happens on every mousemove and must not trigger anything,
// and
// 2. which sortable instance (if any) is the active card drag whose
// geometry needs re-caching.
// jQuery UI marks the elements it moves around itself during a drag: the drop
// shadow ("ui-sortable-placeholder") and the dragged clone
// ("ui-sortable-helper"). Their insertions/removals are part of the drag and
// already followed by the library's own refreshPositions; reacting to them
// would just do the same work twice on every mousemove.
function nodeChangesDragGeometry(node) {
if (!node || node.nodeType !== 1) {
// Text/comment nodes: no box of their own worth re-snapshotting for.
return false;
}
const classList = node.classList;
if (!classList || typeof classList.contains !== 'function') {
// An element we cannot classify still occupies layout space.
return true;
}
return (
!classList.contains('ui-sortable-placeholder') &&
!classList.contains('ui-sortable-helper')
);
}
// Does this MutationObserver batch contain at least one real DOM change
// (an element other than jQuery UI's own drag artefacts was added or
// removed)? Only then is the drag geometry snapshot stale.
function mutationsChangeDragGeometry(mutations) {
if (!mutations) return false;
for (let i = 0; i < mutations.length; i += 1) {
const mutation = mutations[i];
if (!mutation || mutation.type !== 'childList') continue;
const added = mutation.addedNodes || [];
const removed = mutation.removedNodes || [];
for (let j = 0; j < added.length; j += 1) {
if (nodeChangesDragGeometry(added[j])) return true;
}
for (let j = 0; j < removed.length; j += 1) {
if (nodeChangesDragGeometry(removed[j])) return true;
}
}
return false;
}
// Given the sortable instances of every card container on the board, return
// the one an active card drag started from — that instance owns the cached
// geometry of ALL connected containers (its refresh() re-collects items and
// re-measures every container). Returns null when no card drag is running,
// e.g. when the observed change was an ordinary reactive update, or the
// leftover DOM churn of sortable('cancel') after the drag already ended
// (sortable sets `dragging` back to false before its stop event fires).
function findActiveCardDrag(instances) {
if (!instances) return null;
for (let i = 0; i < instances.length; i += 1) {
const instance = instances[i];
if (instance && instance.dragging === true && instance.currentItem) {
return instance;
}
}
return null;
}
module.exports = {
nodeChangesDragGeometry,
mutationsChangeDragGeometry,
findActiveCardDrag,
};
+25 -25
View File
@@ -3,11 +3,12 @@ import { ReactiveVar } from 'meteor/reactive-var';
import { ReactiveCache } from '/imports/reactiveCache';
import { getCurrentCardFromContext } from '/client/lib/currentCard';
import { normalizeDigits } from '/imports/lib/dateUtils';
// Helper to check if a date is valid
function isValidDate(date) {
return date instanceof Date && !isNaN(date);
}
import {
isValidDate,
formatTime,
initialTimeValue,
fallbackSubmitTime,
} from '/imports/lib/datePickerTime';
// Format date as YYYY-MM-DD
function formatDate(date) {
@@ -18,14 +19,6 @@ function formatDate(date) {
return `${year}-${month}-${day}`;
}
// Format time as HH:mm
function formatTime(date) {
if (!isValidDate(date)) return '';
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
return `${hours}:${minutes}`;
}
/**
* Sets up datepicker state on a template instance.
* Call from onCreated. Stores state on tpl.datePicker.
@@ -53,18 +46,21 @@ export function setupDatePicker(tpl, { defaultTime = '1970-01-01 08:00:00', init
*/
export function datePickerRendered(tpl) {
const dp = tpl.datePicker;
if (isValidDate(dp.date.get())) {
const dateInput = tpl.find('#date');
const timeInput = tpl.find('#time');
const dateInput = tpl.find('#date');
const timeInput = tpl.find('#time');
if (dateInput) {
dateInput.value = formatDate(dp.date.get());
}
if (timeInput && !timeInput.value && dp.defaultTime) {
const defaultDate = new Date(dp.defaultTime);
timeInput.value = formatTime(defaultDate);
} else if (timeInput && isValidDate(dp.date.get())) {
timeInput.value = formatTime(dp.date.get());
if (dateInput && isValidDate(dp.date.get())) {
dateInput.value = formatDate(dp.date.get());
}
// Pre-fill the time input: an existing card date keeps its own time; a
// card without this date gets the configured default (e.g. 17:00 for due
// dates) instead of an empty field that would silently save as 12:00
// (#1502). The template already fills the input for existing dates, so
// only ever write into an empty input.
if (timeInput && !timeInput.value) {
const initial = initialTimeValue(dp.date.get(), dp.defaultTime);
if (initial) {
timeInput.value = initial;
}
}
}
@@ -147,8 +143,12 @@ export function datePickerEvents({ storeDate, deleteDate }) {
// Normalize any non-Latin digits (e.g. Persian/Arabic-Indic) before
// parsing so due/start/end dates work in those locales (#5752).
// An empty time falls back to the popup's configured default time
// (e.g. 17:00 for due dates), then 12:00 (#1502).
const dateValue = normalizeDigits(evt.target.date.value);
const timeValue = normalizeDigits(evt.target.time.value) || '12:00'; // Default to 12:00 if no time given
const timeValue =
normalizeDigits(evt.target.time.value) ||
fallbackSubmitTime(tpl.datePicker.defaultTime);
if (!dateValue) {
tpl.datePicker.error.set('invalid-date');
+87 -60
View File
@@ -21,7 +21,14 @@ import {
fromNow,
calendar
} from '/imports/lib/dateUtils';
import {
tokenizeAdvancedFilter,
parseAdvancedFilterDate,
buildDateValueSelector,
} from '/imports/lib/advancedFilter';
import { weekRange } from '/models/lib/weekStart';
import { Session } from 'meteor/session';
import { boardScopedFilterSelector } from '/models/lib/boardScopedSelection';
// Sidebar is imported late to avoid circular dependency (sidebar.js needs its
// jade template loaded first, but router.js → filter.js would load it too early)
let _Sidebar;
@@ -322,55 +329,9 @@ class AdvancedFilter {
}
_filterToCommands() {
const commands = [];
let current = '';
let string = false;
let regex = false;
let wasString = false;
let ignore = false;
for (let i = 0; i < this._filter.length; i++) {
const char = this._filter.charAt(i);
if (ignore) {
ignore = false;
current += char;
continue;
}
if (char === '/') {
string = !string;
if (string) regex = true;
current += char;
continue;
}
// eslint-disable-next-line quotes
if (char === "'") {
string = !string;
if (string) wasString = true;
continue;
}
if (char === '\\' && !string) {
ignore = true;
continue;
}
if (char === ' ' && !string) {
commands.push({
cmd: current,
string: wasString,
regex,
});
wasString = false;
current = '';
continue;
}
current += char;
}
if (current !== '') {
commands.push({
cmd: current,
string: wasString,
regex,
});
}
return commands;
// #2989: tokenizing lives in /imports/lib/advancedFilter.js so slashes
// inside quoted values (dates like '06/04/2020') stay literal strings.
return tokenizeAdvancedFilter(this._filter);
}
_fieldNameToId(field) {
@@ -397,6 +358,36 @@ class AdvancedFilter {
return value;
}
// #2989: date custom fields store Date objects (the date picker calls
// card.setCustomField(id, date)), so comparing them against the typed
// string / parseInt() number can never match. When the field is date-typed
// and the value parses as a date, compare with a Date range instead.
// Returns the operator document for 'customFields.value', or null to fall
// back to the generic string/number selector.
_customFieldDateSelector(field, str, op) {
const found = ReactiveCache.getCustomField({
name: field,
});
if (!found || found.type !== 'date') return null;
// Disambiguate '06/04/2020' (both parts <= 12) with the user's date
// format preference: day-first formats (DD/MM/YYYY, DD.MM.YYYY) read it
// as 6 April, otherwise it is read month-first as 4 June.
let dayFirst = false;
try {
const user = ReactiveCache.getCurrentUser();
const dateFormat =
user && typeof user.getDateFormat === 'function'
? user.getDateFormat()
: 'YYYY-MM-DD';
dayFirst = /^D/.test(dateFormat);
} catch (error) {
dayFirst = false;
}
const range = parseAdvancedFilterDate(str, { dayFirst });
if (!range) return null;
return buildDateValueSelector(op, range);
}
_arrayToSelector(commands) {
try {
//let changed = false;
@@ -471,7 +462,11 @@ class AdvancedFilter {
} else {
commands[i] = {
'customFields._id': this._fieldNameToId(field),
'customFields.value': {
'customFields.value': this._customFieldDateSelector(
field,
str,
commands[i].cmd,
) || {
$in: [this._fieldValueToId(field, str), parseInt(str, 10)],
},
};
@@ -500,7 +495,11 @@ class AdvancedFilter {
} else {
commands[i] = {
'customFields._id': this._fieldNameToId(field),
'customFields.value': {
'customFields.value': this._customFieldDateSelector(
field,
str,
commands[i].cmd,
) || {
$not: {
$in: [this._fieldValueToId(field, str), parseInt(str, 10)],
},
@@ -521,7 +520,11 @@ class AdvancedFilter {
const str = commands[i + 1].cmd;
commands[i] = {
'customFields._id': this._fieldNameToId(field),
'customFields.value': {
'customFields.value': this._customFieldDateSelector(
field,
str,
commands[i].cmd,
) || {
$gt: parseInt(str, 10),
},
};
@@ -540,7 +543,11 @@ class AdvancedFilter {
const str = commands[i + 1].cmd;
commands[i] = {
'customFields._id': this._fieldNameToId(field),
'customFields.value': {
'customFields.value': this._customFieldDateSelector(
field,
str,
commands[i].cmd,
) || {
$gte: parseInt(str, 10),
},
};
@@ -558,7 +565,11 @@ class AdvancedFilter {
const str = commands[i + 1].cmd;
commands[i] = {
'customFields._id': this._fieldNameToId(field),
'customFields.value': {
'customFields.value': this._customFieldDateSelector(
field,
str,
commands[i].cmd,
) || {
$lt: parseInt(str, 10),
},
};
@@ -577,7 +588,11 @@ class AdvancedFilter {
const str = commands[i + 1].cmd;
commands[i] = {
'customFields._id': this._fieldNameToId(field),
'customFields.value': {
'customFields.value': this._customFieldDateSelector(
field,
str,
commands[i].cmd,
) || {
$lte: parseInt(str, 10),
},
};
@@ -772,11 +787,23 @@ export const Filter = {
mongoSelector(additionalSelector) {
const filterSelector = this._getMongoSelector();
if (additionalSelector === undefined) return filterSelector;
else
return {
$and: [filterSelector, additionalSelector],
};
if (additionalSelector === undefined) {
// #2306: a call without an additional selector means "all cards
// matching the filter" (e.g. the filter sidebar's "To selection"
// button). The client cache may also hold cards from OTHER boards
// (a board being navigated away from, linked-board subscriptions,
// notifications, popup card data, ...), so scope the query to the
// board currently being viewed. Callers that pass an additional
// selector are already scoped to a list/swimlane/card of the current
// board.
return boardScopedFilterSelector(
filterSelector,
Session.get('currentBoard'),
);
}
return {
$and: [filterSelector, additionalSelector],
};
},
reset() {
+11 -8
View File
@@ -56,15 +56,18 @@ Meteor.startup(async () => {
navigator.userLanguage,
].filter(Boolean);
if (language) {
// Try with potentially complex language tag
if (TAPi18n.isLanguageSupported(language)) {
TAPi18n.setLanguage(language);
} else if (language.includes('-')) {
// Fallback to a general language
const [general] = language.split('-');
if (TAPi18n.isLanguageSupported(general)) {
TAPi18n.setLanguage(general);
// Match the browser tag, then progressively strip trailing subtags until a supported
// language is found: e.g. 'zh-Hans-CN' -> 'zh-Hans', 'zh-Hant-TW' -> 'zh-Hant',
// 'ja-JP' -> 'ja-JP', bare 'zh' -> 'zh-Hans' (via alias). isLanguageSupported is
// case-insensitive, so 'zh-hant' / 'JA-JP' etc. also match.
let candidate = language;
while (candidate) {
if (TAPi18n.isLanguageSupported(candidate)) {
TAPi18n.setLanguage(candidate);
break;
}
const cut = candidate.lastIndexOf('-');
candidate = cut > 0 ? candidate.slice(0, cut) : '';
}
}
});
+77
View File
@@ -0,0 +1,77 @@
'use strict';
// Pure state transitions for the "only one inlined form open at a time"
// invariant — extracted so it is unit-testable without a DOM / Meteor
// (see tests/inlinedFormSingleOpen.test.cjs).
//
// #2418 ("Checklist item gets overwritten by previous item when selecting
// another item with mouse"): opening a checklist item's edit form while
// another item was already in edit mode did not close the previous form.
// With two edit forms open at once, the submit handlers (which locate the
// textarea with a template-wide `tpl.find('textarea.js-edit-checklist-item')`,
// i.e. FIRST match in DOM order) read the OTHER form's textarea and
// overwrote the submitted item with the previous item's text.
//
// Root cause in current code: the `.js-open-inlined-form` click handler
// tried to close the previously opened form with
// `EscapeActions.clickExecute(evt.target, 'inlinedForm')`, but the
// 'inlinedForm' escape action is registered with `enabledOnClick: false`,
// and EscapeActions._execute skips such actions for click executions
// (`isEnabled = enabledOnClick || !isClick`). So the call was silently a
// no-op and the previous form stayed open. (Regression from 8c3ce4bb7,
// 2021-10-19, which replaced `EscapeActions.executeUpTo('inlinedForm')`
// with `clickExecute` to stop popups from closing.)
//
// A secondary corruption: the close/submit/destroy paths reset the shared
// `currentlyOpenedForm` tracker UNCONDITIONALLY, so closing a stale form
// (e.g. checklists' "click all .js-close-inlined-form" workaround) nulled
// the tracker for a DIFFERENT, still-open form — after which Escape no
// longer closed the open form but fell through to closing the whole
// card-details pane.
//
// The functions below centralize the transitions and fix both problems:
// - openForm() explicitly closes the previously tracked form, without
// touching popups (preserving the 8c3ce4bb7 intent).
// - closeForm()/forgetForm() only reset the tracker when the form being
// closed/destroyed IS the tracked one.
//
// `tracker` is a ReactiveVar-like object ({ get(), set(v) }) holding the
// currently opened form; a "form" is any object with an `isOpen`
// ReactiveVar-like property.
/** Open `form`, closing the previously tracked form (if any and different). */
function openForm(tracker, form) {
const previous = tracker.get();
if (previous && previous !== form && previous.isOpen) {
previous.isOpen.set(false);
}
if (form && form.isOpen) {
form.isOpen.set(true);
}
tracker.set(form);
}
/**
* Close `form`. Resets the tracker ONLY when `form` is the tracked one, so
* closing a stale/already-closed form cannot orphan another open form.
*/
function closeForm(tracker, form) {
if (form && form.isOpen) {
form.isOpen.set(false);
}
if (tracker.get() === form) {
tracker.set(null);
}
}
/**
* Stop tracking `form` without touching its own state (template destroyed).
* Only resets the tracker when `form` is the tracked one.
*/
function forgetForm(tracker, form) {
if (tracker.get() === form) {
tracker.set(null);
}
}
module.exports = { openForm, closeForm, forgetForm };
+19 -11
View File
@@ -16,6 +16,11 @@ import { Template } from 'meteor/templating';
import { ReactiveVar } from 'meteor/reactive-var';
import { Tracker } from 'meteor/tracker';
import { EscapeActions } from '/client/lib/escapeActions';
import {
openForm,
closeForm,
forgetForm,
} from '/client/lib/inlinedFormManager';
// We can only have one inlined form element opened at a time
const currentlyOpenedForm = new ReactiveVar(null);
@@ -44,7 +49,9 @@ Template.inlinedForm.onRendered(function () {
});
Template.inlinedForm.onDestroyed(function () {
currentlyOpenedForm.set(null);
// Only reset the tracker if THIS instance is the tracked one; destroying
// an unrelated instance must not orphan another still-open form.
forgetForm(currentlyOpenedForm, this);
});
Template.inlinedForm.helpers({
@@ -55,14 +62,19 @@ Template.inlinedForm.helpers({
Template.inlinedForm.events({
'click .js-close-inlined-form'(evt, tpl) {
tpl.isOpen.set(false);
currentlyOpenedForm.set(null);
closeForm(currentlyOpenedForm, tpl);
},
'click .js-open-inlined-form'(evt, tpl) {
evt.preventDefault();
EscapeActions.clickExecute(evt.target, 'inlinedForm');
tpl.isOpen.set(true);
currentlyOpenedForm.set(tpl);
// #2418: clickExecute above does NOT close the previously opened form:
// the 'inlinedForm' escape action is registered with
// `enabledOnClick: false`, so click executions skip it. With the old
// form left open, submitting the new one located the wrong textarea
// (template-wide first match) and overwrote the item with the previous
// item's text. Close the previous form explicitly instead (this keeps
// popups open, which is why clickExecute replaced executeUpTo here).
openForm(currentlyOpenedForm, tpl);
},
'keydown form textarea'(evt, tpl) {
if (evt.keyCode === 13 && (evt.metaKey || evt.ctrlKey)) {
@@ -73,8 +85,7 @@ Template.inlinedForm.events({
const data = Template.currentData();
if (data.autoclose !== false) {
Tracker.afterFlush(() => {
tpl.isOpen.set(false);
currentlyOpenedForm.set(null);
closeForm(currentlyOpenedForm, tpl);
});
}
},
@@ -86,10 +97,7 @@ EscapeActions.register(
() => {
const form = currentlyOpenedForm.get();
if (form) {
if (form.isOpen) {
form.isOpen.set(false);
currentlyOpenedForm.set(null);
}
closeForm(currentlyOpenedForm, form);
}
},
() => {
+20 -3
View File
@@ -1,8 +1,13 @@
import { ReactiveVar } from 'meteor/reactive-var';
import { Session } from 'meteor/session';
import { ReactiveCache } from '/imports/reactiveCache';
import { Filter } from '/client/lib/filter';
import { EscapeActions } from '/client/lib/escapeActions';
import { Utils } from '/client/lib/utils';
import {
boardScopedSelectionSelector,
cardIdsOnBoard,
} from '/models/lib/boardScopedSelection';
// Late-bind Sidebar to avoid circular dependency (sidebar.js needs its template first)
let _Sidebar;
@@ -78,9 +83,15 @@ export const MultiSelection = {
},
getMongoSelector() {
return Filter.mongoSelector({
_id: { $in: this._selectedCards.get() },
});
// #2306: scope the selection to the board currently being viewed so bulk
// actions (archive, move, label, ...) never touch cards that were
// selected on a previously visited board.
return Filter.mongoSelector(
boardScopedSelectionSelector(
this._selectedCards.get(),
Session.get('currentBoard'),
),
);
},
isActive() {
@@ -147,6 +158,12 @@ export const MultiSelection = {
toggle(cardIds, options = {}) {
cardIds = typeof cardIds === 'string' ? [cardIds] : cardIds;
// #2306: never let cards that verifiably live on ANOTHER board enter the
// selection (e.g. handed over by a caller that queried the client card
// cache without a board scope).
cardIds = cardIdsOnBoard(cardIds, Session.get('currentBoard'), id =>
ReactiveCache.getCard(id),
);
options = {
add: true,
remove: true,
+15 -2
View File
@@ -67,14 +67,27 @@ describe('subtaskNavTarget (#3743)', function() {
expect(target.cardId).to.not.equal(parentCard._id);
});
it('returns undefined when the subtask board is not loaded yet (#4762)', function() {
it('falls back to the subtask boardId when its board is not loaded (#1853/#4762)', function() {
// The deposit/target board is often ANOTHER board that is not in
// minimongo while the parent board is open; navigation must still work
// (the card route loads the board), it must not throw or no-op.
const subtask = makeSubtask();
subtask.board = () => undefined;
expect(subtaskNavTarget(subtask)).to.equal(undefined);
const target = subtaskNavTarget(subtask);
expect(target.boardId).to.equal('subtaskBoardId');
expect(target.slug).to.equal('board');
expect(target.cardId).to.equal('subtaskRealId');
});
it('returns undefined for a missing subtask', function() {
expect(subtaskNavTarget(undefined)).to.equal(undefined);
expect(subtaskNavTarget(null)).to.equal(undefined);
});
it('returns undefined for a broken subtask with no board reference at all', function() {
const subtask = makeSubtask();
subtask.board = () => undefined;
subtask.boardId = undefined;
expect(subtaskNavTarget(subtask)).to.equal(undefined);
});
});
+8 -11
View File
@@ -5,6 +5,7 @@ import { findWhere, where, uniqBy, groupBy, indexBy, debounce, once } from '/imp
import Settings from '/models/settings';
import Users from '/models/users';
import { computeBoardBackground } from '/models/lib/boardBackground';
import { buildCardAttachmentMeta } from '/models/lib/attachmentMeta';
export const Utils = {
async setBackgroundImage(url) {
@@ -595,18 +596,14 @@ export const Utils = {
})
);
},
// Shared by every card attachment upload path — the card Attachments popup,
// the clipboard upload AND images uploaded inside card comments through the
// rich text editor (client/components/main/editor.js). Keeping the meta
// identical (same meta.cardId) is what makes comment attachments appear in
// the card's Attachments list (#3843); the actual logic lives in
// models/lib/attachmentMeta.js so it can be unit tested.
getCommonAttachmentMetaFrom(card) {
const meta = {};
if (card.isLinkedCard()) {
meta.boardId = ReactiveCache.getCard(card.linkedId).boardId;
meta.cardId = card.linkedId;
} else {
meta.boardId = card.boardId;
meta.swimlaneId = card.swimlaneId;
meta.listId = card.listId;
meta.cardId = card._id;
}
return meta;
return buildCardAttachmentMeta(card, id => ReactiveCache.getCard(id));
},
// Collection helpers (replacing underscore.js)
findWhere,
+4 -2
View File
@@ -686,13 +686,15 @@ services:
# When true, sync a user's LDAP groups as Wekan Organizations.
#- LDAP_SYNC_ORGANIZATIONS=false
#
# Comma separated allowlist of LDAP group names to sync as Organizations. Empty = all of the user's groups.
# Comma separated allowlist of LDAP group names/patterns to sync as Organizations.
# Wildcards supported: * (any chars), ? (single char). Empty = all of the user's groups.
#- LDAP_SYNC_ORGANIZATIONS_GROUPS=
#
# When true, sync a user's LDAP groups as Wekan Teams.
#- LDAP_SYNC_TEAMS=false
#
# Comma separated allowlist of LDAP group names to sync as Teams. Empty = all of the user's groups.
# Comma separated allowlist of LDAP group names/patterns to sync as Teams.
# Wildcards supported: * (any chars), ? (single char). Empty = all of the user's groups.
#- LDAP_SYNC_TEAMS_GROUPS=
#---------------------------------------------------------------------
# Login to LDAP automatically with HTTP header.
+4 -2
View File
@@ -920,13 +920,15 @@ services:
# When true, sync a user's LDAP groups as Wekan Organizations.
#- LDAP_SYNC_ORGANIZATIONS=false
#
# Comma separated allowlist of LDAP group names to sync as Organizations. Empty = all of the user's groups.
# Comma separated allowlist of LDAP group names/patterns to sync as Organizations.
# Wildcards supported: * (any chars), ? (single char). Empty = all of the user's groups.
#- LDAP_SYNC_ORGANIZATIONS_GROUPS=
#
# When true, sync a user's LDAP groups as Wekan Teams.
#- LDAP_SYNC_TEAMS=false
#
# Comma separated allowlist of LDAP group names to sync as Teams. Empty = all of the user's groups.
# Comma separated allowlist of LDAP group names/patterns to sync as Teams.
# Wildcards supported: * (any chars), ? (single char). Empty = all of the user's groups.
#- LDAP_SYNC_TEAMS_GROUPS=
#---------------------------------------------------------------------
# Login to LDAP automatically with HTTP header.
+4 -2
View File
@@ -713,13 +713,15 @@ services:
# When true, sync a user's LDAP groups as Wekan Organizations.
#- LDAP_SYNC_ORGANIZATIONS=false
#
# Comma separated allowlist of LDAP group names to sync as Organizations. Empty = all of the user's groups.
# Comma separated allowlist of LDAP group names/patterns to sync as Organizations.
# Wildcards supported: * (any chars), ? (single char). Empty = all of the user's groups.
#- LDAP_SYNC_ORGANIZATIONS_GROUPS=
#
# When true, sync a user's LDAP groups as Wekan Teams.
#- LDAP_SYNC_TEAMS=false
#
# Comma separated allowlist of LDAP group names to sync as Teams. Empty = all of the user's groups.
# Comma separated allowlist of LDAP group names/patterns to sync as Teams.
# Wildcards supported: * (any chars), ? (single char). Empty = all of the user's groups.
#- LDAP_SYNC_TEAMS_GROUPS=
#---------------------------------------------------------------------
# Login to LDAP automatically with HTTP header.
+8
View File
@@ -46,6 +46,14 @@ When calling a production Wekan server, ensure it is running via HTTPS and has a
| `POST` | `/api/boards/:boardId/lists/:listId/cards` | [Add a card to a list, board, and swimlane.](Cards.md#add-card-to-list-board-swimlane) |
| `PUT` | `/api/boards/:boardId/lists/:fromListId/cards/:cardId` | [Update a card.](Cards.md#update-a-card) |
| `DELETE` | `/api/boards/:boardId/lists/:listId/cards/:cardId` | [Delete a card.](Cards.md#update-a-card) |
### Rules (Board Automation / IFTTT)
| HTTP Method | Url | Short Description |
| :--- | :--- | :--- |
| `GET` | `/api/boards/:boardId/rules` | [List all automation rules of a board.](Rules.md#list-rules) |
| `GET` | `/api/boards/:boardId/rules/:ruleId` | [Get one rule with its trigger and action.](Rules.md#get-one-rule) |
| `POST` | `/api/boards/:boardId/rules` | [Add an automation rule, e.g. add/remove a member when a card is moved to/from a list (#2674).](Rules.md#add-a-rule) |
| `PUT` | `/api/boards/:boardId/rules/:ruleId` | [Edit a rule's title, trigger and/or action.](Rules.md#edit-a-rule) |
| `DELETE` | `/api/boards/:boardId/rules/:ruleId` | [Remove a rule and its trigger and action.](Rules.md#delete-a-rule) |
### Board Domain Sharing
| HTTP Method | Url | Short Description |
| :--- | :--- | :--- |
+185
View File
@@ -0,0 +1,185 @@
# Rules (Board Automation / IFTTT) REST API
Board automation rules ("IFTTT rules") link a **trigger** (an event on the
board) to an **action** (what happens to the card/board). The REST API embeds
the full trigger and action inline, so a rule is self-contained.
This API makes the workflow of
[issue #2674](https://github.com/wekan/wekan/issues/2674) scriptable: add a
user to a card when it is moved **to** a list, and remove the user again when
the card is moved **away from** that list.
## Summary
| HTTP Method | Url | Short Description |
| :--- | :--- | :--- |
| `GET` | `/api/boards/:boardId/rules` | List all automation rules of a board |
| `GET` | `/api/boards/:boardId/rules/:ruleId` | Get one rule (with its trigger and action) |
| `POST` | `/api/boards/:boardId/rules` | Add an automation rule |
| `PUT` | `/api/boards/:boardId/rules/:ruleId` | Edit a rule's title, trigger and/or action |
| `DELETE` | `/api/boards/:boardId/rules/:ruleId` | Remove a rule (and its trigger and action) |
All endpoints require a `Bearer` token; write endpoints require board write
access (BoardAdmin).
## Trigger matching and the `*` wildcard
The rule engine matches an incoming board activity against **every** matching
field of the trigger's `activityType` (for example `moveCard` matches on
`boardId`, `listName`, `oldListName`, `userId`, `swimlaneName`, `cardTitle`).
A field set to `'*'` matches anything.
You only need to supply the fields you want to constrain: any matching field
missing from the trigger you POST/PUT is stored as the `'*'` wildcard
automatically. (Before this normalization existed, an API-created trigger
that omitted a field such as `userId` could never match any activity, so the
rule silently never fired — the bug reported in issue #2674.)
### Trigger `activityType` values
| `activityType` | fires when | matching fields |
| :--- | :--- | :--- |
| `createCard` | a card is created | `boardId`, `listName`, `userId`, `swimlaneName`, `cardTitle` |
| `moveCard` | a card is moved to/from a list or swimlane | `boardId`, `listName` (destination), `oldListName` (source), `userId`, `swimlaneName`, `cardTitle` |
| `archivedCard` / `restoredCard` | a card is archived / unarchived | `boardId`, `userId`, `cardTitle` |
| `joinMember` / `unjoinMember` | a member is added to / removed from a card | `boardId`, `username`, `userId` |
| `addChecklist` / `removeChecklist` / `completeChecklist` / `uncompleteChecklist` | checklist events | `boardId`, `checklistName`, `userId` |
| `addedChecklistItem` / `removedChecklistItem` / `checkedItem` / `uncheckedItem` | checklist item events | `boardId`, `checklistItemName`, `userId` |
| `addAttachment` / `deleteAttachment` | attachment events | `boardId`, `userId` |
| `addedLabel` / `removedLabel` | label events | `boardId`, `labelId`, `userId` |
| `scheduledTrigger` | time-based (due/aging/recurring); see `scheduleKind`, `days`, `atTime` | evaluated by the scheduler, not by activities |
For a card moved **to** a list, constrain `listName` (the destination list's
title). For a card moved **away from** a list, constrain `oldListName` (the
source list's title) and leave `listName` as `'*'`.
### Action `actionType` values
`moveCardToTop`, `moveCardToBottom`, `sendEmail`, `setDate`, `updateDate`,
`removeDate`, `setDateRelative`, `archive`, `unarchive`, `setColor`,
`addLabel`, `removeLabel`, `addMember`, `removeMember`, `checkAll`,
`uncheckAll`, `checkItem`, `uncheckItem`, `addChecklist`, `removeChecklist`,
`addChecklistWithItems`, `addSwimlane`, `createCard`, `linkCard`,
`markCardComplete`, `markCardIncomplete`, `sortList`, `moveAllCardsInList`.
The member actions take a `username`:
* `{"actionType": "addMember", "username": "someuser"}` — add the user to the card
* `{"actionType": "removeMember", "username": "someuser"}` — remove the user from the card
* `{"actionType": "removeMember", "username": "*"}` — remove **all** members from the card
## List rules
```shell
curl -H "Authorization: Bearer TOKEN" \
-X GET \
http://localhost:3000/api/boards/BOARDID/rules
```
## Get one rule
```shell
curl -H "Authorization: Bearer TOKEN" \
-X GET \
http://localhost:3000/api/boards/BOARDID/rules/RULEID
```
Result example:
```json
{
"_id": "8gDW2AtwbpNbqSyEw",
"title": "Remove member when moved away from Doing",
"trigger": {
"activityType": "moveCard",
"listName": "*",
"oldListName": "Doing",
"swimlaneName": "*",
"cardTitle": "*",
"userId": "*"
},
"action": {
"actionType": "removeMember",
"username": "someuser"
}
}
```
## Add a rule
```shell
curl -H "Authorization: Bearer TOKEN" \
-H "Content-type: application/json" \
-X POST \
http://localhost:3000/api/boards/BOARDID/rules \
-d '{
"title": "Add member when moved to Doing",
"trigger": { "activityType": "moveCard", "listName": "Doing" },
"action": { "actionType": "addMember", "username": "someuser" }
}'
```
### Full example: issue #2674 workflow
Add the user when a card is moved **to** the list "Doing", remove the user
again when the card is moved **away from** "Doing":
```shell
# Rule 1: card moved TO "Doing" -> add member
curl -H "Authorization: Bearer TOKEN" -H "Content-type: application/json" -X POST \
http://localhost:3000/api/boards/BOARDID/rules \
-d '{ "title": "Add member on move to Doing",
"trigger": { "activityType": "moveCard", "listName": "Doing" },
"action": { "actionType": "addMember", "username": "someuser" } }'
# Rule 2: card moved AWAY FROM "Doing" -> remove member
curl -H "Authorization: Bearer TOKEN" -H "Content-type: application/json" -X POST \
http://localhost:3000/api/boards/BOARDID/rules \
-d '{ "title": "Remove member on move from Doing",
"trigger": { "activityType": "moveCard", "oldListName": "Doing" },
"action": { "actionType": "removeMember", "username": "someuser" } }'
```
The omitted trigger fields (`listName` in rule 2, `oldListName` in rule 1,
plus `userId`, `swimlaneName`, `cardTitle`) are stored as `'*'` wildcards.
## Edit a rule
Any of `title`, `trigger` and `action` may be supplied; a supplied trigger or
action document replaces the stored fields. When the supplied trigger includes
an `activityType`, its missing matching fields are defaulted to `'*'` too.
```shell
curl -H "Authorization: Bearer TOKEN" \
-H "Content-type: application/json" \
-X PUT \
http://localhost:3000/api/boards/BOARDID/rules/RULEID \
-d '{ "action": { "actionType": "removeMember", "username": "*" } }'
```
## Delete a rule
Removes the rule together with its trigger and action documents.
```shell
curl -H "Authorization: Bearer TOKEN" \
-X DELETE \
http://localhost:3000/api/boards/BOARDID/rules/RULEID
```
## Python CLI (api.py)
The bundled `api.py` exposes the same capability:
```shell
python3 api.py listrules BOARDID
python3 api.py getrule BOARDID RULEID
python3 api.py addrule BOARDID 'TITLE' 'TRIGGER_JSON' 'ACTION_JSON'
python3 api.py editrule BOARDID RULEID 'PATCH_JSON'
python3 api.py removerule BOARDID RULEID
# Issue #2674: remove a user from the card when it is moved away from a list
python3 api.py addrule BOARDID 'Remove member on move from Doing' \
'{"activityType":"moveCard","oldListName":"Doing"}' \
'{"actionType":"removeMember","username":"someuser"}'
```
+29
View File
@@ -1,3 +1,32 @@
## Built-in: WeKan cpu-exec runs binaries with qemu-user automatically
Since WeKan 9.96 (issue [#6458](https://github.com/wekan/wekan/issues/6458)), WeKan ships a general
`cpu-exec` helper on every Linux platform — in the Snap (`$SNAP/bin/cpu-exec`), in every
`wekan-<version>-<arch>.zip` bundle (`bundle/cpu-exec`, next to a same-arch `qemu-<arch>` static
binary), in the Docker image (`/build/cpu-exec`) and in the Sandstorm .spk. It checks
`/proc/cpuinfo` for the CPU features a binary needs and, when one is missing, transparently re-runs
the binary through qemu-user (which implements the full modern instruction set):
```
cpu-exec --features x86_64=avx,aarch64=atomics mongod --dbpath ...
```
- With no `--features` (or no entry for the current architecture) it is a plain `exec` — zero
overhead, safe for every binary.
- `WEKAN_REQUIRED_CPU_FEATURES` (same syntax) overrides `--features`, so any script or user can
declare requirements without editing commands.
- qemu-user lookup order: `$WEKAN_QEMU_USER`, `qemu-<arch>` next to cpu-exec (the bundle),
`$SNAP/qemu-<arch>`, the Snap's `migratemongo/avx/qemu-x86_64`, then `qemu-<arch>`/
`qemu-<arch>-static` on `$PATH` (install with `sudo apt install qemu-user-static`).
- `aarch64=atomics` (LSE, ARMv8.1) is the practical `/proc/cpuinfo` proxy for MongoDB's ARMv8.2-A
requirement: Raspberry Pi 3/4 (Cortex-A53/A72) lack it, ARMv8.2-A cores have it.
The Snap's `mongodb-control` and `migration-control` run every `mongod 7` invocation through
cpu-exec, so WeKan's MongoDB works (slower) on CPUs without AVX — including hypervisors/sandboxes
that mask AVX — and the MongoDB → FerretDB migration can read modern MongoDB data there too.
FerretDB (pure Go + SQLite) needs no special CPU features and is the native-speed alternative:
`snap run wekan.migrate`.
## Meteor podcast about using MongoDB at unsupported CPUs
- https://www.youtube.com/watch?v=bnU9bUVeN04
+14
View File
@@ -1,3 +1,17 @@
## Built-in: WeKan cpu-exec does this automatically
Since WeKan 9.96, the manual wrapper below is built in: every Linux WeKan bundle/Snap/Docker
image ships a general `cpu-exec` helper (plus a same-arch `qemu-<arch>` static binary in the
bundles) that runs any binary through qemu-user automatically when the CPU lacks features the
binary needs — e.g. MongoDB 5+ on Raspberry Pi 4 and older (ARMv8.0, no ARMv8.2-A):
```
cpu-exec --features x86_64=avx,aarch64=atomics mongod --config /etc/mongod.conf
```
See [mongodb-avx-qemu.md](mongodb-avx-qemu.md) for details. The manual steps below still work
for a system-wide MongoDB outside WeKan.
## Meteor podcast about using MongoDB at unsupported CPUs
- https://www.youtube.com/watch?v=bnU9bUVeN04
+12 -4
View File
@@ -179,12 +179,15 @@ Source). On Snap use the lower-case dash-separated equivalent (for example
- `LDAP_SYNC_ORGANIZATIONS` (default `false`) — when `true`, a user's LDAP groups
are synced into that user's Wekan **Organizations**.
- `LDAP_SYNC_ORGANIZATIONS_GROUPS` (default empty) — comma-separated list of LDAP
group names to sync as Organizations. Leave empty to sync all of the user's
groups.
group names/patterns to sync as Organizations. Leave empty to sync all of the
user's groups. Supports wildcards: `*` (any number of characters) and `?`
(single character).
- `LDAP_SYNC_TEAMS` (default `false`) — when `true`, a user's LDAP groups are
synced into that user's Wekan **Teams**.
- `LDAP_SYNC_TEAMS_GROUPS` (default empty) — comma-separated list of LDAP group
names to sync as Teams. Leave empty to sync all of the user's groups.
names/patterns to sync as Teams. Leave empty to sync all of the user's
groups. Supports wildcards: `*` (any number of characters) and `?` (single
character).
Notes:
@@ -382,7 +385,12 @@ services:
# LDAP_BACKGROUND_SYNC_IMPORT_NEW_USERS :
# example : LDAP_BACKGROUND_SYNC_IMPORT_NEW_USERS=true
- LDAP_BACKGROUND_SYNC_IMPORT_NEW_USERS=false
# LDAP_ENCRYPTION : If using LDAPS
# LDAP_ENCRYPTION : Connection encryption. Accepted values:
# 'true' : LDAPS, TLS from the first byte (usually port 636)
# 'starttls' : connect unencrypted (usually port 389), then upgrade with STARTTLS
# 'false' : no encryption (default; strongly advised against)
# Deprecated but still working: 'ssl' (same as 'true'), 'tls' (same as 'starttls').
# Any other value logs a warning and means no encryption.
# example : LDAP_ENCRYPTION=true
- LDAP_ENCRYPTION=false
# LDAP_CA_CERT : The certification for the LDAPS server
+2 -2
View File
@@ -10,7 +10,7 @@ This is without container (without Docker or Snap).
Right click and download files 1-4:
1. [wekan-9.90-win64.zip](https://github.com/wekan/wekan/releases/download/v9.90/wekan-9.90-win64.zip) or newest available at https://github.com/wekan/wekan/releases/
1. [wekan-9.97-win64.zip](https://github.com/wekan/wekan/releases/download/v9.97/wekan-9.97-win64.zip) or newest available at https://github.com/wekan/wekan/releases/
2. [node.exe](https://nodejs.org/dist/latest-v24.x/win-x64/node.exe)
@@ -22,7 +22,7 @@ Right click and download files 1-4:
6. Double click `mongodb-windows-x86_64-7.0.34-signed.msi` . In installer, uncheck downloading MongoDB compass.
7. Unzip `wekan-9.90-win64.zip` , inside it is directory `bundle`, to it copy other files:
7. Unzip `wekan-9.97-win64.zip` , inside it is directory `bundle`, to it copy other files:
```
bundle (directory)
+10 -10
View File
@@ -599,22 +599,22 @@
"import-board-instruction-openproject": "Einfügen von OpenProjekt work-pagages JSON (GET /api/v3/work_packages). Status wird zu Listen und work pagages werden zu Karten.",
"import-board-instruction-issues": "Einfügen einer __sourceName__ Vorfälle JSON Liste(__endpoint__). Vorfälle werden zu Karten in Offen / Geschlossen Listen gruppiert.",
"import-board-instruction-asana": "Einfügen einer Asana Aufgaben Export JSON ({ \"data\": [...] } vom Asana Export oder GET /tasks). Aufgaben werden in Abschnitte gruppiert (memberships); abgeschlossene Aufgaben kommen in Erledigt.",
"import-board-instruction-zenkit": "Paste a ZenKit list export JSON ({ \"title\", \"stages\":[...], \"items\":[...] }). Stages become lists and items become cards.",
"import-board-instruction-zenkit": "Einfügen eines ZenKit Listen Export JSON ({ \"title\", \"stages\":[...], \"items\":[...] }). Aus Stapeln werden Listen und aus Items werden Karten.",
"import-board-instruction-trello": "Gehen Sie in ihrem Trello-Board auf 'Menü', dann 'Mehr', 'Drucken und Exportieren', 'JSON-Export' und kopieren Sie den dort angezeigten Text",
"import-board-instruction-csv": "Fügen Sie die Ihre Comma-Separated- (CSV) / bzw. Tab-Separated-Values (TSV) ein.",
"import-board-instruction-jira": "Paste the JSON from the Jira Cloud REST API issue search (GET /rest/api/2/search), or an equivalent { \"issues\": [...] } object. Jira statuses become lists and issues become cards. Optionally include an \"automationRules\" array to import rules.",
"import-board-instruction-excel": "Choose a WeKan-style .xlsx spreadsheet (the same columns as the Excel export: Title, Description, Status/List, Members, Labels, dates, custom fields). The first row is the header.",
"import-excel-file": "Excel file (.xlsx)",
"import-board-instruction-jira": "Einfügen des JSON von der Jira Cloud API Issue Suche (GET /rest/api/2/search), oder gleichwertiges ({ \"issues\": [...] } Objekt. Jira Status werden Listen und Issues werden zu Karten. Optional kann eine \"automationRules\" Liste hinzugefügt werden, um Regeln zu importieren.",
"import-board-instruction-excel": "Wähle eine .xlsx Tabelle im WeKan-Stil (die gleichen Spalten wie im Excel Export: Titel, Beschreibung, Status/Liste, Mitglieder, Labels, Datum, benutzerdefinierte Felder). Die erste Zeile ist der Kopf.",
"import-excel-file": "Excel Datei (.xlsx)",
"import-board-instruction-wekan": "Gehen Sie in Ihrem Board auf 'Menü', danach auf 'Board exportieren' und kopieren Sie den Text aus der heruntergeladenen Datei.",
"import-board-instruction-about-errors": "Treten beim importieren eines Board Fehler auf, so kann der Import dennoch erfolgreich abgeschlossen sein und das Board ist auf der Seite \"Alle Boards\" zusehen.",
"import-without-mapping-members": "Import without mapping members (map later)",
"import-without-mapping-members": "Import ohne Zuordnung der Mitglieder (später zuordnen)",
"import-json-placeholder": "Fügen Sie die korrekten JSON-Daten hier ein",
"import-csv-placeholder": "Fügen Sie die korrekten CSV/TSV-Daten hier ein",
"import-json-file": "Or select a Trello JSON file",
"import-attachments-zip": "Trello attachments ZIP (optional, from Trello Card Attachments Downloader)",
"import-trello-json-file": "Trello .json file",
"import-trello-json-file-hint": "One Trello board exported as .json. If you have saved Trello API key and token, its attachments, board background and member avatars are downloaded too.",
"import-trello-zip-file": "Trello .zip file",
"import-json-file": "Oder wähle eine Trello JSON Datei",
"import-attachments-zip": "Trello Anhang ZIP (optional, vom Trello Karten Anhang Downloader)",
"import-trello-json-file": "Trello .json Datei",
"import-trello-json-file-hint": "Ein Trello Brett exportiert als .json. Wenn der Trello API Schlüssel und Token gesichert wurde werden die Anhänge, Bretthintergrund und Benutzeravatare auch heruntergeladen.",
"import-trello-zip-file": "Trello .zip Datei",
"import-trello-zip-file-hint": "A .zip with one or more board .json files and their attachments in board-name subfolders (from the Trello Card Attachments Downloader). All boards are imported.",
"import-trello-zip-no-boards": "No Trello board .json files were found in the .zip.",
"import-trello-zip-progress": "Importing boards from .zip, please wait…",
+28 -28
View File
@@ -588,8 +588,8 @@
"headerBarCreateBoardPopup-title": "Criar Quadro",
"home": "Início",
"import": "Importar",
"imported-member-no-account": "Imported member — no matching account yet",
"inactive-member": "Inactive member",
"imported-member-no-account": "Membro importado — ainda não há conta correspondente",
"inactive-member": "Membro inativo",
"impersonate-user": "Logar como",
"link": "Ligação",
"import-board": "importar quadro",
@@ -1557,10 +1557,10 @@
"rulesReportTitle": "Relatório de regras",
"boardsReportTitle": "Relatório de Quadros",
"cardsReportTitle": "Relatório de Cartões",
"impersonationReportTitle": "Impersonation Report",
"impersonationReportTitle": "Relatório de personificação de usuários",
"impersonation-admin": "Administrador",
"impersonation-user": "Impersonated user",
"reason": "Reason",
"impersonation-user": "Usuário personificado",
"reason": "Razão",
"copy-swimlane": "Copiar Raia",
"copySwimlanePopup-title": "Copiar Raia",
"display-card-creator": "Exibir Criador do Cartão",
@@ -1868,31 +1868,31 @@
"cards-loading-lazy": "Carregamento lento (apenas cartões visíveis)",
"cards-loading-description": "Como cada quadro carrega seus cartões. Todos os cartões: cada cartão é carregado no navegador (mais simples, todas as funcionalidades funcionam, mas um quadro com milhares de cartões envia muitos dados para cada visualizador). Carregamento lento: cada lista carrega apenas os cartões atualmente visíveis (rolagem infinita) mais uma contagem em tempo real, portanto, quadros muito grandes usam menos memória e largura de banda. Também definido pela variável de ambiente CARDS_LOADING.",
"cards-loading-lazy-note": "O carregamento lento de cartões é experimental: os contadores de cartões e os limites de trabalho em andamento estão corretos, mas as visualizações de Calendário/Tabela/Gantt e a seleção múltipla refletem apenas os cartões carregados até o momento. Recarregue os quadros abertos após alterar essa configuração.",
"features-security": "Security",
"render-links-as-plain-text": "Render links as plain text",
"render-links-as-plain-text-description": "When enabled, all links (both markdown links like [label](url) and raw HTML <a href> tags) are always shown as plain, non-clickable text in every rich text field (board and card titles, descriptions, comments, checklists, etc.). This prevents misleading clickable links. Default is off, so links stay clickable.",
"always-show-code-as-text": "Always show all code as plain text",
"always-show-code-as-text-description": "When enabled, rich text is never rendered as markdown or HTML: the entire source is always shown as plain text in every rich text field (board and card titles, descriptions, comments, checklists, etc.). This reveals hidden content — HTML comments (<!-- -->), the target of markdown links, JavaScript and any other code — so all code is always visible, not clickable, and not running. Default is off, so markdown is rendered normally.",
"features-security": "Segurança",
"render-links-as-plain-text": "Exibir links como texto simples",
"render-links-as-plain-text-description": "Quando ativada, todos os links (tanto links Markdown como [label](url) como tags HTML simples) são sempre apresentadas como texto simples, não clicável, em todos os campos de texto formatado (títulos de quadros e cartões, descrições, comentários, listas de verificação, etc.). Isto evita links clicáveis ​​enganosos. A configuração padrão é desativada, então os links permanecem clicáveis.",
"always-show-code-as-text": "Sempre exibir todo o código como texto simples",
"always-show-code-as-text-description": "Quando ativado, o texto formatado nunca é renderizado como Markdown ou HTML: todo o código-fonte é sempre exibido como texto simples em todos os campos de texto formatado (títulos de quadros e cartões, descrições, comentários, listas de verificação etc.). Isso revela conteúdo oculto — comentários HTML (<!-- -->), o destino de links Markdown, JavaScript e qualquer outro código — portanto, todo o código está sempre visível, não clicável e não em execução. O padrão é desativado, então o Markdown é renderizado normalmente.",
"anonymized-user": "usuário",
"disable-all-import": "Disable all import",
"disable-all-import-description": "When enabled, all import features are turned off: importing a board from WeKan JSON, Trello, CSV/Excel, Jira, Kanboard, NextCloud Deck, OpenProject, GitHub, GitLab, Gitea and Forgejo, as well as cloning a board. The import menu options are hidden and the server rejects any import request. Default is off.",
"disable-all-export": "Disable all export",
"disable-all-export-description": "When enabled, all export features are turned off: exporting a board as WeKan JSON, CSV, Excel, Kanboard, or to NextCloud Deck / OpenProject / GitHub / GitLab / Gitea / Forgejo, and single-attachment export. The export menu options are hidden and the server rejects any export request. Default is off.",
"disable-import-avatars": "Disable import avatars",
"disable-import-avatars-description": "When enabled, avatars (user profile pictures) are never imported. This covers WeKan JSON import, Trello import, and avatar sync from external identity providers on login (LDAP, OIDC/OAuth2). Names and other data are still imported; only avatars are skipped. Default is off.",
"disable-export-avatars": "Disable export avatars",
"disable-export-avatars-description": "When enabled, avatars (user profile pictures) are never included when exporting a board (WeKan JSON and CSV export). Usernames and other data are still exported; only avatars are omitted. Default is off.",
"anonymize-import-users": "Anonymize import users",
"anonymize-import-users-description": "When enabled, importing a WeKan JSON board replaces every imported user's username, full name and initials with counter placeholders (user1, user2, ...), drops their avatar, and rewrites @username mentions (and the requested-by / assigned-by fields) inside imported card and comment content. No real user identity from the source board is stored. The word \"user\" follows the language of the person importing. Default is off.",
"anonymize-export-users": "Anonymize export users",
"anonymize-export-users-description": "When enabled, exporting a board replaces every exported user's username, full name and initials with counter placeholders (user1, user2, ...), drops their avatar, and rewrites @username mentions (and the requested-by / assigned-by fields) inside card and comment content. The exported file carries no real user identity. The word \"user\" follows the language of the person exporting. Default is off.",
"disable-all-import": "Desativar todas as importações",
"disable-all-import-description": "Quando ativada, todas as funcionalidades de importação são desativadas: importar um quadro do WeKan JSON, Trello, CSV/Excel, Jira, Kanboard, NextCloud Deck, OpenProject, GitHub, GitLab, Gitea e Forgejo, bem como clonar um quadro. As opções do menu de importação ficam ocultas e o servidor rejeita qualquer solicitação de importação. A configuração padrão é desativada.",
"disable-all-export": "Desativar todas as exportações",
"disable-all-export-description": "Quando ativada, todas as funcionalidades de exportação são desativadas: exportar um quadro como WeKan JSON, CSV, Excel, Kanboard ou para NextCloud Deck / OpenProject / GitHub / GitLab / Gitea / Forgejo, e exportação de anexo único. As opções do menu de exportação ficam ocultas e o servidor rejeita qualquer solicitação de exportação. A configuração padrão é desativada.",
"disable-import-avatars": "Desativar importação de avatares",
"disable-import-avatars-description": "Quando ativada, a importação de avatares (fotos de perfil do usuário) é interrompida. Isso inclui a importação de JSON do WeKan, a importação do Trello e a sincronização de avatares de provedores de identidade externos no login (LDAP, OIDC/OAuth2). Nomes e outros dados continuam sendo importados; apenas os avatares são ignorados. A configuração padrão é desativada.",
"disable-export-avatars": "Desativar exportação de avatares",
"disable-export-avatars-description": "Quando ativada, a opção impede a inclusão de avatares (fotos de perfil do usuário) na exportação de um quadro (exportação em JSON e CSV do WeKan). Os nomes de usuário e outros dados continuam sendo exportados; apenas os avatares são omitidos. A opção padrão é desativada.",
"anonymize-import-users": "Anonimizar importação de usuários",
"anonymize-import-users-description": "Quando ativada, a importação de um quadro JSON do WeKan substitui o nome de usuário, o nome completo e as iniciais de cada usuário importado por marcadores (usuário1, usuário2, ...), remove o avatar e reescreve as menções a @nome de usuário (e os campos solicitado por / atribuído por) no conteúdo dos cartões e comentários importados. Nenhuma identidade real do usuário do quadro de origem é armazenada. A palavra \"usuário\" segue o idioma da pessoa que está importando. O padrão é desativado.",
"anonymize-export-users": "Anonimizar exportação de usuários",
"anonymize-export-users-description": "Quando ativada, a exportação de um quadro substitui o nome de usuário, o nome completo e as iniciais de cada usuário exportado por marcadores (usuário1, usuário2, ...), remove o avatar e reescreve as menções a @nome de usuário (e os campos solicitado por / atribuído por) no conteúdo dos cartões e comentários. O arquivo exportado não contém a identidade real do usuário. A palavra \"usuário\" segue o idioma da pessoa que exportou o arquivo. A opção padrão é desativada.",
"features-notifications": "Notificações",
"disable-activities": "Disable all activities",
"disable-activities-description": "When enabled, activity-feed entries are never recorded and never shown anywhere (board sidebar and card activity tab). No history of who did what is kept. Default is off.",
"disable-notifications": "Disable all notifications",
"disable-notifications-description": "When enabled, WeKan never sends watch notifications (in-app, email or other services) for any activity. Activities can still be recorded (unless also disabled above); only the notifications are suppressed. Default is off.",
"disable-watch": "Disable watch",
"disable-watch-description": "When enabled, the watch feature is turned off — users cannot subscribe to boards, lists or cards to receive notifications, and any attempt to change a watch level is rejected. Default is off.",
"disable-activities": "Desativar todas as atividades",
"disable-activities-description": "Quando ativada, as entradas do feed de atividades nunca são registradas e nunca são exibidas em lugar nenhum (barra lateral do quadro e aba de atividades do cartão). Nenhum histórico de quem fez o quê é mantido. A configuração padrão é desativada.",
"disable-notifications": "Desativar todas as notificações",
"disable-notifications-description": "Quando ativado, o WeKan nunca envia notificações para o monitoramento (no aplicativo, por e-mail ou outros serviços) para nenhuma atividade. As atividades ainda podem ser registradas (a menos que também estejam desativadas acima); apenas as notificações são suprimidas. A configuração padrão é desativada.",
"disable-watch": "Desativar monitoramento",
"disable-watch-description": "Quando ativada, a função de monitoramento é desativada — os usuários não podem se inscrever em quadros, listas ou cartões para receber notificações, e qualquer tentativa de alterar o nível de monitoramento é rejeitada. O padrão é desativado.",
"backup": "Backup",
"backup-description": "Faça backup de anexos, avatares e/ou dados (todas as coleções baseadas em texto que não sejam anexos ou avatares). O arquivo .zip é transmitido diretamente para o armazenamento selecionado — sem arquivo temporário — como backup/AAAA/MM/DD/HH_MM_SS/backup.zip, contendo as pastas AAAA_MM_DD-HH_MM_SS/attachments, /avatars e /data. Os armazenamentos em nuvem (S3/MinIO, Azure, GCS) usam as credenciais configuradas em suas respectivas abas de armazenamento.",
"backup-data": "Dados (texto)",
+26 -26
View File
@@ -1557,10 +1557,10 @@
"rulesReportTitle": "規則報告",
"boardsReportTitle": "看板報告",
"cardsReportTitle": "卡片報告",
"impersonationReportTitle": "Impersonation Report",
"impersonationReportTitle": "模擬使用者報告",
"impersonation-admin": "管理員",
"impersonation-user": "Impersonated user",
"reason": "Reason",
"impersonation-user": "被模擬的使用者",
"reason": "理由",
"copy-swimlane": "複製泳道流程圖",
"copySwimlanePopup-title": "複製泳道流程圖",
"display-card-creator": "顯示卡片建立者",
@@ -1868,31 +1868,31 @@
"cards-loading-lazy": "延遲載入(僅顯示可見的卡片)",
"cards-loading-description": "各看板載入卡片的方式。全部卡片:每張卡片都會載入至瀏覽器(最簡單的方式,所有功能皆可正常運作,但包含數千張卡片的看板會向每位瀏覽者傳送大量資料)。延遲載入:每個清單僅載入目前可見的卡片(無限捲動)加上即時計數,因此非常龐大的看板能減少記憶體與頻寬的消耗。此設定亦可透過 CARDS_LOADING 環境變數進行調整。",
"cards-loading-lazy-note": "延遲載入功能尚處於實驗階段:卡片計數器與進行中工作量上限的數值是準確的,但「日曆」、「表格」與「甘特圖」檢視模式以及多選功能僅反映目前已載入的卡片。變更此設定後,請重新載入已開啟的看板。",
"features-security": "Security",
"render-links-as-plain-text": "Render links as plain text",
"render-links-as-plain-text-description": "When enabled, all links (both markdown links like [label](url) and raw HTML <a href> tags) are always shown as plain, non-clickable text in every rich text field (board and card titles, descriptions, comments, checklists, etc.). This prevents misleading clickable links. Default is off, so links stay clickable.",
"always-show-code-as-text": "Always show all code as plain text",
"always-show-code-as-text-description": "When enabled, rich text is never rendered as markdown or HTML: the entire source is always shown as plain text in every rich text field (board and card titles, descriptions, comments, checklists, etc.). This reveals hidden content — HTML comments (<!-- -->), the target of markdown links, JavaScript and any other code — so all code is always visible, not clickable, and not running. Default is off, so markdown is rendered normally.",
"features-security": "安全性",
"render-links-as-plain-text": "將連結顯示為純文字",
"render-links-as-plain-text-description": "啟用後,所有連結(包含如 [標籤](URL) 的 Markdown 連結與原始 HTML <a href> 標籤)在每個富文字欄位(看板和卡片標題、描述、留言、待辦清單等)中,都會始終以純文字形式顯示,且無法點擊。此舉可避免出現誤導性的可點擊連結。預設為關閉狀態,因此連結仍可點擊。",
"always-show-code-as-text": "一律將所有程式碼顯示為純文字",
"always-show-code-as-text-description": "啟用後,富文字絕不會以 Markdown 或 HTML 格式呈現:在所有富文本欄位(看板和卡片標題、描述、留言、待辦清單等)中,整個原始碼皆會以純文字形式顯示。此舉會揭露隱藏的內容:HTML 註解 (<!-- -->)、Markdown 連結的目標、JavaScript 以及任何其他程式碼,因此所有程式碼始終可見,但無法點擊,也不會執行。預設為關閉狀態,因此 Markdown 會如常繪製。",
"anonymized-user": "使用者",
"disable-all-import": "Disable all import",
"disable-all-import-description": "When enabled, all import features are turned off: importing a board from WeKan JSON, Trello, CSV/Excel, Jira, Kanboard, NextCloud Deck, OpenProject, GitHub, GitLab, Gitea and Forgejo, as well as cloning a board. The import menu options are hidden and the server rejects any import request. Default is off.",
"disable-all-export": "Disable all export",
"disable-all-export-description": "When enabled, all export features are turned off: exporting a board as WeKan JSON, CSV, Excel, Kanboard, or to NextCloud Deck / OpenProject / GitHub / GitLab / Gitea / Forgejo, and single-attachment export. The export menu options are hidden and the server rejects any export request. Default is off.",
"disable-import-avatars": "Disable import avatars",
"disable-import-avatars-description": "When enabled, avatars (user profile pictures) are never imported. This covers WeKan JSON import, Trello import, and avatar sync from external identity providers on login (LDAP, OIDC/OAuth2). Names and other data are still imported; only avatars are skipped. Default is off.",
"disable-export-avatars": "Disable export avatars",
"disable-export-avatars-description": "When enabled, avatars (user profile pictures) are never included when exporting a board (WeKan JSON and CSV export). Usernames and other data are still exported; only avatars are omitted. Default is off.",
"anonymize-import-users": "Anonymize import users",
"anonymize-import-users-description": "When enabled, importing a WeKan JSON board replaces every imported user's username, full name and initials with counter placeholders (user1, user2, ...), drops their avatar, and rewrites @username mentions (and the requested-by / assigned-by fields) inside imported card and comment content. No real user identity from the source board is stored. The word \"user\" follows the language of the person importing. Default is off.",
"anonymize-export-users": "Anonymize export users",
"anonymize-export-users-description": "When enabled, exporting a board replaces every exported user's username, full name and initials with counter placeholders (user1, user2, ...), drops their avatar, and rewrites @username mentions (and the requested-by / assigned-by fields) inside card and comment content. The exported file carries no real user identity. The word \"user\" follows the language of the person exporting. Default is off.",
"disable-all-import": "停用所有匯入",
"disable-all-import-description": "啟用後,所有匯入功能將被停用:包括從 WeKan JSON、Trello、CSV/Excel、Jira、Kanboard、NextCloud Deck、OpenProject、GitHub、GitLab、Gitea 及 Forgejo 匯入看板,以及再製看板。匯入選單中的選項將被隱藏,且伺服器會拒絕任何匯入請求。預設為關閉。",
"disable-all-export": "停用所有匯出",
"disable-all-export-description": "啟用後,所有匯出功能將被停用:包括將看板匯出為 WeKan JSON、CSV、Excel、Kanboard 格式,或匯出至 Nextcloud Deck / OpenProject / GitHub / GitLab / Gitea / Forgejo,以及單一附件匯出。匯出選單中的選項將被隱藏,且伺服器會拒絕任何匯出請求。預設為關閉。",
"disable-import-avatars": "停用匯入大頭照",
"disable-import-avatars-description": "啟用後,大頭照(使用者個人資料圖片)將永遠不會被匯入。此設定適用於 WeKan JSON 匯入、Trello 匯入,以及登入時從外部身分識別供應商(LDAP、OIDC/OAuth2)同步大頭照。姓名及其他資料仍會被匯入;僅跳過大頭照。預設為關閉。",
"disable-export-avatars": "停用匯出大頭照",
"disable-export-avatars-description": "啟用後,在匯出看板時(WeKan JSON 和 CSV 匯出),大頭照(使用者個人資料圖片)將永遠不會被包含在內。使用者名稱及其他資料仍會被匯出;僅大頭照會被省略。預設為關閉。",
"anonymize-import-users": "匿名化匯入使用者",
"anonymize-import-users-description": "啟用後,匯入 WeKan JSON 看板時,系統會將每位匯入使用者的使用者名稱、全名及縮寫替換為計數佔位字串 (user1, user2, ...),移除其大頭照,並重新撰寫匯入卡片及留言內容中的 @使用者名稱提及(以及「請求者」/「分配者」欄位)。來源看板中的真實使用者身分資訊均不會被儲存。「user」一詞會依照匯入者的語言進行轉換。預設為關閉。",
"anonymize-export-users": "匿名化匯出使用者",
"anonymize-export-users-description": "啟用後,匯出看板時會將每位被匯出使用者的使用者名稱、全名及縮寫替換為計數佔位字串 (user1, user2, ...),移除其大頭照,並將卡片和留言內容中的 @使用者名稱提及(以及「請求者」/「分配者」欄位)重新撰寫。匯出檔案中不包含任何真實使用者身分資訊。「使用者」一詞的語言設定將遵循匯出者的語言設定。預設為關閉。",
"features-notifications": "通知",
"disable-activities": "Disable all activities",
"disable-activities-description": "When enabled, activity-feed entries are never recorded and never shown anywhere (board sidebar and card activity tab). No history of who did what is kept. Default is off.",
"disable-notifications": "Disable all notifications",
"disable-notifications-description": "When enabled, WeKan never sends watch notifications (in-app, email or other services) for any activity. Activities can still be recorded (unless also disabled above); only the notifications are suppressed. Default is off.",
"disable-watch": "Disable watch",
"disable-watch-description": "When enabled, the watch feature is turned off — users cannot subscribe to boards, lists or cards to receive notifications, and any attempt to change a watch level is rejected. Default is off.",
"disable-activities": "停用所有活動",
"disable-activities-description": "啟用後,活動動態的記錄將不會被保存,也不會顯示在任何地方(包括看板側邊欄與卡片活動分頁)。系統不會保留任何關於「誰做了什麼」的歷史紀錄。預設為關閉。",
"disable-notifications": "停用所有通知",
"disable-notifications-description": "啟用後,WeKan 將不會針對任何活動傳送追蹤通知(無論是應用程式內、電子郵件或其他服務)。活動仍會被記錄(除非在上方也已停用該功能);僅會抑制通知的傳送。預設為關閉。",
"disable-watch": "停用監視",
"disable-watch-description": "啟用後,監視功能將被關閉,使用者無法訂閱看板、清單或卡片以接收通知,且任何嘗試變更監視層級的操作都會被拒絕。預設為關閉。",
"backup": "備份",
"backup-description": "備份附件、大頭照或資料(所有非附件或大頭照的文字型資料集)。該 .zip 檔案將直接串流至選定的儲存空間(無需臨時檔案),檔案名稱為 backup/YYYY/MM/DD/HH_MM_SS/backup.zip,其中包含 YYYY_MM_DD-HH_MM_SS/attachments、/avatars 及 /data 目錄。雲端儲存服務 (S3/MinIO, Azure, GCS) 將使用其「儲存空間」分頁中設定的憑證。",
"backup-data": "資料(文字)",
+65
View File
@@ -204,6 +204,71 @@ describe('TAPi18n', () => {
});
describe('.resolveTag / case-insensitive detection (Japanese & Chinese variants)', () => {
beforeEach(async () => {
await TAPi18n.init();
});
it('resolveTag returns the canonical tag, case-insensitively', () => {
expect(TAPi18n.resolveTag('ja')).to.equal('ja');
expect(TAPi18n.resolveTag('ja-JP')).to.equal('ja-JP');
expect(TAPi18n.resolveTag('ja-jp')).to.equal('ja-JP'); // lowercase region
expect(TAPi18n.resolveTag('JA')).to.equal('ja'); // uppercase language
expect(TAPi18n.resolveTag('zh-Hant')).to.equal('zh-Hant');
expect(TAPi18n.resolveTag('zh-hant')).to.equal('zh-Hant'); // lowercase script
expect(TAPi18n.resolveTag('zh-CN')).to.equal('zh-CN');
// legacy underscore key matched from a browser hyphen tag (and vice versa)
expect(TAPi18n.resolveTag('af-ZA')).to.equal('af_ZA');
expect(TAPi18n.resolveTag('af_ZA')).to.equal('af_ZA');
});
it('resolveTag maps bare Chinese "zh" to Simplified (alias)', () => {
expect(TAPi18n.resolveTag('zh')).to.equal('zh-Hans');
expect(TAPi18n.resolveTag('ZH')).to.equal('zh-Hans');
});
it('resolveTag returns undefined for an unsupported language', () => {
expect(TAPi18n.resolveTag('not-a-real-lang')).to.equal(undefined);
expect(TAPi18n.resolveTag('')).to.equal(undefined);
});
it('isLanguageSupported is case-insensitive (and honours the zh alias)', () => {
expect(TAPi18n.isLanguageSupported('ja-jp')).to.be.true;
expect(TAPi18n.isLanguageSupported('ZH-HANT')).to.be.true;
expect(TAPi18n.isLanguageSupported('de')).to.be.true;
expect(TAPi18n.isLanguageSupported('zh')).to.be.true;
expect(TAPi18n.isLanguageSupported('xx-nope')).to.be.false;
});
it('each Japanese variant loads its own file under its own i18next code', async () => {
const has = (t) => TAPi18n.i18n.hasResourceBundle(TAPi18n.toI18nCode(t), 'translation');
await TAPi18n.setLanguage('ja');
expect(TAPi18n.getLanguage()).to.equal('ja');
expect(has('ja')).to.be.true;
await TAPi18n.setLanguage('ja-JP');
expect(TAPi18n.getLanguage()).to.equal('ja-JP');
expect(has('ja-JP')).to.be.true;
await TAPi18n.setLanguage('ja-Hira');
expect(TAPi18n.getLanguage()).to.equal('ja-Hira');
expect(has('ja-Hira')).to.be.true;
});
it('setLanguage normalises a case-insensitive tag to the canonical one', async () => {
await TAPi18n.setLanguage('ja-jp');
expect(TAPi18n.getLanguage()).to.equal('ja-JP');
await TAPi18n.setLanguage('zh-hant');
expect(TAPi18n.getLanguage()).to.equal('zh-Hant');
});
it('setLanguage("zh") selects Simplified Chinese (alias), not English', async () => {
await TAPi18n.setLanguage('zh');
expect(TAPi18n.getLanguage()).to.equal('zh-Hans');
expect(TAPi18n.i18n.hasResourceBundle(TAPi18n.toI18nCode('zh-Hans'), 'translation')).to.be.true;
});
});
describe('.ensureLanguageLoaded (#5875)', () => {
beforeEach(async () => {
+76 -6
View File
@@ -2,7 +2,7 @@ export default {
"ace": {
code: "ace",
tag: "ace",
name: "Acehnese",
name: "Bahsa Acèh",
load: () => import('./data/ace.i18n.json'),
rtl: false,
},
@@ -16,7 +16,7 @@ export default {
"af_ZA": {
code: "af",
tag: "af_ZA",
name: "Afrikaans (South Africa)",
name: "Afrikaans (Suid-Afrika)",
load: () => import('./data/af_ZA.i18n.json'),
rtl: false,
},
@@ -126,8 +126,8 @@ export default {
rtl: false,
},
"cmn": {
code: "cn",
tag: "cnm",
code: "cmn",
tag: "cmn",
name: "官話 / 官话",
load: () => import('./data/cmn.i18n.json'),
rtl: false,
@@ -149,14 +149,14 @@ export default {
"cy-GB": {
code: "cy",
tag: "cy-GB",
name: "Welsh (UK)",
name: "Cymraeg (Y Deyrnas Unedig)",
load: () => import('./data/cy-GB.i18n.json'),
rtl: false,
},
"cy": {
code: "cy",
tag: "cy",
name: "Welsh",
name: "Cymraeg",
load: () => import('./data/cy.i18n.json'),
rtl: false,
},
@@ -992,5 +992,75 @@ export default {
name: "IsiZulu",
load: () => import('./data/zu.i18n.json'),
rtl: false,
},
"ca-valencia": {
code: "ca",
tag: "ca-valencia",
name: "Català (Valencià)",
load: () => import('./data/ca@valencia.i18n.json'),
rtl: false,
},
"en_ID": {
code: "en",
tag: "en_ID",
name: "English (Indonesia)",
load: () => import('./data/en_ID.i18n.json'),
rtl: false,
},
"en_SG": {
code: "en",
tag: "en_SG",
name: "English (Singapore)",
load: () => import('./data/en_SG.i18n.json'),
rtl: false,
},
"en_TR": {
code: "en",
tag: "en_TR",
name: "English (Turkey)",
load: () => import('./data/en_TR.i18n.json'),
rtl: false,
},
"es_CO": {
code: "es",
tag: "es_CO",
name: "Español (Colombia)",
load: () => import('./data/es_CO.i18n.json'),
rtl: false,
},
"fr-FR": {
code: "fr",
tag: "fr-FR",
name: "Français (France)",
load: () => import('./data/fr-FR.i18n.json'),
rtl: false,
},
"pt_PT": {
code: "pt",
tag: "pt_PT",
name: "Português (Portugal)",
load: () => import('./data/pt_PT.i18n.json'),
rtl: false,
},
"ru-UA": {
code: "ru",
tag: "ru-UA",
name: "Русский (Украина)",
load: () => import('./data/ru-UA.i18n.json'),
rtl: false,
},
"tk_TM": {
code: "tk",
tag: "tk_TM",
name: "Türkmençe (Türkmenistan)",
load: () => import('./data/tk_TM.i18n.json'),
rtl: false,
},
"wuu-Hans": {
code: "wuu",
tag: "wuu-Hans",
name: "吴语(简体)",
load: () => import('./data/wuu-Hans.i18n.json'),
rtl: false,
}
};
+45 -13
View File
@@ -8,6 +8,12 @@ const DEFAULT_NAMESPACE = 'translation';
const DEFAULT_LANGUAGE = 'en';
const getTranslationCollection = () => require('/models/translation').default;
// Base languages with no plain-code file of their own resolve to a sensible default
// variant, so a browser reporting the bare code still gets that language, not English.
// Chinese has only script/region files (zh-Hans, zh-Hant, zh-CN, …), so plain 'zh' maps
// to Simplified. Keys are compared case-insensitively (see resolveTag).
const LANGUAGE_ALIASES = { zh: 'zh-Hans' };
// Map a Wekan language tag (the key/`tag` from languages.js, e.g. 'zh-CN',
// 'zh-Hans', 'ar-DZ' or the legacy underscore form 'en_AU', 'af_ZA') to the
// code i18next actually stores and looks translations up under.
@@ -70,8 +76,27 @@ export const TAPi18n = {
await TAPi18n.loadLanguage(DEFAULT_LANGUAGE);
this.ready.set(true);
},
// Resolve an arbitrary language string to the canonical Wekan tag (a key in
// languages.js), CASE-INSENSITIVELY (e.g. 'zh-hant' -> 'zh-Hant', 'JA-JP' -> 'ja-JP'),
// applying LANGUAGE_ALIASES for bare base codes (e.g. 'zh' -> 'zh-Hans'). Returns the
// canonical tag, or undefined when the language is not supported.
resolveTag(language) {
if (!language) return undefined;
if (language in languages) return language; // fast path: exact canonical key
// Case-insensitive AND underscore<->hyphen-insensitive, so a region/script tagged
// language matches however the browser spells it (legacy 'af_ZA' vs browser 'af-ZA',
// 'zh-hant' vs 'zh-Hant', 'JA-JP' vs 'ja-JP').
const norm = String(language).toLowerCase().replace(/_/g, '-');
for (const key of Object.keys(languages)) {
if (key.toLowerCase().replace(/_/g, '-') === norm ||
String(languages[key].tag).toLowerCase().replace(/_/g, '-') === norm) return key;
}
const alias = LANGUAGE_ALIASES[norm];
if (alias && alias in languages) return alias;
return undefined;
},
isLanguageSupported(language) {
return Object.values(languages).some(({ tag }) => tag === language);
return this.resolveTag(language) !== undefined;
},
getSupportedLanguages() {
return Object.values(languages).map(({ name, code, tag, rtl }) => ({ name, code, tag, rtl }));
@@ -107,8 +132,11 @@ export const TAPi18n = {
});
},
async loadLanguage(language) {
if (language in languages && 'load' in languages[language]) {
let data = await languages[language].load();
// Resolve to the canonical tag so a case-insensitive / aliased input (e.g. 'zh-hant',
// 'zh') still finds the right file and registers under the code i18next looks up.
const key = this.resolveTag(language);
if (key && 'load' in languages[key]) {
let data = await languages[key].load();
// Dynamic `import()` of a JSON module can resolve to an ES-module
// namespace ({ default: {...} }) rather than the bare object, depending on
// the bundler/interop. Unwrap it so addResourceBundle receives the actual
@@ -130,10 +158,10 @@ export const TAPi18n = {
}
let custom_translations = [];
await this.loadTranslation(language);
await this.loadTranslation(key);
const Translation = getTranslationCollection();
const cursor = Translation.find(
{ language },
{ language: key },
{ fields: { text: true, translationText: true } },
);
custom_translations =
@@ -156,18 +184,21 @@ export const TAPi18n = {
// Register the bundle under the code i18next will actually look it up
// under, so storage and lookup agree for region/script/underscore tags.
this.i18n.addResourceBundle(this.toI18nCode(language), DEFAULT_NAMESPACE, data);
this.i18n.addResourceBundle(this.toI18nCode(key), DEFAULT_NAMESPACE, data);
} else {
throw new Error(`Language ${language} is not supported`);
}
},
async setLanguage(language) {
await this.loadLanguage(language);
// Resolve to the canonical tag first, so the loaded file, the i18next code and the
// stored `current` all agree even for a case-insensitive / aliased input.
const key = this.resolveTag(language) || language;
await this.loadLanguage(key);
// Switch i18next using the same normalised code the bundle is stored under.
await this.i18n.changeLanguage(this.toI18nCode(language));
// `current` keeps the original Wekan tag (used for the profile, the language
await this.i18n.changeLanguage(this.toI18nCode(key));
// `current` keeps the canonical Wekan tag (used for the profile, the language
// picker and the reactive UI), not the i18next-internal code.
this.current.set(language);
this.current.set(key);
},
// Make sure the resource bundle for `language` is available before a
// synchronous __() call. On the server only the default (English) bundle is
@@ -175,9 +206,10 @@ export const TAPi18n = {
// emails) otherwise silently fell back to English. See #5875.
async ensureLanguageLoaded(language) {
if (!language || !this.i18n) return;
if (!this.isLanguageSupported(language)) return;
if (this.i18n.hasResourceBundle(this.toI18nCode(language), DEFAULT_NAMESPACE)) return;
await this.loadLanguage(language);
const key = this.resolveTag(language);
if (!key) return;
if (this.i18n.hasResourceBundle(this.toI18nCode(key), DEFAULT_NAMESPACE)) return;
await this.loadLanguage(key);
},
// Return translation by key
__(key, options, language) {
+213
View File
@@ -0,0 +1,213 @@
// Pure helpers for the sidebar "Advanced filter" (no Meteor imports, so the
// logic is unit-testable with plain Node — see tests/advancedFilterDate.test.cjs).
//
// #2989 "Date custom field, filter problem": filtering a date-type custom
// field with `'Date de fin' == '06/04/2020'` never matched anything, for two
// independent reasons fixed here:
//
// 1. Tokenizer: inside a '…'-quoted value every '/' toggled the tokenizer's
// string mode (it is also the regex delimiter), so '06/04/2020' came out
// flagged as a regex and the whole filter string failed to parse (the
// filter silently fell back to the last valid selector).
// 2. Selector: date custom-field values are stored as Date objects (the date
// picker calls card.setCustomField(id, date)), but the '==' selector
// compared them with {$in: ['06/04/2020', NaN]} — a string and a number
// never equal a BSON date, so '==' matched nothing while '!=' matched
// everything. parseAdvancedFilterDate()/buildDateValueSelector() translate
// the typed date into a Date range selector instead.
// --- Tokenizer ---------------------------------------------------------------
/**
* Split an advanced-filter string into commands.
* Returns [{cmd, string, regex}, …]:
* - '…' quotes a literal string (may contain spaces and slashes),
* - /…/ delimits a regex (only when not inside a '…' string),
* - '\' escapes the next character outside strings,
* - space separates commands.
*/
export function tokenizeAdvancedFilter(filter) {
const commands = [];
let current = '';
let string = false;
let regex = false;
let wasString = false;
let ignore = false;
for (let i = 0; i < filter.length; i++) {
const char = filter.charAt(i);
if (ignore) {
ignore = false;
current += char;
continue;
}
// '/' starts/ends a regex — but inside a '…'-quoted string it is a plain
// character (#2989: dates like '06/04/2020' must stay literal strings).
if (char === '/' && (!string || regex)) {
string = !string;
if (string) regex = true;
current += char;
continue;
}
// eslint-disable-next-line quotes
if (char === "'" && !regex) {
string = !string;
if (string) wasString = true;
continue;
}
if (char === '\\' && !string) {
ignore = true;
continue;
}
if (char === ' ' && !string) {
commands.push({
cmd: current,
string: wasString,
regex,
});
wasString = false;
regex = false;
current = '';
continue;
}
current += char;
}
if (current !== '') {
commands.push({
cmd: current,
string: wasString,
regex,
});
}
return commands;
}
// --- Date parsing ------------------------------------------------------------
// YYYY-MM-DD / YYYY/MM/DD / YYYY.MM.DD, optional " HH:mm[:ss]" (or T separator)
const YMD_RE = /^(\d{4})[-/.](\d{1,2})[-/.](\d{1,2})(?:[ T](\d{1,2}):(\d{2})(?::(\d{2}))?)?$/;
// DD/MM/YYYY or MM/DD/YYYY (separators -, / or .), optional time as above
const DMY_RE = /^(\d{1,2})[-/.](\d{1,2})[-/.](\d{4})(?:[ T](\d{1,2}):(\d{2})(?::(\d{2}))?)?$/;
function buildRange(year, month, day, hour, minute, second) {
// Validate by round-trip: new Date() rolls over out-of-range components
// (e.g. 31 February becomes 2/3 March), which must be rejected.
const hasTime = hour !== undefined;
const hasSeconds = second !== undefined;
const h = hasTime ? Number(hour) : 0;
const min = hasTime ? Number(minute) : 0;
const s = hasSeconds ? Number(second) : 0;
const start = new Date(year, month - 1, day, h, min, s);
if (
start.getFullYear() !== year ||
start.getMonth() !== month - 1 ||
start.getDate() !== day ||
start.getHours() !== h ||
start.getMinutes() !== min ||
start.getSeconds() !== s
) {
return null;
}
let end;
if (hasSeconds) {
end = new Date(year, month - 1, day, h, min, s + 1);
} else if (hasTime) {
end = new Date(year, month - 1, day, h, min + 1);
} else {
end = new Date(year, month - 1, day + 1);
}
return { start, end };
}
/**
* Parse a date typed in the advanced filter into a {start, end} range
* (half-open: start inclusive, end exclusive) in the local timezone.
* The range spans the given day, minute or second depending on how much
* precision the user typed. Returns null when the string is not a date.
*
* options.dayFirst resolves ambiguous "a/b/yyyy" input (both a and b <= 12):
* true reads it day-first (DD/MM/YYYY, e.g. French locale), false month-first.
* Unambiguous input (one component > 12) ignores the flag.
*/
export function parseAdvancedFilterDate(str, options = {}) {
if (typeof str !== 'string') return null;
const dayFirst = !!options.dayFirst;
const trimmed = str.trim();
let m = trimmed.match(YMD_RE);
if (m) {
return buildRange(
Number(m[1]),
Number(m[2]),
Number(m[3]),
m[4],
m[5],
m[6],
);
}
m = trimmed.match(DMY_RE);
if (m) {
const a = Number(m[1]);
const b = Number(m[2]);
const year = Number(m[3]);
let day;
let month;
if (a > 12 && b <= 12) {
day = a;
month = b;
} else if (b > 12 && a <= 12) {
day = b;
month = a;
} else if (dayFirst) {
day = a;
month = b;
} else {
month = a;
day = b;
}
return buildRange(year, month, day, m[4], m[5], m[6]);
}
return null;
}
// --- Selector building -------------------------------------------------------
/**
* Build the Mongo operator document for 'customFields.value' comparing a
* Date-typed custom field against the {start, end} range from
* parseAdvancedFilterDate(). Returns null for unknown operators.
*/
export function buildDateValueSelector(op, range) {
if (!range) return null;
switch (op) {
case '=':
case '==':
case '===':
return { $gte: range.start, $lt: range.end };
case '!=':
case '!==':
return { $not: { $gte: range.start, $lt: range.end } };
case '>':
case 'gt':
case 'Gt':
case 'GT':
return { $gte: range.end };
case '>=':
case '>==':
case 'gte':
case 'Gte':
case 'GTE':
return { $gte: range.start };
case '<':
case 'lt':
case 'Lt':
case 'LT':
return { $lt: range.start };
case '<=':
case '<==':
case 'lte':
case 'Lte':
case 'LTE':
return { $lt: range.end };
default:
return null;
}
}
+138
View File
@@ -0,0 +1,138 @@
'use strict';
// Pure helpers for auto-scrolling the board while a card is dragged near an
// edge. Extracted so the decision logic is unit-testable in plain Node
// without Meteor (same pattern as client/lib/cardDragGeometry.js and
// imports/lib/advancedFilter.js). See tests/boardAutoScroll.test.cjs.
//
// #443 "Cannot automatically slide when moving item from list to list":
// dragging a card towards a list that is outside the viewport does not
// scroll the board, so the user has to drop the card on an intermediate
// list and scroll manually.
//
// The card sortable's `sort` callback (client/components/lists/list.js) does
// contain horizontal auto-scroll code, but it mutates
// `$('.board-canvas')[0].scrollLeft`. Since the swimlane layout, the element
// that actually overflows horizontally is the lane that holds the lists —
// `.swimlane.js-lists` (`.swimlane { display: flex; overflow: auto }` in
// client/components/swimlanes/swimlanes.css) — in BOTH board views
// (swimlanes.jade renders `.swimlane.js-lists.js-swimlane` per swimlane and
// `.swimlane.list-group.js-lists` in Lists mode). `.board-canvas` only
// scrolls vertically (boardBody.css: `overflow-y: auto`), so its
// scrollWidth === clientWidth: the old guard
// `boardCanvas.scrollLeft < (scrollWidth - clientWidth)` compares 0 < 0 and
// the right-scroll branch never fires, while the left-scroll branch
// decrements a scrollLeft that is already 0. jQuery UI's own `scroll` option
// cannot help either: sortable takes `this.placeholder.scrollParent()` ONCE
// at drag start, which resolves to the list body (the vertical card
// scroller), never the lane.
//
// These helpers compute WHAT to scroll (the lane under the pointer, found by
// hit-testing lane rectangles) and BY HOW MUCH (an edge-proximity step,
// clamped to the real scroll range). The caller applies the returned value:
//
// const lanes = document.querySelectorAll('.js-lists');
// const i = findLaneUnderPointer([...lanes].map(l =>
// l.getBoundingClientRect()), event.clientX, event.clientY);
// if (i !== -1) {
// const lane = lanes[i];
// const rect = lane.getBoundingClientRect();
// const next = computeEdgeScroll({
// pointer: event.clientX,
// lowEdge: rect.left,
// highEdge: rect.right,
// scrollPos: lane.scrollLeft,
// scrollSize: lane.scrollWidth,
// clientSize: lane.clientWidth,
// });
// if (next !== null) lane.scrollLeft = next;
// }
// How close (px) to an edge the pointer must be before scrolling starts.
// The old code used 10px from the viewport edge, which was nearly impossible
// to hit while holding a card; 40px matches common kanban implementations.
const EDGE_SIZE = 40;
// How far (px) to scroll per sort/mousemove event (same speed as the old
// board-canvas code and the sortable `scrollSpeed: 10..15` range).
const SCROLL_STEP = 15;
// Compute the next scroll position along ONE axis, or null when nothing
// should change. Axis-agnostic: pass clientX/left/right/scrollLeft/
// scrollWidth/clientWidth for horizontal, clientY/top/bottom/scrollTop/
// scrollHeight/clientHeight for vertical.
//
// pointer current pointer coordinate (viewport space, e.g. clientX)
// lowEdge scroller's near edge (rect.left / rect.top)
// highEdge scroller's far edge (rect.right / rect.bottom)
// scrollPos scroller's current scrollLeft / scrollTop
// scrollSize scroller's scrollWidth / scrollHeight
// clientSize scroller's clientWidth / clientHeight
//
// Returns the clamped new scroll position, or null when the pointer is not
// in an edge zone, the element cannot scroll further in that direction, or
// it does not overflow at all (this is exactly why the old code was a no-op:
// for .board-canvas, scrollSize - clientSize is 0 horizontally).
function computeEdgeScroll({
pointer,
lowEdge,
highEdge,
scrollPos,
scrollSize,
clientSize,
edgeSize = EDGE_SIZE,
step = SCROLL_STEP,
}) {
const maxScroll = Math.max(0, scrollSize - clientSize);
if (maxScroll === 0) {
// No overflow on this axis: nothing to scroll.
return null;
}
const distLow = pointer - lowEdge;
const distHigh = highEdge - pointer;
const inLow = distLow < edgeSize;
const inHigh = distHigh < edgeSize;
// A negative distance means the pointer was dragged slightly PAST the
// edge (the sortable helper can hover outside the lane box); that still
// counts as being in that edge zone. When the element is so small that
// both zones overlap, the nearer edge wins.
if (inLow && (!inHigh || distLow <= distHigh)) {
const next = Math.max(0, scrollPos - step);
return next < scrollPos ? next : null;
}
if (inHigh) {
const next = Math.min(maxScroll, scrollPos + step);
return next > scrollPos ? next : null;
}
return null;
}
// Given the bounding rectangles ({left, right, top, bottom}) of every
// horizontal lane on the board (each `.js-lists` element — one per swimlane
// in Swimlanes view, a single one in Lists view), return the index of the
// lane the pointer is currently over, or -1. The drag may hover a DIFFERENT
// swimlane than the one the card came from; the lane under the pointer is
// the one the user is aiming at, so that is the one to scroll.
function findLaneUnderPointer(laneRects, pointerX, pointerY) {
if (!laneRects) return -1;
for (let i = 0; i < laneRects.length; i += 1) {
const r = laneRects[i];
if (
r &&
pointerX >= r.left &&
pointerX <= r.right &&
pointerY >= r.top &&
pointerY <= r.bottom
) {
return i;
}
}
return -1;
}
module.exports = {
EDGE_SIZE,
SCROLL_STEP,
computeEdgeScroll,
findLaneUnderPointer,
};
+64
View File
@@ -0,0 +1,64 @@
'use strict';
// Time-default resolution for the card date pickers (due/start/end/received,
// vote and poker end, date custom fields). Meteor-free so it can be unit
// tested with plain Node (see tests/datePickerDefaultTime.test.cjs).
//
// Issue #1502 ("Add Feature: Set default time for time field"): each date
// popup configures an intended default time — 17:00 for due dates, the
// current time for received/start/end — via setupDatePicker({ defaultTime }).
// The old rendered logic only applied that default inside an
// `if (isValidDate(existing date))` guard, i.e. only when the card ALREADY
// had a date, in which case the input was already filled with that date's
// own time. For a card without a date (the only case a default is for) the
// time input stayed empty and submitting stored a hard-coded 12:00.
//
// These helpers make the behavior explicit:
// - a card date that exists always shows (and keeps) its own time;
// - a missing date pre-fills the input with the configured default;
// - an empty time at submit falls back to the configured default, then 12:00.
// Whether `date` is a real, valid Date instance.
function isValidDate(date) {
return date instanceof Date && !isNaN(date);
}
// Format a Date's local time as 'HH:mm' (24-hour, zero-padded) — the exact
// value format of a native <input type="time">, in every locale.
function formatTime(date) {
if (!isValidDate(date)) return '';
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
return `${hours}:${minutes}`;
}
// Parse a configured default-time string (e.g. '1970-01-01 17:00:00' or a
// full 'YYYY-MM-DD HH:mm' timestamp) into 'HH:mm', or '' when absent/invalid.
function defaultTimeValue(defaultTime) {
if (!defaultTime) return '';
const d = new Date(defaultTime);
return formatTime(d);
}
// The 'HH:mm' value the picker's time input should initially show:
// - `date` valid (card already has this date) -> that date's own time,
// never the default;
// - otherwise -> the configured default time;
// - no (or unparseable) default -> '' (leave the input empty).
function initialTimeValue(date, defaultTime) {
if (isValidDate(date)) return formatTime(date);
return defaultTimeValue(defaultTime);
}
// The 'HH:mm' to store when the form is submitted with an empty time field:
// the configured default when one parses, else the legacy 12:00.
function fallbackSubmitTime(defaultTime) {
return defaultTimeValue(defaultTime) || '12:00';
}
module.exports = {
isValidDate,
formatTime,
initialTimeValue,
fallbackSubmitTime,
};
+25 -3
View File
@@ -1180,11 +1180,33 @@ const ReactiveCache = {
}
},
getCard(idOrFirstObjectSelector = null, options = {}, noCache = false) {
if (Meteor.isServer || noCache === true) {
if (Meteor.isServer) {
return ReactiveCacheServer.getCard(idOrFirstObjectSelector, options);
} else {
return ReactiveCacheClient.getCard(idOrFirstObjectSelector, options);
}
if (noCache === true) {
// #2494 (cards sent to another board appear/disappear when reordering):
// on the CLIENT, `noCache` must bypass the DataCache but stay
// SYNCHRONOUS like every other client-side ReactiveCache getter.
// Routing it to the async ReactiveCacheServer.getCard returned a
// Promise; synchronous callers such as the multi-select "Move/Copy
// selection" max-sort lookup (client/components/sidebar/
// sidebarFilters.js getMaxSortForList) read `.sort` off that Promise,
// got `undefined`, and wrote `sort: NaN` to every card moved to the
// target list — the cards then landed at unpredictable positions,
// hid behind each other and could not be reordered. Minimongo's
// findOne is synchronous on the client, and callers that `await`
// this call (models/cards.js getSort, models/boards.js
// getNextCardNumber) work unchanged when given a plain document.
if (
idOrFirstObjectSelector === null ||
idOrFirstObjectSelector === undefined ||
idOrFirstObjectSelector === ''
) {
return null;
}
return Cards.findOne(idOrFirstObjectSelector, options);
}
return ReactiveCacheClient.getCard(idOrFirstObjectSelector, options);
},
getCards(selector = {}, options = {}, getQuery = false) {
if (Meteor.isServer) {
+54 -79
View File
@@ -1668,17 +1668,27 @@ Boards.helpers({
// that belong to itself.
getDefaultSubtasksBoardId() {
// #3868 / #5788 / #2256: only the SERVER may auto-create the default
// subtasks board (+ its swimlane). On the client the board's
// subtasksDefaultBoardId can momentarily read as unset (e.g. the helper
// board is not in the published set "if you don't navigate through All
// Boards first"), and creating it client-side produced a new board/swimlane
// on every subtask creation. Server-authoritative creation happens once.
if (
Meteor.isServer &&
(this.subtasksDefaultBoardId === null ||
this.subtasksDefaultBoardId === undefined)
) {
this.subtasksDefaultBoardId = Boards.insert({
// subtasks board (+ its swimlane) — and #6456: on Meteor 3 the server may
// not use the sync insert/update APIs either ("insert is not available on
// the server"), which made addSubtaskCard throw here. This is now a PURE
// getter; the server-side creation lives in getDefaultSubtasksBoardAsync
// (the only path the addSubtaskCard method uses).
return this.subtasksDefaultBoardId;
},
getDefaultSubtasksBoard() {
return ReactiveCache.getBoard(this.getDefaultSubtasksBoardId());
},
async getDefaultSubtasksBoardAsync() {
let boardId = this.getDefaultSubtasksBoardId();
// #6456: server-authoritative lazy creation, once, with the async APIs
// (the sync Boards.insert/Swimlanes.insert/Boards.update this used to rely
// on throw on the Meteor 3 server, so creating a subtask crashed with
// "Exception while invoking method 'addSubtaskCard'").
if (!boardId && Meteor.isServer) {
boardId = await Boards.insertAsync({
title: `^${this.title}^`,
permission: this.permission,
members: sanitizeBoardMembers(this.members),
@@ -1690,25 +1700,14 @@ Boards.helpers({
),
});
Swimlanes.insert({
await Swimlanes.insertAsync({
title: getTranslatedString('default', 'Default'),
boardId: this.subtasksDefaultBoardId,
});
Boards.update(this._id, {
$set: {
subtasksDefaultBoardId: this.subtasksDefaultBoardId,
},
boardId,
});
await this.setSubtasksDefaultBoardId(boardId);
this.subtasksDefaultBoardId = boardId;
}
return this.subtasksDefaultBoardId;
},
getDefaultSubtasksBoard() {
return ReactiveCache.getBoard(this.getDefaultSubtasksBoardId());
},
async getDefaultSubtasksBoardAsync() {
const boardId = this.getDefaultSubtasksBoardId();
if (!boardId) {
return null;
}
@@ -1722,32 +1721,13 @@ Boards.helpers({
//Date Settings option such as received date, start date and so on.
getDefaultDateSettingsBoardId() {
if (
this.dateSettingsDefaultBoardId === null ||
this.dateSettingsDefaultBoardId === undefined
) {
this.dateSettingsDefaultBoardId = Boards.insert({
title: `^${this.title}^`,
permission: this.permission,
members: sanitizeBoardMembers(this.members),
color: this.color,
description: getTranslatedString(
'default-dates-board',
`Default dates board for ${this.title}`,
{ board: this.title },
),
});
Swimlanes.insert({
title: getTranslatedString('default', 'Default'),
boardId: this.dateSettingsDefaultBoardId,
});
Boards.update(this._id, {
$set: {
dateSettingsDefaultBoardId: this.dateSettingsDefaultBoardId,
},
});
}
// #6456 (same class): PURE getter. The lazy sync creation this used had
// BOTH bug classes — no Meteor.isServer guard (client-side creation on
// every reactive read, the #2256/#3868 duplicate-boards class) and the
// sync Boards.insert/Swimlanes.insert/Boards.update APIs that throw on the
// Meteor 3 server. Nothing in the codebase calls it today; if a feature
// needs the dates helper board again, add an async server-side ensure like
// getDefaultSubtasksBoardAsync.
return this.dateSettingsDefaultBoardId;
},
@@ -1756,21 +1736,10 @@ Boards.helpers({
},
getDefaultSubtasksListId() {
// #3868 / #5788 / #2256: server-only auto-creation of the default subtasks
// list (see getDefaultSubtasksBoardId) so the client cannot create
// duplicate lists when the field momentarily reads as unset.
if (
Meteor.isServer &&
(this.subtasksDefaultListId === null ||
this.subtasksDefaultListId === undefined)
) {
this.subtasksDefaultListId = Lists.insert({
title: getTranslatedString('queue', 'Queue'),
boardId: this._id,
swimlaneId: this.getDefaultSwimline()._id, // Set default swimlane for subtasks list
});
this.setSubtasksDefaultListId(this.subtasksDefaultListId);
}
// #3868 / #5788 / #2256 / #6456: PURE getter — client-side creation
// duplicated lists, and the sync Lists.insert this used on the server
// throws on Meteor 3. Server-side creation lives in
// getDefaultSubtasksListAsync.
return this.subtasksDefaultListId;
},
@@ -1779,7 +1748,23 @@ Boards.helpers({
},
async getDefaultSubtasksListAsync() {
const listId = this.getDefaultSubtasksListId();
let listId = this.getDefaultSubtasksListId();
// #6456: server-authoritative lazy creation with the async APIs (the sync
// Lists.insert + getDefaultSwimline() this relied on throw on the Meteor 3
// server — getDefaultSwimline's sync ReactiveCache read even returns a
// Promise there, so .._id was never valid).
if (!listId && Meteor.isServer) {
const swimlane = await this.getDefaultSwimlineAsync();
listId = await Lists.insertAsync({
title: getTranslatedString('queue', 'Queue'),
boardId: this._id,
swimlaneId: swimlane ? swimlane._id : undefined, // Set default swimlane for subtasks list
});
await this.setSubtasksDefaultListId(listId);
this.subtasksDefaultListId = listId;
}
if (!listId) {
return null;
}
@@ -1792,17 +1777,7 @@ Boards.helpers({
},
getDefaultDateSettingsListId() {
if (
this.dateSettingsDefaultListId === null ||
this.dateSettingsDefaultListId === undefined
) {
this.dateSettingsDefaultListId = Lists.insert({
title: getTranslatedString('queue', 'Queue'),
boardId: this._id,
swimlaneId: this.getDefaultSwimline()._id, // Set default swimlane for date settings list
});
this.setDateSettingsDefaultListId(this.dateSettingsDefaultListId);
}
// #6456 (same class): PURE getter — see getDefaultDateSettingsBoardId.
return this.dateSettingsDefaultListId;
},
+8 -39
View File
@@ -1299,51 +1299,20 @@ Cards.helpers({
// customFields with definitions
customFieldsWD() {
// get all definitions
// get all definitions attached to this card's CURRENT board
const definitions = ReactiveCache.getCustomFields({
boardIds: { $in: [this.boardId] },
});
if (!definitions) {
return {};
}
// match right definition to each field
if (!this.customFields) return [];
const ret = this.customFields.map(customField => {
const definition = definitions.find(definition => {
return definition._id === customField._id;
});
if (!definition) {
return {};
}
//search for "True Value" which is for DropDowns other then the Value (which is the id)
let trueValue = customField.value;
if (
definition.settings.dropdownItems &&
definition.settings.dropdownItems.length > 0
) {
for (let i = 0; i < definition.settings.dropdownItems.length; i++) {
if (definition.settings.dropdownItems[i]._id === customField.value) {
trueValue = definition.settings.dropdownItems[i].name;
}
}
}
return {
_id: customField._id,
value: customField.value,
trueValue,
definition,
};
});
// at linked cards custom fields definition is not found
ret.sort(
(a, b) =>
a.definition !== undefined &&
b.definition !== undefined &&
a.definition.name !== undefined &&
b.definition.name !== undefined &&
a.definition.name.localeCompare(b.definition.name),
);
return ret;
// #3748: entries whose definition is not attached to THIS board are
// skipped — on a cross-board linked card the customFields snapshot copied
// by Cards.link() references the ORIGINAL board's definitions, and the old
// `{}` placeholders rendered phantom empty rows in the card details and
// threw in the cardCustomField getTemplate helper.
const { buildCustomFieldsWD } = require('./lib/customFieldsWD');
return buildCustomFieldsWD(this.customFields, definitions);
},
colorClass() {
+84
View File
@@ -0,0 +1,84 @@
'use strict';
// Pure helper for the POST /users/logout REST endpoint (issue #1437: "Old
// tokens are not replaced or set invalid"). Extracted so the request
// validation / Mongo-update planning is unit-testable in plain Node without
// Meteor (mirrors models/lib/restLabel.js and models/lib/boardSortReorder.js).
//
// #1437: the REST API has always had POST /users/login (which mints a new
// resume login token on every call) but never a logout, so tokens acquired
// via the API could not be invalidated — they simply piled up in
// services.resume.loginTokens until their ~90 day expiry ("I have probably
// created 50+ valid tokens recently"). A leaked token therefore stayed valid
// with no server-side way to revoke it short of editing the database.
//
// buildLogoutPlan validates the (already-authenticated) request and yields a
// definite outcome for the route handler:
// - { ok: true, all, selector, modifier } -> caller runs
// Meteor.users.updateAsync(selector, modifier) and reports success.
// - { ok: false, status, error, reason } -> caller sends that JSON error.
//
// Two modes:
// - default: revoke ONLY the token presented in the Authorization header
// ($pull of its hashed form) — other sessions (e.g. the browser GUI)
// stay logged in;
// - { "all": true } in the request body: revoke EVERY resume token of the
// user ("logout everywhere"), cleaning up any accumulated/leaked tokens.
// Truthy spellings accepted for the `all` flag. Body parsing may deliver a
// boolean (JSON body) or a string (urlencoded body), so accept both.
function wantsAllSessions(rawAll) {
if (rawAll === true) return true;
if (typeof rawAll === 'string') {
const s = rawAll.trim().toLowerCase();
return s === 'true' || s === '1' || s === 'yes';
}
if (rawAll === 1) return true;
return false;
}
function buildLogoutPlan(request) {
const { userId, hashedToken, all } =
request && typeof request === 'object' ? request : {};
if (typeof userId !== 'string' || userId.length === 0) {
return {
ok: false,
status: 401,
error: 'unauthorized',
reason:
'You must be logged in to log out. Send your token as an Authorization: Bearer header.',
};
}
const everywhere = wantsAllSessions(all);
if (everywhere) {
return {
ok: true,
all: true,
selector: { _id: userId },
modifier: { $set: { 'services.resume.loginTokens': [] } },
};
}
if (typeof hashedToken !== 'string' || hashedToken.length === 0) {
return {
ok: false,
status: 401,
error: 'unauthorized',
reason: 'No login token found on the request.',
};
}
return {
ok: true,
all: false,
selector: { _id: userId },
modifier: { $pull: { 'services.resume.loginTokens': { hashedToken } } },
};
}
module.exports = {
buildLogoutPlan,
wantsAllSessions,
};
+50
View File
@@ -0,0 +1,50 @@
'use strict';
// Pure helper: build the `meta` object stored on every card attachment
// (Attachments FilesCollection, ostrio:files). Kept side-effect free so it can
// be unit tested without a database or the Meteor client environment.
//
// This single builder is shared by ALL card attachment upload paths:
// - the card Attachments popup and clipboard upload
// (client/components/cards/attachments.js), and
// - images uploaded inside card COMMENTS / the card description through the
// rich text editor (client/components/main/editor.js, summernote
// onImageUpload), via Utils.getCommonAttachmentMetaFrom().
//
// Because comment uploads carry the exact same `meta.cardId` as direct card
// uploads, they are listed in the card's Attachments section, whose queries
// all key on `meta.cardId` (Template.attachmentGallery in
// client/components/cards/attachments.js and Cards.helpers.attachments in
// models/cards.js) with no `meta.source` filtering. That is the behaviour
// requested in https://github.com/wekan/wekan/issues/3843 — an attachment
// added in a card comment must stay linked to (and visible in) the card's
// global attachment list.
//
// For a linked card the attachment is attached to the REAL card (linkedId),
// so it shows up on the original card and on every linked copy.
//
// `getCardById` resolves the real card of a linked card (the client passes
// ReactiveCache.getCard). A missing/null card yields an empty meta rather
// than throwing, so a failed lookup cannot crash an upload handler.
function buildCardAttachmentMeta(card, getCardById) {
const meta = {};
if (!card) {
return meta;
}
if (typeof card.isLinkedCard === 'function' && card.isLinkedCard()) {
const realCard =
typeof getCardById === 'function' ? getCardById(card.linkedId) : null;
if (realCard) {
meta.boardId = realCard.boardId;
}
meta.cardId = card.linkedId;
} else {
meta.boardId = card.boardId;
meta.swimlaneId = card.swimlaneId;
meta.listId = card.listId;
meta.cardId = card._id;
}
return meta;
}
module.exports = { buildCardAttachmentMeta };
+34
View File
@@ -0,0 +1,34 @@
// Pure, dependency-free storage path computation (no Meteor imports) so it can
// be unit tested directly with plain Node. Used by the attachment storage
// settings (Admin Panel > Attachments) and kept in sync with the path logic in
// models/attachments.js, models/avatars.js and server/initializeDirs.js.
//
// #6473: the Admin Panel used to compute these paths ON THE CLIENT from
// process.env.WRITABLE_PATH, which never exists in a browser, so it always
// showed "/data" — a path that does not exist on a Snap install
// (WRITABLE_PATH=$SNAP_COMMON/files there). The real paths are:
// - Docker (WRITABLE_PATH=/data): /data/files/{attachments,avatars}
// - Snap (WRITABLE_PATH=$SNAP_COMMON/files): $SNAP_COMMON/files/{attachments,avatars}
// - Dev (WRITABLE_PATH unset): <cwd>/files/{attachments,avatars}
//
// Snap already appends '/files' to WRITABLE_PATH, so that case is detected and
// '/files' is not appended twice.
const path = require('path');
/**
* Compute the real attachment/avatar storage paths for a given base path.
* @param {string} [basePath] WRITABLE_PATH (falls back to process.cwd())
* @return {{writablePath: string, attachments: string, avatars: string}}
*/
function computeStoragePaths(basePath) {
const base = basePath || process.cwd();
const endsWithFiles = base.endsWith('/files') || base.endsWith('\\files');
const root = endsWithFiles ? base : path.join(base, 'files');
return {
writablePath: base,
attachments: path.join(root, 'attachments'),
avatars: path.join(root, 'avatars'),
};
}
module.exports = { computeStoragePaths };
+75
View File
@@ -0,0 +1,75 @@
'use strict';
// Pure decision helpers for board invitation accept / decline (quit) flows.
// Extracted so the logic is unit-testable in plain Node without Meteor
// (mirrors models/lib/boardSortReorder.js).
//
// #4730 ("Bugs in adding and removing users"):
//
// Case 2 of the issue — "User A declines the invitation but still sees board 1
// in the personal overview" — was caused by the decline handler on the All
// Boards page (client/components/boards/boardsList.js), which calls
// `quitBoard` (deactivates the member entry) and then `acceptInvite` to clear
// the invitation. The old server-side `acceptInvite` unconditionally set
// `members.$.isActive = true`, immediately RE-ACTIVATING the membership that
// `quitBoard` had just deactivated — so the declined board stayed in the
// user's personal overview as an active membership.
//
// The same unconditional re-activation also let any user with a deactivated
// member entry (i.e. someone an admin had removed from the board) re-add
// themselves simply by calling `Meteor.call('acceptInvite', boardId)` — the
// "adding and removing user A again doesn't fix it" half of Case 1.
//
// Fix: activating a membership through acceptInvite is only legitimate while
// the user actually holds an invitation (profile.invitedBoards contains the
// board id). Declining is made robust by having quitBoard clear the pending
// invitation itself, so the follow-up acceptInvite call finds no invitation
// and becomes a no-op. quitBoard also succeeds (instead of throwing
// error-board-notAMember) for a user who holds a stale invitation without a
// member entry — e.g. after an admin removed them — so a stuck invited board
// can always be removed from the personal overview.
// Whether the given user profile holds a pending invitation to boardId.
function isInvitedToBoard(profile, boardId) {
if (!boardId) return false;
const invitedBoards = (profile && profile.invitedBoards) || [];
return Array.isArray(invitedBoards) && invitedBoards.includes(boardId);
}
// Decide what `quitBoard` (leave board / decline invitation) must do.
// - A member quits: deactivate the member entry, and clear any pending
// invitation so a later acceptInvite cannot resurrect the membership.
// - A non-member with a pending (stale) invitation: just clear the invitation
// and report success, so the board disappears from the personal overview.
// - Neither member nor invited: nothing to quit — error.
function planQuitBoard({ isMember, isInvited }) {
if (!isMember && !isInvited) {
return {
ok: false,
removeMember: false,
pullInvite: false,
error: 'error-board-notAMember',
};
}
return {
ok: true,
removeMember: !!isMember,
pullInvite: !!isInvited,
};
}
// Decide what `acceptInvite` must do. Only a user actually holding an
// invitation may (re)activate their member entry; for anyone else the call is
// a no-op (#4730: this is what used to re-activate declined/removed members).
function planAcceptInvite({ isInvited }) {
if (!isInvited) {
return { ok: false, pullInvite: false, activateMember: false };
}
return { ok: true, pullInvite: true, activateMember: true };
}
module.exports = {
isInvitedToBoard,
planQuitBoard,
planAcceptInvite,
};
+60
View File
@@ -0,0 +1,60 @@
'use strict';
// Pure, Meteor-free helpers that scope the Filter / MultiSelection card
// selectors to a single board. Extracted so they are unit-testable in plain
// Node (mirrors models/lib/calendarFilter.js and models/lib/swimlaneFilter.js).
//
// #2306 ("filter to selection"): the filter sidebar's "To selection" button
// queried the client card cache with ONLY the Filter's selector — no boardId —
// so it swept up matching cards from every board present in Minimongo (cards
// from a board being navigated away from, linked-board subscriptions, the
// notifications drawer, popup card data, ...). A later bulk action (archive,
// move, label, ...) on the selection then silently mutated cards on other
// boards. These helpers AND a `boardId` clause into the relevant selectors so
// both the selection query and every bulk action stay contained to the board
// the user is looking at.
// Scope a Filter selector (the object produced by Filter._getMongoSelector())
// to one board. Without a boardId (e.g. on a non-board page) the selector is
// returned unchanged. The board clause is combined via `$and` so it can never
// collide with the Filter's own top-level `$or`.
function boardScopedFilterSelector(filterSelector, boardId) {
const base =
filterSelector && typeof filterSelector === 'object' ? filterSelector : {};
if (!boardId) return base;
return { $and: [base, { boardId }] };
}
// Selector for the cards of a multi-selection, scoped to one board. Bulk
// actions iterate the cards this selector matches, so even if a stale
// selection still holds ids from a previously visited board (the selection is
// not always reset on every navigation path), those foreign cards are never
// touched.
function boardScopedSelectionSelector(selectedCardIds, boardId) {
const selector = {
_id: { $in: Array.isArray(selectedCardIds) ? selectedCardIds : [] },
};
if (boardId) selector.boardId = boardId;
return selector;
}
// Keep only the card ids that belong to `boardId`. `getCard` is a lookup
// (id -> card doc or undefined/null). Ids whose card cannot be found or has no
// boardId are kept (they cannot be positively identified as foreign, and a
// card missing from the cache cannot be acted on anyway); ids whose card
// verifiably lives on ANOTHER board are dropped. Without a boardId or lookup
// function the input is returned unchanged.
function cardIdsOnBoard(cardIds, boardId, getCard) {
if (!Array.isArray(cardIds)) return cardIds;
if (!boardId || typeof getCard !== 'function') return cardIds;
return cardIds.filter(cardId => {
const card = getCard(cardId);
return !card || !card.boardId || card.boardId === boardId;
});
}
module.exports = {
boardScopedFilterSelector,
boardScopedSelectionSelector,
cardIdsOnBoard,
};
+119
View File
@@ -0,0 +1,119 @@
'use strict';
// Pure helpers for the All Boards page board tiles: the per-list card-count
// line ("To Do: 3 Doing: 1 ...") and the board-member avatar row shown on
// each board tile. Extracted so the decision logic is unit-testable in plain
// Node without Meteor (mirrors models/lib/boardSortReorder.js).
//
// Background (#5174 screenshots / #4825 / #4214):
// - The original client helpers computed the counts from reactive
// ReactiveCache.getLists()/getCards() cursors inside the tile helpers,
// which made the All Boards icons re-render in a loop ("icons random
// dance", #4214). They were stubbed out to `return []`, so NO tile ever
// showed its card counts or member avatars again, regardless of the
// Admin Panel settings (hideCardCounterList / hideBoardMemberList) or the
// per-board flags.
// - Before the stubbing, tiles rendered inconsistently (#4825: "Show card
// count per list doesn't deactivate", members never shown): the per-board
// flags (allowsCardCounterList / allowsBoardMemberList, opt-in, default
// false) were evaluated loosely and boards created before the feature
// (#4691) have no field at all.
//
// The fix: a Meteor method (getAllBoardsTileData, server/publications/
// boards.js) computes everything ONCE server-side — list titles + card counts
// via a single grouped query, member ids from the board doc — and the client
// stores the result in a ReactiveVar it sets exactly once (no reactive
// cursors), so #4214 cannot return. These helpers are the pure core:
//
// - showsCardCounterList / showsBoardMemberList: the per-board flags are
// honored STRICTLY (=== true). Disabled or missing flag -> hidden, for
// every board, deterministically (fixes both directions of #4825).
// - buildBoardTileData: folds boards + lists + card counts into the map the
// tiles render from, already gated by those flags so a disabled board
// never even carries the data.
// Whether this board opted in to showing the per-list card counter line on
// its All Boards tile. The schema default is false (opt-in via the board
// sidebar "Show card count per list" checkbox); boards created before the
// feature existed have no field, which must mean "off" — not "sometimes on"
// (#4825).
function showsCardCounterList(board) {
return !!(board && board.allowsCardCounterList === true);
}
// Whether this board opted in to showing the member avatar row on its tile
// ("Show Board members avatars" checkbox). Same strict semantics.
function showsBoardMemberList(board) {
return !!(board && board.allowsBoardMemberList === true);
}
// One entry of the tile's card-counter line, e.g. "To Do: 3".
function formatListCount(title, count) {
const n = typeof count === 'number' && count > 0 ? count : 0;
return `${title || ''}: ${n}`;
}
// Fold card docs (only their listId is needed) into { listId: count }. Used
// by the server method as the portable alternative to a $group aggregation.
function countCardsByListId(cards) {
const counts = {};
(cards || []).forEach((card) => {
if (card && card.listId) {
counts[card.listId] = (counts[card.listId] || 0) + 1;
}
});
return counts;
}
// Build the per-board tile data map:
// { [boardId]: { showLists, showMembers, lists: ['Title: N', ...],
// memberIds: ['userId', ...] } }
//
// - boards: board docs with _id, members, allowsCardCounterList,
// allowsBoardMemberList.
// - lists: list docs with _id, boardId, title, sort (non-archived lists of
// the boards that show counters). Rendered in board order (sort asc, title
// as tiebreaker), like the lists on the board itself.
// - cardCountByListId: { listId: count } for non-archived cards.
//
// Boards whose flag is off (or missing) get empty arrays, so the tile shows
// nothing for them even if a caller forgets to check the show* flags.
function buildBoardTileData(boards, lists, cardCountByListId) {
const counts = cardCountByListId || {};
const tiles = {};
(boards || []).forEach((board) => {
if (!board || !board._id) return;
const showMembers = showsBoardMemberList(board);
tiles[board._id] = {
showLists: showsCardCounterList(board),
showMembers,
lists: [],
memberIds: showMembers
? (board.members || [])
.filter((m) => m && m.userId && m.isActive !== false)
.map((m) => m.userId)
: [],
};
});
const orderedLists = (lists || []).slice().sort((a, b) => {
const sa = a && typeof a.sort === 'number' ? a.sort : 0;
const sb = b && typeof b.sort === 'number' ? b.sort : 0;
if (sa !== sb) return sa - sb;
return String((a && a.title) || '').localeCompare(String((b && b.title) || ''));
});
orderedLists.forEach((list) => {
if (!list || !list.boardId || !list._id) return;
const tile = tiles[list.boardId];
if (!tile || !tile.showLists) return;
tile.lists.push(formatListCount(list.title, counts[list._id]));
});
return tiles;
}
module.exports = {
showsCardCounterList,
showsBoardMemberList,
formatListCount,
countCardsByListId,
buildBoardTileData,
};
+93
View File
@@ -0,0 +1,93 @@
'use strict';
// Pure helpers for repairing duplicate/inverted card `sort` values when a card
// is drag-dropped between two neighbours. Extracted so the decision logic is
// unit-testable in plain Node without Meteor (mirrors models/lib/boardSortReorder.js).
//
// #3826 (cannot reorder cards in a list full of subtask cards): every card
// created through the "add subtask" flow used to be inserted with a constant
// `sort: -1`, so a list populated by subtasks contains ONLY ties. Dropping a
// card between two cards whose sorts are equal is unsolvable for the
// drag-index math (client/lib/utils.js calculateIndexData): no number lies
// strictly between -1 and -1, so it returned base === -1 with increment 0.
// The dropped card's sort was already -1, Card.move()'s no-op guard
// (models/lib/cardMoveModifier.js) discarded the write, and the card snapped
// back to its old place. Worse, a multi-selection drop wrote the SAME sort to
// every selected card (increment 0), permanently destroying their relative
// order — the data-loss noted in triage.
//
// The wiring lives in client/components/lists/list.js (sortable `stop`
// handler); the pieces below are the decisions worth testing in isolation:
// 1. whether the drop landed in a "degenerate" gap that needs repair,
// 2. the minimal set of sort rewrites that makes the visible order strictly
// increasing, and
// 3. the drop index (base + increment) computed from the repaired
// neighbours, guaranteed to fall strictly between them and to give every
// card of a multi-selection a distinct sort.
// A drop between two neighbours is degenerate when both neighbours exist and
// their sorts do not strictly increase (ties from constant-sort inserts,
// legacy inverted data, or non-numeric garbage). Drops at the very top or
// bottom of a list (a single neighbour) always have room and never need
// repair.
function isDegenerateSortGap(prevSort, nextSort) {
if (prevSort === undefined || prevSort === null) return false;
if (nextSort === undefined || nextSort === null) return false;
// Also catches NaN / non-numeric sorts: NaN comparisons are false.
return !(Number(nextSort) - Number(prevSort) > 0);
}
// Given the sibling cards of the drop target in their current VISUAL order
// (excluding the dragged card), return the minimal `{ _id, sort }` rewrites
// that make the sequence strictly increasing. Cards already in strictly
// increasing positions are left untouched (no needless writes / reactive
// churn); each offender is bumped to `previous + 1`.
function computeMonotonicSortRepair(orderedCards) {
const updates = [];
let last = null;
(orderedCards || []).forEach(card => {
if (!card || !card._id) return;
let sort = Number(card.sort);
if (!Number.isFinite(sort) || (last !== null && sort <= last)) {
sort = last === null ? 0 : last + 1;
updates.push({ _id: card._id, sort });
}
last = sort;
});
return updates;
}
// Repair the sibling sorts and compute the drop index between `prevCard` and
// `nextCard` (both `{ _id, sort }`, both members of `orderedCards`). Returns
// {
// updates, // sort rewrites to persist for the sibling cards
// base, // sort for the (first) dropped card
// increment, // spacing for the 2nd..nth card of a multi-selection drop
// }
// After the repair the neighbours strictly increase, so `base` lies strictly
// between them and `increment` is strictly positive: every card of a
// multi-selection keeps a distinct sort (no order data-loss), and the write is
// never equal to a neighbour's sort (so it can not be dropped as a no-op).
function computeRepairedDropIndex(orderedCards, prevCard, nextCard, nCards = 1) {
const updates = computeMonotonicSortRepair(orderedCards);
const repaired = {};
updates.forEach(u => {
repaired[u._id] = u.sort;
});
const sortOf = card =>
card && card._id && Object.prototype.hasOwnProperty.call(repaired, card._id)
? repaired[card._id]
: Number(card && card.sort);
const prevSort = sortOf(prevCard);
const nextSort = sortOf(nextCard);
const n = Number(nCards) >= 1 ? Number(nCards) : 1;
const increment = (nextSort - prevSort) / (n + 1);
const base = prevSort + increment;
return { updates, base, increment };
}
module.exports = {
isDegenerateSortGap,
computeMonotonicSortRepair,
computeRepairedDropIndex,
};
+73
View File
@@ -0,0 +1,73 @@
'use strict';
// #3748: match a card's `customFields` entries to the custom-field definitions
// attached to the card's CURRENT board ("customFields With Definitions").
//
// Linked cards are by design pointers that mirror the original card; labels and
// custom-field DEFINITIONS are board-scoped, so they are deliberately not
// inherited across boards (that remapping-by-name behaviour belongs to the
// COPY path — Cards.copy()/mapCustomFieldsToBoard — not to links). However,
// Cards.link() deep-copies the original document, so a cross-board linked card
// carries a `customFields` snapshot whose definition ids do not exist on the
// viewing board. The old customFieldsWD() returned an empty `{}` placeholder
// for every unmatched entry, which rendered a phantom empty row in the card
// details and made the `cardCustomField` template's getTemplate() helper throw
// "TypeError: Cannot read properties of undefined (reading 'type')" on every
// render. Unmatched entries must be SKIPPED instead.
// A dropdown custom field stores the selected item's id as `value`; the
// human-readable "true value" is the matching dropdown item's name. Any other
// field type (or an id that no longer matches an item) keeps the raw value.
function resolveTrueValue(definition, value) {
const items =
definition && definition.settings && definition.settings.dropdownItems;
if (Array.isArray(items)) {
for (const item of items) {
if (item && item._id === value) {
return item.name;
}
}
}
return value;
}
// customFields: the card's own `customFields` array ([{_id, value}, ...]).
// definitions: the CustomFields definitions attached to the card's board.
// Returns [{_id, value, trueValue, definition}, ...] sorted by definition
// name, with entries whose definition is not on this board left out.
function buildCustomFieldsWD(customFields, definitions) {
if (!Array.isArray(customFields) || !Array.isArray(definitions)) {
return [];
}
const ret = [];
for (const customField of customFields) {
if (!customField) {
continue;
}
const definition = definitions.find(
def => def && def._id === customField._id,
);
if (!definition) {
// e.g. a linked card's snapshot from the original board, or a definition
// that was deleted / detached from this board.
continue;
}
ret.push({
_id: customField._id,
value: customField.value,
trueValue: resolveTrueValue(definition, customField.value),
definition,
});
}
ret.sort((a, b) => {
const aName = a.definition.name;
const bName = b.definition.name;
if (aName === undefined || bName === undefined) {
return 0;
}
return aName.localeCompare(bName);
});
return ret;
}
module.exports = { buildCustomFieldsWD, resolveTrueValue };
+51
View File
@@ -0,0 +1,51 @@
// #1992: restore ALL card date fields when importing a WeKan board export.
//
// The exporter (models/exporter.js) dumps full card documents, so an export
// carries createdAt, receivedAt, startAt, dueAt and endAt. The importer
// (models/wekanCreator.js) previously restored only startAt and dueAt, and
// derived createdAt exclusively from a matching `createCard` activity — but
// Sandstorm exports and old/pruned boards often have no such activity, so the
// card's creation date silently reset to the import time ("dates missing" in
// the issue). receivedAt and endAt were dropped for every import.
//
// This module is pure (no Meteor) so it can be unit-tested with plain Node.
/**
* Parse a date-ish value (ISO string or Date) into a valid Date, or null.
* Invalid values return null instead of an Invalid Date so a corrupt field in
* a foreign/hand-edited export can never fail collection2 validation and
* abort the whole card insert (which would make cards go missing).
*/
function toValidDateOrNull(value) {
if (!value) return null;
const d = new Date(value);
return isNaN(d.getTime()) ? null : d;
}
/**
* Compute the date fields for a card being imported.
*
* @param {Object} card the card object from the export
* @param {String|Date|null} activityCreatedAt creation date recovered from the
* export's `createCard` activity, when one exists (takes precedence,
* matching the importer's historical behaviour)
* @param {Date} now fallback timestamp (the import operation's shared date)
* @returns {{createdAt: Date, receivedAt: ?Date, startAt: ?Date, dueAt: ?Date, endAt: ?Date}}
*/
function importedCardDates(card, activityCreatedAt, now) {
const fallbackNow =
now instanceof Date && !isNaN(now.getTime()) ? now : new Date();
const createdAt =
toValidDateOrNull(activityCreatedAt) ||
toValidDateOrNull(card && card.createdAt) ||
fallbackNow;
return {
createdAt,
receivedAt: toValidDateOrNull(card && card.receivedAt),
startAt: toValidDateOrNull(card && card.startAt),
dueAt: toValidDateOrNull(card && card.dueAt),
endAt: toValidDateOrNull(card && card.endAt),
};
}
module.exports = { importedCardDates, toValidDateOrNull };
+88
View File
@@ -0,0 +1,88 @@
'use strict';
// Pure helpers for the "invite by email" flow (Meteor method `sendInvitation`
// in server/models/settings.js). Extracted so the rules that guarantee "an
// invitation email always carries a code that will validate at sign-up" are
// unit-testable without Meteor.
//
// #4043 ("Sometimes user get board invitation by mail without invitation
// code"): recipients received an invitation email whose code the sign-up form
// then rejected with "The invitation code doesn't exist". Sign-up only accepts
// a code whose stored document matches { code, email, valid: true }
// (server/models/users.js onCreateUser), so the SENDING side must guarantee:
// 1. the stored email is lowercase — the sign-up form lowercases the typed
// address and MongoDB string matching is case sensitive, so a mixed-case
// invitation document can never match (normalizeInviteEmail);
// 2. a RE-INVITE never re-sends a stale code: when the stored invitation is
// no longer valid (e.g. consumed and left with valid:false) or has no
// usable code, a fresh code must overwrite the old one with `valid`
// restored to true (buildReinviteModifier) — this is the fix proposed in
// the #4043 thread ("send a new invitation code that overwrites the last
// one");
// 3. an email is only sent for an invitation document that exists, has a
// non-empty string code, and is still valid (isInvitationCodeSendable) —
// otherwise fail loudly instead of mailing a dead code;
// 4. a failed SMTP send may only roll back (delete) an invitation code that
// was created by this very invite; deleting a PRE-EXISTING document would
// silently invalidate the code already delivered in an earlier email
// (shouldRemoveInvitationOnEmailFailure).
// Lowercase + trim an invitee address so the stored invitation email always
// matches the (lowercased) address the user signs up with. Non-strings
// normalize to '' (callers skip empty results).
function normalizeInviteEmail(email) {
if (typeof email !== 'string') {
return '';
}
return email.trim().toLowerCase();
}
// True when `code` is a non-empty string — the only shape the sign-up lookup
// { code: <string from the form>, valid: true } can ever match. Legacy or
// hand-inserted documents may carry a Number code, which MongoDB will never
// match against the form's string.
function hasUsableCode(invitation) {
return Boolean(
invitation &&
typeof invitation.code === 'string' &&
invitation.code.length > 0,
);
}
// An invitation email may only be sent for a document that exists, carries a
// usable code, and has not been invalidated (valid === false). A missing
// `valid` field (legacy documents predating the field's defaultValue) counts
// as valid.
function isInvitationCodeSendable(invitation) {
return hasUsableCode(invitation) && invitation.valid !== false;
}
// Build the Mongo modifier for re-inviting an email that already has an
// invitation document. Always refreshes boardsToBeInvited; additionally
// overwrites the code (and restores valid:true) when the stored one could
// never validate at sign-up — stale (valid:false), missing, empty, or not a
// string. `generateCode` supplies the new code (coerced to String so it
// matches the form input type regardless of the generator).
function buildReinviteModifier(invitation, boards, generateCode) {
const $set = { boardsToBeInvited: boards };
if (!invitation || invitation.valid === false || !hasUsableCode(invitation)) {
$set.code = String(generateCode());
$set.valid = true;
}
return { $set };
}
// After an SMTP failure, only an invitation created by this very invite call
// may be deleted (nothing was ever delivered for it). A pre-existing document
// must survive, because its code was already delivered in an earlier email.
function shouldRemoveInvitationOnEmailFailure({ isNewInvitation } = {}) {
return isNewInvitation === true;
}
module.exports = {
normalizeInviteEmail,
hasUsableCode,
isInvitationCodeSendable,
buildReinviteModifier,
shouldRemoveInvitationOnEmailFailure,
};
+71
View File
@@ -0,0 +1,71 @@
'use strict';
// Pure helpers for deriving a username for a NEW user invited to a board by
// email address (Meteor method `inviteUserToBoard` in server/models/users.js).
// Extracted so the username-collision rules are unit-testable without Meteor.
//
// #619 ("Not possible to invite multiple users with similar email
// addresses"): inviting cats@foo.com creates a user named "cats" (the email
// local part). Inviting cats@facebook.com afterwards passed the bare local
// part to Accounts.createUser again, which threw Meteor's raw
// `Error 403: Username already exists.` — surfaced in the Add-Member popup as
// an "inaccurate error: 403". The invitee's username is an implementation
// detail here (the human typed an EMAIL, not a username), so instead of
// failing, the caller should pick the first free variant of the local part:
// "cats", "cats1", "cats2", … up to a bounded number of attempts.
// Lowercased local part of an email address ("Cats@Foo.com" -> "cats").
// Mirrors the normalization inviteUserToBoard applies (whole address is
// lowercased before splitting). Returns '' for non-strings and for strings
// without a usable local part (no '@', or '@' first), so callers can treat
// falsy as "not an email".
function usernameFromEmail(email) {
if (typeof email !== 'string') {
return '';
}
const normalized = email.trim().toLowerCase();
const posAt = normalized.indexOf('@');
if (posAt <= 0) {
return '';
}
return normalized.substring(0, posAt);
}
// Derive a username for a new invitee that does not collide with an existing
// account: the email local part itself when free, otherwise the first free
// "<localPart><n>" (n = 1, 2, …). `isUsernameTaken(candidate)` is supplied by
// the caller (sync or async, e.g. a ReactiveCache.getUser lookup) so this
// stays a pure, Meteor-free module.
//
// Returns null when the email has no usable local part or when every
// candidate within `maxAttempts` is taken — callers must treat null as
// "could not create the user" and raise a proper, translatable error instead
// of letting Accounts.createUser throw a raw 403.
async function deriveUniqueInviteeUsername(
email,
isUsernameTaken,
{ maxAttempts = 100 } = {},
) {
if (typeof isUsernameTaken !== 'function') {
throw new TypeError('isUsernameTaken must be a function');
}
const base = usernameFromEmail(email);
if (!base) {
return null;
}
if (!(await isUsernameTaken(base))) {
return base;
}
for (let suffix = 1; suffix < maxAttempts; suffix += 1) {
const candidate = `${base}${suffix}`;
if (!(await isUsernameTaken(candidate))) {
return candidate;
}
}
return null;
}
module.exports = {
usernameFromEmail,
deriveUniqueInviteeUsername,
};
+84
View File
@@ -0,0 +1,84 @@
'use strict';
// #5659 "List Width settings do not affect Public Board".
//
// The default list width used to be duplicated (and DISAGREE) across the
// width-resolution paths:
// - client/components/lists/list.js -> 272 (DEFAULT_LIST_WIDTH)
// - client/components/lists/listHeader.js -> 272/270 hardcoded literals
// - models/lists.js (schema defaultValue) -> 272
// - models/users.js getListWidth() -> 270
// - models/users.js getListWidthFromStorage() (anonymous/public-board
// storage path) -> 270
// - models/users.js getFixedListWidth() -> 272
//
// Depending on which path resolved a given list's width (logged-in member
// profile, anonymous localStorage on a public board, the shared lists.width,
// or fixed-width mode), the fallback "default" differed, so lists on the SAME
// board could render at different widths even though nobody had customized
// anything — most visibly for logged-out visitors of public boards.
//
// This module is the single source of truth. It is Meteor-free so it can be
// unit tested in plain Node (see tests/listWidthDefaults.test.cjs) and is
// imported by both the client width helpers and the user model helpers.
// The one default width every list renders at when no customization exists.
const DEFAULT_LIST_WIDTH = 272;
// The minimum width a customized list may have (matches the resize handle,
// the Set-Width popup validation and the server-side setFixedListWidth check).
const MIN_LIST_WIDTH = 270;
// A width "counts" (may override the default) only when it is a real, finite
// number within the allowed range.
function isValidListWidth(width) {
return (
typeof width === 'number' &&
Number.isFinite(width) &&
width >= MIN_LIST_WIDTH
);
}
// Normalize a stored width: return it when valid, otherwise the fallback
// (the board-wide default unless the caller supplies another).
function normalizeListWidth(width, fallback = DEFAULT_LIST_WIDTH) {
return isValidListWidth(width) ? width : fallback;
}
// Resolve the width ONE list renders at, given the viewer's context:
// - fixedEnabled / fixedWidth : the viewer's per-board "same width for all
// lists" mode (#5729). When on, every list uses the single fixedWidth.
// - sharedWidth : lists.width — the board-wide width shared by
// all viewers (#6409), including logged-out visitors of public boards.
// - personalMode : board.allowsPersonalListWidth.
// - personalWidth : the viewer's own width for this list
// (profile for logged-in users, localStorage for anonymous ones). Only
// consulted in personal mode.
//
// With NO customization at all this always returns DEFAULT_LIST_WIDTH, for
// every list and every viewer — which is what keeps all lists of a public
// board the same width by default.
function resolveListWidth(options) {
const {
fixedEnabled = false,
fixedWidth = null,
sharedWidth = null,
personalMode = false,
personalWidth = null,
} = options || {};
if (fixedEnabled) {
return normalizeListWidth(fixedWidth);
}
const shared = normalizeListWidth(sharedWidth);
if (!personalMode) {
return shared;
}
return normalizeListWidth(personalWidth, shared);
}
module.exports = {
DEFAULT_LIST_WIDTH,
MIN_LIST_WIDTH,
isValidListWidth,
normalizeListWidth,
resolveListWidth,
};
+80
View File
@@ -0,0 +1,80 @@
'use strict';
// #2345 "basic card title filter rules issue".
//
// The board-rule triggers ("when a card is created / moved / archived ...")
// offer a magnifier popup that lets the user restrict the trigger to cards
// whose title matches a filter. Three things were broken:
//
// 1. The generic "when a card is moved" and the archive/unarchive triggers
// never stored the filter at all — worse, they stored NO `cardTitle`
// field, and because the server matches triggers with
// `cardTitle: { $in: [...] }`, a trigger document that lacks the field
// can never match an activity that carries a card title, so those rules
// never fired for anything.
// 2. A stored filter never appeared in the trigger's human-readable
// description ("When a card is moved to list X" — no trace of "Part A"),
// which is exactly what the issue reporter complained about.
// 3. Old trigger documents created before the fix (without a `cardTitle`
// field) must keep behaving as "match every card".
//
// These helpers are pure (no Meteor imports) so both the client wizard and
// server/rulesHelper.js share one tested implementation.
// Normalize the raw popup input into the value stored on the trigger document.
// An empty / whitespace-only / missing filter means "match every card", which
// the rules engine expresses with the '*' wildcard (this matches the UI note:
// "leave a field empty to match every possible value").
function cardTitleFilterOrWildcard(raw) {
if (typeof raw !== 'string') return '*';
const trimmed = raw.trim();
return trimmed === '' ? '*' : trimmed;
}
// Build the list of trigger `cardTitle` values that match an activity whose
// card title is `activityCardTitle`, used as `cardTitle: { $in: [...] }` when
// looking up triggers. A trigger matches when its stored filter is:
// - the exact card title,
// - any single word of the card title (historic behaviour: the title is
// split on non-word characters),
// - the '*' wildcard (no filter set), or
// - null / a missing field (legacy triggers saved without a cardTitle —
// in MongoDB `$in: [null, ...]` also matches documents lacking the field,
// which keeps pre-fix rules firing as "every card").
function cardTitleMatchList(activityCardTitle) {
const matches = ['*', null];
if (activityCardTitle !== undefined && activityCardTitle !== null) {
const title = String(activityCardTitle);
return title
.split(/\W/)
.filter(word => word !== '')
.concat([title])
.concat(matches);
}
return matches;
}
// Pure predicate mirroring the $in semantics above: does a trigger stored with
// `filter` fire for a card titled `cardTitle`? (A missing/null filter — legacy
// trigger — matches everything, like the wildcard.)
function cardTitleFilterMatches(filter, cardTitle) {
if (filter === undefined || filter === null) return true;
return cardTitleMatchList(cardTitle).includes(filter);
}
// Append the filter to the trigger's human-readable description so the rule
// list / rule details show it ("when a card is moved to list x (card title
// filter: "Part A")"). A wildcard/empty filter leaves the description alone.
function appendCardTitleFilterToDesc(desc, cardTitle, label) {
const base = typeof desc === 'string' ? desc : '';
if (!cardTitle || cardTitle === '*') return base;
const tag = label && typeof label === 'string' ? label : 'card title filter';
return `${base} (${tag}: "${cardTitle}")`;
}
module.exports = {
cardTitleFilterOrWildcard,
cardTitleMatchList,
cardTitleFilterMatches,
appendCardTitleFilterToDesc,
};
+80
View File
@@ -0,0 +1,80 @@
'use strict';
// Pure helpers for deriving a unique WeKan username from a Sandstorm
// preferredHandle (used by the Users.after.insert hook in sandstorm.js), split
// out so they can be unit-tested in plain Node (tests/*.test.cjs) without a
// Meteor context.
//
// Fixes #574 "Sandstorm - generation of unique usernames":
// - The uniqueness probe must be CASE-INSENSITIVE. Meteor usernames are
// case-preserving but case-insensitively unique, while the old exact-match
// query was case-sensitive: an existing 'Max' did not stop a new 'max',
// producing two accounts that Meteor's account machinery considers the
// same username.
// - The handle must be regex-escaped before interpolation into the probe so
// a handle containing regex metacharacters is matched literally (Sandstorm
// promises lower-case ASCII letters/digits/underscores, but we must not
// rely on that for query correctness).
// - The probe -> update window is racy: a concurrent insert can claim the
// probed name between our find and our update. accounts-base keeps a
// unique index on `username`, so the losing update throws a MongoDB
// E11000 duplicate-key error; instead of letting that abort the insert
// hook we catch it and retry with the next appended number.
// 'max' + 0 -> 'max', 'max' + 1 -> 'max1', ... (historical numbering: the
// first fallback is 'max1', there is no 'max0').
function generateUniqueUsername(username, appendNumber) {
return username + String(appendNumber === 0 ? '' : appendNumber);
}
// Escape regex metacharacters so the text is matched literally.
function escapeForRegex(text) {
return String(text).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
// Anchored, case-insensitive matcher for a username candidate, safe to put in
// a Mongo `username:` selector.
function usernameCaseInsensitiveRegex(username) {
return new RegExp(`^${escapeForRegex(username)}$`, 'i');
}
// True for MongoDB's duplicate-key error (unique index violation) in the
// shapes the Node driver / Meteor surface it: numeric code 11000/11001, or an
// E11000 marker in the message/errmsg.
function isDuplicateKeyError(error) {
if (!error) return false;
if (error.code === 11000 || error.code === 11001) return true;
const text = `${error.message || ''} ${error.errmsg || ''}`;
return text.includes('E11000') || text.includes('E11001');
}
// Walk appendNumber upward until `isTakenAsync(candidate)` reports the name
// free, then hand the candidate to `claimAsync(candidate)` (the DB update).
// If claiming throws a duplicate-key error — another session raced us to the
// same name — move on to the next number instead of crashing. Any other error
// propagates unchanged. Resolves to the username that was actually claimed.
async function claimUniqueUsername(base, isTakenAsync, claimAsync) {
for (let appendNumber = 0; ; appendNumber += 1) {
const candidate = generateUniqueUsername(base, appendNumber);
if (await isTakenAsync(candidate)) {
continue;
}
try {
await claimAsync(candidate);
return candidate;
} catch (error) {
if (!isDuplicateKeyError(error)) {
throw error;
}
// Lost the race for this candidate; try the next number.
}
}
}
module.exports = {
generateUniqueUsername,
escapeForRegex,
usernameCaseInsensitiveRegex,
isDuplicateKeyError,
claimUniqueUsername,
};
+52
View File
@@ -0,0 +1,52 @@
'use strict';
// Pure, Meteor-free helpers for the swimlane archive/restore card cascade.
// Extracted so the cascade decisions are unit-testable in plain Node
// (mirrors models/lib/defaultSwimlane.js / models/lib/swimlaneFilter.js).
//
// #2292 ("Archive a swimlane drives to deletion of all cards included"):
// archiving a swimlane used to flag ONLY the swimlane document. Its cards
// stayed `archived: false` but became invisible everywhere — the board views
// only render unarchived swimlanes, and the Archive sidebar only lists
// documents with `archived: true`, so the cards showed up in neither. Worse,
// the startup schema upgrade (server/lib/schemaUpgradeSteps.js,
// `swimlane-structure`, #1959/#1971) treats "unarchived card under an
// ARCHIVED swimlane" as broken state and reassigns such cards to a visible
// swimlane — so after a server restart the archived swimlane was emptied for
// good and restoring it produced an empty swimlane, exactly as reported.
//
// The fix mirrors the existing list cascade (models/lists.js archive()/
// restore(), which archive/restore the list's cards with card.archive() /
// card.restore()): archiving a swimlane archives its still-unarchived cards
// so they are visible in Archive and restorable, and restoring the swimlane
// restores the cards that were archived WITH it — not cards the user had
// individually archived beforehand.
// Cards that must be archived together with the swimlane: every card of the
// swimlane that is not archived yet. Already-archived cards are left alone so
// their own archivedAt (and their place in the user's Archive history) is not
// overwritten by the swimlane cascade.
function cardsToArchiveWithSwimlane(cards) {
return (cards || []).filter(card => card && card.archived !== true);
}
// Cards that must be restored together with the swimlane: archived cards of
// the swimlane whose archivedAt is at/after the swimlane's own archivedAt —
// i.e. the ones the archive cascade above archived (the swimlane's archivedAt
// is stamped before the per-card archivedAt). Cards the user archived
// individually BEFORE archiving the swimlane keep their archived state.
// A swimlane archived before this fix has cascade-untouched cards (and may
// even lack archivedAt), so nothing is restored for it — its unarchived cards
// were never hidden by an `archived` flag in the first place.
function cardsToRestoreWithSwimlane(cards, swimlaneArchivedAt) {
if (!swimlaneArchivedAt) return [];
const archivedAtMs = new Date(swimlaneArchivedAt).getTime();
if (Number.isNaN(archivedAtMs)) return [];
return (cards || []).filter(card => {
if (!card || card.archived !== true || !card.archivedAt) return false;
const cardArchivedAtMs = new Date(card.archivedAt).getTime();
return !Number.isNaN(cardArchivedAtMs) && cardArchivedAtMs >= archivedAtMs;
});
}
module.exports = { cardsToArchiveWithSwimlane, cardsToRestoreWithSwimlane };
+108
View File
@@ -0,0 +1,108 @@
'use strict';
// Pure decision logic for keeping board memberships in sync when a user's
// teams change. Extracted so it is unit-testable without Meteor
// (see tests/teamBoardMemberSync.test.cjs).
//
// #4593 ("The new added user that was assigned to existing team cannot be
// applied to kanban with the right authority"): when a team is assigned to a
// board through the board sidebar (addBoardTeamPopup), every user who is in
// the team AT THAT MOMENT is pushed into board.members as a normal member.
// But a user added to the team AFTERWARDS never got a member entry: the
// publications grant them read visibility of the board (boards / board
// publications match `teams.teamId`), yet every authority check that gates
// interaction — board.hasMember() (models/boards.js), allowIsBoardMember*()
// (server/lib/utils.js), Attachments.protected (models/attachments.server.js)
// and board.isVisibleBy() (export) — only looks at board.members. So the new
// team member could at best view the board read-only, could not download its
// attachments, and had strictly less authority than teammates who happened to
// be in the team when it was assigned.
//
// These helpers compute, from a user's old and new team lists, which boards
// must gain the user as a member so a late-joining team member ends up with
// the same authority the team's original members received.
// Return the de-duplicated teamId strings of a user.teams-shaped array
// (`[{ teamId, teamDisplayName }, ...]`). Tolerates a missing/invalid list and
// entries without a teamId.
function teamIdsOf(teams) {
if (!Array.isArray(teams)) return [];
const ids = [];
const seen = new Set();
teams.forEach(team => {
const id = team && team.teamId;
if (!id || typeof id !== 'string' || seen.has(id)) return;
seen.add(id);
ids.push(id);
});
return ids;
}
// Team ids present in newTeams but not in oldTeams — the teams the user just
// gained. Removals are intentionally NOT reported: a user removed from a team
// may also have been invited to a board individually, and membership data
// cannot tell those apart, so team-loss cleanup stays the explicit board-admin
// action it always was (removeBoardTeamPopup).
function gainedTeamIds(oldTeams, newTeams) {
const before = new Set(teamIdsOf(oldTeams));
return teamIdsOf(newTeams).filter(id => !before.has(id));
}
// The member entry a team-derived user receives: a plain active, non-admin
// member, exactly like the entries addBoardTeamPopup creates and with the
// same fully-defaulted flags reconcileBoardTeamMembers assigns to members
// introduced through the team-management path.
function newTeamBoardMemberEntry(userId) {
return {
userId,
isAdmin: false,
isActive: true,
isNoComments: false,
isCommentOnly: false,
isWorker: false,
isNormalAssignedOnly: false,
isCommentAssignedOnly: false,
isReadOnly: false,
isReadAssignedOnly: false,
};
}
// Given the candidate board documents (each with at least _id, type, teams,
// members), the user id and the team ids the user just gained, return the ids
// of the boards the user must be added to as a member:
// - the board must have one of the gained teams assigned AND active,
// - template boards/containers are skipped (#5850: sharing on those is
// group-only; the members tab shows only the creator),
// - a user with ANY existing member entry (even inactive) is left untouched,
// so an explicit per-board decision (e.g. a deactivated member) is never
// silently overridden by a team change.
function boardsToAddMemberTo(boards, userId, gainedIds) {
if (!userId || typeof userId !== 'string') return [];
if (!Array.isArray(boards) || !Array.isArray(gainedIds) || !gainedIds.length) {
return [];
}
const gained = new Set(gainedIds);
const ids = [];
boards.forEach(board => {
if (!board || !board._id) return;
if (board.type === 'template-board' || board.type === 'template-container') {
return;
}
const teams = Array.isArray(board.teams) ? board.teams : [];
const sharedWithGainedTeam = teams.some(
team => team && team.isActive === true && gained.has(team.teamId),
);
if (!sharedWithGainedTeam) return;
const members = Array.isArray(board.members) ? board.members : [];
if (members.some(member => member && member.userId === userId)) return;
ids.push(board._id);
});
return ids;
}
module.exports = {
teamIdsOf,
gainedTeamIds,
newTeamBoardMemberEntry,
boardsToAddMemberTo,
};
+129
View File
@@ -0,0 +1,129 @@
'use strict';
// Cleanup planning for user deletion (issue #1289: "Error after deleting a
// user").
//
// Deleting a user — Admin Panel / People (Meteor method `removeUser`), the
// self-service "delete account" button, or `DELETE /api/users/:userId` — only
// removed the `users` document itself. Every reference to that user stayed
// behind as a dangling id:
//
// - boards.members ([{ userId, isAdmin, ... }]) -> "ghost" members with
// empty avatars that confused boards for years (see the issue thread:
// 2017, 2019, 2021, 2022 and 2025 reports),
// - boards.watchers ([{ userId, level }], complexWatchable),
// - cards.members ([userId]),
// - cards.assignees ([userId]),
// - cards.watchers ([userId], simpleWatchable),
// - lists.watchers ([userId], simpleWatchable),
// - the user's uploaded avatar files (Avatars FilesCollection).
//
// While the client now null-guards missing users (so nothing crashes any
// more), the ghost references themselves previously had to be cleaned up by
// hand, board by board, or by editing MongoDB directly. This module computes
// the cleanup a user deletion implies; models/users.js applies it from a
// `Users.after.remove` collection hook, so every deletion path (method, REST,
// direct removeAsync) is covered.
//
// Activities and comments authored by the user are intentionally KEPT — the
// issue discussion settled on preserving history ("Replacing the username of
// every deleted user ... leaves a lot of conversations indecipherable"), and
// their rendering handles a missing author.
//
// Pure and Meteor-free so tests/userDeletionCleanup.test.cjs can exercise it
// in plain Node (same pattern as models/lib/apiLogout.js and
// models/lib/teamBoardMemberSync.js).
// A userId acceptable in a Mongo selector: a non-empty string. Anything else
// (undefined, null, objects — including selector-injection attempts like
// { $ne: null } — numbers, empty string) yields no cleanup plan.
function isValidUserId(userId) {
return typeof userId === 'string' && userId.length > 0;
}
// Build the collection-by-collection cleanup implied by deleting `userId`.
// Returns null when userId is not a valid id (callers skip cleanup entirely
// rather than run an overly-broad selector).
//
// Shapes follow the schemas:
// boards.members / boards.watchers hold OBJECTS with a userId field, so the
// $pull argument is a sub-document match ({ members: { userId } });
// cards.members / cards.assignees / cards.watchers / lists.watchers hold
// plain userId STRINGS, so the $pull argument is the id itself.
function buildUserDeletionCleanupPlan(userId) {
if (!isValidUserId(userId)) {
return null;
}
return {
boards: {
selector: {
$or: [{ 'members.userId': userId }, { 'watchers.userId': userId }],
},
modifier: {
$pull: { members: { userId }, watchers: { userId } },
},
},
cards: {
selector: {
$or: [{ members: userId }, { assignees: userId }, { watchers: userId }],
},
modifier: {
$pull: { members: userId, assignees: userId, watchers: userId },
},
},
lists: {
selector: { watchers: userId },
modifier: { $pull: { watchers: userId } },
},
avatars: {
// Avatars is an ostrio:files FilesCollection: removeAsync(selector)
// deletes both the records and the stored files, returning the number
// removed (0 when none match — no throw).
selector: { userId },
},
};
}
// Apply a cleanup plan against the given collections. Collections are
// dependency-injected ({ boards, cards, lists, avatars }) so the logic is
// unit-testable with fakes; any collection may be omitted and is then
// skipped. boards/cards/lists need `updateAsync(selector, modifier, options)`
// (multi-update), avatars needs `removeAsync(selector)`.
//
// Returns { boards, cards, lists, avatars } — the per-collection counts the
// drivers reported (0 for skipped collections).
async function applyUserDeletionCleanup(plan, collections) {
const result = { boards: 0, cards: 0, lists: 0, avatars: 0 };
if (!plan || !collections) {
return result;
}
const { boards, cards, lists, avatars } = collections;
if (boards && typeof boards.updateAsync === 'function') {
result.boards =
(await boards.updateAsync(plan.boards.selector, plan.boards.modifier, {
multi: true,
})) || 0;
}
if (cards && typeof cards.updateAsync === 'function') {
result.cards =
(await cards.updateAsync(plan.cards.selector, plan.cards.modifier, {
multi: true,
})) || 0;
}
if (lists && typeof lists.updateAsync === 'function') {
result.lists =
(await lists.updateAsync(plan.lists.selector, plan.lists.modifier, {
multi: true,
})) || 0;
}
if (avatars && typeof avatars.removeAsync === 'function') {
result.avatars = (await avatars.removeAsync(plan.avatars.selector)) || 0;
}
return result;
}
module.exports = {
isValidUserId,
buildUserDeletionCleanupPlan,
applyUserDeletionCleanup,
};
+36 -22
View File
@@ -331,15 +331,25 @@ Lists.helpers({
if (!swimlaneId) {
return undefined;
}
// Only the first swimlane surfaces orphaned cards.
const pick = (swimlanes) => {
if (!swimlanes || !swimlanes.length || swimlanes[0]._id !== swimlaneId) {
return undefined;
}
return swimlanes.map(s => s._id).filter(id => id !== swimlaneId);
};
const swimlanes = ReactiveCache.getSwimlanes(
{ boardId: this.boardId, archived: false },
{ sort: ['sort'] },
);
// Only the first swimlane surfaces orphaned cards.
if (!swimlanes.length || swimlanes[0]._id !== swimlaneId) {
return undefined;
// On the SERVER ReactiveCache.getSwimlanes returns a Promise; reading
// .length off it made this always return undefined there (the orphan
// fallback silently never applied server-side). Resolve it instead; the
// client path stays synchronous.
if (swimlanes && typeof swimlanes.then === 'function') {
return swimlanes.then(pick);
}
return swimlanes.map(s => s._id).filter(id => id !== swimlaneId);
return pick(swimlanes);
},
cards(swimlaneId) {
@@ -348,28 +358,32 @@ Lists.helpers({
// bare top-level `$or`, so it never competes with the board Filter's own
// top-level `$or` when the two selectors are combined.
// #6443: also surface orphaned cards in the first swimlane.
const selector = listCardsSelector(
this._id,
swimlaneId,
this.orphanedCardsSwimlaneIds(swimlaneId),
);
const filterSelector =
typeof Filter !== 'undefined' && typeof Filter.mongoSelector === 'function'
? Filter.mongoSelector(selector)
: selector;
const ret = ReactiveCache.getCards(filterSelector, { sort: ['sort'] });
return ret;
const query = (orphanedIds) => {
const selector = listCardsSelector(this._id, swimlaneId, orphanedIds);
const filterSelector =
typeof Filter !== 'undefined' && typeof Filter.mongoSelector === 'function'
? Filter.mongoSelector(selector)
: selector;
return ReactiveCache.getCards(filterSelector, { sort: ['sort'] });
};
const orphaned = this.orphanedCardsSwimlaneIds(swimlaneId);
if (orphaned && typeof orphaned.then === 'function') {
return orphaned.then(query); // server (async ReactiveCache)
}
return query(orphaned);
},
cardsUnfiltered(swimlaneId) {
// Same swimlane-membership fallback as cards() (#6441/#6443), without the Filter.
const selector = listCardsSelector(
this._id,
swimlaneId,
this.orphanedCardsSwimlaneIds(swimlaneId),
);
const ret = ReactiveCache.getCards(selector, { sort: ['sort'] });
return ret;
const query = (orphanedIds) =>
ReactiveCache.getCards(listCardsSelector(this._id, swimlaneId, orphanedIds), {
sort: ['sort'],
});
const orphaned = this.orphanedCardsSwimlaneIds(swimlaneId);
if (orphaned && typeof orphaned.then === 'function') {
return orphaned.then(query); // server (async ReactiveCache)
}
return query(orphaned);
},
allCards(swimlaneId) {
+25 -1
View File
@@ -524,7 +524,22 @@ Swimlanes.helpers({
await list.archive();
}
}
return await Swimlanes.updateAsync(this._id, { $set: { archived: true, archivedAt: new Date() } });
// #2292: archive the swimlane's cards WITH it, mirroring the card cascade
// of Lists.archive() (models/lists.js). Without this the cards stayed
// `archived: false` under an archived swimlane — invisible in every board
// view AND in the Archive sidebar, and reassigned to another swimlane by
// the startup rescue of #1959/#1971 (server/lib/schemaUpgradeSteps.js),
// so restoring the swimlane later found it empty. The swimlane's
// archivedAt is captured BEFORE the per-card archive() calls stamp each
// card's archivedAt, so restore() below can recognise the cards that were
// archived with the swimlane. Cards already archived by the user keep
// their own archivedAt (see models/lib/swimlaneArchive.js).
const { cardsToArchiveWithSwimlane } = require('./lib/swimlaneArchive');
const archivedAt = new Date();
for (const card of cardsToArchiveWithSwimlane(await this.allCards())) {
await card.archive();
}
return await Swimlanes.updateAsync(this._id, { $set: { archived: true, archivedAt } });
},
async restore() {
@@ -533,6 +548,15 @@ Swimlanes.helpers({
await list.restore();
}
}
// #2292: restore the cards that were archived WITH this swimlane by
// archive() above (their archivedAt is at/after the swimlane's),
// mirroring the card cascade of Lists.restore() (models/lists.js). Cards
// the user archived individually BEFORE archiving the swimlane stay
// archived (see models/lib/swimlaneArchive.js).
const { cardsToRestoreWithSwimlane } = require('./lib/swimlaneArchive');
for (const card of cardsToRestoreWithSwimlane(await this.allCards(), this.archivedAt)) {
await card.restore();
}
return await Swimlanes.updateAsync(this._id, { $set: { archived: false } });
},
+53 -7
View File
@@ -5,6 +5,14 @@ import InviteToBoardRolesSettings, {
INVITE_TO_BOARD_ROLES_ID,
INVITE_TO_BOARD_ROLES_DEFAULT,
} from '/models/inviteToBoardRolesSettings';
// #5659: the default/minimum list width must be the SAME on every resolution
// path (it used to be 270 here but 272 in the client and the lists schema, so
// lists could fall back to different "defaults" on public boards).
import {
DEFAULT_LIST_WIDTH,
MIN_LIST_WIDTH,
normalizeListWidth,
} from '/models/lib/listWidth';
// import { Index, MongoDBEngine } from 'meteor/easy:search'; // Temporarily disabled due to compatibility issues
const { SimpleSchema } = require('/imports/simpleSchema');
const Users = Meteor.users;
@@ -1077,8 +1085,7 @@ Users.helpers({
// #5729 The single width applied to every list when fixed width mode is on.
getFixedListWidth(boardId) {
const { fixedListWidths = {} } = this.profile || {};
const w = fixedListWidths[boardId];
return typeof w === 'number' && w >= 270 ? w : 272;
return normalizeListWidth(fixedListWidths[boardId]);
},
invitedBoards() {
@@ -1168,9 +1175,11 @@ Users.helpers({
getListWidth(boardId, listId) {
const listWidths = this.getListWidths();
if (listWidths[boardId] && listWidths[boardId][listId]) {
return listWidths[boardId][listId];
// #5659: normalize so an out-of-range stored value can not make one
// list's width differ from the shared default everyone else sees.
return normalizeListWidth(listWidths[boardId][listId]);
} else {
return 270; //TODO(mark-i-m): default?
return DEFAULT_LIST_WIDTH;
}
},
getListConstraints() {
@@ -1451,7 +1460,7 @@ Users.helpers({
if (widths[boardId] && widths[boardId][listId]) {
const width = widths[boardId][listId];
// Validate it's a valid number
if (validators.isValidNumber(width, 270, 1000)) {
if (validators.isValidNumber(width, MIN_LIST_WIDTH, 1000)) {
return width;
}
}
@@ -1460,7 +1469,8 @@ Users.helpers({
}
}
return 270; // Return default width
// #5659: same default as every other width-resolution path.
return DEFAULT_LIST_WIDTH;
},
setListWidthToStorage(boardId, listId, width) {
@@ -1470,7 +1480,7 @@ Users.helpers({
}
// Validate width before storing
if (!validators.isValidNumber(width, 270, 1000)) {
if (!validators.isValidNumber(width, MIN_LIST_WIDTH, 1000)) {
console.warn('Invalid list width:', width);
return false;
}
@@ -1949,6 +1959,42 @@ Users.helpers({
});
if (Meteor.isServer) {
// #1289 ("Error after deleting a user"): deleting a user (Admin Panel
// `removeUser` method, self-service account delete, or
// DELETE /api/users/:userId) removed only the users document and left
// dangling references everywhere — "ghost" board members with empty
// avatars, stale card members/assignees and watcher entries — that
// previously had to be cleaned up by hand or by editing the database.
// This after.remove hook runs for every deletion path (they all go through
// Users.removeAsync / Meteor.users.removeAsync on this same collection) and
// prunes those references. Activities/comments are intentionally kept so
// history stays readable; see models/lib/userDeletionCleanup.js.
const {
buildUserDeletionCleanupPlan,
applyUserDeletionCleanup,
} = require('/models/lib/userDeletionCleanup');
Users.after.remove(async function(currentUserId, doc) {
try {
const plan = buildUserDeletionCleanupPlan(doc && doc._id);
if (!plan) return;
await applyUserDeletionCleanup(plan, {
boards: Boards,
// Required lazily: cards/lists/avatars are not imported at the top of
// this shared model, and avatars.js must only resolve server-side
// config when actually needed here.
cards: require('/models/cards').default,
lists: require('/models/lists').default,
avatars: require('/models/avatars').default,
});
} catch (error) {
console.error(
'[userDeletionCleanup] Failed to prune references of deleted user',
doc && doc._id,
error,
);
}
});
Meteor.methods({
// Permanently dismiss the current global announcement for the logged-in
// user (#6051). The version is computed server-side from the current
+20 -6
View File
@@ -8,6 +8,7 @@ import { BOARD_COLORS, CARD_COLORS, SWIMLANE_COLORS } from '/models/metadata/col
import Users from '/models/users';
import { generateUniversalAttachmentUrl } from '/models/lib/universalUrlGenerator';
import { planImportedBoardMember } from '/models/lib/importedBoardMemberPlan';
import { importedCardDates } from '/models/lib/importedCardDates';
import {
getImportExportSecuritySettings,
anonymizedUserWord,
@@ -435,23 +436,36 @@ export class WekanCreator {
if (!listId) {
listId = await this._createDefaultList(boardId);
}
// #1992: restore every card date carried in the export. createdAt
// prefers the export's createCard activity but falls back to the
// card's own createdAt (Sandstorm and old/pruned exports have no
// createCard activity, which used to reset the creation date to the
// import time); receivedAt and endAt were previously dropped entirely.
const cardDates = importedCardDates(
card,
this.createdAt.cards[card._id],
this._now(),
);
const cardToCreate = {
archived: card.archived,
boardId,
cardNumber: card.cardNumber || (await boardObj.getNextCardNumber()),
// very old boards won't have a creation activity so no creation date
createdAt: this._now(this.createdAt.cards[card._id]),
createdAt: cardDates.createdAt,
dateLastActivity: this._now(),
description: card.description,
listId,
swimlaneId: this.swimlanes[card.swimlaneId] || this._defaultSwimlaneId,
sort: card.sort,
title: card.title,
// we attribute the card to its creator if available
userId: this._user(this.createdBy.cards[card._id]),
// we attribute the card to its creator if available: the createCard
// activity's author when present, else the userId stored on the
// exported card itself (again, Sandstorm/old exports lack activities).
userId: this._user(this.createdBy.cards[card._id] || card.userId),
isOvertime: card.isOvertime || false,
startAt: card.startAt ? this._now(card.startAt) : null,
dueAt: card.dueAt ? this._now(card.dueAt) : null,
receivedAt: cardDates.receivedAt,
startAt: cardDates.startAt,
dueAt: cardDates.dueAt,
endAt: cardDates.endAt,
spentTime: card.spentTime || null,
};
// add labels
+10 -1
View File
@@ -408,7 +408,16 @@ var makeTagConstructor = function (tagName) {
var attrs = arguments.length && arguments[0]; // 19
if (attrs && (typeof attrs === 'object')) { // 20
// Treat vanilla JS object as an attributes dictionary. // 21
if (! HTML.isConstructedObject(attrs)) { // 22
// Patched (WeKan #6459): an ARRAY first argument is tag CONTENT, never an
// attributes dictionary. The vm-sandbox patch below made
// isConstructedObject(Array) === false (upstream htmljs returns true), so a
// tag whose inline text compiles to an array — e.g. the jade line
// `label {{_ 'source-board'}}:`, i.e. [TemplateTag, ":"] — got its content
// array assigned to instance.attrs. blaze-tools then serialized it as
// HTML.Attrs(...), and at runtime Blaze._expandAttributes threw "The basic
// TransformingVisitor does not support foreign objects in attributes",
// rendering the whole cardMorePopup (with the Delete option) empty.
if (! Array.isArray(attrs) && ! HTML.isConstructedObject(attrs)) { // 22
instance.attrs = attrs; // 23
i++; // 24
} else if (attrs instanceof HTML.Attrs) { // 25
+5 -5
View File
@@ -1,12 +1,12 @@
{
"name": "wekan",
"version": "v9.90.0",
"version": "v9.97.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "wekan",
"version": "v9.90.0",
"version": "v9.97.0",
"hasInstallScript": true,
"license": "MIT",
"dependencies": {
@@ -12235,9 +12235,9 @@
}
},
"node_modules/websocket-driver": {
"version": "0.7.4",
"resolved": "https://registry.npmjs.org/websocket-driver/-/websocket-driver-0.7.4.tgz",
"integrity": "sha512-b17KeDIQVjvb0ssuSDF2cYXSg2iztliJ4B9WdsuB6J952qCPKmnVq4DyW5motImXHDC1cBT/1UezrJVsKw5zjg==",
"version": "0.7.5",
"resolved": "https://registry.npmjs.org/websocket-driver/-/websocket-driver-0.7.5.tgz",
"integrity": "sha512-ZL2+3c7kMBdIRCMz6l8jQMHyGVxj+UL+xVk74Ombiciboca8rHa15L86B19E5oh1pL9Ii/uj54gtsIrZGMo6zA==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "wekan",
"version": "v9.90.0",
"version": "v9.97.0",
"description": "Open-Source kanban",
"private": true,
"repository": {
@@ -25,7 +25,7 @@
},
"scripts": {
"test": "meteor test --once --driver-package meteortesting:mocha",
"test:unit:node": "node tests/filenameSanitizer.test.cjs && node tests/cardBoardConsistency.test.cjs && node tests/cardUrl.test.cjs && node tests/defaultSwimlane.test.cjs && node tests/cardMoveModifier.test.cjs && node tests/authenticationMethod.test.cjs && node tests/linkedCardTarget.test.cjs && node tests/staleWhileRevalidate.test.cjs && node tests/restArrayParam.test.cjs && node tests/minicardLabelHeight.test.cjs && node tests/dateUtils.normalizeDigits.test.cjs && node tests/reconcileBoardTeamMembers.test.cjs && node tests/rulesBoardSelector.test.cjs && node tests/ruleActionResolve.test.cjs && node tests/boardBackground.test.cjs && node tests/weekStart.test.cjs && node tests/ldapUsernameSlug.test.cjs && node tests/editorSubmitKey.test.cjs && node tests/isoWeek.test.cjs && node tests/boardCopyDefaults.test.cjs && node tests/linkedCardTitle.test.cjs && node tests/commentActivity.test.cjs && node tests/swimlaneSort.test.cjs && node tests/subtaskCopy.test.cjs && node tests/scrollbarCss.test.cjs && node tests/minicardBidiIsolation.test.cjs && node tests/notificationCleanup.test.cjs && node tests/cardSearch.test.cjs && node tests/linkedCardMembers.test.cjs && node tests/verificationEmail.test.cjs && node tests/boardSortReorder.test.cjs && node tests/checklistItemTitles.test.cjs && node tests/swimlaneFilter.test.cjs && node tests/popupOffset.test.cjs && node tests/linkedCardCover.test.cjs && node tests/inviteEmailLanguage.test.cjs && node tests/domainTablePage.test.cjs && node tests/mongoSelectorSafety.test.cjs && node tests/cardsLoading.test.cjs && node tests/base64Chunk.test.cjs && node tests/backupPaths.test.cjs && node tests/backupCron.test.cjs && node tests/avatarUrlSafety.test.cjs && node tests/importedUserReconciliationPlan.test.cjs && node tests/ldapPhoto.test.cjs && node tests/importedBoardMemberPlan.test.cjs && node tests/unit/resetPasswordEmail.test.js",
"test:unit:node": "node tests/filenameSanitizer.test.cjs && node tests/cardBoardConsistency.test.cjs && node tests/cardUrl.test.cjs && node tests/defaultSwimlane.test.cjs && node tests/cardMoveModifier.test.cjs && node tests/authenticationMethod.test.cjs && node tests/linkedCardTarget.test.cjs && node tests/staleWhileRevalidate.test.cjs && node tests/restArrayParam.test.cjs && node tests/minicardLabelHeight.test.cjs && node tests/dateUtils.normalizeDigits.test.cjs && node tests/reconcileBoardTeamMembers.test.cjs && node tests/rulesBoardSelector.test.cjs && node tests/ruleActionResolve.test.cjs && node tests/boardBackground.test.cjs && node tests/weekStart.test.cjs && node tests/ldapUsernameSlug.test.cjs && node tests/ldapGroupAllowlist.test.cjs && node tests/htmljsArrayContent.test.cjs && node tests/cardDescriptionDraft.test.cjs && node tests/commentDraft.test.cjs && node tests/attachmentDeleteGuard.test.cjs && node tests/ruleMoveAction.test.cjs && node tests/snapMigrationRecovery.test.cjs && node tests/migrationAttachmentExtraction.test.cjs && node tests/attachmentRepair.test.cjs && node tests/attachmentStoragePath.test.cjs && node tests/schemaUpgradeSteps.test.cjs && node tests/cpuExec.test.cjs && node tests/cpuExecWiring.test.cjs && node tests/ferretdbHasData.test.cjs && node tests/ferretdbPolling.test.cjs && node tests/uiDensity.test.cjs && node tests/editorSubmitKey.test.cjs && node tests/isoWeek.test.cjs && node tests/boardCopyDefaults.test.cjs && node tests/linkedCardTitle.test.cjs && node tests/commentActivity.test.cjs && node tests/swimlaneSort.test.cjs && node tests/subtaskCopy.test.cjs && node tests/subtasksDefaultBoard.test.cjs && node tests/scrollbarCss.test.cjs && node tests/minicardBidiIsolation.test.cjs && node tests/notificationCleanup.test.cjs && node tests/cardSearch.test.cjs && node tests/linkedCardMembers.test.cjs && node tests/verificationEmail.test.cjs && node tests/boardSortReorder.test.cjs && node tests/checklistItemTitles.test.cjs && node tests/swimlaneFilter.test.cjs && node tests/popupOffset.test.cjs && node tests/linkedCardCover.test.cjs && node tests/inviteEmailLanguage.test.cjs && node tests/domainTablePage.test.cjs && node tests/mongoSelectorSafety.test.cjs && node tests/cardsLoading.test.cjs && node tests/base64Chunk.test.cjs && node tests/backupPaths.test.cjs && node tests/backupCron.test.cjs && node tests/avatarUrlSafety.test.cjs && node tests/importedUserReconciliationPlan.test.cjs && node tests/ldapPhoto.test.cjs && node tests/importedBoardMemberPlan.test.cjs && node tests/unit/resetPasswordEmail.test.js",
"test:unit:all": "npm run test:unit:node && node tests/cards.stickers.test.js && node tests/stickers.test.js && node tests/stickers.packs.test.js && node tests/linkCardPopup.test.js && node tests/trelloCreator.import.test.js && node tests/trelloImport.maplink.test.js && node tests/trelloImport.zip.test.js && node tests/wekanCreator.import.test.js && node tests/wekanCreator.inconsistent.test.js && node tests/unit/oauth2-admin-groups.test.js",
"test:watch": "meteor test --driver-package meteortesting:mocha",
"test:e2e": "node tests/e2e/list-regressions.js",
+3
View File
@@ -19,6 +19,9 @@ Package.onUse(function(api) {
api.use('accounts-base', 'server');
api.use('accounts-password', 'server');
// DDP._CurrentMethodInvocation: server/sync.js clears the inherited login
// invocation context so the org/team sync method call is server-to-server.
api.use('ddp', 'server');
api.use('quave:synced-cron', 'server');
api.addFiles('client/loginHelper.js', 'client');
@@ -0,0 +1,87 @@
'use strict';
// #4158 "Documentation/configuration of LDAP_ENCRYPTION". Historically the
// code only understood two magic strings, and both were misleadingly named:
//
// - 'ssl' meant LDAPS (connect to e.g. port 636, TLS from the first byte),
// which was only discoverable by reading the source;
// - 'tls' meant STARTTLS (connect plaintext, then upgrade), even though the
// wiki claimed 'tls' was "more secure than standard LDAPS" (untrue);
// - the documented value 'true' NEVER worked: settings_get() JSON-parses
// the env string 'true' into boolean true, which matched neither 'ssl'
// nor 'tls', so WeKan silently connected WITHOUT encryption;
// - any other value (typos, 'TRUE', 'StartTLS', ...) also silently meant
// "no encryption".
//
// normalizeLdapEncryption() maps every raw LDAP_ENCRYPTION value onto one of
// three explicit connection modes and, where appropriate, a warning for the
// admin. It never throws and never silently guesses:
//
// raw value (case-insensitive) -> mode warning
// -----------------------------------------------------------------------
// 'true' / boolean true -> 'tls' - (LDAPS)
// 'ssl' (legacy) -> 'tls' deprecation: use 'true'
// 'starttls' -> 'starttls' -
// 'tls' (legacy) -> 'starttls' deprecation: use 'starttls'
// 'false' / boolean false / '' /
// undefined / null -> 'off' -
// anything else -> 'off' clear warning listing the
// accepted values
//
// Backwards compatibility: the legacy values keep their historical meaning
// ('ssl' -> LDAPS, 'tls' -> STARTTLS); they only gain a one-line deprecation
// notice. Unknown values still result in an unencrypted connection (as
// before), but now log loudly instead of failing silent.
//
// The function is dependency-free (no Meteor, no Log) so it can be unit
// tested with plain Node; the caller (ldap.js) decides how to emit warnings.
//
// CommonJS module.exports so it can be `import`ed by the ecmascript package
// and `require`d directly by the plain-Node unit test.
const ACCEPTED_VALUES_HELP =
"accepted values are 'true' (LDAPS), 'starttls' (STARTTLS) and 'false' (no encryption); " +
"the legacy values 'ssl' (same as 'true') and 'tls' (same as 'starttls') also still work";
function normalizeLdapEncryption(value) {
// settings_get() JSON-parses 'true'/'false' env strings into booleans, so
// accept booleans as well as strings.
if (value === true) {
return { mode: 'tls' };
}
if (value === undefined || value === null || value === false) {
return { mode: 'off' };
}
const normalized = String(value).trim().toLowerCase();
switch (normalized) {
case '':
case 'false':
return { mode: 'off' };
case 'true':
return { mode: 'tls' };
case 'ssl':
return {
mode: 'tls',
warning:
"LDAP_ENCRYPTION='ssl' is deprecated, please use LDAP_ENCRYPTION='true' instead (both mean LDAPS; 'ssl' keeps working for now)",
};
case 'starttls':
return { mode: 'starttls' };
case 'tls':
return {
mode: 'starttls',
warning:
"LDAP_ENCRYPTION='tls' is deprecated, please use LDAP_ENCRYPTION='starttls' instead (both mean STARTTLS; 'tls' keeps working for now)",
};
default:
return {
mode: 'off',
warning:
`LDAP_ENCRYPTION='${value}' is not a valid value, connecting WITHOUT encryption; ${ACCEPTED_VALUES_HELP}`,
};
}
}
module.exports = { normalizeLdapEncryption, ACCEPTED_VALUES_HELP };
@@ -0,0 +1,92 @@
'use strict';
// Parse a comma-separated LDAP group allowlist into trimmed non-empty patterns.
// Empty/unset means "no restriction".
function parseGroupAllowlist(value) {
if (typeof value !== 'string' || value.trim() === '') {
return [];
}
return value.split(',').map((s) => s.trim()).filter(Boolean);
}
function normalizeGroupName(value) {
if (typeof value === 'string') {
const v = value.trim();
return v === '' ? null : v;
}
if (Array.isArray(value)) {
for (const entry of value) {
const normalized = normalizeGroupName(entry);
if (normalized) {
return normalized;
}
}
return null;
}
if (value === undefined || value === null) {
return null;
}
const v = String(value).trim();
return v === '' ? null : v;
}
function escapeRegExpChar(ch) {
return /[\\^$.*+?()[\]{}|]/.test(ch) ? `\\${ch}` : ch;
}
// Convert a simple glob pattern to RegExp.
// Supported wildcards:
// * -> any number of characters
// ? -> exactly one character
function globToRegExp(pattern) {
let source = '^';
for (const ch of String(pattern)) {
if (ch === '*') {
source += '.*';
} else if (ch === '?') {
source += '.';
} else {
source += escapeRegExpChar(ch);
}
}
source += '$';
return new RegExp(source);
}
function groupNameMatchesAllowPattern(groupName, pattern) {
const normalizedGroupName = normalizeGroupName(groupName);
if (!normalizedGroupName || typeof pattern !== 'string' || pattern === '') {
return false;
}
if (!pattern.includes('*') && !pattern.includes('?')) {
return normalizedGroupName === pattern;
}
return globToRegExp(pattern).test(normalizedGroupName);
}
function filterGroupsByAllowlist(userGroups, allowPatterns) {
const groups = Array.isArray(userGroups)
? userGroups
.map((groupName) => normalizeGroupName(groupName))
.filter(Boolean)
: [];
if (!Array.isArray(allowPatterns) || allowPatterns.length === 0) {
return groups;
}
return groups.filter((groupName) =>
allowPatterns.some((pattern) => groupNameMatchesAllowPattern(groupName, pattern)),
);
}
module.exports = {
parseGroupAllowlist,
normalizeGroupName,
groupNameMatchesAllowPattern,
filterGroupsByAllowlist,
};
+59 -15
View File
@@ -1,5 +1,18 @@
import { Client } from 'ldapts';
import { Log } from 'meteor/logging';
import { normalizeLdapEncryption } from './encryptionSetting';
import { buildUserIdFilter } from './userIdFilter';
// #4158: warn about a deprecated/invalid LDAP_ENCRYPTION value only once per
// distinct message, not on every single login attempt (LDAP instantiates a
// new connection per login).
const encryptionWarningsShown = new Set();
function warnOnceAboutEncryption(warning) {
if (warning && !encryptionWarningsShown.has(warning)) {
encryptionWarningsShown.add(warning);
Log.warn(warning);
}
}
// copied from https://github.com/ldapjs/node-ldapjs/blob/a113953e0d91211eb945d2a3952c84b7af6de41c/lib/filters/index.js#L167
function escapedToHex (str) {
@@ -53,7 +66,10 @@ export default class LDAP {
timeout : this.constructor.settings_get('LDAP_TIMEOUT'),
connect_timeout : this.constructor.settings_get('LDAP_CONNECT_TIMEOUT'),
idle_timeout : this.constructor.settings_get('LDAP_IDLE_TIMEOUT'),
encryption : this.constructor.settings_get('LDAP_ENCRYPTION'),
// #4158: normalized to 'tls' (LDAPS), 'starttls' or 'off'. Accepts the
// documented 'true'/'starttls'/'false' plus the legacy 'ssl'/'tls'
// (deprecated but still working); anything else warns and means 'off'.
encryption : normalizeLdapEncryption(this.constructor.settings_get('LDAP_ENCRYPTION')).mode,
ca_cert : this.constructor.settings_get('LDAP_CA_CERT'),
reject_unauthorized : this.constructor.settings_get('LDAP_REJECT_UNAUTHORIZED') !== undefined ? this.constructor.settings_get('LDAP_REJECT_UNAUTHORIZED') : true,
Authentication : this.constructor.settings_get('LDAP_AUTHENTIFICATION'),
@@ -117,8 +133,14 @@ export default class LDAP {
tlsOptions.ca = ca;
}
// #4158: surface a deprecation notice for legacy values ('ssl', 'tls')
// and a clear warning for unknown values instead of failing silently.
warnOnceAboutEncryption(
normalizeLdapEncryption(this.constructor.settings_get('LDAP_ENCRYPTION')).warning,
);
let url;
if (this.options.encryption === 'ssl') {
if (this.options.encryption === 'tls') {
url = `ldaps://${this.options.host}:${this.options.port}`;
} else {
url = `ldap://${this.options.host}:${this.options.port}`;
@@ -133,7 +155,7 @@ export default class LDAP {
strictDN : false,
};
if (this.options.encryption === 'ssl') {
if (this.options.encryption === 'tls') {
clientOptions.tlsOptions = tlsOptions;
}
@@ -141,7 +163,7 @@ export default class LDAP {
this.client = new Client(clientOptions);
if (this.options.encryption === 'tls') {
if (this.options.encryption === 'starttls') {
// Set host parameter for tls.connect which is used by starttls. This shouldn't be needed in newer nodejs versions (e.g v5.6.0).
// https://github.com/RocketChat/Rocket.Chat/issues/2035
tlsOptions.host = this.options.host;
@@ -322,16 +344,24 @@ export default class LDAP {
async getUserById(id, attribute) {
await this.bindIfNecessary();
const Unique_Identifier_Field = this.constructor.settings_get('LDAP_UNIQUE_IDENTIFIER_FIELD').split(',');
const escapedValue = hexToLdapEscaped(id);
let filter;
if (attribute) {
filter = `(${attribute}=${escapedValue})`;
} else {
const filters = Unique_Identifier_Field.map((item) => `(${item}=${escapedValue})`);
filter = `(|${filters.join('')})`;
// #4654: the stored services.ldap.id may come from LDAP_UNIQUE_IDENTIFIER_FIELD
// or, when that is unset/empty, from LDAP_USER_SEARCH_FIELD (see
// getLdapUserUniqueID in sync.js), so search over both attribute lists.
// The old code read only LDAP_UNIQUE_IDENTIFIER_FIELD and crashed
// (undefined.split) or built the invalid filter "(|(=value))" when it was
// unset/empty, so background sync never updated existing users.
const filter = buildUserIdFilter(
attribute,
escapedValue,
this.constructor.settings_get('LDAP_UNIQUE_IDENTIFIER_FIELD'),
this.constructor.settings_get('LDAP_USER_SEARCH_FIELD'),
);
if (!filter) {
Log.error('Can\'t search user by id: neither LDAP_UNIQUE_IDENTIFIER_FIELD nor LDAP_USER_SEARCH_FIELD is configured');
return;
}
const searchOptions = {
@@ -420,7 +450,7 @@ export default class LDAP {
// Escape the username to prevent LDAP injection
const escapedUsername = escapedToHex(username);
const searchOptions = {
filter: filter.join('').replace(/#{username}/g, escapedUsername).replace(/\\/g, "\\\\"),
filter: filter.join('').replace(/#{username}/g, escapedUsername),
scope : 'sub',
};
@@ -463,14 +493,28 @@ export default class LDAP {
}
if (this.options.group_filter_group_id_attribute !== '') {
filter.push(`(${this.options.group_filter_group_id_attribute}=${this.options.group_filter_group_name})`);
// #4036: LDAP_GROUP_FILTER_GROUP_NAME accepts a comma-separated list, and
// members of LDAP_SYNC_ADMIN_GROUPS may also log in when admin sync is on
// (previously an admin only in the admin group was locked out entirely).
const names = String(this.options.group_filter_group_name || '')
.split(',').map((s) => s.trim()).filter(Boolean);
if (this.constructor.settings_get('LDAP_SYNC_ADMIN_STATUS') === true) {
names.push(...String(this.constructor.settings_get('LDAP_SYNC_ADMIN_GROUPS') || '')
.split(',').map((s) => s.trim()).filter(Boolean));
}
const clauses = names.map((n) => `(${this.options.group_filter_group_id_attribute}=${n})`);
if (clauses.length === 1) {
filter.push(clauses[0]);
} else if (clauses.length > 1) {
filter.push(`(|${clauses.join('')})`);
}
}
filter.push(')');
// Escape the username to prevent LDAP injection
const escapedUsername = escapedToHex(username);
const searchOptions = {
filter: filter.join('').replace(/#{username}/g, escapedUsername).replace(/\\/g, "\\\\"),
filter: filter.join('').replace(/#{username}/g, escapedUsername),
scope : 'sub',
};
+17 -8
View File
@@ -2,6 +2,16 @@ import {slug, getLdapUsername, getLdapEmail, getLdapUserUniqueID, syncUserData,
import LDAP from './ldap';
import { log_debug, log_info, log_warn, log_error } from './logger';
// Org/team sync is optional enrichment; failed sync must not block login.
async function syncUserGroupsToOrgsTeamsSafe(ldap, ldapUser, userId) {
try {
await syncUserGroupsToOrgsTeams(ldap, ldapUser, userId);
} catch (error) {
const reason = error && (error.reason || error.message || error.error);
log_warn('LDAP org/team sync failed during login; continuing without org/team sync', reason);
}
}
function fallbackDefaultAccountSystem(bind, username, password) {
if (typeof username === 'string') {
if (username.indexOf('@') === -1) {
@@ -199,9 +209,9 @@ Accounts.registerLoginHandler('ldap', async function(loginRequest) {
}
// #4737: sync LDAP groups as Organizations/Teams at login too (default off).
await syncUserGroupsToOrgsTeams(ldap, ldapUser, user._id);
await syncUserGroupsToOrgsTeamsSafe(ldap, ldapUser, user._id);
await Meteor.users.updateAsync(user._id, update_data );
await Meteor.users.updateAsync({ _id: user._id }, update_data);
await syncUserData(user, ldapUser);
@@ -229,6 +239,10 @@ Accounts.registerLoginHandler('ldap', async function(loginRequest) {
const result = await addLdapUser(ldapUser, username, loginRequest.ldapPass);
if (result instanceof Error) {
throw result;
}
if (LDAP.settings_get('LDAP_SYNC_ADMIN_STATUS') === true) {
log_debug('Updating admin status');
const targetGroups = LDAP.settings_get('LDAP_SYNC_ADMIN_GROUPS').split(',');
@@ -247,12 +261,7 @@ Accounts.registerLoginHandler('ldap', async function(loginRequest) {
}
// #4737: sync LDAP groups as Organizations/Teams for the new user (default off).
await syncUserGroupsToOrgsTeams(ldap, ldapUser, result.userId);
if (result instanceof Error) {
throw result;
}
await syncUserGroupsToOrgsTeamsSafe(ldap, ldapUser, result.userId);
return result;
});
+29 -16
View File
@@ -1,7 +1,9 @@
import { SyncedCron } from 'meteor/quave:synced-cron';
import { DDP } from 'meteor/ddp';
import limax from 'limax';
import LDAP from './ldap';
import { slugifyPreservingHyphens } from './usernameSlug';
import { parseGroupAllowlist, filterGroupsByAllowlist } from './groupAllowlist';
import { log_debug, log_info, log_warn, log_error } from './logger';
import { getLdapPhotoBuffer } from './ldapPhoto';
@@ -18,15 +20,6 @@ Object.defineProperty(Object.prototype, "getLDAPValue", {
enumerable: false
});
// #4737: parse a comma-separated LDAP group allowlist setting into a trimmed,
// non-empty array. Returns [] when unset/empty, meaning "no restriction".
function parseGroupAllowlist(value) {
if (typeof value !== 'string' || value.trim() === '') {
return [];
}
return value.split(',').map((s) => s.trim()).filter(Boolean);
}
export function slug(text) {
if (LDAP.settings_get('LDAP_UTF8_NAMES_SLUGIFY') !== true) {
return text;
@@ -253,7 +246,10 @@ export async function syncUserData(user, ldapUser) {
const username = slug(getLdapUsername(ldapUser));
if (user && user._id && username !== user.username) {
log_info('Syncing user username', user.username, '->', username);
await Meteor.users.findOneAsync({ _id: user._id }, { $set: { username }});
// #4654: this was findOne/findOneAsync with the $set passed as the
// options argument, which performs no write — username changes in the
// directory were logged as synced but never saved.
await Meteor.users.updateAsync({ _id: user._id }, { $set: { username }});
}
}
@@ -345,10 +341,12 @@ export async function addLdapUser(ldapUser, username, password) {
userObject.ldap = true;
userObject._id = await Accounts.createUserAsync(userObject);
// Add the services.ldap identifiers
// Add the services.ldap identifiers. #4654: also persist idAttribute so
// the background sync (getUserById in ldap.js) can search by the exact
// attribute the id was taken from instead of guessing from settings.
await Meteor.users.updateAsync({ _id: userObject._id }, {
$set: {
'services.ldap': { id: uniqueId.value },
'services.ldap': { id: uniqueId.value, idAttribute: uniqueId.attribute },
'emails.0.verified': true,
'authenticationMethod': 'ldap',
}});
@@ -422,6 +420,21 @@ export async function importNewUsers(ldap) {
log_info('Import finished. Users imported:', count);
}
// #6461: invoke the app-side LDAP org/team sync as a true server-to-server call.
// A plain Meteor.callAsync here would inherit the CURRENT method invocation —
// the server's applyAsync copies its userId AND connection into the nested call
// — and during login that is the client's `login` method call, so the admin
// guard in setUserOrgsTeamsFromLdap saw a client connection with no logged-in
// user yet and rejected the sync with 'forbidden'. Clearing the invocation
// context makes applyAsync use userId:null/connection:null — the documented
// internal path the method's guard allows — while still going through the
// normal method dispatch (check() audits, EJSON argument cloning).
async function callLdapOrgTeamSyncInternal(userId, groupNames, asOrganization) {
return await DDP._CurrentMethodInvocation.withValue(undefined, () =>
Meteor.callAsync('setUserOrgsTeamsFromLdap', userId, groupNames, asOrganization),
);
}
// #4737: optionally sync a user's LDAP groups as Wekan Organizations and/or
// Teams. Opt-in via LDAP_SYNC_ORGANIZATIONS / LDAP_SYNC_TEAMS (default off). The
// optional comma-separated allowlists LDAP_SYNC_ORGANIZATIONS_GROUPS /
@@ -445,17 +458,17 @@ export async function syncUserGroupsToOrgsTeams(ldap, ldapUser, userId) {
if (syncOrgs) {
const allow = parseGroupAllowlist(LDAP.settings_get('LDAP_SYNC_ORGANIZATIONS_GROUPS'));
const names = allow.length ? userGroups.filter((g) => allow.includes(g)) : userGroups;
const names = filterGroupsByAllowlist(userGroups, allow);
if (names.length > 0) {
await Meteor.callAsync('setUserOrgsTeamsFromLdap', userId, names, true);
await callLdapOrgTeamSyncInternal(userId, names, true);
}
}
if (syncTeams) {
const allow = parseGroupAllowlist(LDAP.settings_get('LDAP_SYNC_TEAMS_GROUPS'));
const names = allow.length ? userGroups.filter((g) => allow.includes(g)) : userGroups;
const names = filterGroupsByAllowlist(userGroups, allow);
if (names.length > 0) {
await Meteor.callAsync('setUserOrgsTeamsFromLdap', userId, names, false);
await callLdapOrgTeamSyncInternal(userId, names, false);
}
}
}
@@ -0,0 +1,49 @@
'use strict';
// #4654: build the LDAP search filter used to re-find an existing user by the
// stored services.ldap.id during background sync
// (LDAP_BACKGROUND_SYNC_KEEP_EXISTANT_USERS_UPDATED).
//
// The stored id is produced by getLdapUserUniqueID() in sync.js, which takes
// the first non-empty attribute from LDAP_UNIQUE_IDENTIFIER_FIELD and falls
// back to LDAP_USER_SEARCH_FIELD. The lookup therefore has to consider both
// settings too. Previously getUserById() used only LDAP_UNIQUE_IDENTIFIER_FIELD:
// when that variable was unset it crashed (undefined.split), aborting the whole
// sync run, and when it was set but empty it produced the invalid filter
// "(|(=value))" seen in the issue logs — either way existing users were never
// updated after the first import ("Can't sync user").
// Split a comma-separated attribute list setting into non-empty names.
// Mirrors the whitespace handling of getLdapUserUniqueID()/getBufferAttributes().
function splitFieldSetting(value) {
if (typeof value !== 'string' || value === '') {
return [];
}
return value.replace(/\s/g, '').split(',').filter(Boolean);
}
// attribute: the stored services.ldap.idAttribute when known (searched as-is);
// escapedValue: the id value already escaped for use inside an LDAP filter;
// uniqueIdentifierFieldSetting / userSearchFieldSetting: the raw settings values.
// Returns the filter string, or null when no usable attribute is configured.
function buildUserIdFilter(attribute, escapedValue, uniqueIdentifierFieldSetting, userSearchFieldSetting) {
if (attribute) {
return `(${attribute}=${escapedValue})`;
}
const fields = splitFieldSetting(uniqueIdentifierFieldSetting)
.concat(splitFieldSetting(userSearchFieldSetting));
const uniqueFields = [...new Set(fields)];
if (uniqueFields.length === 0) {
return null;
}
const filters = uniqueFields.map((field) => `(${field}=${escapedValue})`);
return filters.length === 1 ? filters[0] : `(|${filters.join('')})`;
}
module.exports = {
splitFieldSetting,
buildUserIdFilter,
};
+38 -32
View File
@@ -3,8 +3,7 @@
// objString = ["Org","Team"] for method mapping
async function createObject(initArr, objString)
{
functionName = objString === "Org" ? 'setCreateOrgFromOidc' : 'setCreateTeamFromOidc';
creationString = 'setCreate'+ objString + 'FromOidc';
const functionName = objString === "Org" ? 'setCreateOrgFromOidc' : 'setCreateTeamFromOidc';
return await Meteor.callAsync(functionName,
initArr[0],//displayName
initArr[1],//desc
@@ -15,7 +14,7 @@ async function createObject(initArr, objString)
}
async function updateObject(initArr, objString)
{
functionName = objString === "Org" ? 'setOrgAllFieldsFromOidc' : 'setTeamAllFieldsFromOidc';
const functionName = objString === "Org" ? 'setOrgAllFieldsFromOidc' : 'setTeamAllFieldsFromOidc';
return await Meteor.callAsync(functionName,
initArr[0],//team || org Object
initArr[1],//displayName
@@ -32,7 +31,7 @@ async function updateObject(initArr, objString)
//e.g. collection = "team"
function contains(userObjs, obj, collection)
{
id = collection+'Id';
const id = collection+'Id';
if(typeof userObjs == "undefined" || !userObjs.length)
{
@@ -98,26 +97,33 @@ oauth2AdminStatusFromGroups: function (groups)
// isAdmin: [true, false] -> admin group becomes admin in wekan
// isOrganization: [true, false] -> creates org and adds to user
// displayName: "string"
// #4897: every variable in here used to be an implicit GLOBAL (teamArray,
// orgArray, isAdmin, teams, orgs, group, org, team, ...) shared by all
// concurrent OIDC logins. This function awaits inside its loop, so two logins
// interleaved and pushed each other's teams/orgs/admin flags onto the same
// arrays before writing them to the wrong user document. All state is local
// now, and the collection is addressed as Meteor.users instead of relying on
// a `users` global leaked by the caller.
addGroupsWithAttributes: async function (user, groups){
teamArray=[];
orgArray=[];
isAdmin = [];
teams = user.teams;
orgs = user.orgs;
for (group of groups)
const teamArray=[];
const orgArray=[];
const isAdmin = [];
const teams = user.teams;
const orgs = user.orgs;
for (const group of groups)
{
initAttributes = [
const initAttributes = [
group.displayName,
group.desc || group.displayName,
group.shortName ||group.displayName,
group.website || group.displayName, group.isActive || false];
isOrg = group.isOrganisation || false;
forceCreate = group.forceCreate|| false;
const isOrg = group.isOrganisation || false;
const forceCreate = group.forceCreate|| false;
isAdmin.push(group.isAdmin || false);
if (isOrg)
{
org = await Org.findOneAsync({"orgDisplayName": group.displayName});
let org = await Org.findOneAsync({"orgDisplayName": group.displayName});
if(org)
{
if(contains(orgs, org, "org"))
@@ -136,14 +142,14 @@ addGroupsWithAttributes: async function (user, groups){
{
continue;
}
orgHash = {'orgId': org._id, 'orgDisplayName': group.displayName};
const orgHash = {'orgId': org._id, 'orgDisplayName': group.displayName};
orgArray.push(orgHash);
}
else
{
//start team routine
team = await Team.findOneAsync({"teamDisplayName": group.displayName});
let team = await Team.findOneAsync({"teamDisplayName": group.displayName});
if (team)
{
if(contains(teams, team, "team"))
@@ -162,7 +168,7 @@ addGroupsWithAttributes: async function (user, groups){
{
continue;
}
teamHash = {'teamId': team._id, 'teamDisplayName': group.displayName};
const teamHash = {'teamId': team._id, 'teamDisplayName': group.displayName};
teamArray.push(teamHash);
}
}
@@ -170,32 +176,33 @@ addGroupsWithAttributes: async function (user, groups){
// hence user will get admin privileges in wekan
// E.g. Admin rights will be withdrawn if no group in oidc provider has isAdmin set to true
await users.updateAsync({ _id: user._id }, { $set: {isAdmin: isAdmin.some(i => (i === true))}});
teams = {'teams': {'$each': teamArray}};
orgs = {'orgs': {'$each': orgArray}};
await users.updateAsync({ _id: user._id }, { $push: teams});
await users.updateAsync({ _id: user._id }, { $push: orgs});
await Meteor.users.updateAsync({ _id: user._id }, { $set: {isAdmin: isAdmin.some(i => (i === true))}});
await Meteor.users.updateAsync({ _id: user._id }, { $push: {'teams': {'$each': teamArray}}});
await Meteor.users.updateAsync({ _id: user._id }, { $push: {'orgs': {'$each': orgArray}}});
// remove temporary oidc data from user collection
await users.updateAsync({ _id: user._id }, { $unset: {"services.oidc.groups": []}});
await Meteor.users.updateAsync({ _id: user._id }, { $unset: {"services.oidc.groups": []}});
return;
},
changeUsername: async function(user, name)
{
username = {'username': name};
if (user.username != username) await users.updateAsync({ _id: user._id }, { $set: username});
// #4897: `username` was an implicit global; use a local and update via
// Meteor.users so this no longer depends on a leaked `users` global.
if (user.username !== name) await Meteor.users.updateAsync({ _id: user._id }, { $set: {'username': name}});
},
changeFullname: async function(user, name)
{
username = {'profile.fullname': name};
if (user.username != username) await users.updateAsync({ _id: user._id }, { $set: username});
if ((user.profile || {}).fullname !== name) await Meteor.users.updateAsync({ _id: user._id }, { $set: {'profile.fullname': name}});
},
addEmail: async function(user, email)
{
user_email = user.emails || [];
var contained = false;
position = 0;
// #4897: `user_email` and `position` were implicit globals shared between
// concurrent logins — one login's email list could be spliced/unshifted by
// another login before being $set on this user's document.
let user_email = user.emails || [];
let contained = false;
let position = 0;
for (const [count, mail_hash] of Object.entries(user_email))
{
if (mail_hash['address'] === email)
@@ -213,8 +220,7 @@ addEmail: async function(user, email)
if(!contained)
{
user_email.unshift({'address': email, 'verified': true});
user_email = {'emails': user_email};
await users.updateAsync({ _id: user._id }, { $set: user_email});
await Meteor.users.updateAsync({ _id: user._id }, { $set: {'emails': user_email}});
}
}
}
Loaded 100 of 206 files, more files were not shown because too many files have changed in this diff. Show more