Compare commits

..
1 Commits
Author SHA1 Message Date
deploy-bot 1c8ad7dd6d v0.7.0 2026-12-04 11:54:45 +00:00
34 changed files with 2007 additions and 19 deletions

No files matched your search

+14
View File
@@ -4,6 +4,20 @@ Every release has a section here, named after its version (for example `v0.1.0 -
heading). The release pull request to `production` is stopped by PR CI when its section is missing, and the text of 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. the section is the text of the release in Gitea.
## v0.7.0 - 2026-12-04
- Per account a primary group (and any number of secondary ones): the primary group is the label of the account and sets its start screen; what the
account may do stays the sum of all its groups. A group can name a start screen. New migration: `is_primary` on the group-user table and `start` on groups.
- The settings screen (module `settings`, whole face only): switch parts of the manager and features of the site on or off and set the keys and addresses of
integrations (the IriksIT API, Turnstile) from the manager, with the rights `settings.manage` and `settings.secrets`. Works at once (database plus one compiled
file laid over the config, also with `config:cache`), optionally written into `.env` too (`manager.settings.write_env`). Sites add their own with
`manager.settings.definitions`. New migration: `settings`.
- More commands: `manager:settings` (list, get, set, reset, refresh; secrets are typed hidden), `manager:users`, `manager:user-password`, `manager:media-prune`
(unused media, or files no row knows; nothing is deleted without `--delete`) and `manager:import media` (the rows of a site's own media table, with `--set` for a value every row gets).
- `php artisan manager:media-move <disk>`: moves the files of the media library to another disk (for example to `iriksit`), keeping their addresses, with `--dry-run`, `--from`, `--limit`, `--verify` and `--delete-source`. Safe to run again.
- The disk `iriksit`: media files at the IriksIT API (`MANAGER_MEDIA_DISK=iriksit`, `manager.media.iriksit`), with a table that remembers which
path is which id (new migration `storage_files`) and `php artisan manager:storage-check` to try it. New requirement: `league/flysystem`.
## v0.6.0 - 2026-12-04 ## v0.6.0 - 2026-12-04
- Per account: the face of the manager (the whole one or the simple one) is stored on the account and wins over what its rights give; an administrator sets it - Per account: the face of the manager (the whole one or the simple one) is stored on the account and wins over what its rights give; an administrator sets it
+38
View File
@@ -144,6 +144,44 @@ Files live on a Laravel filesystem disk (`manager.media.disk`); each row remembe
- Where a file is used: other modules or your app register a source with - 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. `app(IriksIT\Manager\Support\MediaUsage::class)->register(fn () => $texts)`. Posts and Pages do.
- No SVG: it can carry scripts. - No SVG: it can carry scripts.
- **Files at the IriksIT API** (the disk `iriksit`): set `MANAGER_MEDIA_DISK=iriksit` and `MANAGER_IRIKSIT_URL` (the address of the
API with its version, for example `https://api.iriks-it.nl/v1`), `MANAGER_IRIKSIT_EMAIL` and `MANAGER_IRIKSIT_PASSWORD`. The account needs
the permissions `storage.read` and `storage.write`. Run the migrations (table `storage_files`), then `php artisan manager:storage-check`
writes, reads and deletes a test file and says what fails. The API keeps a file under an id of its own; the table remembers
which path of the disk is which id, and a location without a slash that is not in the table is taken for an id (a row of a site's older code
keeps working). Tokens are kept encrypted in the cache of the app. There are no folders and no listing on this disk.
## Commands
| Command | What it does |
|---|---|
| `manager:install`, `manager:doctor [--json]` | Set the manager up, and check that it is wired in (for people and agents). |
| `manager:create-user` | A super admin. |
| `manager:users [--json]` | The accounts with their groups. |
| `manager:user-password <email> [--generate]` | A new password for an account (typed hidden, never an argument). |
| `manager:settings list|get|set|reset|refresh` | The settings screen in the terminal; a secret is typed hidden or read from `--stdin`. |
| `manager:import posts|pages|reviews|media` | Copy the rows of a site's own table (`--map`, `--set=disk=iriksit`, `--dry-run`). |
| `manager:storage-check [--disk]` | Write, read and delete a test file on the disk of the media library. |
| `manager:media-move <disk>` | Move the library to another disk, keeping every address (`--dry-run`, `--verify`, `--delete-source`). |
| `manager:media-prune` | List media nothing uses any more (`--older-than`), or files no row knows (`--orphans`); `--delete` removes. |
| `manager:audit-prune`, `manager:unban`, `manager:make-theme` | Housekeeping of the audit log, bans and themes. |
## Settings module
A screen (`/manager/settings`, only in the whole face of the manager) where an account with `settings.manage` switches parts of the manager on and off and
changes settings, and an account with `settings.secrets` also changes keys, passwords and addresses (the IriksIT API, Turnstile, the disk of the media).
- A change is kept in the table `settings` (secrets encrypted) and in one compiled file, `bootstrap/cache/manager-settings.php`, that is laid over the config while
the app starts. So it works at once, on every server that shares the database, with or without `config:cache`, and a request reads one file from opcache, not the
database. "Refresh now" writes that file again and empties the caches. Without the file the table is read.
- `manager.settings.write_env` (`MANAGER_SETTINGS_WRITE_ENV`, off by default): also write the changed value into `.env`, when that file may be written. The old
one is kept as `.env.manager-backup`. Only variables that a definition names are ever written.
- Only what is defined can be set: the parts of the manager, the integrations of the package, and the site's own in `manager.settings.definitions`
(`'site.contact_form' => ['label' => 'Contact form', 'type' => 'toggle', 'group' => 'Site']`; the key is the config path it overrides, so
`config('site.contact_form')` has the answer). A module of your own can add some with a `settings()` method.
- What can send a password or a file elsewhere (secrets, addresses, accounts, disks) needs `settings.secrets` and the password of whoever saves it. A secret is
never sent to a browser; it is only said to be set. Clearing one is "back to what the config says".
- A part that is switched on and misses its tables is named: run `php artisan migrate`.
## Pages module ## Pages module
+2 -1
View File
@@ -16,7 +16,8 @@
"illuminate/routing": "^13.0", "illuminate/routing": "^13.0",
"illuminate/support": "^13.0", "illuminate/support": "^13.0",
"illuminate/validation": "^13.0", "illuminate/validation": "^13.0",
"league/commonmark": "^2.6" "league/commonmark": "^2.6",
"league/flysystem": "^3.0"
}, },
"require-dev": { "require-dev": {
"orchestra/testbench": "^11.0", "orchestra/testbench": "^11.0",
+21
View File
@@ -54,6 +54,7 @@ return [
Modules\Statistics\StatisticsModule::class, Modules\Statistics\StatisticsModule::class,
Modules\Resources\ResourcesModule::class, Modules\Resources\ResourcesModule::class,
Modules\Revisions\RevisionsModule::class, Modules\Revisions\RevisionsModule::class,
Modules\Settings\SettingsModule::class,
], ],
/* /*
@@ -71,6 +72,7 @@ return [
'statistics' => env('MANAGER_STATISTICS', false), 'statistics' => env('MANAGER_STATISTICS', false),
'resources' => true, 'resources' => true,
'revisions' => env('MANAGER_REVISIONS', true), 'revisions' => env('MANAGER_REVISIONS', true),
'settings' => true,
], ],
/* /*
@@ -90,6 +92,15 @@ return [
// File extensions the library accepts. SVG is deliberately missing: it can carry scripts. // File extensions the library accepts. SVG is deliberately missing: it can carry scripts.
'extensions' => ['jpg', 'jpeg', 'png', 'webp', 'gif', 'pdf', 'mp4', 'webm'], 'extensions' => ['jpg', 'jpeg', 'png', 'webp', 'gif', 'pdf', 'mp4', 'webm'],
// The disk `iriksit` keeps files at the IriksIT API (set `disk` to `iriksit`). The account needs the permissions
// `storage.read` and `storage.write`. Leave this empty for any other disk.
'iriksit' => [
'url' => env('MANAGER_IRIKSIT_URL'),
'email' => env('MANAGER_IRIKSIT_EMAIL'),
'password' => env('MANAGER_IRIKSIT_PASSWORD'),
'timeout' => 300,
],
// Visitors loading files per minute per address (the `media-files` rate limiter). // Visitors loading files per minute per address (the `media-files` rate limiter).
'per_minute' => 600, 'per_minute' => 600,
], ],
@@ -228,6 +239,16 @@ return [
*/ */
'mascot' => ['path' => null], 'mascot' => ['path' => null],
/*
| The settings screen (module `settings`, whole face of the manager only). Changes are kept in the database and in one compiled file
| and work at once. `write_env` also writes the changed value into .env, when that file may be written (it is left alone otherwise).
| `definitions` adds settings of the site's own, by the config path they override:
| 'site.contact_form' => ['label' => 'Contact form', 'type' => 'toggle', 'group' => 'Site', 'env' => 'CONTACT_FORM'].
| Types: toggle, text, url, number, select (with `options`), secret (never shown again). A definition with `sensitive` => true needs the
| right `settings.secrets` and the password of whoever saves it.
*/
'settings' => ['write_env' => (bool) env('MANAGER_SETTINGS_WRITE_ENV', false), 'definitions' => []],
/* /*
| Prefix for the tables of the package. | Prefix for the tables of the package.
*/ */
+1 -1
View File
@@ -1,3 +1,3 @@
/*! tailwindcss v4.3.5 | MIT License | https://tailwindcss.com */ /*! tailwindcss v4.3.5 | MIT License | https://tailwindcss.com */
@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:block))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-translate-x:0;--tw-translate-y:0;--tw-translate-z:0;--tw-scale-x:1;--tw-scale-y:1;--tw-scale-z:1;--tw-space-y-reverse:0;--tw-divide-y-reverse:0;--tw-border-style:solid;--tw-leading:initial;--tw-font-weight:initial;--tw-tracking:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000}}}@layer theme{:root,:host{--font-sans:var(--m-font,ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif);--font-mono:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;--color-red-500:oklch(63.7% .237 25.331);--color-emerald-500:oklch(69.6% .17 162.48);--color-black:#000;--color-white:#fff;--spacing:.25rem;--container-xs:20rem;--container-sm:24rem;--container-md:28rem;--container-xl:36rem;--container-2xl:42rem;--container-3xl:48rem;--container-5xl:64rem;--text-xs:.75rem;--text-xs--line-height:calc(1 / .75);--text-sm:.875rem;--text-sm--line-height:calc(1.25 / .875);--text-lg:1.125rem;--text-lg--line-height:calc(1.75 / 1.125);--text-xl:1.25rem;--text-xl--line-height:calc(1.75 / 1.25);--text-2xl:1.5rem;--text-2xl--line-height:calc(2 / 1.5);--text-3xl:1.875rem;--text-3xl--line-height:calc(2.25 / 1.875);--font-weight-normal:400;--font-weight-medium:500;--font-weight-semibold:600;--font-weight-bold:700;--tracking-wide:.025em;--leading-snug:1.375;--leading-relaxed:1.625;--radius-sm:.25rem;--radius-lg:.5rem;--radius-xl:.75rem;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1);--default-font-family:var(--m-font,ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif);--default-mono-font-family:var(--font-mono)}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;tab-size:4;line-height:1.5;font-family:var(--default-font-family,-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Noto Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring:where(:not(iframe)){outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab, red, red)){::placeholder{color:color-mix(in oklab, currentcolor 50%, transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fieldLine truncated @layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:block))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-translate-x:0;--tw-translate-y:0;--tw-translate-z:0;--tw-scale-x:1;--tw-scale-y:1;--tw-scale-z:1;--tw-space-y-reverse:0;--tw-divide-y-reverse:0;--tw-border-style:solid;--tw-leading:initial;--tw-font-weight:initial;--tw-tracking:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000}}}@layer theme{:root,:host{--font-sans:var(--m-font,ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif);--font-mono:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;--color-red-500:oklch(63.7% .237 25.331);--color-emerald-500:oklch(69.6% .17 162.48);--color-black:#000;--color-white:#fff;--spacing:.25rem;--container-xs:20rem;--container-sm:24rem;--container-md:28rem;--container-xl:36rem;--container-2xl:42rem;--container-3xl:48rem;--container-5xl:64rem;--text-xs:.75rem;--text-xs--line-height:calc(1 / .75);--text-sm:.875rem;--text-sm--line-height:calc(1.25 / .875);--text-lg:1.125rem;--text-lg--line-height:calc(1.75 / 1.125);--text-xl:1.25rem;--text-xl--line-height:calc(1.75 / 1.25);--text-2xl:1.5rem;--text-2xl--line-height:calc(2 / 1.5);--text-3xl:1.875rem;--text-3xl--line-height:calc(2.25 / 1.875);--font-weight-normal:400;--font-weight-medium:500;--font-weight-semibold:600;--font-weight-bold:700;--tracking-wide:.025em;--leading-snug:1.375;--leading-relaxed:1.625;--radius-sm:.25rem;--radius-lg:.5rem;--radius-xl:.75rem;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1);--default-font-family:var(--m-font,ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif);--default-mono-font-family:var(--font-mono)}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;tab-size:4;line-height:1.5;font-family:var(--default-font-family,-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Noto Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring:where(:not(iframe)){outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab, red, red)){::placeholder{color:color-mix(in oklab, currentcolor 50%, transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fieldLine truncated
/*$vite$:1*/ /*$vite$:1*/
+4 -4
View File
@@ -1,7 +1,7 @@
var e=Object.defineProperty,t=(t,n)=>{let r=Object.setPrototypeOf({},null);for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n&1||e(r,Symbol.toStringTag,{value:`Module`}),n&2?r:Object.preventExtensions(r)};function n(e){let t=Object.create(null);for(let n of e.split(`,`))t[n]=1;return e=>e in t}var r={},i=[],a=()=>{},o=()=>!1,s=e=>e.charCodeAt(0)===111&&e.charCodeAt(1)===110&&(e.charCodeAt(2)>122||e.charCodeAt(2)<97),c=e=>e.startsWith(`onUpdate:`),l=Object.assign,u=(e,t)=>{let n=e.indexOf(t);n>-1&&e.splice(n,1)},d=Object.prototype.hasOwnProperty,f=(e,t)=>d.call(e,t),p=Array.isArray,m=e=>C(e)===`[object Map]`,h=e=>C(e)===`[object Set]`,g=e=>C(e)===`[object Date]`,_=e=>C(e)===`[object RegExp]`,v=e=>typeof e==`function`,y=e=>typeof e==`string`,b=e=>typeof e==`symbol`,x=e=>typeof e==`object`&&!!e,S=e=>(x(e)||v(e))&&v(e.then)&&v(e.catch),ee=Object.prototype.toString,C=e=>ee.call(e),te=e=>C(e).slice(8,-1),w=e=>C(e)===`[object Object]`,T=e=>y(e)&&e!==`NaN`&&e[0]!==`-`&&``+parseInt(e,10)===e,ne=n(`,key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted`),re=1e4,ie=e=>{let t=Object.create(null),n=0;return(r=>{let i=t[r];return i===void 0?(++n>re&&(t=Object.create(null),n=1),t[r]=e(r)):i})},ae=/-\w/g,E=ie(e=>e.replace(ae,e=>e.slice(1).toUpperCase())),oe=/\B([A-Z])/g,se=ie(e=>e.replace(oe,`-$1`).toLowerCase()),ce=ie(e=>e.charAt(0).toUpperCase()+e.slice(1)),le=ie(e=>e?`on${ce(e)}`:``),D=(e,t)=>!Object.is(e,t),ue=(e,...t)=>{for(let n=0;n<e.length;n++)e[n](...t)},de=(e,t,n,r=!1)=>{Object.defineProperty(e,t,{configurable:!0,enumerable:!1,writable:r,value:n})},fe=e=>{let t=parseFloat(e);return isNaN(t)?e:t},pe=e=>{let t=y(e)?Number(e):NaN;return isNaN(t)?e:t},me,he=()=>me||=typeof globalThis<`u`?globalThis:typeof self<`u`?self:typeof window<`u`?window:typeof global<`u`?global:{},ge=n(`Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt,console,Error,Symbol`);function _e(e){if(p(e)){let t={};for(let n=0;n<e.length;n++){let r=e[n],i=y(r)?xe(r):_e(r);if(i)for(let e in i)t[e]=i[e]}return t}if(y(e)||x(e))return e}var ve=/;(?![^(]*\))/g,ye=/:([^]+)/,be=/"(?:[^"\\]|\\[^])*"|'(?:[^'\\]|\\[^])*'|\\[^]|\/\*[^]*?\*\//g;function xe(e){let t={};return e.replace(be,e=>e.startsWith(`/*`)?``:e).split(ve).forEach(e=>{if(e){let n=e.split(ye);n.length>1&&(t[n[0].trim()]=n[1].trim())}}),t}function O(e){let t=``;if(y(e))t=e;else if(p(e))for(let n=0;n<e.length;n++){let r=O(e[n]);r&&(t+=r+` `)}else if(x(e))for(let n in e)e[n]&&(t+=n+` `);return t.trim()}function Se(e){if(!e)return null;let{class:t,style:n}=e;return t&&!y(t)&&(e.class=O(t)),n&&(e.style=_e(n)),e}var Ce=`itemscope,allowfullscreen,disablepictureinpicture,disableremoteplayback,formnovalidate,ismap,nomodule,novalidate,playsinline,readonly`,we=n(Ce);Ce+``;function Te(e){return!!e||e===``}function Ee(e,t,n){if(e.length!==t.length)return!1;let r=!0;for(let i=0;r&&i<e.length;i++)r=Ae(e[i],t[i],n);return r}function De(e,t,n){if(e.size!==t.size)return!1;let r=Array.from(t),i=new Uint8Array(r.length);for(let t of e){let e=-1;for(let a=0;a<r.length;a++)if(!i[a]&&Ae(t,r[a],n)){e=a;break}if(e<0)return!1;i[e]=1}return!0}function Oe(e,t,n){let r=m(e),i=m(t);if(r||i||(r=h(e),i=h(t),r||i))return r&&i?De(e,t,n):!1;if(Object.keys(e).length!==Object.keys(t).length)return!1;for(let r in e){let i=f(e,r),a=f(t,r);if(i&&!a||!i&&a||!Ae(e[r],t[r],n))return!1}return Me(e)===Me(t)}function ke(e,t,n,r){n||=[new Map,new Map];let[i,a]=n;if(i.has(e)||a.has(t))return i.get(e)===t&&a.get(t)===e;i.set(e,t),a.set(t,e);let o=r(e,t,n);return i.delete(e),a.delete(t),o}function Ae(e,t,n){if(e===t)return!0;let r=g(e),i=g(t);return r||i?r&&i?e.getTime()===t.getTime():!1:(r=b(e),i=b(t),r||i?e===t:(r=p(e),i=p(t),r||i?r&&i?ke(e,t,n,Ee):!1:(r=x(e),i=x(t),r||i?!r||!i?!1:ke(e,t,n,Oe):String(e)===String(t))))}function je(e,t){return e.findIndex(e=>Ae(e,t))}function Me(e){return Object.getPrototypeOf(e)===null&&e[Symbol.toPrimitive]==null&&typeof e.toString!=`function`&&typeof e.valueOf!=`function`?C(e):String(e)}var Ne=e=>!!(e&&e.__v_isRef===!0),k=e=>y(e)?e:e==null?``:p(e)||x(e)&&(e.toString===ee||!v(e.toString))?Ne(e)?k(e.value):JSON.stringify(e,Pe,2):String(e),Pe=(e,t)=>Ne(t)?Pe(e,t.value):m(t)?{[`Map(${t.size})`]:[...t.entries()].reduce((e,[t,n],r)=>(e[Fe(t,r)+` =>`]=n,e),{})}:h(t)?{[`Set(${t.size})`]:[...t.values()].map(e=>Fe(e))}:b(t)?Fe(t):x(t)&&!p(t)&&!w(t)?String(t):t,Fe=(e,t=``)=>b(e)?`Symbol(${e.description??t})`:e;function Ie(e){return e==null?`initial`:typeof e==`string`?e===``?` `:e:String(e)}var Le,Re=class{constructor(e=!1){this.detached=e,this._active=!0,this._on=0,this.effects=[],this.cleanups=[],this._isPaused=!1,this._warnOnRun=!0,this.__v_skip=!0,!e&&Le&&(Le.active?(this.parent=Le,this.index=(Le.scopes||(Le.scopes=[])).push(this)-1):(this._active=!1,this._warnOnRun=!1))}get active(){return thLine truncated var e=Object.defineProperty,t=(t,n)=>{let r=Object.setPrototypeOf({},null);for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n&1||e(r,Symbol.toStringTag,{value:`Module`}),n&2?r:Object.preventExtensions(r)};function n(e){let t=Object.create(null);for(let n of e.split(`,`))t[n]=1;return e=>e in t}var r={},i=[],a=()=>{},o=()=>!1,s=e=>e.charCodeAt(0)===111&&e.charCodeAt(1)===110&&(e.charCodeAt(2)>122||e.charCodeAt(2)<97),c=e=>e.startsWith(`onUpdate:`),l=Object.assign,u=(e,t)=>{let n=e.indexOf(t);n>-1&&e.splice(n,1)},d=Object.prototype.hasOwnProperty,f=(e,t)=>d.call(e,t),p=Array.isArray,m=e=>C(e)===`[object Map]`,h=e=>C(e)===`[object Set]`,g=e=>C(e)===`[object Date]`,_=e=>C(e)===`[object RegExp]`,v=e=>typeof e==`function`,y=e=>typeof e==`string`,b=e=>typeof e==`symbol`,x=e=>typeof e==`object`&&!!e,S=e=>(x(e)||v(e))&&v(e.then)&&v(e.catch),ee=Object.prototype.toString,C=e=>ee.call(e),te=e=>C(e).slice(8,-1),w=e=>C(e)===`[object Object]`,T=e=>y(e)&&e!==`NaN`&&e[0]!==`-`&&``+parseInt(e,10)===e,ne=n(`,key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted`),re=1e4,ie=e=>{let t=Object.create(null),n=0;return(r=>{let i=t[r];return i===void 0?(++n>re&&(t=Object.create(null),n=1),t[r]=e(r)):i})},ae=/-\w/g,E=ie(e=>e.replace(ae,e=>e.slice(1).toUpperCase())),oe=/\B([A-Z])/g,se=ie(e=>e.replace(oe,`-$1`).toLowerCase()),ce=ie(e=>e.charAt(0).toUpperCase()+e.slice(1)),le=ie(e=>e?`on${ce(e)}`:``),ue=(e,t)=>!Object.is(e,t),de=(e,...t)=>{for(let n=0;n<e.length;n++)e[n](...t)},fe=(e,t,n,r=!1)=>{Object.defineProperty(e,t,{configurable:!0,enumerable:!1,writable:r,value:n})},pe=e=>{let t=parseFloat(e);return isNaN(t)?e:t},me=e=>{let t=y(e)?Number(e):NaN;return isNaN(t)?e:t},he,ge=()=>he||=typeof globalThis<`u`?globalThis:typeof self<`u`?self:typeof window<`u`?window:typeof global<`u`?global:{},_e=n(`Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt,console,Error,Symbol`);function ve(e){if(p(e)){let t={};for(let n=0;n<e.length;n++){let r=e[n],i=y(r)?Se(r):ve(r);if(i)for(let e in i)t[e]=i[e]}return t}if(y(e)||x(e))return e}var ye=/;(?![^(]*\))/g,be=/:([^]+)/,xe=/"(?:[^"\\]|\\[^])*"|'(?:[^'\\]|\\[^])*'|\\[^]|\/\*[^]*?\*\//g;function Se(e){let t={};return e.replace(xe,e=>e.startsWith(`/*`)?``:e).split(ye).forEach(e=>{if(e){let n=e.split(be);n.length>1&&(t[n[0].trim()]=n[1].trim())}}),t}function D(e){let t=``;if(y(e))t=e;else if(p(e))for(let n=0;n<e.length;n++){let r=D(e[n]);r&&(t+=r+` `)}else if(x(e))for(let n in e)e[n]&&(t+=n+` `);return t.trim()}function Ce(e){if(!e)return null;let{class:t,style:n}=e;return t&&!y(t)&&(e.class=D(t)),n&&(e.style=ve(n)),e}var we=`itemscope,allowfullscreen,disablepictureinpicture,disableremoteplayback,formnovalidate,ismap,nomodule,novalidate,playsinline,readonly`,Te=n(we);we+``;function Ee(e){return!!e||e===``}function De(e,t,n){if(e.length!==t.length)return!1;let r=!0;for(let i=0;r&&i<e.length;i++)r=je(e[i],t[i],n);return r}function Oe(e,t,n){if(e.size!==t.size)return!1;let r=Array.from(t),i=new Uint8Array(r.length);for(let t of e){let e=-1;for(let a=0;a<r.length;a++)if(!i[a]&&je(t,r[a],n)){e=a;break}if(e<0)return!1;i[e]=1}return!0}function ke(e,t,n){let r=m(e),i=m(t);if(r||i||(r=h(e),i=h(t),r||i))return r&&i?Oe(e,t,n):!1;if(Object.keys(e).length!==Object.keys(t).length)return!1;for(let r in e){let i=f(e,r),a=f(t,r);if(i&&!a||!i&&a||!je(e[r],t[r],n))return!1}return Ne(e)===Ne(t)}function Ae(e,t,n,r){n||=[new Map,new Map];let[i,a]=n;if(i.has(e)||a.has(t))return i.get(e)===t&&a.get(t)===e;i.set(e,t),a.set(t,e);let o=r(e,t,n);return i.delete(e),a.delete(t),o}function je(e,t,n){if(e===t)return!0;let r=g(e),i=g(t);return r||i?r&&i?e.getTime()===t.getTime():!1:(r=b(e),i=b(t),r||i?e===t:(r=p(e),i=p(t),r||i?r&&i?Ae(e,t,n,De):!1:(r=x(e),i=x(t),r||i?!r||!i?!1:Ae(e,t,n,ke):String(e)===String(t))))}function Me(e,t){return e.findIndex(e=>je(e,t))}function Ne(e){return Object.getPrototypeOf(e)===null&&e[Symbol.toPrimitive]==null&&typeof e.toString!=`function`&&typeof e.valueOf!=`function`?C(e):String(e)}var Pe=e=>!!(e&&e.__v_isRef===!0),O=e=>y(e)?e:e==null?``:p(e)||x(e)&&(e.toString===ee||!v(e.toString))?Pe(e)?O(e.value):JSON.stringify(e,Fe,2):String(e),Fe=(e,t)=>Pe(t)?Fe(e,t.value):m(t)?{[`Map(${t.size})`]:[...t.entries()].reduce((e,[t,n],r)=>(e[Ie(t,r)+` =>`]=n,e),{})}:h(t)?{[`Set(${t.size})`]:[...t.values()].map(e=>Ie(e))}:b(t)?Ie(t):x(t)&&!p(t)&&!w(t)?String(t):t,Ie=(e,t=``)=>b(e)?`Symbol(${e.description??t})`:e;function Le(e){return e==null?`initial`:typeof e==`string`?e===``?` `:e:String(e)}var Re,ze=class{constructor(e=!1){this.detached=e,this._active=!0,this._on=0,this.effects=[],this.cleanups=[],this._isPaused=!1,this._warnOnRun=!0,this.__v_skip=!0,!e&&Re&&(Re.active?(this.parent=Re,this.index=(Re.scopes||(Re.scopes=[])).push(this)-1):(this._active=!1,this._warnOnRun=!1))}get active(){return tLine truncated
`&&(e.tagName===`PRE`||e.tagName===`TEXTAREA`)&&(n=n.slice(1));let{textContent:r}=e;r!==n&&r!==n.replace(/\r\n|\r/g,` `&&(e.tagName===`PRE`||e.tagName===`TEXTAREA`)&&(n=n.slice(1));let{textContent:r}=e;r!==n&&r!==n.replace(/\r\n|\r/g,`
`)&&(Ai(e,0)||bi(),e.textContent=t.children)}if(d){if(_||b||!o||f&48){let t=e.tagName.includes(`-`),i=e.namespaceURI.includes(`svg`)?`svg`:e.namespaceURI.includes(`MathML`)?`mathml`:void 0;for(let a in d)if(_&&(a.endsWith(`value`)||a===`indeterminate`)||s(a)&&!ne(a)||a[0]===`.`||t&&!ne(a)||u&&u.includes(a)){if(Di(e,a,d[a]))continue;r(e,a,null,d[a],i,n)}}else if(d.onClick)r(e,`onClick`,null,d.onClick,void 0,n);else if(f&4&&ln(d.style))for(let e in d.style)d.style[e]}let x;(x=d&&d.onVnodeBeforeMount)&&Rs(x,n,t),h&&wr(t,null,n,`beforeMount`),((x=d&&d.onVnodeMounted)||h||l)&&ms(()=>{x&&Rs(x,n,t),l&&g.enter(e),h&&wr(t,null,n,`mounted`)},i)}return e.nextSibling},m=(e,t,r,o,s,c,u,d)=>{u||=!!t.dynamicChildren;let p=t.children,m=p.length,h=t.type===B,g=!1;for(let t=0;t<m;t++){let _=u?p[t]:p[t]=Ps(p[t]),v=_.type===_s;h&&e&&wi(e)&&e.data===`]`&&(d=e),e&&e!==d?(v&&!u&&t+1<m&&Ps(p[t+1]).type===_s&&(l(i(e.data.slice(_.children.length)),r,a(e)),e.data=_.children),e=f(e,_,o,s,c,u)):v&&!_.children?l(_.el=i(``),r,d):(g||(g=!0,Ai(r,1)||bi()),n(null,_,r,d,o,s,Ci(r),c))}return e},h=(e,t,n,r,i,s)=>{let{slotScopeIds:c}=t;c&&(i=i?i.concat(c):c);let d=o(e),f=m(a(e),t,d,n,r,i,s);return f&&wi(f)&&f.data===`]`?a(t.anchor=f):(bi(),l(t.anchor=u(`]`),d,f),f)},g=(e,t,r,i,s,l)=>{if(Mi(e,t)||bi(),t.el=null,l){let t=_(e);for(;;){let n=a(e);if(n&&n!==t)c(n);else break}}let u=a(e),d=o(e);return c(e),n(null,t,d,u,r,i,Ci(d),s),r&&r.vnode.el===e&&(r.vnode.el=t.el,wo(r,t.el)),u},_=(e,t=`[`,n=`]`)=>{let r=0;for(;e;)if(e=a(e),e&&wi(e)&&(e.data===t&&r++,e.data===n)){if(r===0)return a(e);r--}return e},v=(e,t,n)=>{let r=t.parentNode;r&&r.replaceChild(e,t);let i=n;for(;i;)i.vnode.el===t&&(i.vnode.el=i.subTree.el=e),i=i.parent},y=e=>e.nodeType===1&&e.tagName===`TEMPLATE`;return[d,f]}var Ei=new Set([`src`,`srcset`,`href`,`poster`]);function Di(e,t,n){return Ei.has(t)?e.getAttribute(t)===(n==null?null:`${n}`):!1}var Oi=`data-allow-mismatch`,ki={0:`text`,1:`children`,2:`class`,3:`style`,4:`attribute`};function Ai(e,t){if(t===0||t===1)for(;e&&!e.hasAttribute(Oi);)e=e.parentElement;return ji(e&&e.getAttribute(Oi),t)}function ji(e,t){if(e==null)return!1;if(e===``)return!0;{let n=e.split(`,`);return t===0&&n.includes(`children`)?!0:n.includes(ki[t])}}function Mi(e,t){return Ai(e.parentElement,1)||Ni(e)||Pi(t)}function Ni(e){return e.nodeType===1&&ji(e.getAttribute(Oi),1)}function Pi({props:e}){let t=e&&e[Oi];return typeof t==`string`&&ji(t,1)}var Fi=he().requestIdleCallback||(e=>setTimeout(e,1)),Ii=he().cancelIdleCallback||(e=>clearTimeout(e)),Li=(e=1e4)=>t=>{let n=Fi(t,{timeout:e});return()=>Ii(n)};function Ri(e){let{top:t,left:n,bottom:r,right:i}=e.getBoundingClientRect(),{innerHeight:a,innerWidth:o}=window;return(t>0&&t<a||r>0&&r<a)&&(n>0&&n<o||i>0&&i<o)}var zi=e=>(t,n)=>{let r=new IntersectionObserver(e=>{for(let n of e)if(n.isIntersecting){r.disconnect(),t();break}},e),i=e=>{if(Ri(e))return t(),r.disconnect(),!1;if(getComputedStyle(e).display===`contents`){for(let t=0;t<e.children.length;t++)if(i(e.children[t])===!1)return!1}r.observe(e)};return n(e=>{if(e instanceof Element)return i(e)}),()=>r.disconnect()},Bi=e=>t=>{if(e){let n=matchMedia(e);if(n.matches)t();else return n.addEventListener(`change`,t,{once:!0}),()=>n.removeEventListener(`change`,t)}},Vi=(e=[])=>(t,n)=>{y(e)&&(e=[e]);let r=!1,i=e=>{r||(r=!0,a(),t(),e.target.dispatchEvent(new e.constructor(e.type,e)))},a=()=>{n(t=>{for(let n of e)t.removeEventListener(n,i)})};return n(t=>{for(let n of e)t.addEventListener(n,i,{once:!0})}),a};function Hi(e,t){if(wi(e)&&e.data===`[`){let n=1,r=e.nextSibling;for(;r;){if(r.nodeType===1){if(t(r)===!1)break}else if(wi(r)){if(r.data===`]`){if(--n===0)break}else r.data===`[`&&n++}r=r.nextSibling}}else t(e)}var Ui=e=>!!e.type.__asyncLoader;function Wi(e){v(e)&&(e={loader:e});let{loader:t,loadingComponent:n,errorComponent:r,delay:i=200,hydrate:a,timeout:o,suspensible:s=!0,onError:c}=e,l=null,u,d=0,f=()=>(d++,l=null,p()),p=()=>{let e;return l||(e=l=t().catch(e=>{if(e=e instanceof Error?e:Error(String(e)),c)return new Promise((t,n)=>{c(e,()=>t(f()),()=>n(e),d+1)});throw e}).then(t=>e!==l&&l?l:(t&&(t.__esModule||t[Symbol.toStringTag]===`Module`)&&(t=t.default),u=t,t)))};return L({name:`AsyncComponentWrapper`,__asyncLoader:p,__asyncHydrate(e,t,n){let r=e.isConnected,i=!1;(t.bu||=[]).push(()=>i=!0);let o=()=>{i||!e.parentNode||r&&!e.isConnected||n()},s=a?()=>{let n=a(o,t=>Hi(e,t));n&&(t.bum||=[]).push(n)}:o;u?s():p().then(()=>!t.isUnmounted&&s())},get __asyncResolved(){return u},setup(){let e=Us;if(pi(e),u)return()=>Gi(u,e);let t=t=>{l=null,Yn(t,e,13,!r,!0)};if(s&&e.suspense||Xs)return p().then(t=>()=>Gi(t,e)).catch(e=>(t(e),()=>r?K(r,{error:e}):null));let a=N(!1),c=N(),d=N(!!i),f,m;return Ve(()=>{f!=null&&clearTimeout(f),m!=null&&clearTimeout(m)}),i&&(m=setTimeout(()=>{e.isUnmounted||(d.value=!1)},i)),o!=null&&(f=setTimeout(()=>{if(!e.isUnmounted&&!a.value&&!c.value){let e=Error(`Async component timed out after ${o}ms.`);t(e),c.value=e}},o)),p().then(()=>{e.isUnmounted| Line truncated `)&&(ji(e,0)||xi(),e.textContent=t.children)}if(d){if(_||b||!o||f&48){let t=e.tagName.includes(`-`),i=e.namespaceURI.includes(`svg`)?`svg`:e.namespaceURI.includes(`MathML`)?`mathml`:void 0;for(let a in d)if(_&&(a.endsWith(`value`)||a===`indeterminate`)||s(a)&&!ne(a)||a[0]===`.`||t&&!ne(a)||u&&u.includes(a)){if(Oi(e,a,d[a]))continue;r(e,a,null,d[a],i,n)}}else if(d.onClick)r(e,`onClick`,null,d.onClick,void 0,n);else if(f&4&&un(d.style))for(let e in d.style)d.style[e]}let x;(x=d&&d.onVnodeBeforeMount)&&zs(x,n,t),h&&Tr(t,null,n,`beforeMount`),((x=d&&d.onVnodeMounted)||h||l)&&hs(()=>{x&&zs(x,n,t),l&&g.enter(e),h&&Tr(t,null,n,`mounted`)},i)}return e.nextSibling},m=(e,t,r,o,s,c,u,d)=>{u||=!!t.dynamicChildren;let p=t.children,m=p.length,h=t.type===z,g=!1;for(let t=0;t<m;t++){let _=u?p[t]:p[t]=Fs(p[t]),v=_.type===vs;h&&e&&Ti(e)&&e.data===`]`&&(d=e),e&&e!==d?(v&&!u&&t+1<m&&Fs(p[t+1]).type===vs&&(l(i(e.data.slice(_.children.length)),r,a(e)),e.data=_.children),e=f(e,_,o,s,c,u)):v&&!_.children?l(_.el=i(``),r,d):(g||(g=!0,ji(r,1)||xi()),n(null,_,r,d,o,s,wi(r),c))}return e},h=(e,t,n,r,i,s)=>{let{slotScopeIds:c}=t;c&&(i=i?i.concat(c):c);let d=o(e),f=m(a(e),t,d,n,r,i,s);return f&&Ti(f)&&f.data===`]`?a(t.anchor=f):(xi(),l(t.anchor=u(`]`),d,f),f)},g=(e,t,r,i,s,l)=>{if(Ni(e,t)||xi(),t.el=null,l){let t=_(e);for(;;){let n=a(e);if(n&&n!==t)c(n);else break}}let u=a(e),d=o(e);return c(e),n(null,t,d,u,r,i,wi(d),s),r&&r.vnode.el===e&&(r.vnode.el=t.el,To(r,t.el)),u},_=(e,t=`[`,n=`]`)=>{let r=0;for(;e;)if(e=a(e),e&&Ti(e)&&(e.data===t&&r++,e.data===n)){if(r===0)return a(e);r--}return e},v=(e,t,n)=>{let r=t.parentNode;r&&r.replaceChild(e,t);let i=n;for(;i;)i.vnode.el===t&&(i.vnode.el=i.subTree.el=e),i=i.parent},y=e=>e.nodeType===1&&e.tagName===`TEMPLATE`;return[d,f]}var Di=new Set([`src`,`srcset`,`href`,`poster`]);function Oi(e,t,n){return Di.has(t)?e.getAttribute(t)===(n==null?null:`${n}`):!1}var ki=`data-allow-mismatch`,Ai={0:`text`,1:`children`,2:`class`,3:`style`,4:`attribute`};function ji(e,t){if(t===0||t===1)for(;e&&!e.hasAttribute(ki);)e=e.parentElement;return Mi(e&&e.getAttribute(ki),t)}function Mi(e,t){if(e==null)return!1;if(e===``)return!0;{let n=e.split(`,`);return t===0&&n.includes(`children`)?!0:n.includes(Ai[t])}}function Ni(e,t){return ji(e.parentElement,1)||Pi(e)||Fi(t)}function Pi(e){return e.nodeType===1&&Mi(e.getAttribute(ki),1)}function Fi({props:e}){let t=e&&e[ki];return typeof t==`string`&&Mi(t,1)}var Ii=ge().requestIdleCallback||(e=>setTimeout(e,1)),Li=ge().cancelIdleCallback||(e=>clearTimeout(e)),Ri=(e=1e4)=>t=>{let n=Ii(t,{timeout:e});return()=>Li(n)};function zi(e){let{top:t,left:n,bottom:r,right:i}=e.getBoundingClientRect(),{innerHeight:a,innerWidth:o}=window;return(t>0&&t<a||r>0&&r<a)&&(n>0&&n<o||i>0&&i<o)}var Bi=e=>(t,n)=>{let r=new IntersectionObserver(e=>{for(let n of e)if(n.isIntersecting){r.disconnect(),t();break}},e),i=e=>{if(zi(e))return t(),r.disconnect(),!1;if(getComputedStyle(e).display===`contents`){for(let t=0;t<e.children.length;t++)if(i(e.children[t])===!1)return!1}r.observe(e)};return n(e=>{if(e instanceof Element)return i(e)}),()=>r.disconnect()},Vi=e=>t=>{if(e){let n=matchMedia(e);if(n.matches)t();else return n.addEventListener(`change`,t,{once:!0}),()=>n.removeEventListener(`change`,t)}},Hi=(e=[])=>(t,n)=>{y(e)&&(e=[e]);let r=!1,i=e=>{r||(r=!0,a(),t(),e.target.dispatchEvent(new e.constructor(e.type,e)))},a=()=>{n(t=>{for(let n of e)t.removeEventListener(n,i)})};return n(t=>{for(let n of e)t.addEventListener(n,i,{once:!0})}),a};function Ui(e,t){if(Ti(e)&&e.data===`[`){let n=1,r=e.nextSibling;for(;r;){if(r.nodeType===1){if(t(r)===!1)break}else if(Ti(r)){if(r.data===`]`){if(--n===0)break}else r.data===`[`&&n++}r=r.nextSibling}}else t(e)}var Wi=e=>!!e.type.__asyncLoader;function Gi(e){v(e)&&(e={loader:e});let{loader:t,loadingComponent:n,errorComponent:r,delay:i=200,hydrate:a,timeout:o,suspensible:s=!0,onError:c}=e,l=null,u,d=0,f=()=>(d++,l=null,p()),p=()=>{let e;return l||(e=l=t().catch(e=>{if(e=e instanceof Error?e:Error(String(e)),c)return new Promise((t,n)=>{c(e,()=>t(f()),()=>n(e),d+1)});throw e}).then(t=>e!==l&&l?l:(t&&(t.__esModule||t[Symbol.toStringTag]===`Module`)&&(t=t.default),u=t,t)))};return I({name:`AsyncComponentWrapper`,__asyncLoader:p,__asyncHydrate(e,t,n){let r=e.isConnected,i=!1;(t.bu||=[]).push(()=>i=!0);let o=()=>{i||!e.parentNode||r&&!e.isConnected||n()},s=a?()=>{let n=a(o,t=>Ui(e,t));n&&(t.bum||=[]).push(n)}:o;u?s():p().then(()=>!t.isUnmounted&&s())},get __asyncResolved(){return u},setup(){let e=Ws;if(mi(e),u)return()=>Ki(u,e);let t=t=>{l=null,Xn(t,e,13,!r,!0)};if(s&&e.suspense||Zs)return p().then(t=>()=>Ki(t,e)).catch(e=>(t(e),()=>r?G(r,{error:e}):null));let a=M(!1),c=M(),d=M(!!i),f,m;return He(()=>{f!=null&&clearTimeout(f),m!=null&&clearTimeout(m)}),i&&(m=setTimeout(()=>{e.isUnmounted||(d.value=!1)},i)),o!=null&&(f=setTimeout(()=>{if(!e.isUnmounted&&!a.value&&!c.value){let e=Error(`Async component timed out after ${o}ms.`);t(e),c.value=e}},o)),p().then(()=>{e.isUnmounted| Line truncated
`))),e[cu]=au(i);let a=r||i.props&&i.props.type===`number`;xl(e,t?`change`:`input`,t=>{t.target.composing||e[cu](uu(e.value,n,a))}),(n||a)&&xl(e,`change`,()=>{e.value=uu(e.value,n,a)}),t||(xl(e,`compositionstart`,ou),xl(e,`compositionend`,su),xl(e,`change`,su))},mounted(e,{value:t,modifiers:{trim:n,number:r}}){let i=t??``,a=e[lu];delete e[lu],a!==void 0&&(e.type===`text`||e.type===`textarea`)&&e.value!==a?e[cu](uu(e.value,n,r)):e.value=i},beforeUpdate(e,{value:t,oldValue:n,modifiers:{lazy:r,trim:i,number:a}},o){if(e[cu]=au(o),e.composing)return;let s=(a||e.type===`number`)&&!/^0\d/.test(e.value)?fe(e.value):e.value,c=t??``;if(s===c)return;let l=e.getRootNode();(l instanceof Document||l instanceof ShadowRoot)&&l.activeElement===e&&e.type!==`range`&&(r&&t===n||i&&e.value.trim()===c)||(e.value=c)}},du={deep:!0,created(e,t,n){e[cu]=au(n),xl(e,`change`,()=>{let t=e._modelValue,n=_u(e),r=e.checked,i=e[cu];if(p(t)){let e=je(t,n),a=e!==-1;if(r&&!a)i(t.concat(n));else if(!r&&a){let n=[...t];n.splice(e,1),i(n)}}else if(h(t)){let e=new Set(t);r?e.add(n):e.delete(n),i(e)}else i(vu(e,r))})},mounted:fu,beforeUpdate(e,t,n){e[cu]=au(n),fu(e,t,n)}};function fu(e,{value:t,oldValue:n},r){e._modelValue=t;let i;if(p(t))i=je(t,r.props.value)>-1;else if(h(t))i=t.has(r.props.value);else{if(t===n)return;i=Ae(t,vu(e,!0))}e.checked!==i&&(e.checked=i)}var pu={created(e,{value:t},n){e.checked=Ae(t,n.props.value),e[cu]=au(n),xl(e,`change`,()=>{e[cu](_u(e))})},beforeUpdate(e,{value:t,oldValue:n},r){e[cu]=au(r),t!==n&&(e.checked=Ae(t,r.props.value))}},mu={deep:!0,created(e,{value:t,modifiers:{number:n}},r){e._modelValue=t,xl(e,`change`,()=>{let t=Array.prototype.filter.call(e.options,e=>e.selected).map(e=>n?fe(_u(e)):_u(e)),r=e.multiple,i=r?h(e._modelValue)?new Set(t):t:t[0],a=e._pendingValue=[r,r?p(i)?t.slice():t:i];try{e[cu](i)}finally{ir(()=>{e._pendingValue===a&&(e._pendingValue=void 0)})}}),e[cu]=au(r)},mounted(e,{value:t,modifiers:{number:n}}){gu(e,t,n)},beforeUpdate(e,{value:t},n){e._modelValue=t,e[cu]=au(n)},updated(e,{value:t,modifiers:{number:n}}){let r=e._pendingValue;e._pendingValue=void 0,r&&r[0]===e.multiple&&hu(t,r[1],r[0])||gu(e,t,n)}};function hu(e,t,n){if(!n||p(e))return Ae(e,t);if(h(e)){if(e.size!==t.length)return!1;for(let n of t)if(!e.has(n))return!1;return!0}return!1}function gu(e,t,n=!1){let r=e.multiple,i=p(t);if(!r||i||h(t)){for(let a=0,o=e.options.length;a<o;a++){let o=e.options[a],s=_u(o);if(r){if(i){let e=typeof s;o.selected=e===`string`||e===`number`?t.some(e=>String(e)===String(s)):je(t,s)>-1}else o.selected=t.has(s)||n&&typeof s==`string`&&t.has(fe(s))}else if(Ae(_u(o),t)){e.selectedIndex!==a&&(e.selectedIndex=a);return}}!r&&e.selectedIndex!==-1&&(e.selectedIndex=-1)}}function _u(e){return`_value`in e?e._value:e.value}function vu(e,t){let n=t?`_trueValue`:`_falseValue`;return n in e?e[n]:t}var yu={created(e,t,n){xu(e,t,n,null,`created`)},mounted(e,t,n){xu(e,t,n,null,`mounted`)},beforeUpdate(e,t,n,r){xu(e,t,n,r,`beforeUpdate`)},updated(e,t,n,r){xu(e,t,n,r,`updated`)}};function bu(e,t){switch(e){case`SELECT`:return mu;case`TEXTAREA`:return Y;default:switch(t){case`checkbox`:return du;case`radio`:return pu;default:return Y}}}function xu(e,t,n,r,i){let a=bu(e.tagName,n.props&&n.props.type)[i];a&&a(e,t,n,r)}function Su(){Y.getSSRProps=({value:e})=>({value:e}),pu.getSSRProps=({value:e},t)=>{if(t.props&&Ae(t.props.value,e))return{checked:!0}},du.getSSRProps=({value:e},t)=>{if(p(e)){if(t.props&&je(e,t.props.value)>-1)return{checked:!0}}else if(h(e)){if(t.props&&e.has(t.props.value))return{checked:!0}}else if(e)return{checked:!0}},yu.getSSRProps=(e,t)=>{if(typeof t.type!=`string`)return;let n=bu(t.type.toUpperCase(),t.props&&t.props.type);if(n.getSSRProps)return n.getSSRProps(e,t)}}var Cu=[`ctrl`,`shift`,`alt`,`meta`],wu={stop:e=>e.stopPropagation(),prevent:e=>e.preventDefault(),self:e=>e.target!==e.currentTarget,ctrl:e=>!e.ctrlKey,shift:e=>!e.shiftKey,alt:e=>!e.altKey,meta:e=>!e.metaKey,left:e=>`button`in e&&e.button!==0,middle:e=>`button`in e&&e.button!==1,right:e=>`button`in e&&e.button!==2,exact:(e,t)=>Cu.some(n=>e[`${n}Key`]&&!t.includes(n))},Tu=(e,t)=>{if(!e)return e;let n=e._withMods||={},r=t.join(`.`);return n[r]||(n[r]=((n,...r)=>{for(let e=0;e<t.length;e++){let r=wu[t[e]];if(r&&r(n,t))return}return e(n,...r)}))},Eu={esc:`escape`,space:` `,up:`arrow-up`,left:`arrow-left`,right:`arrow-right`,down:`arrow-down`,delete:`backspace`},Du=(e,t)=>{let n=e._withKeys||={},r=t.join(`.`),i=n[r];if(i)return i;let a=t.some(e=>e===`left`||e===`right`);return n[r]=(n=>{if(!(`key`in n))return a?e(n):void 0;let r=se(n.key);if(t.some(e=>e===r||Eu[e]===r))return e(n)})},Ou=l({patchProp:Nl},kc),ku,Au=!1;function ju(){return ku||=Uo(Ou)}function Mu(){return ku=Au?ku:Wo(Ou),Au=!0,ku}var Nu=((...e)=>{ju().render(...e)}),Pu=((...e)=>{Mu().hydrate(...e)}),Fu=((...e)=>{let t=ju().createApp(...e),{mount:n}=t;return t.mount=e=>{let r=Ru(e);if(!r)return;let i=t._component;v(i)||i.render||i.template||(i.template=r.innerHTML),r.nodeType=== Line truncated `))),e[lu]=ou(i);let a=r||i.props&&i.props.type===`number`;Sl(e,t?`change`:`input`,t=>{t.target.composing||e[lu](du(e.value,n,a))}),(n||a)&&Sl(e,`change`,()=>{e.value=du(e.value,n,a)}),t||(Sl(e,`compositionstart`,su),Sl(e,`compositionend`,cu),Sl(e,`change`,cu))},mounted(e,{value:t,modifiers:{trim:n,number:r}}){let i=t??``,a=e[uu];delete e[uu],a!==void 0&&(e.type===`text`||e.type===`textarea`)&&e.value!==a?e[lu](du(e.value,n,r)):e.value=i},beforeUpdate(e,{value:t,oldValue:n,modifiers:{lazy:r,trim:i,number:a}},o){if(e[lu]=ou(o),e.composing)return;let s=(a||e.type===`number`)&&!/^0\d/.test(e.value)?pe(e.value):e.value,c=t??``;if(s===c)return;let l=e.getRootNode();(l instanceof Document||l instanceof ShadowRoot)&&l.activeElement===e&&e.type!==`range`&&(r&&t===n||i&&e.value.trim()===c)||(e.value=c)}},fu={deep:!0,created(e,t,n){e[lu]=ou(n),Sl(e,`change`,()=>{let t=e._modelValue,n=vu(e),r=e.checked,i=e[lu];if(p(t)){let e=Me(t,n),a=e!==-1;if(r&&!a)i(t.concat(n));else if(!r&&a){let n=[...t];n.splice(e,1),i(n)}}else if(h(t)){let e=new Set(t);r?e.add(n):e.delete(n),i(e)}else i(yu(e,r))})},mounted:pu,beforeUpdate(e,t,n){e[lu]=ou(n),pu(e,t,n)}};function pu(e,{value:t,oldValue:n},r){e._modelValue=t;let i;if(p(t))i=Me(t,r.props.value)>-1;else if(h(t))i=t.has(r.props.value);else{if(t===n)return;i=je(t,yu(e,!0))}e.checked!==i&&(e.checked=i)}var mu={created(e,{value:t},n){e.checked=je(t,n.props.value),e[lu]=ou(n),Sl(e,`change`,()=>{e[lu](vu(e))})},beforeUpdate(e,{value:t,oldValue:n},r){e[lu]=ou(r),t!==n&&(e.checked=je(t,r.props.value))}},hu={deep:!0,created(e,{value:t,modifiers:{number:n}},r){e._modelValue=t,Sl(e,`change`,()=>{let t=Array.prototype.filter.call(e.options,e=>e.selected).map(e=>n?pe(vu(e)):vu(e)),r=e.multiple,i=r?h(e._modelValue)?new Set(t):t:t[0],a=e._pendingValue=[r,r?p(i)?t.slice():t:i];try{e[lu](i)}finally{ar(()=>{e._pendingValue===a&&(e._pendingValue=void 0)})}}),e[lu]=ou(r)},mounted(e,{value:t,modifiers:{number:n}}){_u(e,t,n)},beforeUpdate(e,{value:t},n){e._modelValue=t,e[lu]=ou(n)},updated(e,{value:t,modifiers:{number:n}}){let r=e._pendingValue;e._pendingValue=void 0,r&&r[0]===e.multiple&&gu(t,r[1],r[0])||_u(e,t,n)}};function gu(e,t,n){if(!n||p(e))return je(e,t);if(h(e)){if(e.size!==t.length)return!1;for(let n of t)if(!e.has(n))return!1;return!0}return!1}function _u(e,t,n=!1){let r=e.multiple,i=p(t);if(!r||i||h(t)){for(let a=0,o=e.options.length;a<o;a++){let o=e.options[a],s=vu(o);if(r){if(i){let e=typeof s;o.selected=e===`string`||e===`number`?t.some(e=>String(e)===String(s)):Me(t,s)>-1}else o.selected=t.has(s)||n&&typeof s==`string`&&t.has(pe(s))}else if(je(vu(o),t)){e.selectedIndex!==a&&(e.selectedIndex=a);return}}!r&&e.selectedIndex!==-1&&(e.selectedIndex=-1)}}function vu(e){return`_value`in e?e._value:e.value}function yu(e,t){let n=t?`_trueValue`:`_falseValue`;return n in e?e[n]:t}var bu={created(e,t,n){Su(e,t,n,null,`created`)},mounted(e,t,n){Su(e,t,n,null,`mounted`)},beforeUpdate(e,t,n,r){Su(e,t,n,r,`beforeUpdate`)},updated(e,t,n,r){Su(e,t,n,r,`updated`)}};function xu(e,t){switch(e){case`SELECT`:return hu;case`TEXTAREA`:return J;default:switch(t){case`checkbox`:return fu;case`radio`:return mu;default:return J}}}function Su(e,t,n,r,i){let a=xu(e.tagName,n.props&&n.props.type)[i];a&&a(e,t,n,r)}function Cu(){J.getSSRProps=({value:e})=>({value:e}),mu.getSSRProps=({value:e},t)=>{if(t.props&&je(t.props.value,e))return{checked:!0}},fu.getSSRProps=({value:e},t)=>{if(p(e)){if(t.props&&Me(e,t.props.value)>-1)return{checked:!0}}else if(h(e)){if(t.props&&e.has(t.props.value))return{checked:!0}}else if(e)return{checked:!0}},bu.getSSRProps=(e,t)=>{if(typeof t.type!=`string`)return;let n=xu(t.type.toUpperCase(),t.props&&t.props.type);if(n.getSSRProps)return n.getSSRProps(e,t)}}var wu=[`ctrl`,`shift`,`alt`,`meta`],Tu={stop:e=>e.stopPropagation(),prevent:e=>e.preventDefault(),self:e=>e.target!==e.currentTarget,ctrl:e=>!e.ctrlKey,shift:e=>!e.shiftKey,alt:e=>!e.altKey,meta:e=>!e.metaKey,left:e=>`button`in e&&e.button!==0,middle:e=>`button`in e&&e.button!==1,right:e=>`button`in e&&e.button!==2,exact:(e,t)=>wu.some(n=>e[`${n}Key`]&&!t.includes(n))},Eu=(e,t)=>{if(!e)return e;let n=e._withMods||={},r=t.join(`.`);return n[r]||(n[r]=((n,...r)=>{for(let e=0;e<t.length;e++){let r=Tu[t[e]];if(r&&r(n,t))return}return e(n,...r)}))},Du={esc:`escape`,space:` `,up:`arrow-up`,left:`arrow-left`,right:`arrow-right`,down:`arrow-down`,delete:`backspace`},Ou=(e,t)=>{let n=e._withKeys||={},r=t.join(`.`),i=n[r];if(i)return i;let a=t.some(e=>e===`left`||e===`right`);return n[r]=(n=>{if(!(`key`in n))return a?e(n):void 0;let r=se(n.key);if(t.some(e=>e===r||Du[e]===r))return e(n)})},ku=l({patchProp:Pl},Ac),Au,ju=!1;function Mu(){return Au||=Wo(ku)}function Nu(){return Au=ju?Au:Go(ku),ju=!0,Au}var Pu=((...e)=>{Mu().render(...e)}),Fu=((...e)=>{Nu().hydrate(...e)}),Iu=((...e)=>{let t=Mu().createApp(...e),{mount:n}=t;return t.mount=e=>{let r=zu(e);if(!r)return;let i=t._component;v(i)||i.render||i.template||(i.template=r.innerHTML),r.nodeType=== Line truncated
`,t.selectionStart-1)+1,o=t.selectionEnd,s=n.modelValue.slice(a,o).split(` `,t.selectionStart-1)+1,o=t.selectionEnd,s=n.modelValue.slice(a,o).split(`
`).map(t=>e+t).join(` `).map(t=>e+t).join(`
`);r(`update:modelValue`,n.modelValue.slice(0,a)+s+n.modelValue.slice(o)),requestAnimationFrame(()=>t.focus())}function f(e,t){c.value=!1;let a=(t?.alt||t?.name||``).replace(/[[\]]/g,``),o=i.value,s=o.selectionStart,l=`![${a}](${e})`;r(`update:modelValue`,n.modelValue.slice(0,s)+l+n.modelValue.slice(o.selectionEnd)),requestAnimationFrame(()=>{o.focus(),o.setSelectionRange(s+l.length,s+l.length)})}async function p(e){if(a.value=e,e===`preview`){s.value=!0;try{o.value=(await Z.post(`${X.base}/markdown`,{text:n.modelValue})).html}finally{s.value=!1}}}return(t,n)=>(H(),U(`div`,null,[G(`div`,{class:`mb-2 flex flex-wrap items-center gap-1`,role:`toolbar`,"aria-label":P(Q)(`Formatting`)},[G(`button`,{type:`button`,class:`m-btn m-btn-secondary !px-2 !py-1 font-bold`,disabled:a.value===`preview`,title:P(Q)(`Bold`),onClick:n[0]||=e=>u(`**`,`**`,P(Q)(`bold`))},`B`,8,Wd),G(`button`,{type:`button`,class:`m-btn m-btn-secondary !px-2 !py-1 italic`,disabled:a.value===`preview`,title:P(Q)(`Italic`),onClick:n[1]||=e=>u(`*`,`*`,P(Q)(`italic`))},`I`,8,Gd),G(`button`,{type:`button`,class:`m-btn m-btn-secondary !px-2 !py-1`,disabled:a.value===`preview`,title:P(Q)(`Heading`),onClick:n[2]||=e=>d(`## `)},`H`,8,Kd),G(`button`,{type:`button`,class:`m-btn m-btn-secondary !px-2 !py-1`,disabled:a.value===`preview`,title:P(Q)(`List`),onClick:n[3]||=e=>d(`- `)},`•`,8,qd),G(`button`,{type:`button`,class:`m-btn m-btn-secondary !px-2 !py-1`,disabled:a.value===`preview`,title:P(Q)(`Quote`),onClick:n[4]||=e=>d(`> `)},`”`,8,Jd),G(`button`,{type:`button`,class:`m-btn m-btn-secondary !px-2 !py-1`,disabled:a.value===`preview`,title:P(Q)(`Link`),onClick:n[5]||=e=>u(`[`,`](https://)`,P(Q)(`text`))},`🔗`,8,Yd),P(l)?(H(),U(`button`,{key:0,type:`button`,class:`m-btn m-btn-secondary !px-2 !py-1`,disabled:a.value===`preview`,onClick:n[6]||=e=>c.value=!0},k(P(Q)(`Photo`)),9,Xd)):J(``,!0),G(`span`,Zd,[G(`button`,{type:`button`,class:O([`m-btn !px-3 !py-1`,a.value===`write`?`m-btn-primary`:`m-btn-secondary`]),onClick:n[7]||=e=>p(`write`)},k(P(Q)(`Write`)),3),G(`button`,{type:`button`,class:O([`m-btn !px-3 !py-1`,a.value===`preview`?`m-btn-primary`:`m-btn-secondary`]),onClick:n[8]||=e=>p(`preview`)},k(P(Q)(`Preview`)),3)])],8,Ud),I(G(`textarea`,{id:e.id,ref_key:`area`,ref:i,value:e.modelValue,rows:e.rows??14,required:e.required,maxlength:e.maxlength,class:`m-input font-mono`,onInput:n[9]||=e=>r(`update:modelValue`,e.target.value)},null,40,Qd),[[$c,a.value===`write`]]),a.value===`preview`?(H(),U(`div`,$d,[s.value?(H(),U(`p`,ef,k(P(Q)(`Loading…`)),1)):(H(),U(`div`,{key:1,class:`m-prose`,innerHTML:o.value},null,8,tf))])):J(``,!0),c.value?(H(),W(Hd,{key:1,onPick:f,onClose:n[10]||=e=>c.value=!1})):J(``,!0)]))}}),rf={class:`m-card mt-6 max-w-3xl p-5`},af={class:`font-display text-lg font-bold`},of={key:0,class:`mt-2 text-sm text-muted`},sf={key:1,class:`mt-2 text-sm text-muted`},cf={key:2,class:`mt-3 divide-y divide-line`},lf={class:`flex flex-wrap items-center justify-between gap-2`},uf=[`aria-expanded`,`onClick`],df={class:`font-semibold`},ff={key:0,class:`text-muted`},pf={key:1,class:`m-badge ml-2`},mf={class:`block text-xs text-muted`},hf=[`onClick`],gf={key:0,class:`mt-2 space-y-2 text-sm`},_f={class:`text-xs font-semibold uppercase tracking-wide text-muted`},vf={class:`whitespace-pre-wrap break-words`},yf=L({__name:`RevisionsPanel`,props:{type:{},id:{}},setup(e){let t=e,n=N([]),r=N(!1),i=N(null),a=N(!0),o=`${X.base}/revisions/${t.type}/${t.id}`;ia(async()=>{try{let e=await Z.get(o);n.value=e.revisions,r.value=e.can_restore}finally{a.value=!1}});async function s(e){window.confirm(Q(`Put this version back? The text now is kept in the history.`))&&(await Z.post(`${o}/${e.id}/restore`),B1(Q(`The earlier version is back.`)),await W1())}let c=e=>new Date(e).toLocaleString(X.locale||void 0);return(e,t)=>(H(),U(`section`,rf,[G(`h2`,af,k(P(Q)(`History`)),1),a.value?(H(),U(`p`,of,k(P(Q)(`Loading…`)),1)):n.value.length?(H(),U(`ul`,cf,[(H(!0),U(B,null,R(n.value,e=>(H(),U(`li`,{key:e.id,class:`py-3`},[G(`div`,lf,[G(`button`,{type:`button`,class:`text-left text-sm`,"aria-expanded":i.value===e.id,onClick:t=>i.value=i.value===e.id?null:e.id},[G(`span`,df,k(c(e.created_at)),1),e.user?(H(),U(`span`,ff,` · `+k(e.user),1)):J(``,!0),e.current?(H(),U(`span`,pf,k(P(Q)(`Now`)),1)):J(``,!0),G(`span`,mf,k(e.changed.join(`, `)),1)],8,uf),r.value&&!e.current?(H(),U(`button`,{key:0,type:`button`,class:`m-btn m-btn-secondary`,onClick:t=>s(e)},k(P(Q)(`Put back`)),9,hf)):J(``,!0)]),i.value===e.id?(H(),U(`dl`,gf,[(H(!0),U(B,null,R(e.values,(e,t)=>(H(),U(`div`,{key:t},[G(`dt`,_f,k(t),1),G(`dd`,vf,k(e),1)]))),128))])):J(``,!0)]))),128))])):(H(),U(`p`,sf,k(P(Q)(`Nothing here yet.`)),1))]))}}),bf={class:`mb-6 flex items-center justify-between gap-3`},xf={class:`font-display text-2xl font-bold`},Sf={for:`title`,class:`m-label`},Cf={key:0,class:`m-error`},wf={class:`grid gap-5 sm:grid-cols-2`},Tf={for:`slug`,class:`m-label`},Ef={key:0,class:`m-error`},Df={for:`category`,class:`m-label Line truncated `);r(`update:modelValue`,n.modelValue.slice(0,a)+s+n.modelValue.slice(o)),requestAnimationFrame(()=>t.focus())}function f(e,t){c.value=!1;let a=(t?.alt||t?.name||``).replace(/[[\]]/g,``),o=i.value,s=o.selectionStart,l=`![${a}](${e})`;r(`update:modelValue`,n.modelValue.slice(0,s)+l+n.modelValue.slice(o.selectionEnd)),requestAnimationFrame(()=>{o.focus(),o.setSelectionRange(s+l.length,s+l.length)})}async function p(e){if(a.value=e,e===`preview`){s.value=!0;try{o.value=(await X.post(`${Y.base}/markdown`,{text:n.modelValue})).html}finally{s.value=!1}}}return(t,n)=>(V(),H(`div`,null,[W(`div`,{class:`mb-2 flex flex-wrap items-center gap-1`,role:`toolbar`,"aria-label":N(Z)(`Formatting`)},[W(`button`,{type:`button`,class:`m-btn m-btn-secondary !px-2 !py-1 font-bold`,disabled:a.value===`preview`,title:N(Z)(`Bold`),onClick:n[0]||=e=>u(`**`,`**`,N(Z)(`bold`))},`B`,8,Gd),W(`button`,{type:`button`,class:`m-btn m-btn-secondary !px-2 !py-1 italic`,disabled:a.value===`preview`,title:N(Z)(`Italic`),onClick:n[1]||=e=>u(`*`,`*`,N(Z)(`italic`))},`I`,8,Kd),W(`button`,{type:`button`,class:`m-btn m-btn-secondary !px-2 !py-1`,disabled:a.value===`preview`,title:N(Z)(`Heading`),onClick:n[2]||=e=>d(`## `)},`H`,8,qd),W(`button`,{type:`button`,class:`m-btn m-btn-secondary !px-2 !py-1`,disabled:a.value===`preview`,title:N(Z)(`List`),onClick:n[3]||=e=>d(`- `)},`•`,8,Jd),W(`button`,{type:`button`,class:`m-btn m-btn-secondary !px-2 !py-1`,disabled:a.value===`preview`,title:N(Z)(`Quote`),onClick:n[4]||=e=>d(`> `)},`”`,8,Yd),W(`button`,{type:`button`,class:`m-btn m-btn-secondary !px-2 !py-1`,disabled:a.value===`preview`,title:N(Z)(`Link`),onClick:n[5]||=e=>u(`[`,`](https://)`,N(Z)(`text`))},`🔗`,8,Xd),N(l)?(V(),H(`button`,{key:0,type:`button`,class:`m-btn m-btn-secondary !px-2 !py-1`,disabled:a.value===`preview`,onClick:n[6]||=e=>c.value=!0},O(N(Z)(`Photo`)),9,Zd)):q(``,!0),W(`span`,Qd,[W(`button`,{type:`button`,class:D([`m-btn !px-3 !py-1`,a.value===`write`?`m-btn-primary`:`m-btn-secondary`]),onClick:n[7]||=e=>p(`write`)},O(N(Z)(`Write`)),3),W(`button`,{type:`button`,class:D([`m-btn !px-3 !py-1`,a.value===`preview`?`m-btn-primary`:`m-btn-secondary`]),onClick:n[8]||=e=>p(`preview`)},O(N(Z)(`Preview`)),3)])],8,Wd),F(W(`textarea`,{id:e.id,ref_key:`area`,ref:i,value:e.modelValue,rows:e.rows??14,required:e.required,maxlength:e.maxlength,class:`m-input font-mono`,onInput:n[9]||=e=>r(`update:modelValue`,e.target.value)},null,40,$d),[[el,a.value===`write`]]),a.value===`preview`?(V(),H(`div`,ef,[s.value?(V(),H(`p`,tf,O(N(Z)(`Loading…`)),1)):(V(),H(`div`,{key:1,class:`m-prose`,innerHTML:o.value},null,8,nf))])):q(``,!0),c.value?(V(),U(Ud,{key:1,onPick:f,onClose:n[10]||=e=>c.value=!1})):q(``,!0)]))}}),af={class:`m-card mt-6 max-w-3xl p-5`},of={class:`font-display text-lg font-bold`},sf={key:0,class:`mt-2 text-sm text-muted`},cf={key:1,class:`mt-2 text-sm text-muted`},lf={key:2,class:`mt-3 divide-y divide-line`},uf={class:`flex flex-wrap items-center justify-between gap-2`},df=[`aria-expanded`,`onClick`],ff={class:`font-semibold`},pf={key:0,class:`text-muted`},mf={key:1,class:`m-badge ml-2`},hf={class:`block text-xs text-muted`},gf=[`onClick`],_f={key:0,class:`mt-2 space-y-2 text-sm`},vf={class:`text-xs font-semibold uppercase tracking-wide text-muted`},yf={class:`whitespace-pre-wrap break-words`},bf=I({__name:`RevisionsPanel`,props:{type:{},id:{}},setup(e){let t=e,n=M([]),r=M(!1),i=M(null),a=M(!0),o=`${Y.base}/revisions/${t.type}/${t.id}`;aa(async()=>{try{let e=await X.get(o);n.value=e.revisions,r.value=e.can_restore}finally{a.value=!1}});async function s(e){window.confirm(Z(`Put this version back? The text now is kept in the history.`))&&(await X.post(`${o}/${e.id}/restore`),$(Z(`The earlier version is back.`)),await y0())}let c=e=>new Date(e).toLocaleString(Y.locale||void 0);return(e,t)=>(V(),H(`section`,af,[W(`h2`,of,O(N(Z)(`History`)),1),a.value?(V(),H(`p`,sf,O(N(Z)(`Loading…`)),1)):n.value.length?(V(),H(`ul`,lf,[(V(!0),H(z,null,L(n.value,e=>(V(),H(`li`,{key:e.id,class:`py-3`},[W(`div`,uf,[W(`button`,{type:`button`,class:`text-left text-sm`,"aria-expanded":i.value===e.id,onClick:t=>i.value=i.value===e.id?null:e.id},[W(`span`,ff,O(c(e.created_at)),1),e.user?(V(),H(`span`,pf,` · `+O(e.user),1)):q(``,!0),e.current?(V(),H(`span`,mf,O(N(Z)(`Now`)),1)):q(``,!0),W(`span`,hf,O(e.changed.join(`, `)),1)],8,df),r.value&&!e.current?(V(),H(`button`,{key:0,type:`button`,class:`m-btn m-btn-secondary`,onClick:t=>s(e)},O(N(Z)(`Put back`)),9,gf)):q(``,!0)]),i.value===e.id?(V(),H(`dl`,_f,[(V(!0),H(z,null,L(e.values,(e,t)=>(V(),H(`div`,{key:t},[W(`dt`,vf,O(t),1),W(`dd`,yf,O(e),1)]))),128))])):q(``,!0)]))),128))])):(V(),H(`p`,cf,O(N(Z)(`Nothing here yet.`)),1))]))}}),xf={class:`mb-6 flex items-center justify-between gap-3`},Sf={class:`font-display text-2xl font-bold`},Cf={for:`title`,class:`m-label`},wf={key:0,class:`m-error`},Tf={class:`grid gap-5 sm:grid-cols-2`},Ef={for:`slug`,class:`m-label`},Df={key:0,class:`m-error`},Of={for:`category`,class:`m-label` Line truncated
+21 -1
View File
@@ -116,5 +116,25 @@
"Finished or skipped the tour": "Rondleiding afgerond of overgeslagen", "Finished or skipped the tour": "Rondleiding afgerond of overgeslagen",
"Write and put news on your website": "Schrijf nieuws en zet het op je website", "Write and put news on your website": "Schrijf nieuws en zet het op je website",
"Change the texts and photos of your pages": "Pas de teksten en foto's van je pagina's aan", "Change the texts and photos of your pages": "Pas de teksten en foto's van je pagina's aan",
"Your photos and files": "Je foto's en bestanden" "Your photos and files": "Je foto's en bestanden",
"Settings": "Instellingen",
"Switch parts and features on or off and change settings": "Onderdelen en functies aan- of uitzetten en instellingen wijzigen",
"Change keys, passwords and addresses of integrations": "Sleutels, wachtwoorden en adressen van koppelingen wijzigen",
"Changed the settings": "Instellingen gewijzigd",
"Refreshed the settings": "Instellingen ververst",
"Opened the settings": "Instellingen geopend",
"This setting does not exist or you may not change it.": "Deze instelling bestaat niet of je mag hem niet wijzigen.",
"This value is not valid.": "Deze waarde is niet geldig.",
"Type your own password to change this.": "Typ je eigen wachtwoord om dit te wijzigen.",
"Parts of the manager": "Onderdelen van de manager",
"IriksIT API": "IriksIT API",
"Login": "Inloggen",
"Site": "Site",
"Disk for new media files": "Schijf voor nieuwe mediabestanden",
"IriksIT API: address": "IriksIT API: adres",
"IriksIT API: account": "IriksIT API: account",
"IriksIT API: password": "IriksIT API: wachtwoord",
"Turnstile: site key": "Turnstile: sitesleutel",
"Turnstile: secret key": "Turnstile: geheime sleutel",
"With its version, for example https://api.iriks-it.nl/v1": "Met de versie erbij, bijvoorbeeld https://api.iriks-it.nl/v1"
} }
+11 -1
View File
@@ -20,7 +20,17 @@ trait HasManagerAccess
/** @return BelongsToMany<Group, $this> */ /** @return BelongsToMany<Group, $this> */
public function managerGroups(): BelongsToMany public function managerGroups(): BelongsToMany
{ {
return $this->belongsToMany(Group::class, Names::table('group_user'), 'user_id', 'group_id'); return $this->belongsToMany(Group::class, Names::table('group_user'), 'user_id', 'group_id')->withPivot('is_primary');
}
/**
* The group this account is filed under: a label and a start screen, nothing more. What the account may do is
* always the sum of all its groups, the primary one included.
*/
public function managerPrimaryGroup(): ?Group
{
// A group that was attached without a choice (by the site itself) makes the first one the primary one.
return $this->managerGroups->first(fn (Group $group) => (bool) $group->pivot->is_primary) ?? $this->managerGroups->sortBy('id')->first();
} }
public function isManagerSuperAdmin(): bool public function isManagerSuperAdmin(): bool
+17 -3
View File
@@ -16,14 +16,15 @@ use IriksIT\Manager\Support\Importer;
*/ */
class ImportCommand extends Command class ImportCommand extends Command
{ {
protected $signature = 'manager:import {target : posts, pages or reviews} protected $signature = 'manager:import {target : posts, pages, reviews or media}
{--table= : Table to read (default: config manager.import.<target>.table)} {--table= : Table to read (default: config manager.import.<target>.table)}
{--connection= : Database connection of that table (default: the default one)} {--connection= : Database connection of that table (default: the default one)}
{--map=* : package_column=source_column, repeat for each column that is named differently} {--map=* : package_column=source_column, repeat for each column that is named differently}
{--set=* : package_column=value, a value for every row that has none (for media: --set=disk=iriksit)}
{--limit= : Only the first rows} {--limit= : Only the first rows}
{--dry-run : Count what would happen and write nothing}'; {--dry-run : Count what would happen and write nothing}';
protected $description = 'Copy the existing posts, pages or reviews of the site into the package tables'; protected $description = 'Copy the existing posts, pages, reviews or media rows of the site into the package tables';
public function handle(Importer $importer): int public function handle(Importer $importer): int
{ {
@@ -50,9 +51,22 @@ class ImportCommand extends Command
$map[trim($to)] = trim($from); $map[trim($to)] = trim($from);
} }
$fixed = [];
foreach ((array) $this->option('set') as $pair) {
if (! str_contains((string) $pair, '=')) {
$this->error("--set wants package_column=value, got {$pair}");
return self::FAILURE;
}
[$column, $value] = explode('=', (string) $pair, 2);
$fixed[trim($column)] = $value;
}
try { try {
$connection = DB::connection($this->option('connection') ?: ($config['connection'] ?? null)); $connection = DB::connection($this->option('connection') ?: ($config['connection'] ?? null));
$result = $importer->run($target, $connection, $table, $map, (bool) $this->option('dry-run'), $this->option('limit') !== null ? (int) $this->option('limit') : null); $result = $importer->run($target, $connection, $table, $map, (bool) $this->option('dry-run'), $this->option('limit') !== null ? (int) $this->option('limit') : null, $fixed);
} catch (InvalidArgumentException $e) { } catch (InvalidArgumentException $e) {
$this->error($e->getMessage()); $this->error($e->getMessage());
+97
View File
@@ -0,0 +1,97 @@
<?php
namespace IriksIT\Manager\Console;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;
use IriksIT\Manager\Exceptions\MediaStorageException;
use IriksIT\Manager\Models\Media;
use IriksIT\Manager\Modules\Media\MediaLibrary;
use Throwable;
/**
* Moves the files of the media library to another disk, for instance from this server to the IriksIT API. The address of a file
* does not change, so nothing that uses it needs editing. Safe to run again: what already lives on the disk is skipped, and a
* file that fails stays where it was.
*
* php artisan manager:media-move iriksit --dry-run
* php artisan manager:media-move iriksit --from=public --verify --delete-source
*/
class MediaMoveCommand extends Command
{
protected $signature = 'manager:media-move {to : The disk to move the files to}
{--from= : Only move the files that are on this disk}
{--limit=0 : Move at most this many files (0 = all)}
{--verify : Read each copy back and compare it with the checksum}
{--delete-source : Delete the original after the copy was checked}
{--dry-run : Only show what would be moved}';
protected $description = 'Move the files of the media library to another disk';
public function handle(MediaLibrary $library): int
{
$to = (string) $this->argument('to');
if (config("filesystems.disks.{$to}") === null) {
$this->error("There is no disk called {$to}.");
return self::FAILURE;
}
$dryRun = (bool) $this->option('dry-run');
$limit = max((int) $this->option('limit'), 0);
$maxBytes = max(1, (int) config('manager.media.max_file_mb')) * 1024 * 1024;
[$moved, $skipped, $failed] = [0, 0, 0];
$query = Media::query()->where('disk', '!=', $to)->when($this->option('from'), fn ($q, $from) => $q->where('disk', $from))->orderBy('id');
foreach ($query->get() as $media) {
if ($limit > 0 && $moved + $failed >= $limit) {
break;
}
$label = "#{$media->id} {$media->filename}";
if (! Storage::disk($media->disk)->exists($media->location)) {
$this->warn("{$label}: not on the `{$media->disk}` disk, skipped.");
$skipped++;
continue;
}
if ((int) $media->size > $maxBytes) {
$this->warn("{$label}: larger than manager.media.max_file_mb, stays where it is.");
$skipped++;
continue;
}
if ($dryRun) {
$this->line("{$label}: would be moved from `{$media->disk}`.");
$moved++;
continue;
}
try {
$library->move($media, $to, (bool) $this->option('delete-source'), (bool) $this->option('verify'));
} catch (MediaStorageException|Throwable $e) {
$this->error("{$label}: could not be moved, left where it is ({$e->getMessage()})");
$failed++;
continue;
}
$this->line("{$label}: moved.");
$moved++;
}
$this->info(($dryRun ? 'Would move' : 'Moved')." {$moved}, skipped {$skipped}, failed {$failed}.");
if (! $dryRun && $failed === 0 && config('manager.media.disk') !== $to) {
$this->warn("manager.media.disk is not `{$to}` yet: new uploads still go to `".config('manager.media.disk').'`.');
}
return $failed === 0 ? self::SUCCESS : self::FAILURE;
}
}
+104
View File
@@ -0,0 +1,104 @@
<?php
namespace IriksIT\Manager\Console;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;
use IriksIT\Manager\Models\Media;
use IriksIT\Manager\Modules\Media\MediaLibrary;
use Throwable;
/**
* Finds files of the media library that nothing uses any more (no post, page or other registered source holds their address),
* and with `--delete` removes them. Nothing is deleted without `--delete`, and only files older than `--older-than` days.
* `--orphans` looks for the opposite: files on a disk that no row knows (only for a disk that can list its files).
*
* php artisan manager:media-prune --older-than=30
* php artisan manager:media-prune --older-than=30 --delete
* php artisan manager:media-prune --orphans --disk=public
*/
class MediaPruneCommand extends Command
{
protected $signature = 'manager:media-prune
{--older-than=30 : Only files that were added more than this many days ago}
{--delete : Really delete (without this it only lists)}
{--orphans : List (and with --delete, remove) files on the disk that no media row knows}
{--disk= : For --orphans: the disk to look at (default: the disk of the media library)}';
protected $description = 'Find media files that nothing uses any more, and delete them on request';
public function handle(MediaLibrary $library): int
{
return $this->option('orphans') ? $this->orphans() : $this->unused($library);
}
private function unused(MediaLibrary $library): int
{
$days = max(0, (int) $this->option('older-than'));
$candidates = Media::query()->where('created_at', '<', now()->subDays($days))->orderBy('id')->get();
$counts = $library->usageCounts($candidates);
$found = $deleted = $failed = 0;
foreach ($candidates as $media) {
if (($counts[$media->id] ?? 0) > 0) {
continue;
}
$found++;
$label = "#{$media->id} {$media->filename} (".round($media->size / 1024).' KB)';
if (! $this->option('delete')) {
$this->line("{$label}: not used.");
continue;
}
try {
$library->delete($media);
$this->line("{$label}: deleted.");
$deleted++;
} catch (Throwable $e) {
$this->error("{$label}: could not be deleted ({$e->getMessage()})");
$failed++;
}
}
$this->info($this->option('delete') ? "Deleted {$deleted}, failed {$failed}." : "{$found} not used. Run again with --delete to remove them.");
return $failed === 0 ? self::SUCCESS : self::FAILURE;
}
private function orphans(): int
{
$name = (string) ($this->option('disk') ?: config('manager.media.disk'));
$known = Media::query()->where('disk', $name)->pluck('location')->flip();
$disk = Storage::disk($name);
try {
$files = $disk->allFiles('media');
} catch (Throwable) {
$files = [];
}
if ($files === [] && Media::query()->where('disk', $name)->exists()) {
$this->warn("The disk `{$name}` cannot list its files (or has none), so there is nothing to compare.");
return self::SUCCESS;
}
$found = 0;
foreach ($files as $file) {
if ($known->has($file)) {
continue;
}
$found++;
$this->line($this->option('delete') ? "{$file}: ".($disk->delete($file) ? 'deleted.' : 'could not be deleted.') : "{$file}: no row knows it.");
}
$this->info($this->option('delete') ? "Looked at {$found} unknown files." : "{$found} files that no row knows. Run again with --delete to remove them.");
return self::SUCCESS;
}
}
+144
View File
@@ -0,0 +1,144 @@
<?php
namespace IriksIT\Manager\Console;
use Illuminate\Console\Command;
use IriksIT\Manager\Support\Settings\Definitions;
use IriksIT\Manager\Support\Settings\Store;
use IriksIT\Manager\Support\Settings\Writer;
/**
* The settings screen in the terminal, for scripts, deploys and agents. Whoever may run this may change everything, so there is
* no password or right to ask for. A secret is never printed, and its value is typed hidden (or read from standard input), never
* given as an argument that would stay in the history of the shell.
*
* php artisan manager:settings list
* php artisan manager:settings set manager.modules.reviews true
* php artisan manager:settings set manager.media.iriksit.password (asks, hidden)
* echo "$SECRET" | php artisan manager:settings set manager.login.turnstile.secret --stdin
* php artisan manager:settings reset manager.modules.reviews
* php artisan manager:settings refresh
*/
class SettingsCommand extends Command
{
protected $signature = 'manager:settings {action : list, get, set, reset or refresh}
{key? : The config path of the setting, like manager.modules.reviews}
{value? : The new value (not for a secret)}
{--stdin : Read the value from standard input (for a secret in a script)}
{--json : list: print JSON}';
protected $description = 'List, read, change or reset the settings of the settings screen';
public function handle(Definitions $definitions, Store $store, Writer $writer): int
{
$action = (string) $this->argument('action');
if ($action === 'refresh') {
$this->info($writer->refresh() ? 'Refreshed.' : 'The caches are emptied, but the file bootstrap/cache/manager-settings.php could not be written.');
return self::SUCCESS;
}
if ($action === 'list') {
return $this->list($definitions, $store);
}
if (! in_array($action, ['get', 'set', 'reset'], true)) {
$this->error('Use one of: list, get, set, reset, refresh.');
return self::FAILURE;
}
$key = (string) $this->argument('key');
$definition = $definitions->find($key);
if ($definition === null) {
$this->error("There is no setting {$key}. See: php artisan manager:settings list");
return self::FAILURE;
}
if ($action === 'get') {
$this->line($definition['type'] === 'secret' ? (filled(config($key)) ? 'set' : 'not set') : $this->show(config($key)));
return self::SUCCESS;
}
if ($action === 'reset') {
$result = $writer->apply([$key => null]);
$this->info("{$key} is back to what the config says.".($result['file_written'] ? '' : ' (The compiled file could not be written.)'));
return self::SUCCESS;
}
return $this->set($definitions, $writer, $definition);
}
/** @param array<string, mixed> $definition */
private function set(Definitions $definitions, Writer $writer, array $definition): int
{
$key = $definition['key'];
if ($this->option('stdin')) {
$raw = rtrim((string) stream_get_contents(STDIN), "\r\n");
} elseif ($definition['type'] === 'secret') {
if ($this->argument('value') !== null) {
$this->error('Do not type a secret as an argument: it stays in the history of the shell. Leave it out to be asked, or use --stdin.');
return self::FAILURE;
}
$raw = (string) $this->secret($definition['label']);
} else {
$raw = $this->argument('value');
if ($raw === null) {
$this->error('Which value? php artisan manager:settings set '.$key.' <value>');
return self::FAILURE;
}
}
try {
$value = $definitions->cast($definition, $raw);
} catch (\InvalidArgumentException) {
$this->error('This value is not valid for '.$key.' ('.$definition['type'].').');
return self::FAILURE;
}
$result = $writer->apply([$key => $value]);
$this->info("{$key} is set.".($result['env_written'] ? ' Written into .env too.' : '').($result['file_written'] ? '' : ' (The compiled file could not be written: run `manager:settings refresh` when it can.)'));
return self::SUCCESS;
}
private function list(Definitions $definitions, Store $store): int
{
$rows = [];
foreach ($definitions->all() as $key => $definition) {
$rows[] = [
'key' => $key,
'type' => $definition['type'],
'value' => $definition['type'] === 'secret' ? (filled(config($key)) ? 'set' : 'not set') : $this->show(config($key)),
'saved' => $store->has($key),
];
}
if ($this->option('json')) {
$this->line(json_encode($rows, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
return self::SUCCESS;
}
$this->table(['Setting', 'Type', 'Value', 'Saved here'], array_map(fn ($row) => [$row['key'], $row['type'], $row['value'], $row['saved'] ? 'yes' : ''], $rows));
return self::SUCCESS;
}
private function show(mixed $value): string
{
return is_bool($value) ? ($value ? 'true' : 'false') : (string) ($value ?? '');
}
}
+66
View File
@@ -0,0 +1,66 @@
<?php
namespace IriksIT\Manager\Console;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;
use IriksIT\Manager\Exceptions\MediaStorageException;
use Throwable;
/**
* Tries the disk of the media library the way a real upload would: writes a small file, reads it back, checks that it is
* the same and deletes it again. Leaves nothing behind (when the delete fails, it says which file is left).
*
* php artisan manager:storage-check [--disk=iriksit]
*/
class StorageCheckCommand extends Command
{
protected $signature = 'manager:storage-check {--disk= : The disk to try; default: the disk of the media library}';
protected $description = 'Write, read and delete a test file on the disk of the media library';
public function handle(): int
{
$name = (string) ($this->option('disk') ?: config('manager.media.disk'));
$disk = Storage::disk($name);
$location = 'manager-check/'.bin2hex(random_bytes(6)).'.txt';
$content = 'manager storage check '.now()->toIso8601String();
$this->line("Disk: {$name}");
try {
$step = 'write';
if (! $disk->put($location, $content)) {
$this->components->error('The file could not be written. See the log of the app for the reason.');
return self::FAILURE;
}
$this->components->info('Written.');
$step = 'read';
$back = $disk->get($location);
if ($back !== $content) {
$this->components->error('What was read back is not what was written.');
return self::FAILURE;
}
$this->components->info('Read back: the same.');
$step = 'delete';
if (! $disk->delete($location)) {
$this->components->error("The test file could not be deleted: {$location}");
return self::FAILURE;
}
$this->components->info('Deleted.');
} catch (MediaStorageException|Throwable $e) {
$this->components->error("Could not {$step}: ".$e->getMessage());
return self::FAILURE;
}
$this->components->info('The storage works.');
return self::SUCCESS;
}
}
+49
View File
@@ -0,0 +1,49 @@
<?php
namespace IriksIT\Manager\Console;
use Illuminate\Console\Command;
/**
* The accounts of the manager, with their groups. `--json` for scripts and agents.
*
* php artisan manager:users [--json]
*/
class UserListCommand extends Command
{
protected $signature = 'manager:users {--json : Print JSON}';
protected $description = 'List the accounts of the manager with their groups';
public function handle(): int
{
$model = config('manager.user_model');
$rows = [];
foreach ($model::query()->with('managerGroups')->orderBy('id')->get() as $user) {
$primary = $user->managerPrimaryGroup();
$rows[] = [
'id' => $user->getKey(),
'name' => (string) $user->name,
'email' => (string) $user->email,
'super_admin' => $user->isManagerSuperAdmin(),
'primary_group' => $primary?->name,
'groups' => $user->managerGroups->pluck('name')->sort()->values()->all(),
];
}
if ($this->option('json')) {
$this->line(json_encode($rows, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
return self::SUCCESS;
}
$this->table(['Id', 'Name', 'Email', 'Super admin', 'Primary group', 'Groups'], array_map(
fn ($row) => [$row['id'], $row['name'], $row['email'], $row['super_admin'] ? 'yes' : '', $row['primary_group'] ?? '', implode(', ', $row['groups'])],
$rows,
));
return self::SUCCESS;
}
}
+57
View File
@@ -0,0 +1,57 @@
<?php
namespace IriksIT\Manager\Console;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
/**
* Sets a new password for an account, for someone who cannot log in. Typed hidden by default; `--generate` makes a long random
* one and shows it once. The password is never an argument (it would stay in the history of the shell).
*
* php artisan manager:user-password someone@example.com [--generate]
*/
class UserPasswordCommand extends Command
{
protected $signature = 'manager:user-password {email : The email address of the account}
{--generate : Make a random password and show it once}';
protected $description = 'Set a new password for an account of the manager';
public function handle(): int
{
$model = config('manager.user_model');
$user = $model::query()->where('email', strtolower((string) $this->argument('email')))->first();
if ($user === null) {
$this->error('There is no account with that email address.');
return self::FAILURE;
}
if ($this->option('generate')) {
$password = Str::password(20, symbols: false);
} else {
$password = (string) $this->secret('New password (min 12 characters)');
if (mb_strlen($password) < 12) {
$this->error('The password must be at least 12 characters.');
return self::FAILURE;
}
if ($password !== (string) $this->secret('Once more')) {
$this->error('The two passwords are not the same.');
return self::FAILURE;
}
}
$user->forceFill(['password' => Hash::make($password)])->save();
$this->info("New password for {$user->email} is set.");
$this->option('generate') && $this->line($password);
return self::SUCCESS;
}
}
+29 -2
View File
@@ -3,13 +3,17 @@
namespace IriksIT\Manager; namespace IriksIT\Manager;
use Illuminate\Cache\RateLimiting\Limit; use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Filesystem\FilesystemAdapter;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate; use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\RateLimiter; use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\ServiceProvider; use Illuminate\Support\ServiceProvider;
use IriksIT\Manager\Support\IriksStorage;
use IriksIT\Manager\Support\ModuleRegistry; use IriksIT\Manager\Support\ModuleRegistry;
use IriksIT\Manager\Support\Names; use IriksIT\Manager\Support\Names;
use League\Flysystem\Filesystem;
class ManagerServiceProvider extends ServiceProvider class ManagerServiceProvider extends ServiceProvider
{ {
@@ -20,13 +24,16 @@ class ManagerServiceProvider extends ServiceProvider
{ {
$this->mergeConfigFrom(__DIR__.'/../config/manager.php', 'manager'); $this->mergeConfigFrom(__DIR__.'/../config/manager.php', 'manager');
// What was set on the settings screen goes over the config before anything reads it.
Support\Settings\Store::overlay();
$this->app->singleton(Support\MediaUsage::class); $this->app->singleton(Support\MediaUsage::class);
$this->app->singleton(Support\AuditTrail::class); $this->app->singleton(Support\AuditTrail::class);
$this->app->singleton(Modules\Posts\PostLabels::class); $this->app->singleton(Modules\Posts\PostLabels::class);
$this->app->singleton(ModuleRegistry::class, fn ($app) => new ModuleRegistry( $this->app->singleton(ModuleRegistry::class, fn ($app) => new ModuleRegistry(
// A config that was published before resources existed does not list their module. // A config that was published before resources existed does not list their module.
array_values(array_unique([...$app['config']->get('manager.available', []), Modules\Resources\ResourcesModule::class, Modules\Revisions\RevisionsModule::class])), array_values(array_unique([...$app['config']->get('manager.available', []), Modules\Resources\ResourcesModule::class, Modules\Revisions\RevisionsModule::class, Modules\Settings\SettingsModule::class])),
$app['config']->get('manager.modules', []), $app['config']->get('manager.modules', []),
)); ));
} }
@@ -45,6 +52,8 @@ class ManagerServiceProvider extends ServiceProvider
$this->app['router']->aliasMiddleware('manager.locale', Http\Middleware\SetLocale::class); $this->app['router']->aliasMiddleware('manager.locale', Http\Middleware\SetLocale::class);
RateLimiter::for('manager-login', fn (Request $request) => Limit::perMinute(5)->by(strtolower((string) $request->input('email')).'|'.$request->ip())); RateLimiter::for('manager-login', fn (Request $request) => Limit::perMinute(5)->by(strtolower((string) $request->input('email')).'|'.$request->ip()));
$this->registerIriksStorage();
foreach ($modules->active() as $module) { foreach ($modules->active() as $module) {
if ($module->migrations() !== null) { if ($module->migrations() !== null) {
$this->loadMigrationsFrom($module->migrations()); $this->loadMigrationsFrom($module->migrations());
@@ -58,13 +67,31 @@ class ManagerServiceProvider extends ServiceProvider
} }
if ($this->app->runningInConsole()) { if ($this->app->runningInConsole()) {
$this->commands([Console\InstallCommand::class, Console\DoctorCommand::class, Console\MakeThemeCommand::class, Console\ImportCommand::class]); $this->commands([Console\InstallCommand::class, Console\DoctorCommand::class, Console\MakeThemeCommand::class, Console\ImportCommand::class, Console\StorageCheckCommand::class, Console\MediaMoveCommand::class, Console\SettingsCommand::class, Console\UserListCommand::class, Console\UserPasswordCommand::class, Console\MediaPruneCommand::class]);
} }
$this->registerGates($modules); $this->registerGates($modules);
$this->registerRoutes($modules); $this->registerRoutes($modules);
} }
/**
* The disk `iriksit`: files at the IriksIT API. A site that wants it sets `manager.media.disk` to `iriksit` (or any disk
* of its own with `driver` => `iriksit` in config/filesystems.php) and gives the address and the account
* in `manager.media.iriksit`. The disk is added here when the site has not made one itself.
*/
private function registerIriksStorage(): void
{
Storage::extend('iriksit', function ($app, array $config) {
$adapter = new IriksStorage\Adapter(new IriksStorage\Client($config));
return new FilesystemAdapter(new Filesystem($adapter, $config), $adapter, $config);
});
if (config('filesystems.disks.iriksit') === null) {
config(['filesystems.disks.iriksit' => ['driver' => 'iriksit', ...(array) config('manager.media.iriksit', [])]]);
}
}
/** /**
* One gate per permission, and no Gate::before: a package must never answer for abilities * 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. * of the host app. A super admin passes inside hasManagerPermission, for these gates only.
+50
View File
@@ -55,6 +55,56 @@ class MediaLibrary
]); ]);
} }
/**
* Move a file to another disk: copy it (the same location on the new disk), check the size (and, with $verify, what comes
* back), only then point the row at the new disk and, when asked, delete the original. The address of the file does not
* change, because it holds the id of the row. A file that is already there is not copied again.
*
* @throws MediaStorageException with the file still where it was
*/
public function move(Media $media, string $disk, bool $deleteSource = false, bool $verify = false): void
{
$from = Storage::disk($media->disk);
$to = Storage::disk($disk);
$wrote = false;
if (! $to->exists($media->location)) {
$stream = $this->open($media);
try {
$stored = $to->put($media->location, $stream);
} finally {
is_resource($stream) && fclose($stream);
}
if ($stored === false) {
throw new MediaStorageException('The file could not be written to the new disk.');
}
$wrote = true;
}
if ($to->size($media->location) !== (int) $media->size) {
$wrote && $to->delete($media->location);
throw new MediaStorageException('The copy on the new disk is not the size of the original.');
}
if ($verify && $media->checksum !== null && hash('sha256', (string) $to->get($media->location)) !== $media->checksum) {
$wrote && $to->delete($media->location);
throw new MediaStorageException('The copy on the new disk is not the same as the original.');
}
$source = $media->disk;
$media->update(['disk' => $disk]);
if ($deleteSource && $source !== $disk) {
Storage::disk($source)->delete($media->location);
}
}
/** /**
* How full the library is: what all files together take, how much it may hold * 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. * (`manager.media.max_total_gb`) and what is left. In bytes.
+1 -1
View File
@@ -28,7 +28,7 @@ class MediaModule extends BaseModule
public function tables(): array public function tables(): array
{ {
return ['media']; return ['media', 'storage_files'];
} }
public function permissions(): array public function permissions(): array
@@ -0,0 +1,24 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use IriksIT\Manager\Support\Names;
return new class extends Migration
{
public function up(): void
{
// The IriksIT API knows a file by an id of its own: this remembers which id belongs to which path of the `iriksit` disk.
Schema::create(Names::table('storage_files'), function (Blueprint $table) {
$table->id();
$table->string('path')->unique();
$table->string('remote_id', 100);
});
}
public function down(): void
{
Schema::dropIfExists(Names::table('storage_files'));
}
};
+178
View File
@@ -0,0 +1,178 @@
<?php
namespace IriksIT\Manager\Modules\Settings;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Schema;
use Illuminate\Validation\ValidationException;
use IriksIT\Manager\Support\Menu;
use IriksIT\Manager\Support\ModuleRegistry;
use IriksIT\Manager\Support\Names;
use IriksIT\Manager\Support\Settings\Definitions;
use IriksIT\Manager\Support\Settings\EnvFile;
use IriksIT\Manager\Support\Settings\Store;
use IriksIT\Manager\Support\Settings\Writer;
/**
* The settings screen. Only in the whole face of the manager (a simple account gets a 403, whatever its rights). What changes
* how a password or a file travels (secrets, addresses, accounts, disks) also needs `settings.secrets` and the password of the
* account that saves it. A secret is never sent to the browser: it is only said to be set.
*/
class SettingsController
{
public function __construct(
private readonly Definitions $definitions,
private readonly Store $store,
private readonly EnvFile $env,
private readonly Writer $writer,
private readonly ModuleRegistry $modules,
private readonly Menu $menu,
) {}
public function index(Request $request): JsonResponse
{
$this->onlyFull($request);
$groups = [];
foreach ($this->definitions->all() as $key => $definition) {
if (! $this->mayChange($request, $definition)) {
continue;
}
$value = config($key);
$groups[__($definition['group'])][] = [
'key' => $key,
'label' => __($definition['label']),
'type' => $definition['type'],
'help' => $definition['help'] === null ? null : __($definition['help']),
'options' => $definition['options'],
'sensitive' => $definition['sensitive'],
// A secret says only whether it is set.
'value' => $definition['type'] === 'secret' ? null : $value,
'set' => $definition['type'] === 'secret' ? filled($value) : null,
'saved' => $this->store->has($key),
];
}
return response()->json([
'groups' => collect($groups)->map(fn (array $items, string $name) => ['name' => $name, 'items' => $items])->values(),
'write_env' => (bool) config('manager.settings.write_env'),
'env_writable' => $this->env->writable(),
'config_cached' => app()->configurationIsCached(),
]);
}
public function update(Request $request): JsonResponse
{
$this->onlyFull($request);
$request->validate(['values' => ['present', 'array'], 'reset' => ['nullable', 'array'], 'reset.*' => ['string'], 'password' => ['nullable', 'string', 'max:200']]);
$changes = [];
$sensitive = false;
foreach ($request->array('values') as $key => $raw) {
$definition = $this->definitions->find((string) $key);
if ($definition === null || ! $this->mayChange($request, $definition)) {
throw ValidationException::withMessages(['values' => __('This setting does not exist or you may not change it.')]);
}
// A secret that is left empty is left alone (the browser sends an empty field as null): clearing one is `reset`.
if ($definition['type'] === 'secret' && ($raw === '' || $raw === null)) {
continue;
}
try {
$value = $raw === null ? null : $this->definitions->cast($definition, $raw);
} catch (\InvalidArgumentException) {
throw ValidationException::withMessages(['values.'.$key => __('This value is not valid.')]);
}
if ($value !== null && $value === config($key) && ! $this->store->has($key)) {
continue;
}
$changes[$key] = $value;
$sensitive = $sensitive || $definition['sensitive'];
}
// `reset`: back to what the config (and .env) says.
foreach ($request->array('reset') as $key) {
$definition = $this->definitions->find((string) $key);
if ($definition === null || ! $this->mayChange($request, $definition)) {
throw ValidationException::withMessages(['reset' => __('This setting does not exist or you may not change it.')]);
}
$changes[$key] = null;
$sensitive = $sensitive || $definition['sensitive'];
}
if ($sensitive && ! Hash::check((string) $request->input('password'), (string) $request->user()->getAuthPassword())) {
throw ValidationException::withMessages(['password' => __('Type your own password to change this.')]);
}
$result = $this->writer->apply($changes, $request->user()->getAuthIdentifier());
return response()->json([
'saved' => true,
'changed' => count($changes),
...$result,
'migrate' => $this->pendingMigrations(array_keys($changes)),
]);
}
/** Writes the compiled file again and empties what caches the old values. */
public function refresh(Request $request): JsonResponse
{
$this->onlyFull($request);
$written = $this->writer->refresh();
return response()->json(['refreshed' => true, 'file_written' => $written]);
}
private function onlyFull(Request $request): void
{
abort_if($this->menu->view($request->user()) === Menu::SIMPLE, 403);
}
/** @param array<string, mixed> $definition */
private function mayChange(Request $request, array $definition): bool
{
$user = $request->user();
return (! $definition['sensitive'] || Gate::forUser($user)->allows('settings.secrets'))
&& ($definition['permission'] === null || Gate::forUser($user)->allows($definition['permission']));
}
/**
* The parts that were switched on and miss a table: the screen tells to run `php artisan migrate`.
*
* @param list<string> $keys
* @return list<string>
*/
private function pendingMigrations(array $keys): array
{
$labels = [];
foreach ($keys as $key) {
if (! str_starts_with($key, 'manager.modules.') || ! config($key)) {
continue;
}
foreach ($this->modules->all() as $module) {
if ('manager.modules.'.$module->key() === $key && collect($module->tables())->contains(fn (string $table) => ! Schema::hasTable(Names::table($table)))) {
$labels[] = $module->label();
}
}
}
return $labels;
}
}
+58
View File
@@ -0,0 +1,58 @@
<?php
namespace IriksIT\Manager\Modules\Settings;
use IriksIT\Manager\Modules\BaseModule;
use IriksIT\Manager\Support\Names;
use IriksIT\Manager\Support\Permission;
/**
* The settings screen: which parts and features are on, and the keys and addresses of integrations, all changeable from the
* manager by an account with the right, in the whole face of the manager only. A change is saved (secrets encrypted) and works at
* once; see Support\Settings.
*/
class SettingsModule extends BaseModule
{
public function key(): string
{
return 'settings';
}
public function label(): string
{
return 'Settings';
}
public function enabledByDefault(): bool
{
return true;
}
public function tables(): array
{
return ['settings'];
}
public function permissions(): array
{
return [
new Permission('settings.manage', 'Switch parts and features on or off and change settings', 'Settings'),
new Permission('settings.secrets', 'Change keys, passwords and addresses of integrations', 'Settings', needs: ['settings.manage']),
];
}
public function navigation(): array
{
return [['label' => 'Settings', 'route' => Names::route('settings.index'), 'permission' => 'settings.manage', 'icon' => 'cog', 'simple' => false]];
}
public function actions(): array
{
return ['settings.update' => ['Changed the settings'], 'settings.refresh' => ['Refreshed the settings']];
}
public function views(): array
{
return ['settings.index' => 'Opened the settings'];
}
}
@@ -0,0 +1,28 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use IriksIT\Manager\Support\Names;
return new class extends Migration
{
public function up(): void
{
Schema::create(Names::table('settings'), function (Blueprint $table) {
$table->id();
$table->string('key', 150)->unique();
// JSON; a secret is encrypted.
$table->text('value')->nullable();
$table->boolean('is_secret')->default(false);
$table->unsignedBigInteger('updated_by')->nullable();
$table->dateTime('created_at')->nullable();
$table->dateTime('updated_at')->nullable();
});
}
public function down(): void
{
Schema::dropIfExists(Names::table('settings'));
}
};
+10
View File
@@ -0,0 +1,10 @@
<?php
use Illuminate\Support\Facades\Route;
use IriksIT\Manager\Modules\Settings\SettingsController;
Route::middleware('can:settings.manage')->group(function () {
Route::get('/settings', [SettingsController::class, 'index'])->name('settings.index');
Route::put('/settings', [SettingsController::class, 'update'])->name('settings.update');
Route::post('/settings/refresh', [SettingsController::class, 'refresh'])->name('settings.refresh');
});
+19 -3
View File
@@ -41,7 +41,7 @@ class AccountController
'is_you' => $user->is($me), 'is_you' => $user->is($me),
'view' => UserSetting::value($user, 'view'), 'view' => UserSetting::value($user, 'view'),
'tutorial' => UserSetting::value($user, 'tutorial'), 'tutorial' => UserSetting::value($user, 'tutorial'),
'groups' => $user->managerGroups->sortBy('name')->map(fn (Group $group) => ['id' => $group->id, 'name' => $group->name])->values(), 'groups' => $user->managerGroups->sortBy('name')->map(fn (Group $group) => ['id' => $group->id, 'name' => $group->name, 'primary' => (bool) $group->pivot->is_primary])->values(),
'can_change' => $me->managerOutranks($user), 'can_change' => $me->managerOutranks($user),
'can_delete' => $me->managerOutranks($user) && ! $user->is($me), 'can_delete' => $me->managerOutranks($user) && ! $user->is($me),
])->values(), ])->values(),
@@ -66,7 +66,7 @@ class AccountController
$model = $this->model(); $model = $this->model();
$user = new $model; $user = new $model;
$user->forceFill([...$details, 'password' => Hash::make($request->string('password')->toString())])->save(); $user->forceFill([...$details, 'password' => Hash::make($request->string('password')->toString())])->save();
$user->managerGroups()->sync($groups); $user->managerGroups()->sync($this->withPrimary($groups, $request));
$this->settings($request, $user); $this->settings($request, $user);
return response()->json(['id' => $user->getKey()], 201); return response()->json(['id' => $user->getKey()], 201);
@@ -95,7 +95,7 @@ class AccountController
$user->save(); $user->save();
if ($groups !== null) { if ($groups !== null) {
$user->managerGroups()->sync($groups); $user->managerGroups()->sync($this->withPrimary($groups, $request));
} }
$this->settings($request, $user); $this->settings($request, $user);
@@ -160,6 +160,7 @@ class AccountController
'email' => ['required', 'string', 'email', 'max:255'], 'email' => ['required', 'string', 'email', 'max:255'],
'groups' => ['array'], 'groups' => ['array'],
'groups.*' => ['integer'], 'groups.*' => ['integer'],
'primary_group' => ['nullable', 'integer'],
'view' => ['nullable', Rule::in([Menu::FULL, Menu::SIMPLE])], 'view' => ['nullable', Rule::in([Menu::FULL, Menu::SIMPLE])],
'tutorial' => ['nullable', 'boolean'], 'tutorial' => ['nullable', 'boolean'],
]; ];
@@ -181,6 +182,21 @@ class AccountController
return ['name' => $request->string('name')->trim()->toString(), 'email' => $email]; return ['name' => $request->string('name')->trim()->toString(), 'email' => $email];
} }
/**
* The ticked groups as a sync map: exactly one of them is the primary one (the one that was asked for, else the first),
* and none when there are no groups.
*
* @param list<int> $ids
* @return array<int, array{is_primary: bool}>
*/
private function withPrimary(array $ids, Request $request): array
{
$asked = $request->integer('primary_group');
$primary = in_array($asked, $ids, true) ? $asked : ($ids[0] ?? null);
return collect($ids)->mapWithKeys(fn (int $id) => [$id => ['is_primary' => $id === $primary]])->all();
}
/** /**
* The ids of the groups that were ticked. One that does not exist, or that gives more than * 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. * the account that is logged in has, is refused.
+4 -1
View File
@@ -23,6 +23,7 @@ class GroupController
'id' => $group->id, 'id' => $group->id,
'name' => $group->name, 'name' => $group->name,
'description' => $group->description, 'description' => $group->description,
'start' => $group->start,
'permissions' => $group->allowed(), 'permissions' => $group->allowed(),
'accounts' => $group->users_count, 'accounts' => $group->users_count,
])->values(), ])->values(),
@@ -57,7 +58,7 @@ class GroupController
return response()->json(['deleted' => true]); return response()->json(['deleted' => true]);
} }
/** @return array{name: string, description: string|null, permissions: list<string>} */ /** @return array{name: string, description: string|null, start: string|null, permissions: list<string>} */
private function validated(Request $request, ?Group $group = null): array private function validated(Request $request, ?Group $group = null): array
{ {
$table = Names::table('groups'); $table = Names::table('groups');
@@ -65,6 +66,7 @@ class GroupController
$request->validate([ $request->validate([
'name' => ['required', 'string', 'max:60', Rule::unique($table, 'name')->ignore($group?->id)], 'name' => ['required', 'string', 'max:60', Rule::unique($table, 'name')->ignore($group?->id)],
'description' => ['nullable', 'string', 'max:500'], 'description' => ['nullable', 'string', 'max:500'],
'start' => ['nullable', 'string', 'max:200', 'regex:#^/[A-Za-z0-9/_.-]*$#'],
'permissions' => ['array'], 'permissions' => ['array'],
'permissions.*' => ['string', Rule::in($this->modules->permissionValues())], 'permissions.*' => ['string', Rule::in($this->modules->permissionValues())],
]); ]);
@@ -74,6 +76,7 @@ class GroupController
return [ return [
'name' => $request->string('name')->trim()->toString(), 'name' => $request->string('name')->trim()->toString(),
'description' => $description !== '' ? $description : null, 'description' => $description !== '' ? $description : null,
'start' => $request->filled('start') ? $request->string('start')->toString() : null,
'permissions' => $this->modules->complete($request->array('permissions')), 'permissions' => $this->modules->complete($request->array('permissions')),
]; ];
} }
@@ -0,0 +1,29 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use IriksIT\Manager\Support\Names;
return new class extends Migration
{
public function up(): void
{
Schema::table(Names::table('group_user'), fn (Blueprint $table) => $table->boolean('is_primary')->default(false));
Schema::table(Names::table('groups'), fn (Blueprint $table) => $table->string('start', 200)->nullable());
// An account that is in groups already gets the first of them as its primary one.
$pivot = Names::table('group_user');
foreach (DB::table($pivot)->select('user_id', DB::raw('min(group_id) as first'))->groupBy('user_id')->get() as $row) {
DB::table($pivot)->where('user_id', $row->user_id)->where('group_id', $row->first)->update(['is_primary' => true]);
}
}
public function down(): void
{
Schema::table(Names::table('groups'), fn (Blueprint $table) => $table->dropColumn('start'));
Schema::table(Names::table('group_user'), fn (Blueprint $table) => $table->dropColumn('is_primary'));
}
};
+31 -1
View File
@@ -7,6 +7,7 @@ use Illuminate\Database\Eloquent\Model as Eloquent;
use Illuminate\Support\Arr; use Illuminate\Support\Arr;
use Illuminate\Support\Str; use Illuminate\Support\Str;
use InvalidArgumentException; use InvalidArgumentException;
use IriksIT\Manager\Models\Media;
use IriksIT\Manager\Models\Page; use IriksIT\Manager\Models\Page;
use IriksIT\Manager\Models\Post; use IriksIT\Manager\Models\Post;
use IriksIT\Manager\Models\Review; use IriksIT\Manager\Models\Review;
@@ -37,6 +38,13 @@ final class Importer
'required' => ['slug', 'title'], 'required' => ['slug', 'title'],
'key' => ['slug'], 'key' => ['slug'],
], ],
// The rows only; the files stay where they are. `disk` and `location` say where (use `--set=disk=iriksit` when the source has no disk column).
'media' => [
'model' => Media::class,
'columns' => ['disk', 'location', 'name', 'filename', 'mime_type', 'size', 'checksum', 'width', 'height', 'alt', 'focus_x', 'focus_y'],
'required' => ['location', 'filename'],
'key' => ['disk', 'location'],
],
'reviews' => [ 'reviews' => [
'model' => Review::class, 'model' => Review::class,
'columns' => ['author', 'place', 'rating', 'body', 'is_visible'], 'columns' => ['author', 'place', 'rating', 'body', 'is_visible'],
@@ -47,9 +55,10 @@ final class Importer
/** /**
* @param array<string, string> $map package column => column of the source table; same name when left out * @param array<string, string> $map package column => column of the source table; same name when left out
* @param array<string, string> $fixed package column => a value for every row that has none of its own
* @return array{created: int, updated: int, skipped: int, problems: list<string>} * @return array{created: int, updated: int, skipped: int, problems: list<string>}
*/ */
public function run(string $target, ConnectionInterface $source, string $table, array $map = [], bool $dry = false, ?int $limit = null): array public function run(string $target, ConnectionInterface $source, string $table, array $map = [], bool $dry = false, ?int $limit = null, array $fixed = []): array
{ {
$spec = self::TARGETS[$target] ?? throw new InvalidArgumentException("Unknown target {$target}; use one of: ".implode(', ', array_keys(self::TARGETS))); $spec = self::TARGETS[$target] ?? throw new InvalidArgumentException("Unknown target {$target}; use one of: ".implode(', ', array_keys(self::TARGETS)));
@@ -75,6 +84,26 @@ final class Importer
} }
} }
foreach ($fixed as $column => $value) {
if (! in_array($column, $spec['columns'], true)) {
throw new InvalidArgumentException("{$target} has no column {$column}; known: ".implode(', ', $spec['columns']));
}
if (! isset($values[$column]) || $values[$column] === '') {
$values[$column] = $this->convert($column, $value);
}
}
if ($target === 'media') {
foreach (['disk' => config('manager.media.disk'), 'mime_type' => 'application/octet-stream', 'size' => 0] as $column => $default) {
if (! isset($values[$column]) || $values[$column] === '') {
$values[$column] = $default;
}
}
$values['name'] = ($values['name'] ?? '') !== '' ? $values['name'] : pathinfo((string) ($values['filename'] ?? ''), PATHINFO_FILENAME);
}
if ($target === 'posts' || $target === 'pages') { if ($target === 'posts' || $target === 'pages') {
$values['slug'] = ($values['slug'] ?? '') !== '' ? Str::slug((string) $values['slug']) : Str::slug((string) ($values['title'] ?? '')); $values['slug'] = ($values['slug'] ?? '') !== '' ? Str::slug((string) $values['slug']) : Str::slug((string) ($values['title'] ?? ''));
} }
@@ -106,6 +135,7 @@ final class Importer
return match ($column) { return match ($column) {
'tags' => $this->tags($value), 'tags' => $this->tags($value),
'is_featured', 'is_published', 'is_visible' => filter_var($value, FILTER_VALIDATE_BOOLEAN), 'is_featured', 'is_published', 'is_visible' => filter_var($value, FILTER_VALIDATE_BOOLEAN),
'size', 'width', 'height' => $value === null || $value === '' ? null : max(0, (int) $value),
'rating' => $value === null || $value === '' ? null : max(1, min(5, (int) $value)), 'rating' => $value === null || $value === '' ? null : max(1, min(5, (int) $value)),
'published_at' => $value === null || $value === '' ? null : $value, 'published_at' => $value === null || $value === '' ? null : $value,
default => is_string($value) ? trim($value) : $value, default => is_string($value) ? trim($value) : $value,
+208
View File
@@ -0,0 +1,208 @@
<?php
namespace IriksIT\Manager\Support\IriksStorage;
use Illuminate\Support\Facades\DB;
use IriksIT\Manager\Exceptions\MediaStorageException;
use IriksIT\Manager\Support\Names;
use League\Flysystem\Config;
use League\Flysystem\DirectoryAttributes;
use League\Flysystem\FileAttributes;
use League\Flysystem\FilesystemAdapter;
use League\Flysystem\UnableToCopyFile;
use League\Flysystem\UnableToCreateDirectory;
use League\Flysystem\UnableToDeleteDirectory;
use League\Flysystem\UnableToDeleteFile;
use League\Flysystem\UnableToMoveFile;
use League\Flysystem\UnableToReadFile;
use League\Flysystem\UnableToRetrieveMetadata;
use League\Flysystem\UnableToSetVisibility;
use League\Flysystem\UnableToWriteFile;
/**
* A Laravel disk (`driver` => `iriksit`) whose files live at the IriksIT API. The API knows files by an id of its own, not
* by a path, so every path that is written is remembered next to that id (table `storage_files`). A path that has no entry
* and no slash is taken for an id itself: that is how media rows that were made by a site's own code (the id as location)
* keep working. There are no folders, no visibility and no listing.
*/
class Adapter implements FilesystemAdapter
{
public function __construct(private readonly Client $client) {}
public function fileExists(string $path): bool
{
$id = $this->id($path);
if ($id === null) {
return false;
}
try {
return $this->client->details($id) !== null;
} catch (MediaStorageException $e) {
throw UnableToRetrieveMetadata::create($path, 'exists', $e->getMessage(), $e);
}
}
public function directoryExists(string $path): bool
{
return false;
}
public function write(string $path, string $contents, Config $config): void
{
$stream = fopen('php://temp', 'r+b');
fwrite($stream, $contents);
rewind($stream);
try {
$this->writeStream($path, $stream, $config);
} finally {
// The HTTP client closes what it sent itself.
if (is_resource($stream)) {
fclose($stream);
}
}
}
public function writeStream(string $path, $contents, Config $config): void
{
try {
$stored = $this->client->store($contents, basename($path));
} catch (MediaStorageException $e) {
throw UnableToWriteFile::atLocation($path, $e->getMessage(), $e);
}
DB::table($this->table())->updateOrInsert(['path' => $path], ['remote_id' => $stored['id']]);
}
public function read(string $path): string
{
$stream = $this->readStream($path);
$contents = stream_get_contents($stream);
is_resource($stream) && fclose($stream);
return $contents === false ? throw UnableToReadFile::fromLocation($path) : $contents;
}
public function readStream(string $path)
{
$id = $this->id($path) ?? throw UnableToReadFile::fromLocation($path, 'There is no such file.');
try {
$body = $this->client->open($id);
} catch (MediaStorageException $e) {
throw UnableToReadFile::fromLocation($path, $e->getMessage(), $e);
}
$stream = fopen('php://temp', 'r+b');
while (! $body->eof()) {
fwrite($stream, $body->read(1024 * 1024));
}
$body->close();
rewind($stream);
return $stream;
}
public function delete(string $path): void
{
$id = $this->id($path);
if ($id === null) {
return;
}
try {
$this->client->delete($id);
} catch (MediaStorageException $e) {
throw UnableToDeleteFile::atLocation($path, $e->getMessage(), $e);
}
DB::table($this->table())->where('path', $path)->delete();
}
public function deleteDirectory(string $path): void
{
throw UnableToDeleteDirectory::atLocation($path, 'The IriksIT storage has no folders.');
}
public function createDirectory(string $path, Config $config): void
{
throw UnableToCreateDirectory::atLocation($path, 'The IriksIT storage has no folders.');
}
public function setVisibility(string $path, string $visibility): void
{
throw UnableToSetVisibility::atLocation($path, 'The IriksIT storage has no visibility.');
}
public function visibility(string $path): FileAttributes
{
throw UnableToRetrieveMetadata::visibility($path, 'The IriksIT storage has no visibility.');
}
public function mimeType(string $path): FileAttributes
{
$details = $this->details($path, 'mime_type');
return new FileAttributes($path, null, null, null, $details['mime_type'] ?? throw UnableToRetrieveMetadata::mimeType($path));
}
public function lastModified(string $path): FileAttributes
{
$created = $this->details($path, 'last_modified')['created_at'] ?? null;
return new FileAttributes($path, null, null, $created !== null ? strtotime($created) ?: null : throw UnableToRetrieveMetadata::lastModified($path));
}
public function fileSize(string $path): FileAttributes
{
return new FileAttributes($path, $this->details($path, 'file_size')['size']);
}
/** @return iterable<FileAttributes|DirectoryAttributes> */
public function listContents(string $path, bool $deep): iterable
{
return [];
}
public function move(string $source, string $destination, Config $config): void
{
throw UnableToMoveFile::fromLocationTo($source, $destination);
}
public function copy(string $source, string $destination, Config $config): void
{
throw UnableToCopyFile::fromLocationTo($source, $destination);
}
/** @return array{size: int, mime_type: string|null, created_at: string|null} */
private function details(string $path, string $what): array
{
$id = $this->id($path) ?? throw UnableToRetrieveMetadata::create($path, $what, 'There is no such file.');
try {
return $this->client->details($id) ?? throw UnableToRetrieveMetadata::create($path, $what, 'There is no such file.');
} catch (MediaStorageException $e) {
throw UnableToRetrieveMetadata::create($path, $what, $e->getMessage(), $e);
}
}
/** The id the API gave to what was written at this path, or the path itself when it looks like an id. */
private function id(string $path): ?string
{
$id = DB::table($this->table())->where('path', $path)->value('remote_id');
if (is_string($id)) {
return $id;
}
return $path !== '' && ! str_contains($path, '/') ? $path : null;
}
private function table(): string
{
return Names::table('storage_files');
}
}
+250
View File
@@ -0,0 +1,250 @@
<?php
namespace IriksIT\Manager\Support\IriksStorage;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Http;
use IriksIT\Manager\Exceptions\MediaStorageException;
use Psr\Http\Message\StreamInterface;
use Throwable;
/**
* Talks to the IriksIT API (the `/storage` part of it): logs in with an account, keeps the token and the refresh token
* (encrypted) in the cache, renews them, and stores, opens, describes and deletes files. The account needs the
* `storage.read` and `storage.write` permissions. Every failure is a MediaStorageException; what the API says goes into
* its message (never an address, a token or a password).
*/
class Client
{
private const TOKEN = 'manager.iriksit.token';
private const REFRESH = 'manager.iriksit.refresh';
/** @param array{url?: string|null, email?: string|null, password?: string|null, timeout?: int|string|null} $config */
public function __construct(private readonly array $config) {}
/** Whether an address and an account are set at all. */
public function isConfigured(): bool
{
return $this->value('url') !== '' && $this->value('email') !== '' && $this->value('password') !== '';
}
/**
* Store a file. The `id` that comes back is the only handle to it afterwards.
*
* @param resource $stream
* @return array{id: string, size: int, mime_type: string|null, checksum: string|null}
*
* @throws MediaStorageException
*/
public function store($stream, string $filename): array
{
$response = $this->call(fn (PendingRequest $request) => $request->attach('file', $stream, $filename)->post($this->url('/storage'), ['priority' => 'normal']));
$data = $response->json('data');
if ($response->failed() || ! is_array($data) || ! is_string($data['id'] ?? null) || $data['id'] === '') {
throw $this->failure('store a file', $response);
}
return [
'id' => $data['id'],
'size' => is_numeric($data['size'] ?? null) ? (int) $data['size'] : 0,
'mime_type' => is_string($data['mime_type'] ?? null) ? $data['mime_type'] : null,
'checksum' => is_string($data['checksum'] ?? null) ? $data['checksum'] : null,
];
}
/**
* The content of a file as a stream; read it and close it.
*
* @throws MediaStorageException with status 404 when the API does not know the file
*/
public function open(string $id): StreamInterface
{
$response = $this->call(fn (PendingRequest $request) => $request->withOptions(['stream' => true])->get($this->url('/storage/'.rawurlencode($id).'/download')));
if ($response->status() !== 200) {
throw $this->failure('download a file', $response);
}
return $response->toPsrResponse()->getBody();
}
/**
* What the API knows of a file, or null when it does not know it.
*
* @return array{size: int, mime_type: string|null, created_at: string|null}|null
*
* @throws MediaStorageException
*/
public function details(string $id): ?array
{
$response = $this->call(fn (PendingRequest $request) => $request->get($this->url('/storage/'.rawurlencode($id))));
if ($response->status() === 404) {
return null;
}
$data = $response->json('data');
if ($response->failed() || ! is_array($data)) {
throw $this->failure('read a file', $response);
}
return [
'size' => is_numeric($data['size'] ?? null) ? (int) $data['size'] : 0,
'mime_type' => is_string($data['mime_type'] ?? null) ? $data['mime_type'] : null,
'created_at' => is_string($data['created_at'] ?? null) ? $data['created_at'] : null,
];
}
/**
* Delete a file. One the API no longer knows counts as deleted.
*
* @throws MediaStorageException
*/
public function delete(string $id): void
{
$response = $this->call(fn (PendingRequest $request) => $request->delete($this->url('/storage/'.rawurlencode($id))));
if ($response->failed() && $response->status() !== 404) {
throw $this->failure('delete a file', $response);
}
}
/**
* Whether the account can log in at all: the check behind a "test the connection" button.
*
* @throws MediaStorageException
*/
public function check(): void
{
$this->token();
}
/**
* Runs a call with the current token. A 401 means the token was revoked on the API's side: forget it, log in
* again and try once more.
*
* @param \Closure(PendingRequest): Response $call
*
* @throws MediaStorageException
*/
private function call(\Closure $call): Response
{
try {
$response = $call($this->request($this->token()));
if ($response->status() !== 401) {
return $response;
}
Cache::forget(self::TOKEN);
Cache::forget(self::REFRESH);
return $call($this->request($this->token()));
} catch (MediaStorageException $e) {
throw $e;
} catch (Throwable) {
throw new MediaStorageException('The IriksIT storage could not be reached.');
}
}
private function request(string $token): PendingRequest
{
$timeout = $this->config['timeout'] ?? null;
return Http::acceptJson()->withoutRedirecting()->withToken($token)->connectTimeout(5)->timeout(is_numeric($timeout) ? (int) $timeout : 300);
}
/** @throws MediaStorageException */
private function token(): string
{
$token = $this->cached(self::TOKEN);
if ($token !== null) {
return $token;
}
$refresh = $this->cached(self::REFRESH);
if ($refresh !== null) {
$response = Http::acceptJson()->withoutRedirecting()->connectTimeout(5)->timeout(20)->withToken($refresh)->post($this->url('/auth/refresh'));
if ($response->successful() && ($kept = $this->keep($response->json('data'))) !== null) {
return $kept;
}
Cache::forget(self::REFRESH);
}
if (! $this->isConfigured()) {
throw new MediaStorageException('No IriksIT account is set for the storage (address, email and password).');
}
$response = Http::acceptJson()->withoutRedirecting()->connectTimeout(5)->timeout(20)
->post($this->url('/auth/login'), ['email' => $this->value('email'), 'password' => $this->value('password')]);
if ($response->failed()) {
throw new MediaStorageException("The IriksIT login failed (HTTP {$response->status()}).", $response->status());
}
return $this->keep($response->json('data')) ?? throw new MediaStorageException('The IriksIT API sent a login answer without a token.');
}
/** Remembers the tokens of a login answer until they expire (a minute early) and returns the access token. */
private function keep(mixed $data): ?string
{
if (! is_array($data) || ! is_string($data['token'] ?? null) || $data['token'] === '' || ! is_string($data['expire'] ?? null)) {
return null;
}
Cache::put(self::TOKEN, Crypt::encryptString($data['token']), Carbon::parse($data['expire'])->subMinute());
if (is_string($data['refresh_token'] ?? null) && is_string($data['refresh_expire'] ?? null)) {
Cache::put(self::REFRESH, Crypt::encryptString($data['refresh_token']), Carbon::parse($data['refresh_expire'])->subMinute());
}
return $data['token'];
}
private function cached(string $key): ?string
{
$value = Cache::get($key);
try {
return is_string($value) ? Crypt::decryptString($value) : null;
} catch (Throwable) {
return null;
}
}
private function failure(string $action, Response $response): MediaStorageException
{
$reason = $response->json('message');
$detail = is_string($reason) && $reason !== '' ? ': '.mb_substr($reason, 0, 200) : '';
$retry = $response->header('Retry-After');
return new MediaStorageException(
"The IriksIT storage could not {$action} (HTTP {$response->status()}{$detail}).",
$response->status(),
is_numeric($retry) ? (int) $retry : null,
);
}
private function url(string $path): string
{
return rtrim($this->value('url'), '/').$path;
}
private function value(string $key): string
{
$value = $this->config[$key] ?? '';
return is_string($value) ? trim($value) : '';
}
}
+144
View File
@@ -0,0 +1,144 @@
<?php
namespace IriksIT\Manager\Support\Settings;
use IriksIT\Manager\Support\ModuleRegistry;
/**
* What can be set from the settings screen. A definition is keyed by the config path it overrides (`manager.modules.reviews`)
* and has: `label`, `type` (toggle, text, url, number, select, secret), `group`, optional `help`, `options` (select: value => label),
* `env` (the .env variable that is written along when the site allows it) and `permission` (a right on top of `settings.manage`).
* A secret is never sent back to a browser.
*
* They come from three places: the parts of the manager, the integrations the package knows (Turnstile, the IriksIT API) and
* the site itself (`manager.settings.definitions`, and `settings()` of a module of its own). Nothing else can be set: a key that
* is not defined is refused, so the screen can never write an arbitrary setting or .env line.
*/
class Definitions
{
public const TYPES = ['toggle', 'text', 'url', 'number', 'select', 'secret'];
public function __construct(private readonly ModuleRegistry $modules) {}
/** @return array<string, array<string, mixed>> keyed by config path */
public function all(): array
{
$all = [];
foreach ([...$this->parts(), ...$this->integrations(), ...$this->fromModules(), ...(array) config('manager.settings.definitions', [])] as $key => $definition) {
$key = is_string($key) ? $key : (string) ($definition['config'] ?? '');
$definition = $this->normalise($key, (array) $definition);
if ($definition !== null) {
$all[$key] = $definition;
}
}
return $all;
}
/**
* Turns what was typed into the value of the setting, or says it is no good.
*
* @param array<string, mixed> $definition
*
* @throws \InvalidArgumentException
*/
public function cast(array $definition, mixed $raw): mixed
{
$bad = fn () => throw new \InvalidArgumentException('This value is not valid.');
return match ($definition['type']) {
'toggle' => is_bool($raw) || in_array($raw, [0, 1, '0', '1', 'true', 'false'], true) ? filter_var($raw, FILTER_VALIDATE_BOOLEAN) : $bad(),
'number' => is_numeric($raw) ? $raw + 0 : $bad(),
'select' => is_string($raw) && array_key_exists($raw, $definition['options']) ? $raw : $bad(),
'url' => is_string($raw) && mb_strlen($raw) <= 500 && preg_match('#^https?://[^\s<>"\']+$#i', $raw) === 1 ? $raw : $bad(),
default => is_string($raw) && mb_strlen($raw) <= 1000 && preg_match('/[\r\n\0]/', $raw) !== 1 ? trim($raw) : $bad(),
};
}
/** @return array<string, mixed>|null */
public function find(string $key): ?array
{
return $this->all()[$key] ?? null;
}
/** @return array<string, array<string, mixed>> */
private function parts(): array
{
$parts = [];
foreach ($this->modules->all() as $module) {
// Users and media are the core: without them there is no manager.
if (in_array($module->key(), ['users', 'media', 'settings'], true)) {
continue;
}
$parts['manager.modules.'.$module->key()] = [
'label' => $module->label(),
'type' => 'toggle',
'group' => 'Parts of the manager',
'env' => 'MANAGER_'.strtoupper($module->key()),
];
}
return $parts;
}
/** @return array<string, array<string, mixed>> */
private function integrations(): array
{
$disks = array_keys((array) config('filesystems.disks', []));
return [
'manager.media.disk' => ['label' => 'Disk for new media files', 'type' => 'select', 'group' => 'Media', 'sensitive' => true, 'options' => array_combine($disks, $disks), 'env' => 'MANAGER_MEDIA_DISK'],
'manager.media.iriksit.url' => ['label' => 'IriksIT API: address', 'type' => 'url', 'group' => 'IriksIT API', 'sensitive' => true, 'help' => 'With its version, for example https://api.iriks-it.nl/v1', 'env' => 'MANAGER_IRIKSIT_URL'],
'manager.media.iriksit.email' => ['label' => 'IriksIT API: account', 'type' => 'text', 'group' => 'IriksIT API', 'sensitive' => true, 'env' => 'MANAGER_IRIKSIT_EMAIL'],
'manager.media.iriksit.password' => ['label' => 'IriksIT API: password', 'type' => 'secret', 'group' => 'IriksIT API', 'env' => 'MANAGER_IRIKSIT_PASSWORD'],
'manager.login.turnstile.site_key' => ['label' => 'Turnstile: site key', 'type' => 'text', 'group' => 'Login', 'sensitive' => true, 'env' => 'MANAGER_TURNSTILE_SITE_KEY'],
'manager.login.turnstile.secret' => ['label' => 'Turnstile: secret key', 'type' => 'secret', 'group' => 'Login', 'env' => 'MANAGER_TURNSTILE_SECRET'],
];
}
/** @return array<string, array<string, mixed>> */
private function fromModules(): array
{
$found = [];
foreach ($this->modules->active() as $module) {
if (method_exists($module, 'settings')) {
foreach ((array) $module->settings() as $key => $definition) {
$found[$key] = $definition;
}
}
}
return $found;
}
/** @return array<string, mixed>|null null when the definition is no good: it is left out, never half used */
private function normalise(string $key, array $definition): ?array
{
$type = $definition['type'] ?? 'text';
if (preg_match('/^[a-z][a-z0-9_]*(\.[a-zA-Z0-9_-]+)+$/', $key) !== 1 || ! in_array($type, self::TYPES, true) || ! is_string($definition['label'] ?? null)) {
return null;
}
$env = $definition['env'] ?? null;
return [
'key' => $key,
'config' => $key,
'label' => $definition['label'],
'type' => $type,
'group' => is_string($definition['group'] ?? null) ? $definition['group'] : 'Site',
'help' => is_string($definition['help'] ?? null) ? $definition['help'] : null,
'options' => $type === 'select' ? (array) ($definition['options'] ?? []) : [],
'env' => is_string($env) && preg_match('/^[A-Z][A-Z0-9_]*$/', $env) === 1 ? $env : null,
'permission' => is_string($definition['permission'] ?? null) ? $definition['permission'] : null,
// What can send a password or a file somewhere else (an address, an account, a disk) needs the right for secrets too, and the password of whoever saves it.
'sensitive' => $type === 'secret' || (bool) ($definition['sensitive'] ?? false),
];
}
}
+101
View File
@@ -0,0 +1,101 @@
<?php
namespace IriksIT\Manager\Support\Settings;
/**
* Writes variables into the .env file of the app, when the site allows it (`manager.settings.write_env`) and the file may be
* written. Only variables that a definition names are ever written, and a value that could break the file (a line break, a
* null byte) is refused. The file is rewritten as a whole: the old one is kept as `.env.manager-backup`, the new one is
* written next to it and moved over in one step, with the permissions of the old one.
*/
class EnvFile
{
public function __construct(private readonly ?string $path = null) {}
public function path(): string
{
return $this->path ?? app()->environmentFilePath();
}
public function writable(): bool
{
return is_file($this->path()) && is_writable($this->path()) && is_writable(dirname($this->path()));
}
/**
* @param array<string, string|int|float|bool|null> $pairs variable => value (null removes nothing: the line is left alone)
*/
public function set(array $pairs): bool
{
$pairs = array_filter($pairs, fn ($value) => $value !== null);
if ($pairs === [] || ! $this->writable()) {
return false;
}
foreach ($pairs as $name => $value) {
if (preg_match('/^[A-Z][A-Z0-9_]*$/', (string) $name) !== 1 || preg_match('/[\r\n\0]/', (string) $this->text($value)) === 1) {
return false;
}
}
$lock = fopen($this->path().'.manager-lock', 'c');
if ($lock === false || ! flock($lock, LOCK_EX)) {
return false;
}
try {
$old = (string) file_get_contents($this->path());
$lines = preg_split('/\R/', $old) ?: [];
$left = $pairs;
foreach ($lines as $i => $line) {
if (preg_match('/^\s*([A-Z][A-Z0-9_]*)\s*=/', $line, $found) === 1 && array_key_exists($found[1], $left)) {
$lines[$i] = $found[1].'='.$this->quote($left[$found[1]]);
unset($left[$found[1]]);
}
}
foreach ($left as $name => $value) {
$lines[] = $name.'='.$this->quote($value);
}
$new = rtrim(implode("\n", $lines), "\n")."\n";
$temporary = $this->path().'.'.bin2hex(random_bytes(4)).'.tmp';
if (@copy($this->path(), $this->path().'.manager-backup') === false || @file_put_contents($temporary, $new) === false) {
return false;
}
@chmod($temporary, fileperms($this->path()) & 0777);
if (! @rename($temporary, $this->path())) {
@unlink($temporary);
return false;
}
return true;
} finally {
flock($lock, LOCK_UN);
fclose($lock);
}
}
private function text(mixed $value): string
{
return is_bool($value) ? ($value ? 'true' : 'false') : (string) $value;
}
private function quote(mixed $value): string
{
$text = $this->text($value);
if (preg_match('/^[A-Za-z0-9_.:\/@+,-]*$/', $text) === 1) {
return $text;
}
return '"'.str_replace(['\\', '"', '$'], ['\\\\', '\\"', '\\$'], $text).'"';
}
}
+114
View File
@@ -0,0 +1,114 @@
<?php
namespace IriksIT\Manager\Support\Settings;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use IriksIT\Manager\Support\Names;
use Throwable;
/**
* What was set from the settings screen. The table is the truth (with a history of who and when); every change also writes
* one compiled file (`bootstrap/cache/manager-settings.php`, secrets in it stay encrypted) that is laid over the config
* while the app starts, so a request reads one file from opcache and never asks the database. That works with `config:cache`
* too, because it is applied after the config was loaded. Without the file (it could not be written) the table is read once.
*/
class Store
{
public function __construct(private readonly Definitions $definitions) {}
public static function file(): string
{
return app()->bootstrapPath('cache/manager-settings.php');
}
/** Lays the saved settings over the config. Called while the provider registers; it must never fail the app. */
public static function overlay(): void
{
try {
$values = is_file(self::file()) ? (array) (include self::file()) : self::fromTable();
foreach ($values as $key => $value) {
if (is_array($value) && array_key_exists('__enc', $value)) {
$value = json_decode(Crypt::decryptString((string) $value['__enc']), true);
}
config([$key => $value]);
}
} catch (Throwable) {
// A missing table (before the first migrate), a changed APP_KEY, a broken file: the config keeps what it had.
}
}
/** @return array<string, mixed> */
private static function fromTable(): array
{
$values = [];
foreach (DB::table(Names::table('settings'))->get() as $row) {
$values[$row->key] = $row->is_secret ? ['__enc' => $row->value] : json_decode((string) $row->value, true);
}
return $values;
}
/**
* Saves values (null: back to what the config says) and rewrites the compiled file. Returns whether that file could be written.
*
* @param array<string, mixed> $values by config path, already checked against the definitions
*/
public function put(array $values, mixed $userId = null): bool
{
$table = Names::table('settings');
DB::transaction(function () use ($values, $table, $userId) {
foreach ($values as $key => $value) {
$definition = $this->definitions->find($key);
if ($value === null || $definition === null) {
DB::table($table)->where('key', $key)->delete();
continue;
}
$secret = $definition['type'] === 'secret';
$stored = $secret ? Crypt::encryptString(json_encode($value)) : json_encode($value);
DB::table($table)->updateOrInsert(['key' => $key], ['value' => $stored, 'is_secret' => $secret, 'updated_by' => $userId, 'updated_at' => now(), 'created_at' => now()]);
}
});
return $this->compile();
}
/** Writes the compiled file from the table: to a temporary file first, then moved over the old one in one step. */
public function compile(): bool
{
$known = $this->definitions->all();
$values = array_filter(self::fromTable(), fn ($value, $key) => isset($known[$key]), ARRAY_FILTER_USE_BOTH);
$file = self::file();
$temporary = $file.'.'.bin2hex(random_bytes(4)).'.tmp';
try {
if (@file_put_contents($temporary, '<?php return '.var_export($values, true).';'.PHP_EOL, LOCK_EX) === false || ! @rename($temporary, $file)) {
@unlink($temporary);
return false;
}
} catch (Throwable) {
@unlink($temporary);
return false;
}
function_exists('opcache_invalidate') && @opcache_invalidate($file, true);
return true;
}
/** Whether a setting has been saved here (and so wins over .env). */
public function has(string $key): bool
{
return DB::table(Names::table('settings'))->where('key', $key)->exists();
}
}
+77
View File
@@ -0,0 +1,77 @@
<?php
namespace IriksIT\Manager\Support\Settings;
use Illuminate\Support\Facades\Artisan;
use Throwable;
/** Saves changes to settings: the table and the compiled file, the config of this request, and `.env` when the site allows it. */
class Writer
{
public function __construct(private readonly Definitions $definitions, private readonly Store $store, private readonly EnvFile $env) {}
/**
* @param array<string, mixed> $changes config path => value; null puts the setting back to what the config says
* @return array{file_written: bool, env_written: bool}
*/
public function apply(array $changes, mixed $userId = null): array
{
if ($changes === []) {
return ['file_written' => true, 'env_written' => false];
}
$written = $this->store->put($changes, $userId);
foreach ($changes as $key => $value) {
config([$key => $value ?? config($key)]);
}
return ['file_written' => $written, 'env_written' => $this->writeEnv($changes)];
}
/** Writes the compiled file again and empties what caches the old values. */
public function refresh(): bool
{
$written = $this->store->compile();
function_exists('opcache_reset') && @opcache_reset();
$this->recache();
return $written;
}
/** @param array<string, mixed> $changes */
private function writeEnv(array $changes): bool
{
if (! config('manager.settings.write_env')) {
return false;
}
$pairs = [];
foreach ($changes as $key => $value) {
$env = $this->definitions->find($key)['env'] ?? null;
if ($env !== null && $value !== null) {
$pairs[$env] = $value;
}
}
$done = $this->env->set($pairs);
$done && $this->recache();
return $done;
}
private function recache(): void
{
if (! app()->configurationIsCached()) {
return;
}
try {
Artisan::call('config:cache');
} catch (Throwable) {
// The overlay still applies on top of a config cache that is a bit old.
}
}
}
+6
View File
@@ -27,6 +27,10 @@ class Shell
)); ));
$navigation = $this->menu->for($user, $allowed); $navigation = $this->menu->for($user, $allowed);
$base = '/'.trim((string) config('manager.path'), '/');
$primary = $user !== null && method_exists($user, 'managerPrimaryGroup') ? $user->managerPrimaryGroup() : null;
// The start screen of the primary group, when this account has it in its menu.
$start = $primary?->start !== null && in_array($base.$primary->start, array_column($navigation, 'href'), true) ? $base.$primary->start : null;
$extensions = array_values(array_filter( $extensions = array_values(array_filter(
(array) config('manager.extensions', []), (array) config('manager.extensions', []),
@@ -47,7 +51,9 @@ class Shell
'name' => (string) ($user->name ?? ''), 'name' => (string) ($user->name ?? ''),
'email' => (string) ($user->email ?? ''), 'email' => (string) ($user->email ?? ''),
'is_super_admin' => method_exists($user, 'isManagerSuperAdmin') && $user->isManagerSuperAdmin(), 'is_super_admin' => method_exists($user, 'isManagerSuperAdmin') && $user->isManagerSuperAdmin(),
'group' => $primary?->name,
], ],
'start' => $start,
'permissions' => $allowed, 'permissions' => $allowed,
'navigation' => $navigation, 'navigation' => $navigation,
'extensions' => $user === null ? [] : $extensions, 'extensions' => $user === null ? [] : $extensions,