Merge pull request 'Release v0.1.0' (#9) from release/v0.1.0 into production
Release / verify (push) Successful in 23s
Release / tag (push) Successful in 4s
Release / packagist (push) Successful in 3s
Release / sync-develop (push) Successful in 4s

Reviewed-on: #9
This commit was merged in pull request #9.
This commit is contained in:
lil-koneko committed 2026-12-04 01:07:49 +00:00
commit 2539dfcc3e
76 files changed
+3815 -133

No files matched your search

+17
View File
@@ -0,0 +1,17 @@
# Normalise line endings in the repository.
* text=auto eol=lf
# What stays in the repository but is not part of the package that Composer installs (Packagist builds
# the dist archive from `git archive`, which leaves these out).
# Because of that, every CI job that checks out must run in an image with git (webdevops/php has it):
# without git, actions/checkout downloads that same archive and the .gitea/ scripts are missing.
/.gitattributes export-ignore
/.gitea export-ignore
/.gitignore export-ignore
/dev export-ignore
/scripts export-ignore
/TOKENS.md export-ignore
/AGENTS.md export-ignore
/tests export-ignore
/phpunit.xml export-ignore
/pint.json export-ignore
+26
View File
@@ -0,0 +1,26 @@
## Vraag
<!-- Wat was de vraag of de opdracht? Eén of twee zinnen, in de woorden van wie het vroeg. -->
## Wat is er gedaan
<!-- Beknopte lijst: per punt één regel. -->
-
## Zo test je het
<!-- Een checklist die af te vinken is: waar klik je, wat moet je zien. -->
- [ ]
## Zelf getest
<!-- Wat is er al gecontroleerd, en hoe (tests, handmatig, op welke omgeving). Ook wat niet getest is. -->
-
## Tijd en tokens
<!-- De regel(s) uit TOKENS.md van deze PR: uren, tokens, model. -->
## Onderhoud
<!-- Is er onderhoud meegenomen (updates, opruimen, documentatie)? Anders: Niets. -->
## Met de hand te doen
<!-- Wat moet er na het mergen nog met de hand gebeuren (secrets, .env, instellingen)? Anders: Niets. -->
## Vervolgstappen
<!-- Wat ligt er nog, wat is bewust niet gedaan? Anders: Geen. -->
+76
View File
@@ -0,0 +1,76 @@
#!/usr/bin/env python3
"""Turns on auto-merge for a pull request to a release branch (`release/vX.Y.Z`).
Run by the `release-automerge` job whenever such a pull request is opened or updated. Gitea then
merges it by itself once the required check is green, so features flow into the release branch
without anyone pressing the button. A pull request to anything else is left alone: `production`
is merged by hand.
Environment: GT_URL, GT_OWNER, GT_REPO, GT_TOKEN (a token that may edit pull requests),
PULL_REQUEST_NUMBER. Optional: AUTO_MERGE_PREFIX (default "release/"), MERGE_STYLE (default "merge").
Standard library only.
"""
import json
import os
import sys
import urllib.error
import urllib.request
URL = os.environ.get("GT_URL", "").rstrip("/")
OWNER = os.environ.get("GT_OWNER", "")
REPO = os.environ.get("GT_REPO", "")
TOKEN = os.environ.get("GT_TOKEN", "")
NUMBER = os.environ.get("PULL_REQUEST_NUMBER", "").lstrip("#")
PREFIX = os.environ.get("AUTO_MERGE_PREFIX") or "release/"
MERGE_STYLE = os.environ.get("MERGE_STYLE") or "merge"
ALREADY_ON = object()
def api(method, path, body=None):
request = urllib.request.Request(
f"{URL}/api/v1/repos/{OWNER}/{REPO}/{path}",
data=json.dumps(body).encode() if body is not None else None,
method=method,
headers={"Authorization": f"token {TOKEN}", "Content-Type": "application/json"},
)
try:
with urllib.request.urlopen(request, timeout=30) as response:
text = response.read().decode()
except urllib.error.HTTPError as e:
detail = e.read().decode()
# A second push runs this job again while auto-merge is still on: that is what was wanted.
if e.code == 409 and "already scheduled to auto merge" in detail:
return ALREADY_ON
sys.exit(f"Gitea API {method} {path} failed: {e.code} {detail}")
return json.loads(text) if text else None
def main():
if not (URL and OWNER and REPO and TOKEN and NUMBER.isdigit()):
sys.exit("GT_URL, GT_OWNER, GT_REPO, GT_TOKEN and PULL_REQUEST_NUMBER are required.")
pull = api("GET", f"pulls/{NUMBER}") or {}
base_ref = (pull.get("base") or {}).get("ref", "")
if not base_ref.startswith(PREFIX):
print(f"Pull request #{NUMBER} targets {base_ref}, not {PREFIX}*: left alone.")
return
if pull.get("state") != "open" or pull.get("merged"):
print(f"Pull request #{NUMBER} is not open: nothing to do.")
return
answer = api("POST", f"pulls/{NUMBER}/merge", {
"do": MERGE_STYLE,
"merge_when_checks_succeed": True,
"delete_branch_after_merge": False,
})
if answer is ALREADY_ON:
print(f"Auto-merge was already on for pull request #{NUMBER}.")
return
print(f"Auto-merge is on for pull request #{NUMBER}: it merges once the required check is green.")
if __name__ == "__main__":
main()
+85
View File
@@ -0,0 +1,85 @@
#!/usr/bin/env python3
"""PR CI: does this pull request follow the development cycle?
develop -> feature/*, fix/*, ... -> release/vX.Y.Z -> production
(collects features) (release: tag + Packagist)
production -> develop (the sync after a release, by the pipeline)
Pull requests go to a release branch or to production, never to develop.
- to `release/vX.Y.Z`: the release must not be out yet (its version is above the latest tag),
and the pull request does not come from production, develop or another release branch.
- to `production`: only from `release/vX.Y.Z`, with a version above the latest tag, a section
for it in CHANGELOG.md, and no "version" in composer.json (Packagist reads the tag).
Environment: BASE_REF, HEAD_REF. Run in a checkout with the tags (fetch-depth 0).
Standard library + git only.
"""
import json
import os
import subprocess
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import semver # noqa: E402
def tags():
result = subprocess.run(["git", "tag", "--list", "v*"], capture_output=True, text=True)
return result.stdout.split()
def problems(base, head, existing_tags, changelog, composer):
found = []
newest = semver.latest(existing_tags)
if base == "production":
version = semver.release_version(head)
if version is None:
return [f"A pull request to production comes from a branch named release/vX.Y.Z, not from {head or '?'}."]
found += above_latest(version, newest)
if changelog is None or semver.changelog_section(changelog, version) is None:
found.append(f"CHANGELOG.md has no section '## v{semver.text(version)}' for this release.")
if isinstance(composer, dict) and "version" in composer:
found.append("composer.json must not have a \"version\": Packagist takes the version from the tag.")
return found
if base.startswith("release/"):
version = semver.release_version(base)
if version is None:
return [f"{base} is not a release branch name: use release/vX.Y.Z."]
found += above_latest(version, newest, "That release is already out: start the next one.")
if head in ("production", "develop") or head.startswith("release/"):
found.append(f"A release branch takes features (feature/*, fix/*), not {head}.")
return found
return [f"Pull requests go to release/vX.Y.Z or to production, not to {base or '?'}: develop only takes the sync after a release."]
def above_latest(version, newest, hint="The version of a release must be above the latest tag."):
if newest is not None and version <= newest:
return [f"v{semver.text(version)} is not above the latest tag v{semver.text(newest)}. {hint}"]
return []
def main():
base = os.environ.get("BASE_REF", "").strip()
head = os.environ.get("HEAD_REF", "").strip()
changelog = open("CHANGELOG.md", encoding="utf-8").read() if os.path.exists("CHANGELOG.md") else None
try:
composer = json.load(open("composer.json", encoding="utf-8"))
except (OSError, ValueError):
composer = None
found = problems(base, head, tags(), changelog, composer)
for line in found:
print(f"::error::{line}")
if found:
return 1
print(f"{head} -> {base}: follows the development cycle.")
return 0
if __name__ == "__main__":
sys.exit(main())
+82
View File
@@ -0,0 +1,82 @@
#!/usr/bin/env python3
"""PR CI: a pull request must add its row to TOKENS.md.
TOKENS.md holds one row per piece of work: the tokens of the AI model that
went into it and the hours that were worked on it. This check compares the
rows of the pull request with the rows on the branch it goes to, and fails
when the pull request brings no new row. The new rows are printed, so every
pull request shows in its log what it cost.
Exempt, because nobody worked on them: the release pull request of the
pipeline (release/*), the dependency updates (renovate/*), and a pull
request that only carries one long-lived branch into another (production
into staging, staging into production, develop).
Environment (set by the workflow):
BASE_REF the branch the pull request goes to
HEAD_REF the branch the pull request comes from
PR_AUTHOR who opened it
Standard library only.
"""
import os
import subprocess
import sys
LEDGER = "TOKENS.md"
EXEMPT_PREFIXES = ("release/", "renovate/")
EXEMPT_BRANCHES = ("production", "staging", "develop")
EXEMPT_AUTHORS = ("deploy-bot", "renovate-bot")
def rows(text):
"""The rows of the table: the lines that start with a date."""
return [line.strip() for line in text.splitlines() if line.startswith("| 20")]
def git(*args):
return subprocess.run(["git", *args], capture_output=True, text=True)
def main():
base = os.environ.get("BASE_REF", "").strip()
head = os.environ.get("HEAD_REF", "").strip()
author = os.environ.get("PR_AUTHOR", "").strip()
if head.startswith(EXEMPT_PREFIXES) or head in EXEMPT_BRANCHES or author in EXEMPT_AUTHORS:
print(f"No row needed: {head or 'this pull request'} by {author or 'unknown'} is not a piece of work.")
return 0
if not base:
print("BASE_REF is not set: cannot tell which branch this pull request goes to.")
return 1
if not os.path.exists(LEDGER):
print(f"{LEDGER} is missing. See AGENTS.md, 'Token usage and hours'.")
return 1
fetch = git("fetch", "--quiet", "--no-tags", "--depth=1", "origin", base)
if fetch.returncode != 0:
print(f"Could not fetch {base}: {fetch.stderr.strip()}")
return 1
shown = git("show", f"FETCH_HEAD:{LEDGER}")
before = set(rows(shown.stdout)) if shown.returncode == 0 else set()
with open(LEDGER, encoding="utf-8") as handle:
new = [row for row in rows(handle.read()) if row not in before]
if not new:
print(f"This pull request adds no row to {LEDGER}.")
print("Every pull request records what went into it: the tokens of the AI model and the hours.")
print("Add the row with dev/token-usage.py (see AGENTS.md, 'Token usage and hours') and push again.")
return 1
print(f"{len(new)} new row(s) in {LEDGER}:")
for row in new:
print(" " + row)
return 0
if __name__ == "__main__":
sys.exit(main())
+13
View File
@@ -0,0 +1,13 @@
#!/bin/sh
# Installs Trivy at a fixed version, checked against a fixed checksum, so a changed download fails the
# job instead of running. To update: take the version and the checksum of the Linux-64bit tarball from
# https://github.com/aquasecurity/trivy/releases (the checksums file of that release).
set -eu
VERSION=0.77.0
SHA256=c9504e6ff8184b91e8e7266c84ad8538f76347f1e5488e07cb083855883cd9a6
curl -fsSL -o /tmp/trivy.tar.gz "https://github.com/aquasecurity/trivy/releases/download/v${VERSION}/trivy_${VERSION}_Linux-64bit.tar.gz"
echo "${SHA256} /tmp/trivy.tar.gz" | sha256sum -c -
tar -xzf /tmp/trivy.tar.gz -C /usr/local/bin trivy
trivy --version
+49
View File
@@ -0,0 +1,49 @@
#!/usr/bin/env python3
"""Tells Packagist that the package has a new version.
Packagist reads the tags of the repository; this asks it to do that now, instead of waiting for its
own poll. The package must have been submitted on packagist.org once (by hand); until then, and
while PACKAGIST_USERNAME and PACKAGIST_TOKEN are not set, this only says so and succeeds.
Environment: PACKAGIST_USERNAME, PACKAGIST_TOKEN (the API token of the Packagist account, a secret
of the repository), PACKAGE_URL (the public address of the repository).
The token goes in the request and never in the log. Standard library only.
"""
import json
import os
import sys
import urllib.error
import urllib.parse
import urllib.request
USER = os.environ.get("PACKAGIST_USERNAME", "").strip()
TOKEN = os.environ.get("PACKAGIST_TOKEN", "").strip()
PACKAGE_URL = os.environ.get("PACKAGE_URL", "").strip()
def main():
if not (USER and TOKEN):
print("PACKAGIST_USERNAME / PACKAGIST_TOKEN are not set: Packagist was not told. "
"Set both as secrets of the repository once the package is submitted on packagist.org.")
return
if not PACKAGE_URL.startswith("https://"):
sys.exit("PACKAGE_URL must be the public https address of the repository.")
query = urllib.parse.urlencode({"username": USER, "apiToken": TOKEN})
request = urllib.request.Request(
f"https://packagist.org/api/update-package?{query}",
data=json.dumps({"repository": {"url": PACKAGE_URL}}).encode(),
method="POST",
headers={"Content-Type": "application/json"},
)
try:
with urllib.request.urlopen(request, timeout=30) as response:
print(f"Packagist answered {response.status}: it will read the new tag.")
except urllib.error.HTTPError as e:
# Never echo the request (it holds the token); the answer of Packagist says enough.
sys.exit(f"Packagist refused: {e.code} {e.read().decode()[:300]}")
if __name__ == "__main__":
main()
+93
View File
@@ -0,0 +1,93 @@
#!/usr/bin/env python3
"""Removes feature branches that nobody has touched for 30 days.
A branch is removed when all of this is true:
- its name starts with one of PRUNE_PREFIXES (default `feature/,fix/`): production, develop and the
release branches are never touched;
- its last commit is older than PRUNE_DAYS (default 30);
- no pull request from it is open (an open pull request is work in progress, however quiet).
A branch that had a pull request can be brought back from that pull request in Gitea ("Restore branch"),
and a merged one is in its target anyway. DRY_RUN=1 only says what would be removed.
Environment: GT_URL, GT_OWNER, GT_REPO, GT_TOKEN (may delete branches), and optionally PRUNE_DAYS,
PRUNE_PREFIXES, DRY_RUN. Standard library only.
"""
import json
import os
import sys
import urllib.error
import urllib.parse
import urllib.request
from datetime import datetime, timedelta, timezone
URL = os.environ.get("GT_URL", "").rstrip("/")
OWNER = os.environ.get("GT_OWNER", "")
REPO = os.environ.get("GT_REPO", "")
TOKEN = os.environ.get("GT_TOKEN", "")
DAYS = int(os.environ.get("PRUNE_DAYS") or 30)
PREFIXES = tuple(p.strip() for p in (os.environ.get("PRUNE_PREFIXES") or "feature/,fix/").split(",") if p.strip())
DRY_RUN = os.environ.get("DRY_RUN", "").strip().lower() in ("1", "true", "yes")
NEVER = ("production", "develop")
def api(method, path):
request = urllib.request.Request(
f"{URL}/api/v1/repos/{OWNER}/{REPO}/{path}",
method=method,
headers={"Authorization": f"token {TOKEN}"},
)
try:
with urllib.request.urlopen(request, timeout=30) as response:
text = response.read().decode()
except urllib.error.HTTPError as e:
sys.exit(f"Gitea API {method} {path} failed: {e.code} {e.read().decode()}")
return json.loads(text) if text else None
def pages(path):
"""Every item of a paged list."""
page, found = 1, []
while True:
items = api("GET", f"{path}{'&' if '?' in path else '?'}page={page}&limit=50") or []
found += items
if len(items) < 50:
return found
page += 1
def stale(branches, open_heads, now):
"""The names to remove, with how many days they were quiet."""
limit = now - timedelta(days=DAYS)
names = []
for branch in branches:
name = branch["name"]
if name in NEVER or name.startswith("release/") or not name.startswith(PREFIXES) or name in open_heads:
continue
moment = datetime.fromisoformat(branch["commit"]["timestamp"].replace("Z", "+00:00"))
if moment < limit:
names.append((name, (now - moment).days))
return names
def main():
if not (URL and OWNER and REPO and TOKEN):
sys.exit("GT_URL, GT_OWNER, GT_REPO and GT_TOKEN are required.")
open_heads = {(pull.get("head") or {}).get("ref") for pull in pages("pulls?state=open")}
old = stale(pages("branches"), open_heads, datetime.now(timezone.utc))
if not old:
print(f"No {'/'.join(p.rstrip('/') for p in PREFIXES)} branch has been quiet for {DAYS} days.")
return
for name, days in old:
if DRY_RUN:
print(f"Would remove {name} (quiet for {days} days).")
else:
api("DELETE", "branches/" + urllib.parse.quote(name, safe=""))
print(f"Removed {name} (quiet for {days} days).")
if __name__ == "__main__":
main()
+100
View File
@@ -0,0 +1,100 @@
#!/usr/bin/env python3
"""Release step of the `Release` workflow: tag what was just merged into production.
A push to production is a release when it is the merge of a `release/vX.Y.Z` pull request. This
finds that version (from the pull request Gitea knows for the commit, or from the merge message),
and makes the release `vX.Y.Z` on that commit, with the changelog section as its text. Gitea
makes the tag; Packagist picks the tag up in the next step.
Runs again on the same commit without harm: a tag that is already there on that commit is fine.
A push that is not a release merge (a hotfix pushed by an admin, say) makes no release and says so.
Environment: GT_URL, GT_OWNER, GT_REPO, GT_TOKEN (may create releases), COMMIT_HASH.
Standard library + git only.
"""
import json
import os
import re
import subprocess
import sys
import urllib.error
import urllib.request
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import semver # noqa: E402
URL = os.environ.get("GT_URL", "").rstrip("/")
OWNER = os.environ.get("GT_OWNER", "")
REPO = os.environ.get("GT_REPO", "")
TOKEN = os.environ.get("GT_TOKEN", "")
COMMIT = os.environ.get("COMMIT_HASH", "").strip()
def api(method, path, body=None, allow=()):
request = urllib.request.Request(
f"{URL}/api/v1/repos/{OWNER}/{REPO}/{path}",
data=json.dumps(body).encode() if body is not None else None,
method=method,
headers={"Authorization": f"token {TOKEN}", "Content-Type": "application/json"},
)
try:
with urllib.request.urlopen(request, timeout=30) as response:
text = response.read().decode()
except urllib.error.HTTPError as e:
if e.code in allow:
return None
sys.exit(f"Gitea API {method} {path} failed: {e.code} {e.read().decode()}")
return json.loads(text) if text else None
def release_branch_of(commit):
"""The release branch whose pull request made this commit, or None."""
pull = api("GET", f"commits/{commit}/pull", allow=(404,))
head = ((pull or {}).get("head") or {}).get("ref", "")
if semver.release_version(head):
return head
# Gitea's own merge message: "Merge pull request 'title' (#7) from release/v1.2.0 into production".
message = subprocess.run(["git", "log", "-1", "--pretty=%s", commit], capture_output=True, text=True).stdout
found = re.search(r"from (release/v\d+\.\d+\.\d+) into production", message)
return found.group(1) if found else None
def main():
if not (URL and OWNER and REPO and TOKEN):
sys.exit("GT_URL, GT_OWNER, GT_REPO and GT_TOKEN are required.")
if not re.fullmatch(r"[0-9a-f]{40}", COMMIT):
sys.exit("COMMIT_HASH must be the full commit hash.")
branch = release_branch_of(COMMIT)
if branch is None:
print(f"{COMMIT[:8]} is not the merge of a release/vX.Y.Z pull request: no release made.")
return
version = semver.release_version(branch)
tag = f"v{semver.text(version)}"
existing = api("GET", f"releases/tags/{tag}", allow=(404,))
if existing:
print(f"{tag} already exists: nothing to do.")
return
changelog = open("CHANGELOG.md", encoding="utf-8").read() if os.path.exists("CHANGELOG.md") else ""
notes = semver.changelog_section(changelog, version)
if notes is None:
sys.exit(f"CHANGELOG.md has no section for {tag}: the release pull request should have been stopped by PR CI.")
api("POST", "releases", {
"tag_name": tag,
"target_commitish": COMMIT,
"name": tag,
"body": notes,
"draft": False,
"prerelease": False,
})
print(f"Released {tag} on {COMMIT[:8]}.")
if __name__ == "__main__":
main()
+44
View File
@@ -0,0 +1,44 @@
"""Version helpers shared by the release scripts. Standard library only."""
import re
# A version is always three numbers: 1.4.0. The tag has a v in front (v1.4.0), the branch is release/v1.4.0.
VERSION = re.compile(r"(\d+)\.(\d+)\.(\d+)")
RELEASE_BRANCH = re.compile(r"release/v(\d+)\.(\d+)\.(\d+)")
TAG = re.compile(r"v(\d+)\.(\d+)\.(\d+)")
def release_version(branch):
"""The version of a `release/vX.Y.Z` branch as a tuple, or None when it is not one."""
match = RELEASE_BRANCH.fullmatch(branch or "")
return tuple(int(part) for part in match.groups()) if match else None
def tag_version(tag):
match = TAG.fullmatch(tag or "")
return tuple(int(part) for part in match.groups()) if match else None
def latest(tags):
"""The highest version among the tags that are versions, or None."""
versions = [version for version in (tag_version(tag) for tag in tags) if version]
return max(versions) if versions else None
def text(version):
return ".".join(str(part) for part in version)
def changelog_section(changelog, version):
"""The body under `## vX.Y.Z` of the changelog, up to the next `## `; None when there is no such heading."""
heading = re.compile(rf"^##\s+v?{re.escape(text(version))}(\s|$)")
lines = changelog.splitlines()
for index, line in enumerate(lines):
if heading.match(line):
body = []
for following in lines[index + 1:]:
if following.startswith("## "):
break
body.append(following)
return "\n".join(body).strip()
return None
+67
View File
@@ -0,0 +1,67 @@
#!/usr/bin/env python3
"""Starts a release: makes the branch release/vX.Y.Z from develop.
Features are pull requests to that branch (they merge by themselves when CI is green). When the release
is ready, a pull request from it to production makes the release.
Environment: GT_URL, GT_OWNER, GT_REPO, GT_TOKEN (may create branches), VERSION (1.4.0, or v1.4.0).
Standard library only.
"""
import json
import os
import re
import sys
import urllib.error
import urllib.request
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import semver # noqa: E402
URL = os.environ.get("GT_URL", "").rstrip("/")
OWNER = os.environ.get("GT_OWNER", "")
REPO = os.environ.get("GT_REPO", "")
TOKEN = os.environ.get("GT_TOKEN", "")
def api(method, path, body=None, allow=()):
request = urllib.request.Request(
f"{URL}/api/v1/repos/{OWNER}/{REPO}/{path}",
data=json.dumps(body).encode() if body is not None else None,
method=method,
headers={"Authorization": f"token {TOKEN}", "Content-Type": "application/json"},
)
try:
with urllib.request.urlopen(request, timeout=30) as response:
text = response.read().decode()
except urllib.error.HTTPError as e:
if e.code in allow:
return None
sys.exit(f"Gitea API {method} {path} failed: {e.code} {e.read().decode()}")
return json.loads(text) if text else None
def main():
if not (URL and OWNER and REPO and TOKEN):
sys.exit("GT_URL, GT_OWNER, GT_REPO and GT_TOKEN are required.")
given = os.environ.get("VERSION", "").strip().lstrip("v")
if not semver.VERSION.fullmatch(given):
sys.exit(f"'{given}' is not a version: use three numbers, like 1.4.0.")
version = tuple(int(part) for part in given.split("."))
tags = [tag["name"] for tag in api("GET", "tags?limit=50") or []]
newest = semver.latest(tags)
if newest is not None and version <= newest:
sys.exit(f"v{given} is not above the latest tag v{semver.text(newest)}.")
name = f"release/v{given}"
if api("GET", f"branches/{name}", allow=(404,)):
sys.exit(f"{name} already exists.")
api("POST", "branches", {"new_branch_name": name, "old_branch_name": "develop"})
print(f"{name} made from develop. Make features as pull requests to it; when it is ready, open one to production.")
if __name__ == "__main__":
main()
+82
View File
@@ -0,0 +1,82 @@
#!/usr/bin/env python3
"""Sync step of the `Release` workflow: merge production into develop.
Runs after a release, so `develop` always contains what is live. Features are made from develop, so
it must be on the latest production before the next release is started.
`develop` takes direct pushes (only `production` and the release branches are protected),
so this is a plain merge and push: fast-forward when possible, otherwise a
merge commit `chore: sync production into develop`.
A conflict fails the step on purpose. The release itself is done by then; the
red build is the signal that `develop` holds something production does not
and needs a merge by hand.
Environment: GT_URL, GT_OWNER, GT_REPO, GT_TOKEN (an access token
that may push to develop), COMMIT_HASH (the commit this job released; defaults
to the tip of production). SYNC_REMOTE overrides the clone URL (local testing).
Standard library + git only.
"""
import json
import os
import re
import subprocess
import tempfile
import urllib.request
URL = os.environ.get("GT_URL", "").rstrip("/")
OWNER = os.environ.get("GT_OWNER", "")
REPO = os.environ.get("GT_REPO", "")
TOKEN = os.environ.get("GT_TOKEN", "")
REMOTE = os.environ.get("SYNC_REMOTE", "")
MESSAGE = "chore: sync production into develop"
def git(repo, *args, check=True):
result = subprocess.run(["git", "-C", repo, *args], capture_output=True, text=True)
if check and result.returncode != 0:
raise SystemExit(f"git {' '.join(args[:2])} failed: {result.stderr.strip()}")
return result
def main():
user = os.environ.get("GT_BOT_USER") or "sync"
remote = REMOTE
if not remote:
if not (URL and OWNER and REPO and TOKEN):
raise SystemExit("GT_URL, GT_OWNER, GT_REPO and GT_TOKEN are required")
remote = f"https://{user}:{TOKEN}@{URL.split('://', 1)[1]}/{OWNER}/{REPO}.git"
repo = os.path.join(tempfile.mkdtemp(), "repo")
result = subprocess.run(["git", "clone", "--quiet", "--branch", "develop", remote, repo],
capture_output=True, text=True)
if result.returncode != 0:
raise SystemExit(f"Could not clone develop: {result.stderr.strip()}")
git(repo, "config", "user.name", user)
git(repo, "config", "user.email", f"{user}@iriks-it.nl")
commit = os.environ.get("COMMIT_HASH", "").strip()
source = commit if re.fullmatch(r"[0-9a-f]{40}", commit) else "origin/production"
short = git(repo, "rev-parse", "--short", source).stdout.strip()
if git(repo, "merge-base", "--is-ancestor", source, "HEAD", check=False).returncode == 0:
print(f"develop already contains production ({short}) — nothing to do.")
return
merge = git(repo, "merge", "--no-edit", "-m", MESSAGE, source, check=False)
if merge.returncode != 0:
conflicts = git(repo, "diff", "--name-only", "--diff-filter=U", check=False).stdout.strip()
raise SystemExit(
f"production ({short}) does not merge cleanly into develop — merge it by hand.\n"
f"Conflicting files:\n{conflicts or merge.stdout.strip() or merge.stderr.strip()}"
)
push = git(repo, "push", "--quiet", "origin", "HEAD:refs/heads/develop", check=False)
if push.returncode != 0:
raise SystemExit(f"Could not push develop: {push.stderr.strip()}")
print(f"develop now contains production ({short}).")
if __name__ == "__main__":
main()
+101
View File
@@ -0,0 +1,101 @@
"""Tests of the release scripts: `python3 -m unittest discover -s .gitea/scripts` (run by the `flow` job)."""
import os
import sys
import unittest
from datetime import datetime, timezone
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import check_flow # noqa: E402
import prune_branches # noqa: E402
import semver # noqa: E402
TAGS = ["v0.1.0", "v0.2.0", "v0.10.0", "not-a-version"]
CHANGELOG = "# Changelog\n\n## v0.11.0 - 2026-12-10\n\n- A feature\n- Another\n\n## v0.10.0 - 2026-12-01\n\n- Older\n"
class Versions(unittest.TestCase):
def test_release_branch(self):
self.assertEqual(semver.release_version("release/v1.2.3"), (1, 2, 3))
for wrong in ("release/1.2.3", "release/v1.2", "feature/x", "release/v1.2.3-rc1", "", None):
self.assertIsNone(semver.release_version(wrong))
def test_latest_is_numeric_not_alphabetical(self):
self.assertEqual(semver.latest(TAGS), (0, 10, 0))
self.assertIsNone(semver.latest(["x"]))
def test_changelog_section(self):
self.assertEqual(semver.changelog_section(CHANGELOG, (0, 11, 0)), "- A feature\n- Another")
self.assertEqual(semver.changelog_section(CHANGELOG, (0, 10, 0)), "- Older")
self.assertIsNone(semver.changelog_section(CHANGELOG, (0, 1, 0)))
self.assertIsNone(semver.changelog_section(CHANGELOG, (0, 1, 1)))
class Flow(unittest.TestCase):
def check(self, base, head, tags=TAGS, changelog=CHANGELOG, composer=None):
return check_flow.problems(base, head, tags, changelog, composer or {"name": "x/y"})
def test_release_to_production(self):
self.assertEqual(self.check("production", "release/v0.11.0"), [])
def test_production_only_from_a_release_branch(self):
self.assertTrue(self.check("production", "feature/x"))
self.assertTrue(self.check("production", "develop"))
def test_release_must_be_above_the_latest_tag(self):
self.assertTrue(self.check("production", "release/v0.10.0"))
self.assertTrue(self.check("production", "release/v0.9.0"))
def test_release_needs_its_changelog_section(self):
self.assertTrue(self.check("production", "release/v0.12.0"))
self.assertTrue(self.check("production", "release/v0.11.0", changelog=None))
def test_composer_json_has_no_version(self):
self.assertTrue(self.check("production", "release/v0.11.0", composer={"version": "0.11.0"}))
def test_features_into_an_open_release_branch(self):
self.assertEqual(self.check("release/v0.11.0", "feature/x"), [])
self.assertEqual(self.check("release/v0.11.0", "fix/y"), [])
def test_nothing_into_a_release_that_is_out(self):
self.assertTrue(self.check("release/v0.10.0", "feature/x"))
def test_a_release_branch_takes_no_long_lived_branch(self):
for head in ("production", "develop", "release/v0.12.0"):
self.assertTrue(self.check("release/v0.11.0", head))
def test_nothing_goes_to_develop_or_anything_else(self):
self.assertTrue(self.check("develop", "feature/x"))
self.assertTrue(self.check("main", "feature/x"))
def test_first_release_without_tags(self):
self.assertEqual(self.check("production", "release/v0.1.0", tags=[], changelog="## v0.1.0 - x\n\n- a\n"), [])
class Prune(unittest.TestCase):
NOW = datetime(2026, 12, 4, tzinfo=timezone.utc)
def branch(self, name, day):
return {"name": name, "commit": {"timestamp": f"{day}T10:00:00Z"}}
def names(self, branches, open_heads=()):
return [name for name, _ in prune_branches.stale(branches, set(open_heads), self.NOW)]
def test_removes_only_quiet_feature_and_fix_branches(self):
branches = [
self.branch("feature/old", "2026-10-01"), self.branch("fix/old", "2026-11-01"),
self.branch("feature/new", "2026-11-20"), self.branch("feature/edge", "2026-11-05"),
]
self.assertEqual(self.names(branches), ["feature/old", "fix/old"])
def test_never_removes_the_long_lived_branches(self):
old = "2025-01-01"
branches = [self.branch(n, old) for n in ("production", "develop", "release/v0.1.0", "renovate/x", "other")]
self.assertEqual(self.names(branches), [])
def test_keeps_a_branch_with_an_open_pull_request(self):
self.assertEqual(self.names([self.branch("feature/old", "2026-01-01")], open_heads=["feature/old"]), [])
if __name__ == "__main__":
unittest.main()
+142 -8
View File
@@ -1,18 +1,152 @@
name: PR CI
# Pull requests go to a release branch (features) or to production (the release). develop only takes
# the sync after a release. See README.md, "Development cycle".
on:
pull_request:
branches: [production, staging]
branches: ['release/**', production]
env:
COMPOSER_NO_INTERACTION: '1'
jobs:
pr-ci:
# Does the pull request follow the cycle: right branches, a version above the latest tag, a changelog
# section for a release.
flow:
runs-on: docker
container:
image: webdevops/php:8.4
steps:
- uses: actions/checkout@v4
- run: composer validate
- run: composer install --no-interaction --prefer-dist
- run: vendor/bin/pint --test
- run: vendor/bin/pest
- run: composer audit
- name: checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: tests of the release scripts
run: python3 -m unittest discover -s .gitea/scripts
- name: development cycle
run: |
git config --global --add safe.directory "$(pwd)"
python3 .gitea/scripts/check_flow.py
env:
BASE_REF: ${{ github.base_ref }}
HEAD_REF: ${{ github.head_ref }}
# Every piece of work records its tokens and hours (TOKENS.md). Exempt: release/*, renovate/*, bots.
ledger:
runs-on: docker
container:
image: webdevops/php:8.4
steps:
- name: checkout
uses: actions/checkout@v4
- name: token ledger updated
run: |
git config --global --add safe.directory "$(pwd)"
python3 .gitea/scripts/check_tokens.py
env:
BASE_REF: ${{ github.base_ref }}
HEAD_REF: ${{ github.head_ref }}
PR_AUTHOR: ${{ github.event.pull_request.user.login }}
# Style and tests, with the newest dependencies the constraints allow and with the oldest: a package
# has to work for everyone in between.
test:
runs-on: docker
container:
image: webdevops/php:8.4
strategy:
fail-fast: false
matrix:
dependencies: [stable, lowest]
steps:
- name: checkout
uses: actions/checkout@v4
- name: cache composer downloads
uses: actions/cache@v4
with:
path: ~/.composer/cache
key: composer-${{ matrix.dependencies }}-${{ hashFiles('composer.json') }}
restore-keys: |
composer-${{ matrix.dependencies }}-
- name: composer validate
run: composer validate --strict --no-check-lock
- name: install dependencies (${{ matrix.dependencies }})
run: |
if [ "${{ matrix.dependencies }}" = "lowest" ]; then
composer update --prefer-lowest --prefer-stable --prefer-dist
else
composer update --prefer-stable --prefer-dist
fi
- name: lint (pint)
if: matrix.dependencies == 'stable'
run: vendor/bin/pint --test
- name: pest tests
run: vendor/bin/pest
# Known vulnerabilities in the dependencies, and secrets or bad settings in the repository.
security:
runs-on: docker
container:
image: webdevops/php:8.4
steps:
- name: checkout
uses: actions/checkout@v4
- name: install dependencies
run: composer update --prefer-stable --prefer-dist --no-scripts
- name: composer audit
run: composer audit
- name: install trivy
run: .gitea/scripts/install-trivy.sh
# Fails on HIGH and CRITICAL. vendor/ is left out of the secret and settings scan (it is other
# people's code); the lock file made above is what the vulnerability scan reads.
- name: trivy
run: |
trivy fs --no-progress --scanners vuln,secret,misconfig --severity HIGH,CRITICAL --exit-code 1 --skip-dirs vendor .
# Pull requests to a release branch merge by themselves when the check below is green.
# Every job that checks out runs in an image with git: without git the checkout is the archive of the
# repository, which leaves out what .gitattributes export-ignores (.gitea/ with these scripts).
release-automerge:
runs-on: docker
needs: pr-ci
if: startsWith(github.base_ref, 'release/') && needs.pr-ci.result == 'success'
container:
image: webdevops/php:8.4
steps:
- name: checkout
uses: actions/checkout@v4
- name: enable auto-merge
run: python3 .gitea/scripts/auto_merge.py
env:
GT_URL: https://git.iriks.casa
GT_OWNER: iriks-it
GT_REPO: laravel-manager
GT_TOKEN: ${{ secrets.DEPLOY_TOKEN }}
PULL_REQUEST_NUMBER: ${{ github.event.pull_request.number }}
# The one check the branch protection asks for (`PR CI / pr-ci (pull_request)`): green only when
# every job above is. Do not rename it without changing the protection rule.
pr-ci:
runs-on: docker
needs: [flow, ledger, test, security]
if: always()
container:
image: alpine:3.20
steps:
- name: all checks green
run: |
echo "flow=${{ needs.flow.result }} ledger=${{ needs.ledger.result }} test=${{ needs.test.result }} security=${{ needs.security.result }}"
[ "${{ needs.flow.result }}" = "success" ] && [ "${{ needs.ledger.result }}" = "success" ] && [ "${{ needs.test.result }}" = "success" ] && [ "${{ needs.security.result }}" = "success" ]
+30
View File
@@ -0,0 +1,30 @@
name: Prune branches
# Every night: remove feature/* and fix/* branches that nobody touched for 30 days and that have no
# open pull request. production, develop and the release branches are never removed.
on:
schedule:
- cron: '15 4 * * *'
workflow_dispatch:
inputs:
dry_run:
description: 'Only say what would be removed (1) or remove it (0)'
default: '1'
jobs:
prune:
runs-on: docker
container:
image: webdevops/php:8.4
steps:
- name: checkout
uses: actions/checkout@v4
- name: remove quiet branches
run: python3 .gitea/scripts/prune_branches.py
env:
GT_URL: https://git.iriks.casa
GT_OWNER: iriks-it
GT_REPO: laravel-manager
GT_TOKEN: ${{ secrets.DEPLOY_TOKEN }}
DRY_RUN: ${{ inputs.dry_run }}
+90
View File
@@ -0,0 +1,90 @@
name: Release
# A push to production is the merge of a release pull request. Check it once more, tag it, tell
# Packagist, and bring develop up to date, so the next features start from what was released.
on:
push:
branches: [production]
concurrency:
group: release
cancel-in-progress: false
jobs:
verify:
runs-on: docker
container:
image: webdevops/php:8.4
steps:
- name: checkout
uses: actions/checkout@v4
- name: install dependencies
run: composer update --prefer-stable --prefer-dist
- name: pest tests
run: vendor/bin/pest
- name: composer audit
run: composer audit
tag:
runs-on: docker
needs: verify
container:
image: webdevops/php:8.4
steps:
- name: checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: release
run: |
git config --global --add safe.directory "$(pwd)"
python3 .gitea/scripts/release.py
env:
GT_URL: https://git.iriks.casa
GT_OWNER: iriks-it
GT_REPO: laravel-manager
GT_TOKEN: ${{ secrets.DEPLOY_TOKEN }}
COMMIT_HASH: ${{ github.sha }}
# Needs the secrets PACKAGIST_USERNAME and PACKAGIST_TOKEN on the repository, and the package
# submitted on packagist.org once. Without them this step only says so.
packagist:
runs-on: docker
needs: tag
container:
image: webdevops/php:8.4
steps:
- name: checkout
uses: actions/checkout@v4
- name: tell Packagist
run: python3 .gitea/scripts/packagist.py
env:
PACKAGIST_USERNAME: ${{ secrets.PACKAGIST_USERNAME }}
PACKAGIST_TOKEN: ${{ secrets.PACKAGIST_TOKEN }}
PACKAGE_URL: https://git.iriks.casa/iriks-it/laravel-manager
# Last: merge what was released into develop. Runs even when Packagist could not be told.
sync-develop:
runs-on: docker
needs: [tag, packagist]
if: always() && needs.tag.result == 'success'
container:
image: webdevops/php:8.4
steps:
- name: checkout
uses: actions/checkout@v4
- name: sync develop
run: python3 .gitea/scripts/sync_develop.py
env:
GT_URL: https://git.iriks.casa
GT_OWNER: iriks-it
GT_REPO: laravel-manager
GT_TOKEN: ${{ secrets.DEPLOY_TOKEN }}
GT_BOT_USER: deploy-bot
COMMIT_HASH: ${{ github.sha }}
+32
View File
@@ -0,0 +1,32 @@
name: Scheduled checks
# What was released does not stay safe: new vulnerabilities are found in old dependencies. Every
# Monday the released code is checked again; a red run is the signal.
on:
schedule:
- cron: '30 5 * * 1'
workflow_dispatch:
jobs:
audit:
runs-on: docker
container:
image: webdevops/php:8.4
steps:
- name: checkout production
uses: actions/checkout@v4
with:
ref: production
- name: install dependencies
run: composer update --prefer-stable --prefer-dist --no-scripts
- name: composer audit
run: composer audit
- name: install trivy
run: .gitea/scripts/install-trivy.sh
- name: trivy
run: |
trivy fs --no-progress --scanners vuln,secret,misconfig --severity HIGH,CRITICAL --exit-code 1 --skip-dirs vendor .
+27
View File
@@ -0,0 +1,27 @@
name: Start release
# By hand (Actions → Start release → Run workflow): makes release/vX.Y.Z from develop.
on:
workflow_dispatch:
inputs:
version:
description: 'Version of the release, like 0.2.0'
required: true
jobs:
start:
runs-on: docker
container:
image: webdevops/php:8.4
steps:
- name: checkout
uses: actions/checkout@v4
- name: make the release branch
run: python3 .gitea/scripts/start_release.py
env:
GT_URL: https://git.iriks.casa
GT_OWNER: iriks-it
GT_REPO: laravel-manager
GT_TOKEN: ${{ secrets.DEPLOY_TOKEN }}
VERSION: ${{ inputs.version }}
+1
View File
@@ -2,3 +2,4 @@ vendor/
composer.lock
.phpunit.result.cache
.env
__pycache__/
+3 -3
View File
@@ -9,11 +9,11 @@ between lil-koneko.com, CarsHub, iriks-it.nl and bouwbedrijf.iriks-it.nl, as one
- Core modules (users, media) are on by default; the rest is off or on per `config/manager.php`.
- Nothing site-specific in the package. A site's own part is its own module class.
- Tests: `composer test` (Pest + Testbench); style: `composer lint` (Pint).
- Branches: `production` is main, work on `feature/…` from `develop`; I never merge to `production`.
- No mention of an AI in commits or PRs. Keep a row per piece of work in `TOKENS.md` (`dev/token-usage.py`).
- Branches: `production` is what is released, `develop` is production plus nothing (the sync), `release/vX.Y.Z` collects the features of a release. Work on `feature/…` or `fix/…` from `develop` and open the pull request to the **release branch**; never to `develop` or `production`. A release is a pull request from the release branch to `production`, merged by hand: never by me. See the README, "Development cycle".
- No mention of an AI in commits or PRs. Keep a row per piece of work in `TOKENS.md` (`dev/token-usage.py`; helper agents are counted in the row, one row per model).
## Open decisions
1. Frontend: ship the Inertia/Vue screens inside the package (built assets, published to the host) or make the package headless with a separate UI package.
2. Moving the real controllers, revisions, audit log and the Thijs-style "simple screens" from bouwbedrijf.iriks-it.nl, module by module.
2. Moving the rest from bouwbedrijf.iriks-it.nl, module by module: pages, reviews, then revisions, audit log, login and profile. Users, media and posts (with labels) are done. Leave out what is site-specific (the IriksIT API disk, the owner's simple screens, client names): this repo is public.
3. How the host's own `User` and a package `Group` relate when the host has its own roles.
+17
View File
@@ -0,0 +1,17 @@
# Changelog
Every release has a section here, named after its version (for example `v0.1.0 - 2026-12-04`, as a second-level
heading). The release pull request to `production` is stopped by PR CI when its section is missing, and the text of
the section is the text of the release in Gitea.
## v0.1.0 - 2026-12-04
First version.
- The module registry, with a switch per part of the manager. A part that is off has no routes, tables, menu
item or permissions.
- Users: accounts, groups and permissions (a permission can need another), and `manager:create-user`.
- Media: the library on a Laravel disk and the public file route `/media-files/{id}/{name}/view`.
- Posts: drafts, scheduling, Markdown, categories and tags.
- MIT license; the development cycle with release branches, tags and Packagist, and CI with tests, `composer audit`
and Trivy.
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Iriks IT
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+92 -6
View File
@@ -31,11 +31,97 @@ that one is off.
Implement `IriksIT\Manager\Contracts\Module` (or extend `Modules\BaseModule`), keep `routes.php` and a
`migrations/` folder next to the class, and add the class to `available` in the config.
## State of this first version
## Users module
Done: module registry and switches, permissions per module as gates, groups, super admin, routes and
migrations per module, a menu that shows only what an account may reach, tests (`composer test`).
Accounts and groups. `HasManagerAccess` on the host `User` model gives it `managerGroups()`,
`managerPermissions()`, `hasManagerPermission()`, `managerOutranks()` and `managerMayGive()`.
Keep `is_super_admin` out of `$fillable`: nobody becomes a super admin through a form.
Not done yet, on purpose: the screens. The modules answer with JSON; the frontend (the Inertia/Vue
screens of bouwbedrijf.iriks-it.nl, or something the package ships itself) is the next decision, see
`AGENTS.md`.
```bash
php artisan manager:create-user # the only way to make a super admin
```
- A group is a name plus permissions; a permission that needs another one (`posts.publish` needs
`posts.write`) brings it along. Permissions of a module that is off are ignored.
- Whoever manages accounts only touches accounts that need nothing more than their own rights, and
only hands out groups that give nothing they lack themselves.
- `groups.manage` is a gate for super admins only, not a permission of a group.
- The package defines one gate per permission and **no `Gate::before`**: it never answers for the
abilities of your own app.
- The migration adds `is_super_admin` to your users table (the table of `manager.user_model`). It
promotes nobody.
## Media module
Files live on a Laravel filesystem disk (`manager.media.disk`); each row remembers its own disk.
- Manager (behind `manager.middleware`): `GET /manager/media`, `/manager/media/items`, `POST`,
`PUT /{id}`, `DELETE /{id}`. Limits (total room, file size, extensions) are in `manager.media.*`.
- Visitors: `GET /media-files/{id}/{filename}/view`, outside the manager, no session. ETag, byte
ranges, `nosniff`, and only images, video and PDF are shown inline. Rate limiter `media-files`.
- Where a file is used: other modules or your app register a source with
`app(IriksIT\Manager\Support\MediaUsage::class)->register(fn () => $texts)`. Posts and Pages do.
- No SVG: it can carry scripts.
## Posts module
Posts written in Markdown, with drafts, scheduling, categories and tags.
- Routes under `/manager`: `posts` (list, `create`, `{id}/edit`, `{id}/preview`, update, `{id}/online`,
delete) and `labels` (categories and tags: make, rename, merge, remove). Rights: `posts.view`, `write`,
`publish`, `delete`, `labels`.
- Who may not publish only saves drafts, and cannot change or delete a post that is live or scheduled.
- A post is a draft (`published_at` null), scheduled (in the future) or published. For your public pages:
`IriksIT\Manager\Models\Post::published()`, `toCard()` and `IriksIT\Manager\Support\Markdown::toHtml()`
(raw HTML is escaped, external links open in a new window). The package has no public post routes: the
host decides what a visitor sees.
- Categories offered in the form: `manager.posts.categories`, the ones in use, the ones made by hand and
whatever your site adds with
`app(IriksIT\Manager\Modules\Posts\PostLabels::class)->suggestCategories(fn () => $titles)`.
- Covers and bodies count as use of a media file.
## State of this version
Done: module registry and switches, permissions per module, users (accounts, groups, command), media
(library and public file route) and posts (with categories and tags), 59 tests (`composer test`).
The answers of every action are JSON, in the shape the screens of bouwbedrijf.iriks-it.nl got as
Inertia props. The screens themselves are not in the package yet: the frontend is an open decision
(`AGENTS.md`). Pages and reviews are still skeletons (a list), and login, profile, the audit log and revisions are not
ported yet.
## Development cycle
```
develop ── feature/*, fix/* ──► release/vX.Y.Z ──► production ──► tag vX.Y.Z ──► Packagist
▲ (pull request, (collects the (pull request, │
│ merges by itself) features) merged by hand) │
└──────────────────────── sync: production into develop ◄─────────────────────────┘
```
1. **Start a release:** Actions → *Start release* → version (`0.2.0`). That makes `release/v0.2.0` from `develop`.
2. **Features:** branch `feature/…` or `fix/…` from `develop`, open a pull request to the release branch. It
merges by itself when *PR CI* is green. Every pull request adds its row to `TOKENS.md`.
3. **Ready:** add a section `## v0.2.0 - date` to `CHANGELOG.md` and open a pull request from the release branch
to `production`. A person merges it.
4. **Release (automatic, on the merge):** tests and audit once more, the tag `v0.2.0` and a Gitea release with the
changelog text, Packagist is told, and `production` is merged into `develop`.
Nobody opens a pull request to `develop`, and `production` and the release branches take no direct pushes.
| When | What runs |
|---|---|
| Pull request to a release branch or to production | *flow* (right branches, version above the latest tag, changelog section, tests of these scripts), *ledger* (`TOKENS.md`), *test* (Pint, Pest with the newest and the oldest dependencies, `composer validate`), *security* (`composer audit`, Trivy on the dependencies, secrets and settings). The check `PR CI / pr-ci` is green when all are. |
| Push to production | verify (Pest, audit), tag and release, Packagist, sync develop |
| Every Monday | `composer audit` and Trivy on production |
| Every night | *Prune branches*: removes `feature/*` and `fix/*` branches whose last commit is over 30 days old and that have no open pull request (a branch of a pull request can be restored from it in Gitea) |
Secrets of the repository for this: `DEPLOY_TOKEN` (the organisation has it), and `PACKAGIST_USERNAME` and
`PACKAGIST_TOKEN` once the package is submitted on packagist.org (until then that step only says so).
## What Composer installs
`.gitattributes` leaves what only belongs to the repository out of the package (`export-ignore`): `.gitea/`,
`dev/`, `scripts/`, `tests/`, `TOKENS.md`, `AGENTS.md`, `phpunit.xml` and the dotfiles. They stay in the repository.
Packagist builds the archive from `git archive`, so what a site installs is `src/`, `config/`, `routes/`,
`resources/`, `composer.json`, `README.md` and `CHANGELOG.md`. Check it with `git archive HEAD | tar -t`.
+11 -3
View File
@@ -1,6 +1,14 @@
# Tokenverbruik van dit project
# Tokenverbruik en uren van dit project
Per stuk werk een rij; zie `dev/token-usage.py`.
| Datum | Onderdeel | Versie | Model | Stappen | Uitvoer | Invoer | Cache geschreven | Cache gelezen |
|---|---|---|---|---|---|---|---|---|
| Datum | Onderdeel | Versie | Model | Stappen | Uitvoer | Invoer | Cache geschreven | Cache gelezen | Uren |
|---|---|---|---|---:|---:|---:|---:|---:|---:|
| 2026-12-04 | Eerste opzet van het pakket: modules, schakelaars, rechten. Gebruikers en media uit bouwbedrijf overgezet | - | claude-sonnet-5-5 | 34 | 57.433 | 76 | 131.194 | 3.225.205 | 0,18 |
| 2026-12-04 | Posts overgezet: berichten met concepten, inplannen, categorieën en tags | - | claude-sonnet-5-5 | 9 | 19.897 | 20 | 35.420 | 1.584.858 | 0,03 |
| 2026-12-04 | Token-script telt de tokens van helper-agents mee in de rij, per model | - | claude-sonnet-5-5 | 16 | 27.013 | 36 | 45.155 | 2.982.056 | 0,06 |
| 2026-12-04 | CI en releaseproces opgezet: releasebranch, tag, Packagist, sync naar develop, tests, audit en Trivy | - | claude-sonnet-5-5 | 14 | 31.242 | 30 | 48.735 | 3.520.606 | 0,09 |
| 2026-12-04 | Opstart van de release gerepareerd en oude featurebranches na 30 dagen automatisch opruimen | - | claude-sonnet-5-5 | 14 | 14.499 | 32 | 14.175 | 4.138.947 | 0,08 |
| 2026-12-04 | De eerste release gestart en het LICENSE-bestand (MIT) toegevoegd voor Packagist | - | claude-sonnet-5-5 | 13 | 14.884 | 32 | 14.810 | 3.953.265 | 0,07 |
| 2026-12-04 | Changelog van de eerste release ingevuld en de release klaargezet | - | claude-sonnet-5-5 | 8 | 7.421 | 16 | 15.226 | 2.534.041 | 0,02 |
| 2026-12-04 | De changelog van de eerste release hersteld, de kop stond verkeerd | - | claude-sonnet-5-5 | 5 | 3.535 | 10 | 6.917 | 1.656.465 | 0,03 |
+9 -2
View File
@@ -6,10 +6,17 @@
"keywords": ["laravel", "manager", "cms", "admin", "modules"],
"require": {
"php": "^8.4",
"illuminate/support": "^13.0",
"illuminate/auth": "^13.0",
"illuminate/cache": "^13.0",
"illuminate/console": "^13.0",
"illuminate/contracts": "^13.0",
"illuminate/database": "^13.0",
"illuminate/filesystem": "^13.0",
"illuminate/http": "^13.0",
"illuminate/routing": "^13.0"
"illuminate/routing": "^13.0",
"illuminate/support": "^13.0",
"illuminate/validation": "^13.0",
"league/commonmark": "^2.6"
},
"require-dev": {
"orchestra/testbench": "^11.0",
+33 -2
View File
@@ -45,9 +45,40 @@ return [
],
/*
| The disk for uploaded media.
| The media library. Files live on a Laravel filesystem disk; each media row remembers
| its own disk, so a file stays where it was uploaded when `disk` changes later.
*/
'media_disk' => env('MANAGER_MEDIA_DISK', 'public'),
'media' => [
'disk' => env('MANAGER_MEDIA_DISK', 'public'),
// How much room the library has in total, in GB. An upload that would go over it is refused.
'max_total_gb' => (float) env('MANAGER_MEDIA_MAX_TOTAL_GB', 15),
// Largest single upload in MB. PHP and the web server must allow it too
// (upload_max_filesize, post_max_size, client_max_body_size).
'max_file_mb' => (int) env('MANAGER_MEDIA_MAX_FILE_MB', 40),
// File extensions the library accepts. SVG is deliberately missing: it can carry scripts.
'extensions' => ['jpg', 'jpeg', 'png', 'webp', 'gif', 'pdf', 'mp4', 'webm'],
// Visitors loading files per minute per address (the `media-files` rate limiter).
'per_minute' => 600,
],
/*
| Posts. `categories` are always offered in the post form, next to the ones in use and the
| ones made by hand; a site can offer more through PostLabels::suggestCategories().
*/
'posts' => [
'categories' => ['General'],
],
/*
| Markdown in posts: hosts besides APP_URL whose links do not open in a new window.
*/
'markdown' => [
'internal_hosts' => [],
],
/*
| Prefix for the tables of the package.
+37 -19
View File
@@ -4,14 +4,18 @@
Usage: dev/token-usage.py LOG.jsonl [--since 2026-12-02T07:00] [--until 2026-12-02T12:00]
[--row "Wat er is gemaakt" [--version v0.2.0]]
With --row it also prints the line for the table of TOKENS.md, with the hours as its last cell.
With --row it also prints the line(s) for the table of TOKENS.md, with the hours as the last cell.
Helper agents (subagents) are part of the work: their tokens are added to the row. The row is made
per model, because the price differs per model: when helper agents ran on another model than the
session, there is one row for each, and the hours are on the first row only.
The hours are the time that was worked in the period: from one entry of the log to the next,
the time between an answer and the next request included, pauses of more than half an hour
left out.
LOG.jsonl is the log of the session (~/.claude/projects/<folder>/<session>.jsonl); the logs of
helper agents in the folder `<session>/subagents` next to it are counted separately. The moments
helper agents in the folder `<session>/subagents` next to it are shown separately and also counted in the row. The moments
are UTC, as in the log. An answer of the model can be in the log more than once; it is counted
once, by its message id.
@@ -70,20 +74,28 @@ def hours(path, since, until):
def total(found, since, until):
"""Steps, output, input, written to the cache, read from the cache; and the models seen."""
"""Steps, output, input, written to the cache, read from the cache; and the same per model."""
row = [0, 0, 0, 0, 0]
models = {}
per_model = {}
for usage, moment, model in found.values():
if (since and moment[:16] < since) or (until and moment[:16] >= until):
continue
row[0] += 1
row[1] += usage.get("output_tokens", 0)
row[2] += usage.get("input_tokens", 0)
row[3] += usage.get("cache_creation_input_tokens", 0)
row[4] += usage.get("cache_read_input_tokens", 0)
if model and not model.startswith("<"):
models[model] = models.get(model, 0) + 1
return row, models
# Entries the client made itself (model "<synthetic>") hold no tokens and no work.
if model and model.startswith("<"):
continue
add = [
1,
usage.get("output_tokens", 0),
usage.get("input_tokens", 0),
usage.get("cache_creation_input_tokens", 0),
usage.get("cache_read_input_tokens", 0),
]
model = model or "?"
mine = per_model.setdefault(model, [0, 0, 0, 0, 0])
for index, value in enumerate(add):
row[index] += value
mine[index] += value
return row, per_model
def number(value):
@@ -105,9 +117,11 @@ def main():
if len(paths) != 1:
sys.exit(__doc__)
row, models = total(answers(paths[0]), since, until)
session = answers(paths[0])
row, _ = total(session, since, until)
show("session", row)
print(f"hours worked: {hours(paths[0], since, until):.2f}")
worked_hours = hours(paths[0], since, until)
print(f"hours worked: {worked_hours:.2f}")
helpers = {}
for path in glob.glob(os.path.join(os.path.splitext(paths[0])[0], "subagents", "*.jsonl")):
@@ -116,12 +130,16 @@ def main():
show("helper agents", total(helpers, since, until)[0])
if option("--row"):
if len(models) > 1:
print("More than one model in this period: make a row per model (--since/--until).", file=sys.stderr)
model = max(models, key=models.get) if models else "?"
# Session and helper agents together, one row per model.
everything = {**session, **{"helper:" + key: value for key, value in helpers.items()}}
_, per_model = total(everything, since, until)
if not per_model:
per_model = {"?": [0, 0, 0, 0, 0]}
day = (since or "")[:10] or "JJJJ-MM-DD"
worked = f"{hours(paths[0], since, until):.2f}".replace(".", ",")
cells = [day, option("--row"), option("--version") or "", model] + [number(value) for value in row] + [worked]
# The model with the most steps first; the hours go on that row only.
for position, model in enumerate(sorted(per_model, key=lambda name: -per_model[name][0])):
worked = f"{worked_hours:.2f}" if position == 0 else "0.00"
cells = [day, option("--row"), option("--version") or "", model] + [number(value) for value in per_model[model]] + [worked.replace(".", ",")]
print("| " + " | ".join(cells) + " |")
+40 -5
View File
@@ -4,15 +4,18 @@ namespace IriksIT\Manager\Concerns;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use IriksIT\Manager\Models\Group;
use IriksIT\Manager\Support\ModuleRegistry;
/**
* Put this on the User model of the host app. Needs the Users module (its migration
* adds `manager_super_admin` to the users table and creates the groups).
* Put this on the User model of the host app (needs the Users module).
*
* A super admin may do everything. Everyone else may do what any of their groups may do.
* A super admin may do everything of the manager. Everyone else may do what any of their
* groups allows. `is_super_admin` is never fillable and no form sets it: only
* `manager:create-user` makes one. Keep it out of `$fillable` in the host model.
*/
trait HasManagerAccess
{
/** @return BelongsToMany<Group, $this> */
public function managerGroups(): BelongsToMany
{
return $this->belongsToMany(Group::class, config('manager.table_prefix').'group_user', 'user_id', 'group_id');
@@ -20,15 +23,47 @@ trait HasManagerAccess
public function isManagerSuperAdmin(): bool
{
return (bool) $this->manager_super_admin;
return (bool) $this->getAttribute('is_super_admin');
}
/**
* Everything this account may do in the manager.
*
* @return list<string>
*/
public function managerPermissions(): array
{
$registry = app(ModuleRegistry::class);
if ($this->isManagerSuperAdmin()) {
return $registry->permissionValues();
}
return $registry->complete($this->managerGroups->flatMap(fn (Group $group) => $group->allowed())->all());
}
public function hasManagerPermission(string $permission): bool
{
return in_array($permission, $this->managerPermissions(), true);
}
/**
* Whether this account may do everything $other may. Someone who manages accounts only
* touches accounts that stay within their own rights; otherwise a new password for a
* mightier account would be a way up.
*/
public function managerOutranks(self $other): bool
{
if ($this->isManagerSuperAdmin()) {
return true;
}
return $this->managerGroups->contains(fn (Group $group) => in_array($permission, $group->permissions ?? [], true));
return ! $other->isManagerSuperAdmin() && array_diff($other->managerPermissions(), $this->managerPermissions()) === [];
}
/** Whether this account may put someone in $group: only when the group gives nothing it lacks itself. */
public function managerMayGive(Group $group): bool
{
return $this->isManagerSuperAdmin() || array_diff($group->allowed(), $this->managerPermissions()) === [];
}
}
+13 -2
View File
@@ -2,6 +2,8 @@
namespace IriksIT\Manager\Contracts;
use IriksIT\Manager\Support\Permission;
/**
* One switchable part of the manager. A module that is off contributes nothing:
* no routes, no migrations, no menu items, no permissions.
@@ -21,9 +23,9 @@ interface Module
public function requires(): array;
/**
* Permissions this module adds, as value => label. Values are prefixed by the module key.
* Permissions this module adds. Values are prefixed by the module key.
*
* @return array<string, string>
* @return list<Permission>
*/
public function permissions(): array;
@@ -33,6 +35,15 @@ interface Module
/** Absolute path of the routes file, or null. */
public function routes(): ?string;
/** Absolute path of a routes file outside the manager (no prefix, no manager middleware), or null. */
public function publicRoutes(): ?string;
/** Absolute path of the migrations folder, or null. */
public function migrations(): ?string;
/** @return list<class-string> Artisan commands this module adds */
public function commands(): array;
/** Runs at boot, only when the module is on (register rate limiters, usage sources, ...). */
public function boot(): void;
}
+17
View File
@@ -0,0 +1,17 @@
<?php
namespace IriksIT\Manager\Exceptions;
use RuntimeException;
/**
* The storage behind the media library could not store, return or delete a file.
* `status` is 404 when the file is gone, 0 otherwise.
*/
class MediaStorageException extends RuntimeException
{
public function __construct(string $message, public readonly int $status = 0, public readonly ?int $retryAfter = null)
{
parent::__construct($message);
}
}
+3
View File
@@ -9,6 +9,9 @@ use IriksIT\Manager\Support\ModuleRegistry;
* @method static bool enabled(string $key)
* @method static array active()
* @method static array permissions()
* @method static array permissionValues()
* @method static array complete(array $values)
* @method static array catalogue()
* @method static array navigation()
*
* @see ModuleRegistry
+26 -3
View File
@@ -9,10 +9,16 @@ use IriksIT\Manager\Support\ModuleRegistry;
class ManagerServiceProvider extends ServiceProvider
{
/** Only a super admin: the groups decide what everyone else may do. Not a permission of a group. */
public const MANAGE_GROUPS = 'groups.manage';
public function register(): void
{
$this->mergeConfigFrom(__DIR__.'/../config/manager.php', 'manager');
$this->app->singleton(Support\MediaUsage::class);
$this->app->singleton(Modules\Posts\PostLabels::class);
$this->app->singleton(ModuleRegistry::class, fn ($app) => new ModuleRegistry(
$app['config']->get('manager.available', []),
$app['config']->get('manager.modules', []),
@@ -24,25 +30,35 @@ class ManagerServiceProvider extends ServiceProvider
$modules->validate();
$this->publishes([__DIR__.'/../config/manager.php' => config_path('manager.php')], 'manager-config');
$this->loadViewsFrom(__DIR__.'/../resources/views', 'manager');
// A module that is off adds no migrations, so a site without reviews has no reviews table.
foreach ($modules->active() as $module) {
if ($module->migrations() !== null) {
$this->loadMigrationsFrom($module->migrations());
}
if ($this->app->runningInConsole() && $module->commands() !== []) {
$this->commands($module->commands());
}
$module->boot();
}
$this->registerGates($modules);
$this->registerRoutes($modules);
}
/**
* One gate per permission, and no Gate::before: a package must never answer for abilities
* of the host app. A super admin passes inside hasManagerPermission, for these gates only.
*/
private function registerGates(ModuleRegistry $modules): void
{
foreach (array_keys($modules->permissions()) as $permission) {
foreach ($modules->permissionValues() as $permission) {
Gate::define($permission, fn ($user) => method_exists($user, 'hasManagerPermission') && $user->hasManagerPermission($permission));
}
Gate::define(self::MANAGE_GROUPS, fn ($user) => method_exists($user, 'isManagerSuperAdmin') && $user->isManagerSuperAdmin());
}
private function registerRoutes(ModuleRegistry $modules): void
@@ -59,5 +75,12 @@ class ManagerServiceProvider extends ServiceProvider
}
}
});
// Files for visitors: outside the manager, no prefix and none of its middleware.
foreach ($modules->active() as $module) {
if ($module->publicRoutes() !== null) {
$this->loadRoutesFrom($module->publicRoutes());
}
}
}
}
+25
View File
@@ -2,10 +2,35 @@
namespace IriksIT\Manager\Models;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use IriksIT\Manager\Support\ModuleRegistry;
/**
* A set of permissions with a name ("Writers"). Accounts are put in groups; a group is the
* only place where permissions are set.
*
* @property list<string>|null $permissions
*/
class Group extends Model
{
protected function casts(): array
{
return ['permissions' => 'array'];
}
public function users(): BelongsToMany
{
return $this->belongsToMany(config('manager.user_model'), config('manager.table_prefix').'group_user', 'group_id', 'user_id');
}
/**
* What the group allows, without anything that is no permission (any more), for instance
* of a module that was switched off.
*
* @return list<string>
*/
public function allowed(): array
{
return app(ModuleRegistry::class)->complete($this->permissions ?? []);
}
}
+80
View File
@@ -2,10 +2,90 @@
namespace IriksIT\Manager\Models;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* One file in the media library. The row is the bookkeeping; the file itself is stored on the
* filesystem disk `disk` under `location`.
*/
class Media extends Model
{
protected $hidden = ['disk', 'location'];
public function getTable(): string
{
return config('manager.table_prefix').'media';
}
protected function casts(): array
{
return ['size' => 'integer', 'width' => 'integer', 'height' => 'integer', 'focus_x' => 'float', 'focus_y' => 'float'];
}
public function uploader(): BelongsTo
{
return $this->belongsTo(config('manager.user_model'), 'uploaded_by');
}
public function isImage(): bool
{
return str_starts_with($this->mime_type, 'image/');
}
/**
* The start of this file's address. It holds the id, so it stays the same when the file is
* renamed, and is what content is searched for to see where a file is used.
*/
public function urlPrefix(): string
{
return '/media-files/'.$this->id.'/';
}
/**
* The address visitors load the file from. It ends in /view on purpose: web servers tend to
* answer anything that ends in .jpg themselves, as a file on disk, and never ask the app.
*/
public function url(): string
{
return $this->urlPrefix().rawurlencode($this->filename).'/view';
}
/**
* The focus point of the image behind an address from the library, as a CSS `object-position`
* value ("30% 65%"). Null for any other address, or when no focus point was set.
*/
public static function focusFor(?string $url): ?string
{
if ($url === null || preg_match('#^/media-files/(\d+)/#', $url, $match) !== 1) {
return null;
}
$media = static::query()->whereKey((int) $match[1])->whereNotNull('focus_x')->whereNotNull('focus_y')->first(['id', 'focus_x', 'focus_y']);
return $media instanceof self
? round((float) $media->focus_x * 100, 2).'% '.round((float) $media->focus_y * 100, 2).'%'
: null;
}
/** What the manager shows. Never includes where the file is stored. */
public function toLibraryItem(int $usageCount = 0): array
{
return [
'id' => $this->id,
'name' => $this->name,
'filename' => $this->filename,
'url' => $this->url(),
'mime_type' => $this->mime_type,
'is_image' => $this->isImage(),
'size' => $this->size,
'width' => $this->width,
'height' => $this->height,
'alt' => $this->alt,
'focus_x' => $this->focus_x,
'focus_y' => $this->focus_y,
'uploaded_by' => $this->uploader?->name,
'created_at' => $this->created_at?->toIso8601String(),
'usage_count' => $usageCount,
];
}
}
+80 -1
View File
@@ -2,4 +2,83 @@
namespace IriksIT\Manager\Models;
class Post extends Model {}
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Str;
use IriksIT\Manager\Support\Markdown;
class Post extends Model
{
protected function casts(): array
{
return [
'tags' => 'array',
'is_featured' => 'boolean',
'published_at' => 'datetime',
];
}
/**
* Posts that are visible on the public site: published and not scheduled for later.
*
* @param Builder<Post> $query
*/
public function scopePublished(Builder $query): void
{
$query->whereNotNull('published_at')->where('published_at', '<=', now());
}
public function isPublished(): bool
{
return $this->published_at !== null && $this->published_at->lte(now());
}
/** `draft`, `scheduled` or `published`. */
public function status(): string
{
return match (true) {
$this->published_at === null => 'draft',
$this->published_at->isFuture() => 'scheduled',
default => 'published',
};
}
/** A slug for $title that no other post uses yet. */
public static function uniqueSlug(string $title, ?int $ignoreId = null): string
{
$base = Str::slug($title) ?: 'post';
$slug = $base;
$suffix = 2;
while (static::query()->where('slug', $slug)->when($ignoreId, fn (Builder $q) => $q->whereKeyNot($ignoreId))->exists()) {
$slug = $base.'-'.$suffix++;
}
return $slug;
}
public function readingMinutes(): int
{
return max(1, (int) ceil(str_word_count(strip_tags($this->body)) / 220));
}
/**
* The fields a post card or listing needs, for the host's public pages.
*
* @return array<string, mixed>
*/
public function toCard(): array
{
return [
'title' => $this->title,
'slug' => $this->slug,
'excerpt' => $this->excerpt ?? Str::limit(Markdown::toPlainText($this->body), 160),
'cover_image' => $this->cover_image,
'cover_focus' => Media::focusFor($this->cover_image),
'category' => $this->category,
'tags' => $this->tags ?? [],
'is_featured' => $this->is_featured,
'published_at' => $this->published_at?->toIso8601String(),
'reading_minutes' => $this->readingMinutes(),
];
}
}
+12
View File
@@ -35,6 +35,18 @@ abstract class BaseModule implements Module
return $this->path('routes.php');
}
public function publicRoutes(): ?string
{
return $this->path('public-routes.php');
}
public function commands(): array
{
return [];
}
public function boot(): void {}
public function migrations(): ?string
{
return $this->path('migrations');
+138 -3
View File
@@ -2,13 +2,148 @@
namespace IriksIT\Manager\Modules\Media;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Log;
use IriksIT\Manager\Exceptions\MediaStorageException;
use IriksIT\Manager\Models\Media;
/**
* The media library. The library (also when opened as a picker from another form) loads and
* changes its items through these JSON actions.
*/
class MediaController
{
/** First opzet: lists the records as JSON. The screens come with the frontend. */
public function index()
private const UNAVAILABLE = 'The file storage is not available right now. Try again in a moment.';
public function __construct(private readonly MediaLibrary $library) {}
public function index(): JsonResponse
{
return response()->json(Media::query()->latest()->paginate(25));
return response()->json($this->limits());
}
public function items(): JsonResponse
{
$media = Media::query()->with('uploader')->latest()->latest('id')->get();
$usage = $this->library->usageCounts($media);
return response()->json([
'items' => $media->map(fn (Media $item) => $item->toLibraryItem($usage[$item->id] ?? 0))->values(),
...$this->limits(),
]);
}
public function store(Request $request): JsonResponse
{
$request->validate([
'file' => ['required', 'file', 'mimes:'.implode(',', $this->extensions()), 'max:'.($this->maxMegabytes() * 1024)],
...$this->focusRules(),
]);
$file = $request->file('file');
abort_unless($file instanceof UploadedFile, 422);
$room = $this->library->room();
if ($file->getSize() > $room['left']) {
$message = 'The media library is full: this file does not fit in the room that is left. Remove files that are no longer used, or raise manager.media.max_total_gb.';
return response()->json(['message' => $message, 'errors' => ['file' => [$message]], 'storage' => $room], 422);
}
try {
$media = $this->library->store($file, $request->user());
} catch (MediaStorageException $e) {
return $this->unavailable($e);
}
if ($media->isImage()) {
$media->update($this->focus($request));
}
return response()->json(['item' => $media->load('uploader')->toLibraryItem(), 'storage' => $this->library->room()], 201);
}
public function update(Request $request, string $media): JsonResponse
{
$media = Media::query()->findOrFail($media);
$request->validate([
'name' => ['required', 'string', 'max:250'],
'alt' => ['nullable', 'string', 'max:500'],
...$this->focusRules(),
]);
$alt = $request->string('alt')->trim()->toString();
$media->update([
'name' => $request->string('name')->trim()->toString(),
'alt' => $alt !== '' ? $alt : null,
// Only when the request says something about it; renaming keeps the focus point.
...($media->isImage() && $request->has('focus_x') ? $this->focus($request) : []),
]);
$usage = $this->library->usageCounts([$media]);
return response()->json(['item' => $media->load('uploader')->toLibraryItem($usage[$media->id] ?? 0)]);
}
public function destroy(string $media): JsonResponse
{
$media = Media::query()->findOrFail($media);
try {
$this->library->delete($media);
} catch (MediaStorageException $e) {
return $this->unavailable($e);
}
return response()->json(['deleted' => true, 'storage' => $this->library->room()]);
}
/** @return array<string, list<string>> */
private function focusRules(): array
{
return [
'focus_x' => ['nullable', 'numeric', 'between:0,1', 'required_with:focus_y'],
'focus_y' => ['nullable', 'numeric', 'between:0,1', 'required_with:focus_x'],
];
}
/** @return array{focus_x: float|null, focus_y: float|null} both null when none was sent */
private function focus(Request $request): array
{
$x = $request->input('focus_x');
$y = $request->input('focus_y');
$set = is_numeric($x) && is_numeric($y);
return ['focus_x' => $set ? round((float) $x, 4) : null, 'focus_y' => $set ? round((float) $y, 4) : null];
}
/** The reason goes to the log; the browser only hears that it did not work. */
private function unavailable(MediaStorageException $e): JsonResponse
{
Log::warning('Media storage failed.', ['error' => $e->getMessage(), 'status' => $e->status]);
return response()->json(['message' => self::UNAVAILABLE], 502);
}
/** @return array{max_file_mb: int, extensions: list<string>, storage: array{used: int, limit: int, left: int}} */
private function limits(): array
{
return ['max_file_mb' => $this->maxMegabytes(), 'extensions' => $this->extensions(), 'storage' => $this->library->room()];
}
private function maxMegabytes(): int
{
return max(1, config()->integer('manager.media.max_file_mb'));
}
/** @return list<string> */
private function extensions(): array
{
return array_values(array_filter(config()->array('manager.media.extensions'), 'is_string'));
}
}
+156
View File
@@ -0,0 +1,156 @@
<?php
namespace IriksIT\Manager\Modules\Media;
use Illuminate\Http\Request;
use IriksIT\Manager\Exceptions\MediaStorageException;
use IriksIT\Manager\Models\Media;
use Symfony\Component\HttpFoundation\Response;
/** Passes a media file on to the browser, with ETag and byte ranges (video needs them). */
class MediaFileController
{
/**
* Types a browser may show as they are. Anything else is offered as a download, so a
* stored file can never run as a page on this domain.
*/
private const array INLINE_TYPES = [
'image/jpeg', 'image/png', 'image/webp', 'image/gif',
'video/mp4', 'video/webm',
'application/pdf',
];
public function __invoke(Request $request, MediaLibrary $library, string $media): Response
{
$media = Media::query()->findOrFail((int) $media);
$headers = $this->headers($media);
// A media id never gets other content, so what the browser has is still right.
if (in_array($headers['ETag'], $request->getETags(), true)) {
return response('', 304, $headers);
}
$range = $this->range($request, $media->size);
if ($range === null) {
return response('', 416, ['Content-Range' => "bytes */{$media->size}"] + $headers);
}
[$start, $end, $partial] = $range;
$length = $end - $start + 1;
$headers['Content-Length'] = (string) $length;
if ($partial) {
$headers['Content-Range'] = "bytes {$start}-{$end}/{$media->size}";
}
if ($request->isMethod('HEAD')) {
return response('', $partial ? 206 : 200, $headers);
}
try {
$stream = $library->open($media);
} catch (MediaStorageException $e) {
if ($e->status === 404) {
abort(404);
}
return response('This file is temporarily unavailable.', 503, ['Retry-After' => (string) ($e->retryAfter ?? 30), 'Cache-Control' => 'no-store']);
}
return response()->stream(fn () => $this->send($stream, $start, $length), $partial ? 206 : 200, $headers);
}
/** @return array<string, string> */
private function headers(Media $media): array
{
$inline = in_array($media->mime_type, self::INLINE_TYPES, true);
$name = str_replace(['"', '\\', "\r", "\n"], '', $media->filename);
return [
'Content-Type' => $inline ? $media->mime_type : 'application/octet-stream',
'Content-Disposition' => ($inline ? 'inline' : 'attachment').'; filename="'.$name.'"',
'X-Content-Type-Options' => 'nosniff',
'Accept-Ranges' => 'bytes',
'Cache-Control' => 'public, max-age=31536000, immutable',
'ETag' => '"'.($media->checksum ?? 'media-'.$media->id).'"',
];
}
/**
* The part of the file the browser asks for: [first byte, last byte, is it a part].
* Null when the request asks for bytes the file does not have.
*
* @return array{int, int, bool}|null
*/
private function range(Request $request, int $size): ?array
{
$header = $request->headers->get('Range');
$whole = [0, max($size - 1, 0), false];
// No range, an empty file, or something other than one plain byte range: send it all.
if ($header === null || $size === 0 || preg_match('/^bytes=(\d*)-(\d*)$/', trim($header), $match) !== 1) {
return $whole;
}
[, $first, $last] = $match;
if ($first === '' && $last === '') {
return $whole;
}
if ($first === '') {
// "bytes=-500": the last 500 bytes.
$start = max($size - (int) $last, 0);
$end = $size - 1;
} else {
$start = (int) $first;
$end = $last === '' ? $size - 1 : min((int) $last, $size - 1);
}
if ($start >= $size || $start > $end) {
return null;
}
return [$start, $end, true];
}
/** @param resource $stream */
private function send($stream, int $start, int $length): void
{
try {
if ($start > 0 && stream_get_meta_data($stream)['seekable']) {
fseek($stream, $start);
} else {
$skip = $start;
while ($skip > 0 && ! feof($stream)) {
$chunk = fread($stream, min(65536, $skip));
if ($chunk === false || $chunk === '') {
break;
}
$skip -= strlen($chunk);
}
}
while ($length > 0 && ! feof($stream)) {
$chunk = fread($stream, min(65536, $length));
if ($chunk === false || $chunk === '') {
break;
}
echo $chunk;
flush();
$length -= strlen($chunk);
}
} finally {
fclose($stream);
}
}
}
+122
View File
@@ -0,0 +1,122 @@
<?php
namespace IriksIT\Manager\Modules\Media;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use IriksIT\Manager\Exceptions\MediaStorageException;
use IriksIT\Manager\Models\Media;
use IriksIT\Manager\Support\MediaUsage;
/**
* The one place that knows where media files physically are. Everything else works with Media
* rows and their URLs. New uploads go to the disk in config('manager.media.disk'); an existing
* file is always read from and deleted on the disk its own row names.
*/
class MediaLibrary
{
public function __construct(private readonly MediaUsage $usage) {}
/** @throws MediaStorageException */
public function store(UploadedFile $file, ?Authenticatable $uploader = null, ?string $disk = null): Media
{
$extension = strtolower($file->getClientOriginalExtension());
$baseName = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
$filename = (Str::slug($baseName) ?: 'file').($extension !== '' ? '.'.$extension : '');
$path = $file->getRealPath();
if ($path === false) {
throw new MediaStorageException('The uploaded file could not be read.');
}
$mimeType = $file->getMimeType() ?? 'application/octet-stream';
$dimensions = str_starts_with($mimeType, 'image/') ? @getimagesize($path) : false;
$disk ??= config('manager.media.disk');
$location = $file->store('media/'.now()->format('Y/m'), $disk);
if ($location === false) {
throw new MediaStorageException('The file could not be stored.');
}
return Media::create([
'disk' => $disk,
'location' => $location,
'name' => Str::limit(trim($baseName) !== '' ? trim($baseName) : 'File', 250, ''),
'filename' => $filename,
'mime_type' => $mimeType,
'size' => (int) $file->getSize(),
'checksum' => hash_file('sha256', $path) ?: null,
'width' => $dimensions !== false ? $dimensions[0] : null,
'height' => $dimensions !== false ? $dimensions[1] : null,
'uploaded_by' => $uploader?->getAuthIdentifier(),
]);
}
/**
* How full the library is: what all files together take, how much it may hold
* (`manager.media.max_total_gb`) and what is left. In bytes.
*
* @return array{used: int, limit: int, left: int}
*/
public function room(): array
{
$configured = config('manager.media.max_total_gb');
$limit = (int) round((is_numeric($configured) ? max(0.0, (float) $configured) : 15.0) * 1_000_000_000);
$used = (int) Media::query()->sum('size');
return ['used' => $used, 'limit' => $limit, 'left' => max(0, $limit - $used)];
}
/**
* Open a file's content as a stream. Read it and close it.
*
* @return resource
*
* @throws MediaStorageException with status 404 when the file is gone
*/
public function open(Media $media)
{
$stream = Storage::disk($media->disk)->readStream($media->location);
if (! is_resource($stream)) {
throw new MediaStorageException('The file is no longer there.', 404);
}
return $stream;
}
/** Delete the file and then its row. When the storage refuses, the row stays. */
public function delete(Media $media): void
{
$disk = Storage::disk($media->disk);
if ($disk->exists($media->location) && ! $disk->delete($media->location)) {
throw new MediaStorageException('The file could not be deleted.');
}
$media->delete();
}
/**
* How often each media file is used, keyed by media id: how many of the registered sources
* (MediaUsage) hold its address. Nothing registered means 0.
*
* @param iterable<Media> $items
* @return array<int, int>
*/
public function usageCounts(iterable $items): array
{
$haystacks = $this->usage->haystacks();
$counts = [];
foreach ($items as $media) {
$prefix = $media->urlPrefix();
$counts[$media->id] = count(array_filter($haystacks, fn (string $text) => str_contains($text, $prefix)));
}
return $counts;
}
}
+13 -4
View File
@@ -2,7 +2,11 @@
namespace IriksIT\Manager\Modules\Media;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use IriksIT\Manager\Modules\BaseModule;
use IriksIT\Manager\Support\Permission;
class MediaModule extends BaseModule
{
@@ -24,10 +28,10 @@ class MediaModule extends BaseModule
public function permissions(): array
{
return [
'media.view' => 'See the media library',
'media.upload' => 'Upload files',
'media.edit' => 'Change name and description of a file',
'media.delete' => 'Delete files',
new Permission('media.view', 'See the media library and pick files from it', 'Media'),
new Permission('media.upload', 'Upload files', 'Media', needs: ['media.view']),
new Permission('media.edit', 'Change the name, description and focus point of a file', 'Media', needs: ['media.view']),
new Permission('media.delete', 'Delete files', 'Media', needs: ['media.view']),
];
}
@@ -37,4 +41,9 @@ class MediaModule extends BaseModule
['label' => 'Media', 'route' => 'manager.media.index', 'permission' => 'media.view'],
];
}
public function boot(): void
{
RateLimiter::for('media-files', fn (Request $request) => Limit::perMinute(max(1, (int) config('manager.media.per_minute', 600)))->by((string) $request->ip()));
}
}
@@ -8,18 +8,26 @@ return new class extends Migration
{
public function up(): void
{
Schema::create(config('manager.table_prefix').'media', function (Blueprint $table) {
$users = (new (config('manager.user_model')))->getTable();
// The file itself is elsewhere: `disk` says where, `location` is its path there.
Schema::create(config('manager.table_prefix').'media', function (Blueprint $table) use ($users) {
$table->id();
$table->string('disk');
$table->string('path');
$table->string('disk', 40);
$table->string('location');
$table->string('name');
$table->string('filename');
$table->string('mime_type');
$table->string('mime_type', 100);
$table->unsignedBigInteger('size');
$table->string('checksum', 64)->nullable();
$table->unsignedInteger('width')->nullable();
$table->unsignedInteger('height')->nullable();
$table->string('title')->nullable();
$table->text('description')->nullable();
$table->unsignedBigInteger('uploaded_by')->nullable()->index();
$table->string('alt', 500)->nullable();
// The part of an image that must stay in view when it is cropped to fit:
// 0-1 from the left and from the top.
$table->decimal('focus_x', 5, 4)->nullable();
$table->decimal('focus_y', 5, 4)->nullable();
$table->foreignId('uploaded_by')->nullable()->constrained($users)->nullOnDelete();
$table->timestamps();
});
}
+12
View File
@@ -0,0 +1,12 @@
<?php
use Illuminate\Support\Facades\Route;
use IriksIT\Manager\Modules\Media\MediaFileController;
// Files of the media library, for visitors. No session and no cookies: this is a file, not a
// page, and the browser may cache it for good. The address ends in /view on purpose: web servers
// tend to answer anything that ends in .jpg themselves and never ask the app.
Route::get('/media-files/{media}/{filename}/view', MediaFileController::class)
->whereNumber('media')
->middleware('throttle:media-files')
->name('manager.media.file');
+4
View File
@@ -4,3 +4,7 @@ use Illuminate\Support\Facades\Route;
use IriksIT\Manager\Modules\Media\MediaController;
Route::get('/media', [MediaController::class, 'index'])->name('media.index')->middleware('can:media.view');
Route::get('/media/items', [MediaController::class, 'items'])->name('media.items')->middleware('can:media.view');
Route::post('/media', [MediaController::class, 'store'])->name('media.store')->middleware('can:media.upload');
Route::put('/media/{media}', [MediaController::class, 'update'])->name('media.update')->middleware('can:media.edit')->whereNumber('media');
Route::delete('/media/{media}', [MediaController::class, 'destroy'])->name('media.destroy')->middleware('can:media.delete')->whereNumber('media');
+10 -1
View File
@@ -2,7 +2,10 @@
namespace IriksIT\Manager\Modules\Pages;
use IriksIT\Manager\Models\Page;
use IriksIT\Manager\Modules\BaseModule;
use IriksIT\Manager\Support\MediaUsage;
use IriksIT\Manager\Support\Permission;
class PagesModule extends BaseModule
{
@@ -24,7 +27,7 @@ class PagesModule extends BaseModule
public function permissions(): array
{
return [
'pages.edit' => 'Change the texts of the pages',
new Permission('pages.edit', 'Change the texts of the pages', 'Site content'),
];
}
@@ -34,4 +37,10 @@ class PagesModule extends BaseModule
['label' => 'Pages', 'route' => 'manager.pages.index', 'permission' => 'pages.edit'],
];
}
/** Where the media library looks for the use of a file: the texts of the pages. */
public function boot(): void
{
app(MediaUsage::class)->register(fn () => Page::query()->get(['body'])->flatMap(fn (Page $row) => array_values($row->only(['body']))));
}
}
+80
View File
@@ -0,0 +1,80 @@
<?php
namespace IriksIT\Manager\Modules\Posts;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
/**
* The categories and tags of the posts: make one, rename one everywhere, merge two, or take one
* off every post.
*/
class LabelController
{
public function __construct(private readonly PostLabels $labels) {}
public function index(): JsonResponse
{
return response()->json($this->labels->overview());
}
/** A category or tag that no post uses yet; the post form offers it from then on. */
public function store(Request $request): JsonResponse
{
$type = $this->type($request);
$request->validate(['name' => $this->nameRules($type)], $this->messages());
$name = $request->string('name')->trim()->toString();
if (! $this->labels->create($type, $name)) {
return response()->json(['message' => "The {$type} \"{$name}\" already exists.", 'errors' => ['name' => ["The {$type} \"{$name}\" already exists."]]], 422);
}
return response()->json(['created' => $name], 201);
}
public function update(Request $request): JsonResponse
{
$type = $this->type($request);
$request->validate(['name' => ['required', 'string'], 'new_name' => $this->nameRules($type)], $this->messages());
$from = $request->string('name')->toString();
$to = $request->string('new_name')->trim()->toString();
return response()->json(['posts' => $this->labels->rename($type, $from, $to)]);
}
public function destroy(Request $request): JsonResponse
{
$type = $this->type($request);
$request->validate(['name' => ['required', 'string']]);
return response()->json(['posts' => $this->labels->remove($type, $request->string('name')->toString())]);
}
/**
* The same limits as the post form.
*
* @return list<mixed>
*/
private function nameRules(string $type): array
{
return ['required', 'string', 'max:'.($type === PostLabels::CATEGORY ? 60 : 40), ...($type === PostLabels::TAG ? ['not_regex:/,/'] : [])];
}
/** @return array<string, string> */
private function messages(): array
{
$comma = 'A tag cannot hold a comma: the post form separates tags with it.';
return ['name.not_regex' => $comma, 'new_name.not_regex' => $comma];
}
private function type(Request $request): string
{
$request->validate(['type' => ['required', Rule::in([PostLabels::CATEGORY, PostLabels::TAG])]]);
return $request->string('type')->toString();
}
}
+189
View File
@@ -0,0 +1,189 @@
<?php
namespace IriksIT\Manager\Modules\Posts;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Gate;
use Illuminate\Validation\Rule;
use IriksIT\Manager\Models\Post;
use IriksIT\Manager\Support\Markdown;
/**
* The posts. A post that is live or scheduled is only changed or deleted by who may publish: a
* change to it is on the site at once. Who may not publish only ever saves drafts.
*
* The answers have the shape the screens of the sites used as props.
*/
class PostController
{
public function __construct(private readonly PostLabels $labels) {}
public function index(): JsonResponse
{
$posts = Post::query()
->orderByRaw('published_at is null desc')
->latest('published_at')
->latest('id')
->get()
->map(fn (Post $post) => [
'id' => $post->id,
'title' => $post->title,
'slug' => $post->slug,
'category' => $post->category,
'is_featured' => $post->is_featured,
'status' => $post->status(),
'published_at' => $post->published_at?->toIso8601String(),
'can_change' => Gate::allows('posts.write') && $this->mayTouch($post),
'can_delete' => Gate::allows('posts.delete') && $this->mayTouch($post),
])
->values();
return response()->json(['posts' => $posts]);
}
public function create(): JsonResponse
{
return response()->json([
'post' => null,
'categories' => $this->labels->categories(),
'known_tags' => $this->labels->names(PostLabels::TAG),
]);
}
public function store(Request $request): JsonResponse
{
$post = Post::create($this->validated($request));
return response()->json(['id' => $post->id], 201);
}
public function edit(string $post): JsonResponse
{
$post = Post::query()->findOrFail($post);
abort_unless($this->mayTouch($post), 403);
return response()->json([
'post' => [
'id' => $post->id,
'title' => $post->title,
'slug' => $post->slug,
'excerpt' => $post->excerpt,
'body' => $post->body,
'cover_image' => $post->cover_image,
'category' => $post->category,
'tags' => $post->tags ?? [],
'is_featured' => $post->is_featured,
'is_published' => $post->published_at !== null,
// datetime-local value, in the app timezone
'published_at' => $post->published_at?->format('Y-m-d\TH:i'),
'status' => $post->status(),
],
'categories' => $this->labels->categories(),
'known_tags' => $this->labels->names(PostLabels::TAG),
]);
}
/** The post as a visitor will see it, also for drafts and scheduled posts. */
public function preview(string $post): JsonResponse
{
$post = Post::query()->findOrFail($post);
return response()->json(['post' => [...$post->toCard(), 'body_html' => Markdown::toHtml($post->body)], 'preview' => true]);
}
public function update(Request $request, string $post): JsonResponse
{
$post = Post::query()->findOrFail($post);
abort_unless($this->mayTouch($post), 403);
$post->update($this->validated($request, $post));
return response()->json(['saved' => true]);
}
/** Puts a post on the site, or takes it off again (a draft) without opening it. */
public function online(Request $request, string $post): JsonResponse
{
$post = Post::query()->findOrFail($post);
$request->validate(['online' => ['required', 'boolean']]);
$post->update(['published_at' => $request->boolean('online') ? ($post->published_at ?? now()) : null]);
return response()->json(['status' => $post->status()]);
}
public function destroy(string $post): JsonResponse
{
$post = Post::query()->findOrFail($post);
abort_unless($this->mayTouch($post), 403);
$post->delete();
return response()->json(['deleted' => true]);
}
/**
* Validates the post form and turns it into model attributes.
*
* @return array<string, mixed>
*/
private function validated(Request $request, ?Post $post = null): array
{
$request->validate([
'title' => ['required', 'string', 'max:255'],
'slug' => ['nullable', 'string', 'max:255', 'regex:/^[a-z0-9]+(?:-[a-z0-9]+)*$/', Rule::unique(config('manager.table_prefix').'posts', 'slug')->ignore($post?->id)],
'excerpt' => ['nullable', 'string', 'max:500'],
'body' => ['required', 'string'],
'cover_image' => ['nullable', 'string', 'max:2048'],
'category' => ['nullable', 'string', 'max:60'],
'tags' => ['array', 'max:20'],
'tags.*' => ['nullable', 'string', 'max:40'],
'is_featured' => ['boolean'],
'is_published' => ['boolean'],
'published_at' => ['nullable', 'date'],
], [
'slug.regex' => 'Use only lowercase letters, numbers and dashes.',
]);
$title = $request->string('title')->trim()->toString();
$slug = $request->string('slug')->trim()->toString();
// Publishing without a date means "now"; a date in the future schedules the post.
// Who may not publish only gets a draft, and a post that was live is not touched
// (mayTouch refused that before we got here).
$publishedAt = null;
if ($request->boolean('is_published') && Gate::allows('posts.publish')) {
$date = $request->string('published_at')->toString();
$publishedAt = $date !== '' ? Carbon::parse($date) : ($post?->published_at ?? now());
}
return [
'title' => $title,
'slug' => $slug !== '' ? $slug : Post::uniqueSlug($title, $post?->id),
'excerpt' => $this->nullableString($request, 'excerpt'),
'body' => $request->string('body')->toString(),
'cover_image' => $this->nullableString($request, 'cover_image'),
'category' => $this->nullableString($request, 'category'),
'tags' => array_values(array_filter(array_map(
fn (mixed $tag) => is_string($tag) ? trim($tag) : '',
$request->array('tags'),
))),
'is_featured' => $request->boolean('is_featured'),
'published_at' => $publishedAt,
];
}
private function mayTouch(Post $post): bool
{
return $post->published_at === null || Gate::allows('posts.publish');
}
private function nullableString(Request $request, string $key): ?string
{
$value = $request->string($key)->trim()->toString();
return $value !== '' ? $value : null;
}
}
+191
View File
@@ -0,0 +1,191 @@
<?php
namespace IriksIT\Manager\Modules\Posts;
use Closure;
use Illuminate\Support\Facades\DB;
use IriksIT\Manager\Models\Post;
/**
* The categories and tags of the posts, for managing them in one place. A category is the
* `category` of a post and a tag an entry of its `tags`: a new one can simply be typed in a post.
* One that is made by hand, before any post uses it, is a row of `post_labels`; that table only
* remembers names to offer in the post form, a post never points to it.
*
* Renaming to a name that is already in use merges the two. Names are compared as written:
* "Laravel" and "laravel" are two, which is how to merge them.
*/
class PostLabels
{
public const CATEGORY = 'category';
public const TAG = 'tag';
/** @var list<Closure(): iterable<string>> */
private array $suggestions = [];
/** A site offers more categories in the post form, for instance the titles of its services. */
public function suggestCategories(Closure $source): void
{
$this->suggestions[] = $source;
}
/**
* What the post form offers as category: the suggestions of the site, the configured ones,
* and whatever is in use or was made by hand.
*
* @return list<string>
*/
public function categories(): array
{
$suggested = [];
foreach ($this->suggestions as $source) {
array_push($suggested, ...array_values([...$source()]));
}
return array_values(array_unique([...$suggested, ...array_values((array) config('manager.posts.categories', [])), ...$this->names(self::CATEGORY)]));
}
private function table(): string
{
return config('manager.table_prefix').'post_labels';
}
/**
* Every category and tag, the ones made by hand included, with the number of posts (drafts
* included) that use it.
*
* @return array{categories: list<array{name: string, posts: int}>, tags: list<array{name: string, posts: int}>}
*/
public function overview(): array
{
$categories = [];
$tags = [];
foreach (Post::query()->get(['id', 'category', 'tags']) as $post) {
if ($post->category !== null && $post->category !== '') {
$categories[$post->category] = ($categories[$post->category] ?? 0) + 1;
}
foreach (array_unique($this->tagsOf($post)) as $tag) {
$tags[$tag] = ($tags[$tag] ?? 0) + 1;
}
}
foreach (DB::table($this->table())->get(['type', 'name']) as $row) {
if (! is_string($row->name)) {
continue;
}
if ($row->type === self::CATEGORY) {
$categories[$row->name] ??= 0;
} else {
$tags[$row->name] ??= 0;
}
}
return ['categories' => $this->listed($categories), 'tags' => $this->listed($tags)];
}
/**
* The names of all categories or tags, to offer in the post form.
*
* @return list<string>
*/
public function names(string $type): array
{
return array_column($this->overview()[$type === self::CATEGORY ? 'categories' : 'tags'], 'name');
}
/** Makes a category or tag that no post uses yet. False when the name is already there. */
public function create(string $type, string $name): bool
{
if (in_array($name, $this->names($type), true)) {
return false;
}
DB::table($this->table())->insert(['type' => $type, 'name' => $name, 'created_at' => now(), 'updated_at' => now()]);
return true;
}
/** Gives every post with the label the new name. Returns how many posts changed. */
public function rename(string $type, string $from, string $to): int
{
if ($from === $to) {
return 0;
}
// The name that was made by hand moves along, unless the new name is there already.
$made = DB::table($this->table())->where('type', $type);
if ((clone $made)->where('name', $to)->exists()) {
(clone $made)->where('name', $from)->delete();
} else {
(clone $made)->where('name', $from)->update(['name' => $to, 'updated_at' => now()]);
}
return $type === self::CATEGORY
? Post::query()->where('category', $from)->update(['category' => $to])
: $this->changeTags($from, $to);
}
/** Takes the label off every post; the posts stay. Returns how many posts changed. */
public function remove(string $type, string $name): int
{
DB::table($this->table())->where('type', $type)->where('name', $name)->delete();
return $type === self::CATEGORY
? Post::query()->where('category', $name)->update(['category' => null])
: $this->changeTags($name, null);
}
/** Replaces a tag in every post that has it, or takes it out when $to is null. */
private function changeTags(string $from, ?string $to): int
{
return DB::transaction(function () use ($from, $to) {
$changed = 0;
foreach (Post::query()->whereNotNull('tags')->get() as $post) {
$tags = $this->tagsOf($post);
if (! in_array($from, $tags, true)) {
continue;
}
$new = [];
foreach ($tags as $tag) {
$tag = $tag === $from ? $to : $tag;
// A post that had both names keeps the tag once.
if ($tag !== null && ! in_array($tag, $new, true)) {
$new[] = $tag;
}
}
$post->update(['tags' => $new]);
$changed++;
}
return $changed;
});
}
/** @return list<string> */
private function tagsOf(Post $post): array
{
return array_values(array_filter(is_array($post->tags) ? $post->tags : [], fn (mixed $tag) => is_string($tag) && $tag !== ''));
}
/**
* @param array<array-key, int> $counts
* @return list<array{name: string, posts: int}>
*/
private function listed(array $counts): array
{
$names = array_map(fn (int|string $name) => (string) $name, array_keys($counts));
natcasesort($names);
return array_values(array_map(fn (string $name) => ['name' => $name, 'posts' => $counts[$name]], $names));
}
}
-14
View File
@@ -1,14 +0,0 @@
<?php
namespace IriksIT\Manager\Modules\Posts;
use IriksIT\Manager\Models\Post;
class PostsController
{
/** First opzet: lists the records as JSON. The screens come with the frontend. */
public function index()
{
return response()->json(Post::query()->latest()->paginate(25));
}
}
+15 -4
View File
@@ -2,7 +2,10 @@
namespace IriksIT\Manager\Modules\Posts;
use IriksIT\Manager\Models\Post;
use IriksIT\Manager\Modules\BaseModule;
use IriksIT\Manager\Support\MediaUsage;
use IriksIT\Manager\Support\Permission;
class PostsModule extends BaseModule
{
@@ -24,10 +27,11 @@ class PostsModule extends BaseModule
public function permissions(): array
{
return [
'posts.view' => 'See the posts, drafts included',
'posts.write' => 'Write and change posts',
'posts.publish' => 'Publish and unpublish posts',
'posts.delete' => 'Delete posts',
new Permission('posts.view', 'See the posts, drafts included', 'Posts'),
new Permission('posts.write', 'Write posts: create drafts and change them', 'Posts', needs: ['posts.view']),
new Permission('posts.publish', 'Publish, schedule and unpublish posts, and change posts that are live', 'Posts', needs: ['posts.view', 'posts.write']),
new Permission('posts.delete', 'Delete posts (one that is live only together with publishing)', 'Posts', needs: ['posts.view']),
new Permission('posts.labels', 'Manage the categories and tags: make them, and rename, merge and remove them on all posts', 'Posts', needs: ['posts.view']),
];
}
@@ -35,6 +39,13 @@ class PostsModule extends BaseModule
{
return [
['label' => 'Posts', 'route' => 'manager.posts.index', 'permission' => 'posts.view'],
['label' => 'Categories and tags', 'route' => 'manager.labels.index', 'permission' => 'posts.labels'],
];
}
/** Where the media library looks for the use of a file: the texts of the posts. */
public function boot(): void
{
app(MediaUsage::class)->register(fn () => Post::query()->get(['body', 'excerpt', 'cover_image'])->flatMap(fn (Post $row) => array_values($row->only(['body', 'excerpt', 'cover_image']))));
}
}
@@ -8,19 +8,40 @@ return new class extends Migration
{
public function up(): void
{
Schema::create(config('manager.table_prefix').'posts', function (Blueprint $table) {
$prefix = config('manager.table_prefix');
Schema::create($prefix.'posts', function (Blueprint $table) {
$table->id();
$table->string('slug')->unique();
$table->string('title');
$table->text('excerpt')->nullable();
$table->longText('body')->nullable();
$table->string('slug')->unique();
$table->string('excerpt', 500)->nullable();
$table->longText('body');
$table->string('cover_image', 2048)->nullable();
$table->string('category', 60)->nullable();
$table->json('tags')->nullable();
$table->boolean('is_featured')->default(false);
// null = draft; a future date = scheduled
$table->timestamp('published_at')->nullable()->index();
$table->timestamps();
});
// Categories and tags that were made by hand, so one can exist before a post uses it.
// The ones a post uses are in the post itself; this only remembers names to offer.
Schema::create($prefix.'post_labels', function (Blueprint $table) {
$table->id();
$table->string('type', 10);
$table->string('name', 60);
$table->timestamps();
$table->unique(['type', 'name']);
});
}
public function down(): void
{
Schema::dropIfExists(config('manager.table_prefix').'posts');
$prefix = config('manager.table_prefix');
Schema::dropIfExists($prefix.'post_labels');
Schema::dropIfExists($prefix.'posts');
}
};
+18 -2
View File
@@ -1,6 +1,22 @@
<?php
use Illuminate\Support\Facades\Route;
use IriksIT\Manager\Modules\Posts\PostsController;
use IriksIT\Manager\Modules\Posts\LabelController;
use IriksIT\Manager\Modules\Posts\PostController;
Route::get('/posts', [PostsController::class, 'index'])->name('posts.index')->middleware('can:posts.view');
Route::get('/posts', [PostController::class, 'index'])->name('posts.index')->middleware('can:posts.view');
Route::get('/posts/create', [PostController::class, 'create'])->name('posts.create')->middleware('can:posts.write');
Route::post('/posts', [PostController::class, 'store'])->name('posts.store')->middleware('can:posts.write');
Route::get('/posts/{post}/edit', [PostController::class, 'edit'])->name('posts.edit')->middleware('can:posts.write')->whereNumber('post');
Route::get('/posts/{post}/preview', [PostController::class, 'preview'])->name('posts.preview')->middleware('can:posts.view')->whereNumber('post');
Route::put('/posts/{post}', [PostController::class, 'update'])->name('posts.update')->middleware('can:posts.write')->whereNumber('post');
Route::put('/posts/{post}/online', [PostController::class, 'online'])->name('posts.online')->middleware('can:posts.publish')->whereNumber('post');
Route::delete('/posts/{post}', [PostController::class, 'destroy'])->name('posts.destroy')->middleware('can:posts.delete')->whereNumber('post');
// The name of a label travels in the body, not the address: it can hold anything.
Route::middleware('can:posts.labels')->group(function () {
Route::get('/labels', [LabelController::class, 'index'])->name('labels.index');
Route::post('/labels', [LabelController::class, 'store'])->name('labels.store');
Route::put('/labels', [LabelController::class, 'update'])->name('labels.update');
Route::delete('/labels', [LabelController::class, 'destroy'])->name('labels.destroy');
});
+2 -1
View File
@@ -3,6 +3,7 @@
namespace IriksIT\Manager\Modules\Reviews;
use IriksIT\Manager\Modules\BaseModule;
use IriksIT\Manager\Support\Permission;
class ReviewsModule extends BaseModule
{
@@ -24,7 +25,7 @@ class ReviewsModule extends BaseModule
public function permissions(): array
{
return [
'reviews.manage' => 'Manage the reviews',
new Permission('reviews.manage', 'Manage the reviews', 'Site content'),
];
}
+168
View File
@@ -0,0 +1,168 @@
<?php
namespace IriksIT\Manager\Modules\Users;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;
use IriksIT\Manager\Models\Group;
/**
* The accounts of the manager and the groups each is in.
*
* Managing accounts must not be a way to more rights than one has. So, for anyone who is no
* super admin: an account is only changed or deleted when it may do nothing more than oneself
* (`managerOutranks`), and it is only put in a group that gives nothing more than one has
* oneself (`managerMayGive`). Nobody becomes a super admin here: that is `manager:create-user`.
*
* The answers have the shape the screens of the sites used as props.
*/
class AccountController
{
public function index(Request $request): JsonResponse
{
$me = $request->user();
$model = $this->model();
return response()->json([
'accounts' => $model::query()->with('managerGroups')->orderBy('name')->orderBy('id')->get()
->map(fn ($user) => [
'id' => $user->getKey(),
'name' => $user->name,
'email' => $user->email,
'is_super_admin' => $user->isManagerSuperAdmin(),
'is_you' => $user->is($me),
'groups' => $user->managerGroups->sortBy('name')->map(fn (Group $group) => ['id' => $group->id, 'name' => $group->name])->values(),
'can_change' => $me->managerOutranks($user),
'can_delete' => $me->managerOutranks($user) && ! $user->is($me),
])->values(),
'groups' => Group::query()->orderBy('name')->get()
->map(fn (Group $group) => [
'id' => $group->id,
'name' => $group->name,
'description' => $group->description,
'can_give' => $me->managerMayGive($group),
])->values(),
]);
}
public function store(Request $request): JsonResponse
{
$request->validate([...$this->rules(), 'password' => ['required', 'string', 'min:12', 'max:200']]);
// Everything is checked before anything is stored: a refused group leaves no account behind.
$details = $this->details($request, null);
$groups = $this->groups($request);
$model = $this->model();
$user = new $model;
$user->forceFill([...$details, 'password' => Hash::make($request->string('password')->toString())])->save();
$user->managerGroups()->sync($groups);
return response()->json(['id' => $user->getKey()], 201);
}
public function update(Request $request, string $account): JsonResponse
{
$me = $request->user();
$user = $this->find($account);
abort_unless($me->managerOutranks($user), 403);
$request->validate([...$this->rules(), 'password' => ['nullable', 'string', 'min:12', 'max:200']]);
$details = $this->details($request, $user);
// Groups mean nothing for a super admin, and nobody changes their own.
$groups = $user->isManagerSuperAdmin() || $user->is($me) ? null : $this->groups($request);
$user->forceFill($details);
// Empty: the password stays as it is.
if ($request->filled('password')) {
$user->forceFill(['password' => Hash::make($request->string('password')->toString())]);
}
$user->save();
if ($groups !== null) {
$user->managerGroups()->sync($groups);
}
return response()->json(['saved' => true]);
}
public function destroy(Request $request, string $account): JsonResponse
{
$me = $request->user();
$user = $this->find($account);
abort_unless($me->managerOutranks($user), 403);
if ($user->is($me)) {
return response()->json(['message' => 'You cannot delete your own account.'], 422);
}
$user->managerGroups()->detach();
$user->delete();
return response()->json(['deleted' => true]);
}
/** @return class-string<Authenticatable&Model> */
private function model(): string
{
return config('manager.user_model');
}
private function find(string $id)
{
return $this->model()::query()->findOrFail($id);
}
/** @return array<string, list<mixed>> */
private function rules(): array
{
return [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255'],
'groups' => ['array'],
'groups.*' => ['integer'],
];
}
/**
* Name and email address, the address in lower case and not in use by another account.
*
* @return array{name: string, email: string}
*/
private function details(Request $request, $user): array
{
$email = $request->string('email')->trim()->lower()->toString();
if ($this->model()::query()->where('email', $email)->when($user !== null, fn ($query) => $query->whereKeyNot($user->getKey()))->exists()) {
throw ValidationException::withMessages(['email' => 'Another account already uses this email address.']);
}
return ['name' => $request->string('name')->trim()->toString(), 'email' => $email];
}
/**
* The ids of the groups that were ticked. One that does not exist, or that gives more than
* the account that is logged in has, is refused.
*
* @return list<int>
*/
private function groups(Request $request): array
{
$me = $request->user();
$ids = array_values(array_unique(array_map(fn (mixed $id) => is_numeric($id) ? (int) $id : 0, $request->array('groups'))));
$groups = Group::query()->whereKey($ids)->get();
if ($groups->count() !== count($ids) || $groups->contains(fn (Group $group) => ! $me->managerMayGive($group))) {
throw ValidationException::withMessages(['groups' => 'You can only choose groups that allow nothing more than your own account.']);
}
return $ids;
}
}
+78
View File
@@ -0,0 +1,78 @@
<?php
namespace IriksIT\Manager\Modules\Users;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Hash;
/**
* Creates a super admin: an account that may do everything in the manager, and the only kind
* that manages the groups. This is the only place that hands out `is_super_admin`.
*
* php artisan manager:create-user
*
* It asks for name, email and password. For scripts, pass them as options.
*/
class CreateManagerUser extends Command
{
protected $signature = 'manager:create-user
{--name= : Name shown in the manager}
{--email= : Email address to log in with}
{--password= : Password (min 12 characters); leave out to type it hidden}';
protected $description = 'Create a super admin: an account that may do everything in the manager';
public function handle(): int
{
$name = $this->value('name', 'Name');
$email = strtolower($this->value('email', 'Email'));
$password = $this->value('password', 'Password (min 12 characters)', secret: true);
$model = config('manager.user_model');
if ($name === '' || filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$this->error('A name and a valid email address are required.');
return self::FAILURE;
}
if ($model::query()->where('email', $email)->exists()) {
$this->error("A user with email {$email} already exists.");
return self::FAILURE;
}
if (mb_strlen($password) < 12) {
$this->error('Password must be at least 12 characters.');
return self::FAILURE;
}
// Direct assignment: a super admin is never mass-assignable.
$user = new $model;
$user->forceFill(['name' => $name, 'email' => $email, 'password' => Hash::make($password)]);
$user->is_super_admin = true;
$user->save();
$this->info("Super admin account for {$name} <{$email}> created.");
return self::SUCCESS;
}
/** The option when it was given, otherwise the answer to a question. */
private function value(string $option, string $question, bool $secret = false): string
{
$given = $this->option($option);
if (is_string($given) && trim($given) !== '') {
return $secret ? $given : trim($given);
}
$answer = $secret ? $this->secret($question) : $this->ask($question);
if (! is_string($answer)) {
return '';
}
return $secret ? $answer : trim($answer);
}
}
+76
View File
@@ -0,0 +1,76 @@
<?php
namespace IriksIT\Manager\Modules\Users;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use IriksIT\Manager\Models\Group;
use IriksIT\Manager\Support\ModuleRegistry;
/** The groups and what each allows. Only for a super admin (the `groups.manage` gate). */
class GroupController
{
public function __construct(private readonly ModuleRegistry $modules) {}
public function index(): JsonResponse
{
return response()->json([
'groups' => Group::query()->withCount('users')->orderBy('name')->get()
->map(fn (Group $group) => [
'id' => $group->id,
'name' => $group->name,
'description' => $group->description,
'permissions' => $group->allowed(),
'accounts' => $group->users_count,
])->values(),
'catalogue' => $this->modules->catalogue(),
]);
}
public function store(Request $request): JsonResponse
{
$group = Group::create($this->validated($request));
return response()->json(['id' => $group->id], 201);
}
public function update(Request $request, string $group): JsonResponse
{
$group = Group::query()->findOrFail($group);
$group->update($this->validated($request, $group));
return response()->json(['saved' => true]);
}
/** The accounts in it stay; they lose what only this group allowed. */
public function destroy(string $group): JsonResponse
{
$group = Group::query()->findOrFail($group);
$group->users()->detach();
$group->delete();
return response()->json(['deleted' => true]);
}
/** @return array{name: string, description: string|null, permissions: list<string>} */
private function validated(Request $request, ?Group $group = null): array
{
$table = config('manager.table_prefix').'groups';
$request->validate([
'name' => ['required', 'string', 'max:60', Rule::unique($table, 'name')->ignore($group?->id)],
'description' => ['nullable', 'string', 'max:500'],
'permissions' => ['array'],
'permissions.*' => ['string', Rule::in($this->modules->permissionValues())],
]);
$description = $request->string('description')->trim()->toString();
return [
'name' => $request->string('name')->trim()->toString(),
'description' => $description !== '' ? $description : null,
'permissions' => $this->modules->complete($request->array('permissions')),
];
}
}
-14
View File
@@ -1,14 +0,0 @@
<?php
namespace IriksIT\Manager\Modules\Users;
class UsersController
{
/** First opzet: lists the accounts as JSON. The screens come with the frontend. */
public function index()
{
$user = config('manager.user_model');
return response()->json($user::query()->with('managerGroups')->latest()->paginate(25));
}
}
+9 -2
View File
@@ -3,6 +3,7 @@
namespace IriksIT\Manager\Modules\Users;
use IriksIT\Manager\Modules\BaseModule;
use IriksIT\Manager\Support\Permission;
class UsersModule extends BaseModule
{
@@ -24,14 +25,20 @@ class UsersModule extends BaseModule
public function permissions(): array
{
return [
'users.manage' => 'Create, change and delete accounts, and put them in groups',
new Permission('accounts.manage', 'Create, change and delete accounts, and put them in groups', 'Accounts'),
];
}
public function navigation(): array
{
return [
['label' => 'Users', 'route' => 'manager.users.index', 'permission' => 'users.manage'],
['label' => 'Accounts', 'route' => 'manager.accounts.index', 'permission' => 'accounts.manage'],
['label' => 'Groups', 'route' => 'manager.groups.index', 'permission' => 'groups.manage'],
];
}
public function commands(): array
{
return [CreateManagerUser::class];
}
}
@@ -9,31 +9,36 @@ return new class extends Migration
public function up(): void
{
$prefix = config('manager.table_prefix');
$users = (new (config('manager.user_model')))->getTable();
// New accounts are never super admins; an existing one is not promoted here.
// `manager:create-user` is the way to make a super admin.
if (! Schema::hasColumn($users, 'is_super_admin')) {
Schema::table($users, fn (Blueprint $table) => $table->boolean('is_super_admin')->default(false));
}
Schema::create($prefix.'groups', function (Blueprint $table) {
$table->id();
$table->string('name')->unique();
$table->string('description', 500)->nullable();
$table->json('permissions')->nullable();
$table->timestamps();
});
Schema::create($prefix.'group_user', function (Blueprint $table) use ($prefix) {
Schema::create($prefix.'group_user', function (Blueprint $table) use ($prefix, $users) {
$table->foreignId('group_id')->constrained($prefix.'groups')->cascadeOnDelete();
$table->unsignedBigInteger('user_id')->index();
$table->foreignId('user_id')->constrained($users)->cascadeOnDelete();
$table->primary(['group_id', 'user_id']);
});
Schema::table('users', function (Blueprint $table) {
$table->boolean('manager_super_admin')->default(false);
});
}
public function down(): void
{
$prefix = config('manager.table_prefix');
$users = (new (config('manager.user_model')))->getTable();
Schema::table('users', fn (Blueprint $table) => $table->dropColumn('manager_super_admin'));
Schema::dropIfExists($prefix.'group_user');
Schema::dropIfExists($prefix.'groups');
Schema::table($users, fn (Blueprint $table) => $table->dropColumn('is_super_admin'));
}
};
+17 -2
View File
@@ -1,6 +1,21 @@
<?php
use Illuminate\Support\Facades\Route;
use IriksIT\Manager\Modules\Users\UsersController;
use IriksIT\Manager\Modules\Users\AccountController;
use IriksIT\Manager\Modules\Users\GroupController;
Route::get('/users', [UsersController::class, 'index'])->name('users.index')->middleware('can:users.manage');
// `{account}` and `{group}` are resolved in the controllers: the user model is configurable,
// so nothing is bound globally.
Route::middleware('can:accounts.manage')->group(function () {
Route::get('/accounts', [AccountController::class, 'index'])->name('accounts.index');
Route::post('/accounts', [AccountController::class, 'store'])->name('accounts.store');
Route::put('/accounts/{account}', [AccountController::class, 'update'])->name('accounts.update')->whereNumber('account');
Route::delete('/accounts/{account}', [AccountController::class, 'destroy'])->name('accounts.destroy')->whereNumber('account');
});
Route::middleware('can:groups.manage')->group(function () {
Route::get('/groups', [GroupController::class, 'index'])->name('groups.index');
Route::post('/groups', [GroupController::class, 'store'])->name('groups.store');
Route::put('/groups/{group}', [GroupController::class, 'update'])->name('groups.update')->whereNumber('group');
Route::delete('/groups/{group}', [GroupController::class, 'destroy'])->name('groups.destroy')->whereNumber('group');
});
+37
View File
@@ -0,0 +1,37 @@
<?php
namespace IriksIT\Manager\Support;
use Illuminate\Support\Str;
use League\CommonMark\Extension\ExternalLink\ExternalLinkExtension;
/**
* Posts are written in Markdown. Raw HTML in a post is escaped, so the rendered output is safe
* to print. Links to other hosts open in a new window; `manager.markdown.internal_hosts` lists
* more hosts that count as this site.
*/
final class Markdown
{
public static function toHtml(string $markdown): string
{
$host = parse_url((string) config('app.url'), PHP_URL_HOST);
return Str::markdown($markdown, [
'html_input' => 'escape',
'allow_unsafe_links' => false,
'external_link' => [
'internal_hosts' => array_values(array_filter([$host, ...(array) config('manager.markdown.internal_hosts', [])])),
'open_in_new_window' => true,
'noopener' => 'external',
'noreferrer' => 'external',
],
], [new ExternalLinkExtension]);
}
public static function toPlainText(string $markdown): string
{
$text = strip_tags(self::toHtml($markdown));
return trim((string) preg_replace('/\s+/', ' ', html_entity_decode($text, ENT_QUOTES | ENT_HTML5)));
}
}
+36
View File
@@ -0,0 +1,36 @@
<?php
namespace IriksIT\Manager\Support;
use Closure;
/**
* Where media is used. A module or the host app registers a source: a closure that returns the
* texts which may contain the address of a media file (a post body, a cover, a page text).
* The media library counts the files whose address appears in them. No sources, no counts.
*/
final class MediaUsage
{
/** @var list<Closure(): iterable<mixed>> */
private array $sources = [];
/** @param Closure(): iterable<mixed> $source */
public function register(Closure $source): void
{
$this->sources[] = $source;
}
/** @return list<string> */
public function haystacks(): array
{
$texts = [];
foreach ($this->sources as $source) {
foreach ($source() as $text) {
$texts[] = is_string($text) ? $text : '';
}
}
return $texts;
}
}
+56 -2
View File
@@ -65,18 +65,72 @@ final class ModuleRegistry
}
}
/** @return array<string, string> permission value => label, of the active modules only */
/** @return array<string, Permission> permission value => permission, of the active modules only */
public function permissions(): array
{
$permissions = [];
foreach ($this->active() as $module) {
$permissions += $module->permissions();
foreach ($module->permissions() as $permission) {
$permissions[$permission->value] = $permission;
}
}
return $permissions;
}
/** @return list<string> */
public function permissionValues(): array
{
return array_keys($this->permissions());
}
/**
* The given values without what is no permission (any more), completed with what they
* need, in the order of the permissions.
*
* @param array<array-key, mixed> $values
* @return list<string>
*/
public function complete(array $values): array
{
$known = $this->permissions();
$wanted = [];
foreach ($values as $value) {
if (is_string($value) && isset($known[$value])) {
$wanted[$value] = true;
foreach ($known[$value]->needs as $needed) {
$wanted[$needed] = true;
}
}
}
return array_values(array_filter(array_keys($known), fn (string $value) => isset($wanted[$value])));
}
/**
* The list for the group form, per section.
*
* @return list<array{section: string, permissions: list<array{value: string, label: string, needs: list<string>}>}>
*/
public function catalogue(): array
{
$sections = [];
foreach ($this->permissions() as $permission) {
$sections[$permission->section][] = ['value' => $permission->value, 'label' => $permission->label, 'needs' => $permission->needs];
}
$catalogue = [];
foreach ($sections as $section => $permissions) {
$catalogue[] = ['section' => $section, 'permissions' => $permissions];
}
return $catalogue;
}
/** @return list<array{label: string, route: string, permission: string}> */
public function navigation(): array
{
+23
View File
@@ -0,0 +1,23 @@
<?php
namespace IriksIT\Manager\Support;
/**
* One thing an account can be allowed to do. A group holds a list of these values;
* a module declares the ones it adds (Module::permissions()).
*/
final readonly class Permission
{
/**
* @param string $value `<module>.<action>`, also the name of the gate
* @param string $label what the group form says next to the tick box
* @param string $section the heading it is listed under
* @param list<string> $needs values this one is useless without; a group that gets this gets those too
*/
public function __construct(
public string $value,
public string $label,
public string $section,
public array $needs = [],
) {}
}
+14
View File
@@ -0,0 +1,14 @@
<?php
use Illuminate\Support\Facades\Schema;
use IriksIT\Manager\Tests\MediaOffTestCase;
uses(MediaOffTestCase::class);
it('has no routes, no public file route and no table for a site without media', function () {
expect(Route::has('manager.media.index'))->toBeFalse()
->and(Route::has('manager.media.file'))->toBeFalse()
->and(Schema::hasTable('manager_media'))->toBeFalse();
$this->get('/media-files/1/x.png/view')->assertNotFound();
});
+128
View File
@@ -0,0 +1,128 @@
<?php
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use IriksIT\Manager\Models\Media;
use IriksIT\Manager\Models\Post;
use IriksIT\Manager\Tests\TestCase;
uses(TestCase::class);
function png(string $name = 'My Photo.png'): UploadedFile
{
return UploadedFile::fake()->createWithContent($name, file_get_contents(__DIR__.'/../Fixtures/pixel.png'));
}
beforeEach(function () {
Storage::fake('public');
$this->actingAs(makeUser(['media.delete', 'media.edit', 'media.upload']));
});
describe('uploading', function () {
it('stores a file on the disk and records it', function () {
$item = $this->postJson('/manager/media', ['file' => png(), 'focus_x' => 0.3, 'focus_y' => 0.65])->assertCreated()->json('item');
$media = Media::sole();
Storage::disk('public')->assertExists($media->location);
expect($item['url'])->toBe("/media-files/{$media->id}/my-photo.png/view")
->and($item)->not->toHaveKeys(['disk', 'location'])
->and($media->name)->toBe('My Photo')
->and($media->width)->toBe(1)
->and($media->checksum)->toBe(hash_file('sha256', __DIR__.'/../Fixtures/pixel.png'))
->and($media->focus_x)->toBe(0.3)
->and(Media::focusFor($item['url']))->toBe('30% 65%')
->and(Media::focusFor('/somewhere/else'))->toBeNull();
});
it('refuses what is not allowed: svg, too big, no room', function () {
$svg = UploadedFile::fake()->createWithContent('x.svg', '<svg xmlns="http://www.w3.org/2000/svg"/>');
$this->postJson('/manager/media', ['file' => $svg])->assertJsonValidationErrors('file');
config(['manager.media.max_file_mb' => 1]);
$this->postJson('/manager/media', ['file' => UploadedFile::fake()->create('big.pdf', 2048, 'application/pdf')])->assertJsonValidationErrors('file');
config(['manager.media.max_total_gb' => 0.000001]);
$this->postJson('/manager/media', ['file' => UploadedFile::fake()->create('a.pdf', 5, 'application/pdf')])->assertStatus(422)->assertJsonPath('storage.limit', 1000);
expect(Media::count())->toBe(0);
});
it('needs the permission', function () {
$this->actingAs(makeUser(['media.view']));
$this->postJson('/manager/media', ['file' => png()])->assertForbidden();
$this->getJson('/manager/media/items')->assertOk();
});
});
describe('changing and deleting', function () {
it('renames and keeps the focus point unless one is sent', function () {
$id = $this->postJson('/manager/media', ['file' => png(), 'focus_x' => 0.1, 'focus_y' => 0.2])->json('item.id');
$this->putJson("/manager/media/{$id}", ['name' => 'New', 'alt' => ' A cat '])->assertOk()->assertJsonPath('item.alt', 'A cat');
expect(Media::find($id)->focus_y)->toBe(0.2);
$this->putJson("/manager/media/{$id}", ['name' => 'New', 'focus_x' => 0.5])->assertJsonValidationErrors('focus_y');
});
it('deletes the file and the row', function () {
$this->postJson('/manager/media', ['file' => png()]);
$media = Media::sole();
$this->deleteJson("/manager/media/{$media->id}")->assertOk();
Storage::disk('public')->assertMissing($media->location);
expect(Media::count())->toBe(0);
});
});
describe('usage', function () {
it('counts where a file is used, through the registered sources of the modules that are on', function () {
$id = $this->postJson('/manager/media', ['file' => png()])->json('item.id');
Post::create(['slug' => 'a', 'title' => 'A', 'body' => "See ![x](/media-files/{$id}/my-photo.png/view)"]);
expect(collect($this->getJson('/manager/media/items')->json('items'))->firstWhere('id', $id)['usage_count'])->toBe(1);
});
});
describe('the file for visitors', function () {
beforeEach(function () {
$this->postJson('/manager/media', ['file' => png()]);
$this->media = Media::sole();
auth()->logout();
$this->app['auth']->forgetGuards();
});
it('is served without logging in, with caching headers', function () {
$response = $this->get($this->media->url())->assertOk()->assertHeader('Content-Type', 'image/png');
expect($response->headers->get('Cache-Control'))->toContain('immutable')
->and($response->headers->get('X-Content-Type-Options'))->toBe('nosniff')
->and($response->headers->has('Set-Cookie'))->toBeFalse()
->and($response->streamedContent())->toBe(file_get_contents(__DIR__.'/../Fixtures/pixel.png'));
});
it('answers 304 for a known ETag and a part for a range', function () {
$etag = '"'.$this->media->checksum.'"';
$this->get($this->media->url(), ['If-None-Match' => $etag])->assertStatus(304);
$part = $this->get($this->media->url(), ['Range' => 'bytes=0-9'])->assertStatus(206)->assertHeader('Content-Range', "bytes 0-9/{$this->media->size}");
expect($part->streamedContent())->toBe(substr(file_get_contents(__DIR__.'/../Fixtures/pixel.png'), 0, 10));
$this->get($this->media->url(), ['Range' => 'bytes=9999-'])->assertStatus(416);
});
it('offers anything that is not a safe type as a download', function () {
$this->media->update(['mime_type' => 'text/html']);
$this->get($this->media->url())->assertHeader('Content-Type', 'application/octet-stream')
->assertHeader('Content-Disposition', 'attachment; filename="my-photo.png"');
});
it('is 404 when the row or the file is gone', function () {
$this->get('/media-files/9999/x.png/view')->assertNotFound();
Storage::disk('public')->delete($this->media->location);
$this->get($this->media->url())->assertNotFound();
});
});
+16 -10
View File
@@ -1,9 +1,9 @@
<?php
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Schema;
use IriksIT\Manager\Facades\Manager;
use IriksIT\Manager\Models\Group;
use IriksIT\Manager\Tests\Fixtures\User;
use IriksIT\Manager\Tests\TestCase;
uses(TestCase::class);
@@ -28,18 +28,24 @@ it('adds all of it for a module that is on', function () {
});
it('lets a super admin in and keeps others out without the permission', function () {
$admin = User::create(['name' => 'a', 'email' => '[email protected]', 'password' => 'x', 'manager_super_admin' => true]);
$other = User::create(['name' => 'b', 'email' => '[email protected]', 'password' => 'x']);
$this->actingAs($admin)->getJson('/manager/posts')->assertOk();
$this->actingAs($other)->getJson('/manager/posts')->assertForbidden();
$this->actingAs(makeUser(superAdmin: true))->getJson('/manager/posts')->assertOk();
$this->actingAs(makeUser())->getJson('/manager/posts')->assertForbidden();
});
it('gives a group member the permissions of the group', function () {
$user = User::create(['name' => 'c', 'email' => '[email protected]', 'password' => 'x']);
$group = Group::create(['name' => 'Editors', 'permissions' => ['posts.view']]);
$user->managerGroups()->attach($group);
it('gives a group member the permissions of the group, with what they need', function () {
$user = makeUser(['posts.publish']);
expect($user->managerPermissions())->toBe(['posts.view', 'posts.write', 'posts.publish']);
$this->actingAs($user)->getJson('/manager/posts')->assertOk();
$this->actingAs($user)->getJson('/manager/pages')->assertForbidden();
});
it('forgets what a switched-off module allowed', function () {
$group = Group::create(['name' => 'Old', 'permissions' => ['posts.view', 'reviews.manage']]);
expect($group->allowed())->toBe(['posts.view']);
});
it('does not answer for abilities of the host app', function () {
expect(Gate::forUser(makeUser(superAdmin: true))->allows('host.something'))->toBeFalse();
});
+15
View File
@@ -0,0 +1,15 @@
<?php
use Illuminate\Support\Facades\Schema;
use IriksIT\Manager\Facades\Manager;
use IriksIT\Manager\Tests\PostsOffTestCase;
uses(PostsOffTestCase::class);
it('has no posts, labels, tables or rights for a site without posts', function () {
expect(Route::has('manager.posts.index'))->toBeFalse()
->and(Route::has('manager.labels.index'))->toBeFalse()
->and(Schema::hasTable('manager_posts'))->toBeFalse()
->and(Schema::hasTable('manager_post_labels'))->toBeFalse()
->and(Manager::permissionValues())->not->toContain('posts.view', 'posts.labels');
});
+288
View File
@@ -0,0 +1,288 @@
<?php
use IriksIT\Manager\Models\Post;
use IriksIT\Manager\Modules\Posts\PostLabels;
use IriksIT\Manager\Tests\TestCase;
uses(TestCase::class);
function postForm(array $overrides = []): array
{
return [
'title' => 'My first post',
'slug' => '',
'excerpt' => 'A short text',
'body' => "# Hello\n\nSome **markdown**.",
'cover_image' => '',
'category' => 'Tutorial',
'tags' => ['Laravel', ' Vue ', ''],
'is_featured' => true,
'is_published' => true,
'published_at' => '',
...$overrides,
];
}
function post(array $attributes = []): Post
{
static $n = 0;
$n++;
return Post::create([
'title' => "Post {$n}",
'slug' => "post-{$n}",
'body' => 'Body',
'published_at' => now()->subDay(),
...$attributes,
]);
}
beforeEach(fn () => $this->actingAs(makeUser(superAdmin: true)));
describe('post list', function () {
it('shows drafts first, then the newest posts, with their status', function () {
post(['title' => 'Published']);
post(['title' => 'Scheduled', 'published_at' => now()->addWeek()]);
post(['title' => 'Draft', 'published_at' => null]);
$this->getJson('/manager/posts')->assertOk()
->assertJsonCount(3, 'posts')
->assertJsonPath('posts.0.status', 'draft')
->assertJsonPath('posts.1.status', 'scheduled')
->assertJsonPath('posts.2.status', 'published');
});
});
describe('creating a post', function () {
it('offers the configured categories, the ones in use, the ones of the site, and tags', function () {
post(['category' => 'Tutorial', 'tags' => ['php']]);
post(['category' => 'Tutorial']);
post(['category' => null]);
app(PostLabels::class)->suggestCategories(fn () => ['Services']);
$this->getJson('/manager/posts/create')->assertOk()
->assertJsonPath('post', null)
->assertJsonPath('categories', ['Services', 'General', 'Tutorial'])
->assertJsonPath('known_tags', ['php']);
});
it('publishes now when no date is given, and makes the slug from the title', function () {
$this->freezeSecond();
$this->postJson('/manager/posts', postForm())->assertCreated();
$post = Post::sole();
expect($post->slug)->toBe('my-first-post')
->and($post->tags)->toBe(['Laravel', 'Vue'])
->and($post->is_featured)->toBeTrue()
->and($post->published_at?->equalTo(now()))->toBeTrue()
->and(Post::published()->count())->toBe(1);
});
it('saves a draft without a publish date', function () {
$this->postJson('/manager/posts', postForm(['is_published' => false, 'published_at' => '2026-01-01T10:00']));
expect(Post::sole()->published_at)->toBeNull()->and(Post::sole()->status())->toBe('draft');
});
it('schedules a post with a date in the future', function () {
$this->travelTo('2026-11-17 12:00');
$this->postJson('/manager/posts', postForm(['published_at' => '2026-12-01T09:30']));
$post = Post::sole();
expect($post->published_at?->format('Y-m-d H:i'))->toBe('2026-12-01 09:30')
->and($post->isPublished())->toBeFalse()
->and($post->status())->toBe('scheduled')
->and(Post::published()->count())->toBe(0);
});
it('gives a second post with the same title its own slug', function () {
$this->postJson('/manager/posts', postForm());
$this->postJson('/manager/posts', postForm());
expect(Post::orderBy('id')->pluck('slug')->all())->toBe(['my-first-post', 'my-first-post-2']);
});
it('stores empty optional fields as null', function () {
$this->postJson('/manager/posts', postForm(['excerpt' => '', 'cover_image' => '', 'category' => '', 'tags' => []]));
$post = Post::sole();
expect($post->excerpt)->toBeNull()->and($post->cover_image)->toBeNull()->and($post->category)->toBeNull()->and($post->tags)->toBe([]);
});
it('validates the form', function (array $input, string $field) {
post(['slug' => 'taken']);
$this->postJson('/manager/posts', postForm($input))->assertJsonValidationErrors($field);
expect(Post::count())->toBe(1);
})->with([
'missing title' => [['title' => ''], 'title'],
'missing body' => [['body' => ''], 'body'],
'slug in use' => [['slug' => 'taken'], 'slug'],
'slug with spaces' => [['slug' => 'Not A Slug'], 'slug'],
'invalid date' => [['published_at' => 'tomorrow-ish'], 'published_at'],
]);
});
describe('editing a post', function () {
it('shows the form filled in', function () {
$post = post(['published_at' => '2026-03-04 15:30:00']);
$this->getJson("/manager/posts/{$post->id}/edit")->assertOk()
->assertJsonPath('post.id', $post->id)
->assertJsonPath('post.is_published', true)
->assertJsonPath('post.published_at', '2026-03-04T15:30');
});
it('updates the post and keeps its own slug valid', function () {
$post = post(['slug' => 'my-slug']);
$this->putJson("/manager/posts/{$post->id}", postForm(['title' => 'New title', 'slug' => 'my-slug']))->assertOk();
expect($post->refresh()->title)->toBe('New title')->and($post->slug)->toBe('my-slug');
});
it('keeps the original publish date when saving without a date', function () {
$post = post(['published_at' => '2024-04-09 10:00:00']);
$this->putJson("/manager/posts/{$post->id}", postForm(['published_at' => '']));
expect($post->refresh()->published_at?->toDateTimeString())->toBe('2024-04-09 10:00:00');
});
it('unpublishes a post, which hides it from the site', function () {
$post = post(['slug' => 'my-slug']);
$this->putJson("/manager/posts/{$post->id}", postForm(['slug' => 'my-slug', 'is_published' => false]));
expect($post->refresh()->published_at)->toBeNull()->and(Post::published()->count())->toBe(0);
});
it('puts a post online and takes it off again', function () {
$post = post(['published_at' => null]);
$this->putJson("/manager/posts/{$post->id}/online", ['online' => true])->assertJsonPath('status', 'published');
$this->putJson("/manager/posts/{$post->id}/online", ['online' => false])->assertJsonPath('status', 'draft');
});
it('previews a draft, with the markdown rendered and raw html escaped', function () {
$post = post(['published_at' => null, 'body' => "**Draft** text <script>alert(1)</script>\n\n[out](https://example.org)"]);
$html = $this->getJson("/manager/posts/{$post->id}/preview")->assertOk()->assertJsonPath('preview', true)->json('post.body_html');
expect($html)->toContain('<strong>Draft</strong>')->not->toContain('<script>')->toContain('target="_blank"');
});
});
describe('deleting a post', function () {
it('removes it', function () {
$post = post();
$this->deleteJson("/manager/posts/{$post->id}")->assertOk();
expect(Post::count())->toBe(0);
});
});
describe('who may do what', function () {
it('lets a writer work on drafts, but never publish or touch what is live', function () {
$this->actingAs(makeUser(['posts.write', 'posts.delete']));
$live = post();
$draft = post(['published_at' => null]);
// Asking to publish still saves a draft.
$this->postJson('/manager/posts', postForm(['is_published' => true]))->assertCreated();
expect(Post::latest('id')->first()->published_at)->toBeNull();
$this->putJson("/manager/posts/{$draft->id}", postForm(['slug' => $draft->slug, 'is_published' => true]))->assertOk();
expect($draft->refresh()->published_at)->toBeNull();
$this->getJson("/manager/posts/{$live->id}/edit")->assertForbidden();
$this->putJson("/manager/posts/{$live->id}", postForm(['slug' => $live->slug]))->assertForbidden();
$this->deleteJson("/manager/posts/{$live->id}")->assertForbidden();
$this->putJson("/manager/posts/{$draft->id}/online", ['online' => true])->assertForbidden();
$this->deleteJson("/manager/posts/{$draft->id}")->assertOk();
});
it('does not show the delete button for a live post to a writer', function () {
$this->actingAs(makeUser(['posts.write', 'posts.delete']));
post();
$this->getJson('/manager/posts')->assertJsonPath('posts.0.can_change', false)->assertJsonPath('posts.0.can_delete', false);
});
it('keeps a viewer out of the form', function () {
$this->actingAs(makeUser(['posts.view']));
$this->getJson('/manager/posts')->assertOk();
$this->postJson('/manager/posts', postForm())->assertForbidden();
});
});
describe('categories and tags', function () {
it('lists every category and tag with the number of posts, drafts included', function () {
post(['category' => 'Laravel', 'tags' => ['php', 'Tutorial']]);
post(['category' => 'Laravel', 'tags' => ['php', 'php'], 'published_at' => null]);
post(['category' => 'devops', 'tags' => []]);
post(['category' => null, 'tags' => null]);
$this->getJson('/manager/labels')->assertOk()
->assertJsonPath('categories', [['name' => 'devops', 'posts' => 1], ['name' => 'Laravel', 'posts' => 2]])
->assertJsonPath('tags', [['name' => 'php', 'posts' => 2], ['name' => 'Tutorial', 'posts' => 1]]);
});
it('renames a category on every post, and merges two by using a name that exists', function () {
$one = post(['category' => 'Devops']);
$two = post(['category' => 'Dev ops']);
$other = post(['category' => 'Laravel']);
$this->putJson('/manager/labels', ['type' => 'category', 'name' => 'Devops', 'new_name' => ' DevOps '])->assertJsonPath('posts', 1);
$this->putJson('/manager/labels', ['type' => 'category', 'name' => 'Dev ops', 'new_name' => 'DevOps'])->assertJsonPath('posts', 1);
expect($one->refresh()->category)->toBe('DevOps')->and($two->refresh()->category)->toBe('DevOps')->and($other->refresh()->category)->toBe('Laravel');
});
it('renames a tag, keeps the order, and keeps it once in a post that had both names', function () {
$one = post(['tags' => ['first', 'laravel', 'last']]);
$both = post(['tags' => ['Laravel', 'laravel', 'php']]);
$other = post(['tags' => ['php']]);
$this->putJson('/manager/labels', ['type' => 'tag', 'name' => 'laravel', 'new_name' => 'Laravel'])->assertJsonPath('posts', 2);
expect($one->refresh()->tags)->toBe(['first', 'Laravel', 'last'])
->and($both->refresh()->tags)->toBe(['Laravel', 'php'])
->and($other->refresh()->tags)->toBe(['php']);
});
it('takes a label off every post and leaves the posts', function () {
$post = post(['category' => 'Old', 'tags' => ['old', 'php']]);
$this->deleteJson('/manager/labels', ['type' => 'category', 'name' => 'Old'])->assertJsonPath('posts', 1);
$this->deleteJson('/manager/labels', ['type' => 'tag', 'name' => 'old'])->assertJsonPath('posts', 1);
expect($post->refresh()->category)->toBeNull()->and($post->tags)->toBe(['php'])->and(Post::count())->toBe(1);
});
it('makes a label by hand, which a rename and a removal follow', function () {
$this->postJson('/manager/labels', ['type' => 'category', 'name' => 'Future'])->assertCreated();
$this->postJson('/manager/labels', ['type' => 'category', 'name' => 'Future'])->assertStatus(422);
$this->getJson('/manager/labels')->assertJsonPath('categories', [['name' => 'Future', 'posts' => 0]]);
$this->putJson('/manager/labels', ['type' => 'category', 'name' => 'Future', 'new_name' => 'Soon']);
$this->getJson('/manager/labels')->assertJsonPath('categories', [['name' => 'Soon', 'posts' => 0]]);
$this->deleteJson('/manager/labels', ['type' => 'category', 'name' => 'Soon']);
$this->getJson('/manager/labels')->assertJsonPath('categories', []);
});
it('refuses a tag with a comma and an unknown type, and needs its own permission', function () {
$this->postJson('/manager/labels', ['type' => 'tag', 'name' => 'a,b'])->assertJsonValidationErrors('name');
$this->postJson('/manager/labels', ['type' => 'other', 'name' => 'x'])->assertJsonValidationErrors('type');
$this->actingAs(makeUser(['posts.write']));
$this->getJson('/manager/labels')->assertForbidden();
});
});
+132
View File
@@ -0,0 +1,132 @@
<?php
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use IriksIT\Manager\Models\Group;
use IriksIT\Manager\Tests\Fixtures\User;
use IriksIT\Manager\Tests\TestCase;
uses(TestCase::class);
describe('groups', function () {
beforeEach(fn () => $this->actingAs(makeUser(superAdmin: true)));
it('lists the groups with what they allow and everything that can be allowed', function () {
$group = Group::create(['name' => 'Writers', 'permissions' => ['posts.write']]);
makeUser()->managerGroups()->attach($group);
$this->getJson('/manager/groups')->assertOk()
->assertJsonPath('groups.0.name', 'Writers')
->assertJsonPath('groups.0.permissions', ['posts.view', 'posts.write'])
->assertJsonPath('groups.0.accounts', 1);
$values = collect($this->getJson('/manager/groups')->json('catalogue'))->flatMap(fn ($s) => collect($s['permissions'])->pluck('value'))->all();
expect($values)->toContain('accounts.manage', 'media.upload')->not->toContain('groups.manage', 'reviews.manage');
});
it('creates a group, with what its permissions need', function () {
$this->postJson('/manager/groups', ['name' => ' Editors ', 'description' => 'Publish', 'permissions' => ['posts.publish', 'media.upload']])->assertCreated();
expect(Group::sole()->permissions)->toBe(['media.view', 'media.upload', 'posts.view', 'posts.write', 'posts.publish']);
});
it('refuses a name that is taken, a permission that does not exist and groups.manage', function () {
Group::create(['name' => 'Writers']);
$this->postJson('/manager/groups', ['name' => 'Writers'])->assertJsonValidationErrors('name');
$this->postJson('/manager/groups', ['name' => 'Others', 'permissions' => ['groups.manage']])->assertJsonValidationErrors('permissions.0');
expect(Group::count())->toBe(1);
});
it('changes what a group allows, which its accounts feel at once', function () {
$group = Group::create(['name' => 'Writers', 'permissions' => ['posts.write']]);
$writer = makeUser();
$writer->managerGroups()->attach($group);
$this->putJson("/manager/groups/{$group->id}", ['name' => 'Writers', 'permissions' => ['pages.edit']])->assertOk();
$this->actingAs($writer->refresh())->getJson('/manager/posts')->assertForbidden();
$this->getJson('/manager/pages')->assertOk();
});
it('deletes a group and leaves its accounts, without what it allowed', function () {
$group = Group::create(['name' => 'Writers', 'permissions' => ['posts.write']]);
$writer = makeUser();
$writer->managerGroups()->attach($group);
$this->deleteJson("/manager/groups/{$group->id}")->assertOk();
expect(Group::count())->toBe(0)->and($writer->refresh()->managerPermissions())->toBe([]);
});
it('is not for someone who manages accounts but is no super admin', function () {
$this->actingAs(makeUser(['accounts.manage']));
$this->getJson('/manager/groups')->assertForbidden();
$this->postJson('/manager/groups', ['name' => 'Mine'])->assertForbidden();
expect(Group::where('name', 'Mine')->exists())->toBeFalse();
});
});
describe('accounts', function () {
it('creates an account with a hashed password, never as super admin', function () {
$this->actingAs(makeUser(superAdmin: true));
$group = Group::create(['name' => 'Writers', 'permissions' => ['posts.write']]);
$this->postJson('/manager/accounts', ['name' => 'Ann', 'email' => ' [email protected] ', 'password' => 'a-long-password-1', 'groups' => [$group->id], 'is_super_admin' => true])->assertCreated();
$ann = User::where('email', '[email protected]')->sole();
expect(Hash::check('a-long-password-1', $ann->password))->toBeTrue()
->and($ann->isManagerSuperAdmin())->toBeFalse()
->and($ann->managerGroups->pluck('name')->all())->toBe(['Writers']);
});
it('refuses a short password and an address that is in use', function () {
$me = makeUser(superAdmin: true);
$this->actingAs($me);
$this->postJson('/manager/accounts', ['name' => 'A', 'email' => '[email protected]', 'password' => 'short'])->assertJsonValidationErrors('password');
$this->postJson('/manager/accounts', ['name' => 'A', 'email' => $me->email, 'password' => 'a-long-password-1'])->assertJsonValidationErrors('email');
});
it('does not let someone hand out more than they have', function () {
$this->actingAs(makeUser(['accounts.manage', 'posts.write']));
$big = Group::create(['name' => 'Big', 'permissions' => ['pages.edit']]);
$this->postJson('/manager/accounts', ['name' => 'B', 'email' => '[email protected]', 'password' => 'a-long-password-1', 'groups' => [$big->id]])->assertJsonValidationErrors('groups');
expect(User::where('email', '[email protected]')->exists())->toBeFalse();
});
it('does not let someone change or delete a mightier account, or themselves', function () {
$me = makeUser(['accounts.manage']);
$mighty = makeUser(['accounts.manage', 'posts.write']);
$boss = makeUser(superAdmin: true);
$this->actingAs($me);
$this->putJson("/manager/accounts/{$mighty->id}", ['name' => 'X', 'email' => '[email protected]', 'password' => 'a-long-password-1'])->assertForbidden();
$this->deleteJson("/manager/accounts/{$boss->id}")->assertForbidden();
$this->deleteJson("/manager/accounts/{$me->id}")->assertStatus(422);
});
it('keeps the password when it is left empty, and removes the group links on delete', function () {
$this->actingAs(makeUser(superAdmin: true));
$user = makeUser(['posts.view']);
$hash = $user->password;
$this->putJson("/manager/accounts/{$user->id}", ['name' => 'New name', 'email' => $user->email, 'password' => ''])->assertOk();
expect($user->refresh()->name)->toBe('New name')->and($user->password)->toBe($hash);
$this->deleteJson("/manager/accounts/{$user->id}")->assertOk();
expect(DB::table('manager_group_user')->count())->toBe(0);
});
});
it('makes a super admin only with the command', function () {
$this->artisan('manager:create-user', ['--name' => 'Root', '--email' => '[email protected]', '--password' => 'a-long-password-1'])->assertSuccessful();
$root = User::where('email', '[email protected]')->sole();
expect($root->isManagerSuperAdmin())->toBeTrue()->and(Hash::check('a-long-password-1', $root->password))->toBeTrue();
$this->artisan('manager:create-user', ['--name' => 'Root', '--email' => '[email protected]', '--password' => 'a-long-password-1'])->assertFailed();
$this->artisan('manager:create-user', ['--name' => 'Root', '--email' => '[email protected]', '--password' => 'short'])->assertFailed();
});
+4 -1
View File
@@ -5,9 +5,12 @@ namespace IriksIT\Manager\Tests\Fixtures;
use Illuminate\Foundation\Auth\User as Authenticatable;
use IriksIT\Manager\Concerns\HasManagerAccess;
/** Like the User of a normal app: no `hashed` cast, and no `is_super_admin` in $fillable. */
class User extends Authenticatable
{
use HasManagerAccess;
protected $guarded = [];
protected $fillable = ['name', 'email', 'password'];
protected $hidden = ['password'];
}
@@ -13,6 +13,7 @@ return new class extends Migration
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 70 B

+20
View File
@@ -0,0 +1,20 @@
<?php
use IriksIT\Manager\Models\Group;
use IriksIT\Manager\Tests\Fixtures\User;
function makeUser(array $permissions = [], bool $superAdmin = false, string $name = 'Someone'): User
{
static $n = 0;
$n++;
$user = new User(['name' => $name, 'email' => "user{$n}@example.com", 'password' => 'secret']);
$user->is_super_admin = $superAdmin;
$user->save();
if ($permissions !== []) {
$user->managerGroups()->attach(Group::create(['name' => "Group {$n}", 'permissions' => $permissions]));
}
return $user;
}
+8
View File
@@ -0,0 +1,8 @@
<?php
namespace IriksIT\Manager\Tests;
abstract class MediaOffTestCase extends TestCase
{
protected array $modules = ['media' => false];
}
+2
View File
@@ -1 +1,3 @@
<?php
require_once __DIR__.'/Helpers.php';
+8
View File
@@ -0,0 +1,8 @@
<?php
namespace IriksIT\Manager\Tests;
abstract class PostsOffTestCase extends TestCase
{
protected array $modules = ['posts' => false];
}