diff --git a/.agents/skills/frontend-design/LICENSE.txt b/.agents/skills/frontend-design/LICENSE.txt new file mode 100644 index 0000000..f433b1a --- /dev/null +++ b/.agents/skills/frontend-design/LICENSE.txt @@ -0,0 +1,177 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/.agents/skills/frontend-design/SKILL.md b/.agents/skills/frontend-design/SKILL.md new file mode 100644 index 0000000..a533345 --- /dev/null +++ b/.agents/skills/frontend-design/SKILL.md @@ -0,0 +1,71 @@ +--- +name: frontend-design +description: Guidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making choices that don't read as templated defaults. +license: Complete terms in LICENSE.txt +--- + +# Frontend Design + +Approach this as the design lead at a design studio known for giving every client a distinct visual identity that is not mistaken for anyone else's. This client has already rejected proposals that felt cliché or templated, and is paying for a distinctive point of view: make deliberate, opinionated choices about palette, typography, and layout that are specific to this brief, and take aesthetic risk if justified. + +## Ground your designs in the subject matter + +If the brief does not identify what the product or subject matter is, identify it yourself before designing, and confirm with the client. You can come up with one concrete subject, the design's audience, and the design's primary job, as a proposal. If there's any information in your memory about the client's preferences or context about what they're building, use that as a hint. The subject's industry, subject matter, materials, and vernacular are where distinctive visual choices come from — a design for a toy for girls aged 8–11 will be very aesthetically different from a dashboard for financial analysts. Build with the brief's real content and subject matter throughout. + +## Design principles + +For web designs, the hero is the first thing viewers will see. Open with the most characteristic thing in the subject's world, in the form that is most appropriate: a headline, an image, an animation, a live demo, an interactive moment, or other treatments. Be deliberate with your choice: a big number with a small label, supporting stats, and a gradient accent is the default treatment, so only use it if that's truly the best option. + +Typography carries the personality of the page. You don't need a different typeface for display or headline text and body content: use one family or two, and if two, make them clearly distinct. + +Choose your typefaces deliberately, not the default families you would reach for on any other project, and set a clear type scale following the default guidance of The Elements of Typographic Style with intentional weights, widths, and spacing. When type is used as a headline or visual element, use the type treatment itself as an active part of the design, not a neutral delivery vehicle for the content. + +Default to line lengths of less than 80 characters. Serif typefaces can have slightly longer line lengths; give serif body text slightly more line-height than a sans-serif. + +Avoid these default typographic treatments; they are the commonest tells of a generated page: +- Accenting just a single word or phrase in a headline, like putting one word in italic/bold or a different color. +- Using all caps for labels. +- Adding unnecessary typographic labels above content. + +Visual structure is information. Structural devices like outlines, borders, numbering, eyebrows, dividers, labels, etc., encode useful information about the content rather than decorate it. Many generic designs use numbered markers (01 / 02 / 03), but that's only appropriate if the content actually is a sequence — like a stepped process or a timeline. Before adding numbered markers, check the content really is a sequence. + +Use non-user-triggered motion sparingly and deliberately, only to draw attention. A single orchestrated moment — one page-load sequence or one reveal — lands better than scattered effects; fade-and-slide-up entrances on each section and hover transitions on every card are the generic default and read as AI-generated. Motion that answers a person's action (opening, expanding, confirming) is welcome when it shows what changed. + +Consider written content carefully. Often a design brief may not contain real content, and it's up to you to come up with copy and placeholder content. Copy can make a design feel as templated as the design itself. See the below section on writing for more guidance. + +## Process: plan, review against the brief, build, critique + +For calibration, AI-generated design right now clusters around some traits: +1. a warm cream background (near #F4F1EA) with a high-contrast serif display and a terracotta or warm-clay accent (often near #D97757 — Anthropic's own Claude-interaction accent, so on a user's brief it reads as a tell); +2. a near-black background with a single bright acid-green or vermilion accent; +3. a broadsheet-style layout with hairline rules, zero border-radius, and dense newspaper-like columns; +4. the SaaS-card kit: content chopped into identical rounded cards, one border-radius on everything regardless of hierarchy, the same soft grey shadow (rgba(0,0,0,.1)) under each, and gradient washes as decoration; +5. template chrome that appears whatever the subject: a tracked-out ALL-CAPS eyebrow label above every heading; meta strings joined with middle dots ('A · B · C'); labels built as 'WORD — fragment' with a spaced em dash; tinted near-black (#0B0B0B, #111) standing in for black; a monospace face for small data labels; a '→' appended to link and button text. + +All traits are legitimate for some briefs, but they are defaults rather than choices, and they appear regardless of subject. Where the brief pins down a visual direction, follow it exactly — the brief's own words always win, including when it asks for one of these looks. Where it leaves an axis free, don't spend that freedom on one of these defaults. As with a hired human designer, there's often a careful balance between doing what you're good at and taking each project as a chance to experiment and learn. + +Work in two passes. First, brainstorm a short design plan based on the client's design brief: create a compact token system with color, type, layout, and principles. +- Color: describe the core base palette as 4–6 named hex values. +- Type: the typefaces and their roles. +- Layout: a layout concept, using one-sentence prose descriptions and ASCII wireframes to ideate and compare. Include alignment guidance; should the content be left aligned, center aligned, justified? +- Principles: the high-level guidance for what makes this page unique. + +Then review that plan against the brief before building: if any part of it reads like the generic default you would produce for any similar page (work through a similar prompt to see if you arrive somewhere similar) rather than a choice made for this specific brief — revise that part, say what you changed and why. Only after you've confirmed the relative uniqueness of your design plan should you start to write the code, following the revised plan. + +When writing the code, be careful of structuring your CSS selector specificities. It's easy to generate CSS classes that cancel each other out (especially with a type-based selector like .section and an element-based selector like .cta). This can happen often with padding/margin between sections. + +## Restraint and self-critique + +Spend your boldness in one place. Let one element be the memorable thing, keep everything around it quiet and disciplined, and cut any decoration that does not serve the brief. Build to a quality floor without announcing it: responsive down to mobile, visible keyboard focus, reduced motion respected, visually accessible, harmonious color palettes. Critique your own work as you build, taking screenshots to review if your environment supports it — a picture is worth 1000 tokens. Consider Chanel's advice: before leaving the house, take a look in the mirror and remove one accessory. Human creatives have memory and always try to do something new, so if you have a space to quickly jot down notes about what you've tried, it can help you in future passes. + +## More on writing in design + +Words appear in a design for one reason: to make it easier to understand and use. They are design content, not decoration. Bring the same intentionality and minimalism to copywriting that you would bring to spacing and color. Before writing anything, ask what the design needs to say, and how it can best be said to help the person navigate the experience. + +Write from the end user's perspective. Name things by what users will understand in simple language, not by how the system is built. A user manages notifications, not webhook config. Describe what something is or does in plain terms rather than selling it. Being specific and legible to new users is always better than being clever. + +Use active voice as default. A CTA says exactly what happens when it is used: "Save changes," not "Submit." An action keeps the same name through the whole flow, so the button that says "Publish" produces a toast that says "Published." The vocabulary of an interface is the signposting for someone navigating the product. Cohesion and consistency are how people learn their way around. + +Treat failure and emptiness as moments for direction, not mood. Explain what went wrong and how to fix it, in the interface's voice rather than a person's. Errors don't apologize, and they are never vague about what happened. An empty screen is an invitation to act. + +Keep the tone conversational: plain verbs, sentence case, no filler, with tone matched to the brand and the audience. Let each written element do exactly one job. diff --git a/.agents/skills/testsprite-onboard/SKILL.md b/.agents/skills/testsprite-onboard/SKILL.md new file mode 100644 index 0000000..c4dd1a3 --- /dev/null +++ b/.agents/skills/testsprite-onboard/SKILL.md @@ -0,0 +1,252 @@ +--- +name: testsprite-onboard +description: Stand up a complete, runnable TestSprite test suite for the current repo at first use — create a project (with a target URL and auth), derive a coherent set of tests from the codebase, batch-create them, and smoke-run a few to a green verdict so the user immediately has something worth running. Use ONLY when a repo has no TestSprite tests yet (a fresh project), right after `testsprite setup`, or when the user asks to "set up / bootstrap / seed tests". This is first-run setup, NOT change verification — once a project already has tests, use the testsprite-verify skill instead. +--- + + + + +# TestSprite: onboard a repo with a seed test suite + +Your job is to take a repo that has **no TestSprite tests yet** and leave it with a +**coherent, runnable suite** plus a couple of **already-green** smoke tests — in one pass. +A new user who can immediately run a real, passing test is an activated user; an empty +project is the #1 drop-off. + +This skill only uses shipped CLI commands. Do **not** call backend APIs directly. + +Step 3 offers two paths to a suite, tried in order: let TestSprite **generate** the tests +(fastest; needs a V3-platform account and a recent CLI), or **author** them by hand +(always works). Everything else here is identical either way. + +## When to use + +- Right after `testsprite setup`, or any time the active project has 0–1 tests. +- The user says "set up tests", "bootstrap", "seed a suite", "get me started", or similar. + +## When NOT to use + +- The project already has tests — that's the `testsprite-verify` skill's job, not this one. +- The user only changed code and wants it checked — again, `testsprite-verify`. + +## Prerequisites + +`testsprite setup` has run (an API key is configured). If `testsprite project list` errors on +auth, stop and tell the user to run `testsprite setup` first — don't try to configure for them. + +## Steps + +### 1. Understand the app (don't skip — this is where coverage quality comes from) + +Read the repo to establish, concretely: + +- **Frontend**: the deployed/local **URL**, the 4–8 most important user flows (auth, core + CRUD, checkout, search, settings…), and whether flows need **login**. +- **Backend**: the key **API endpoints** and their success/error contracts. + +Prefer **code-derived** routes/handlers over guessing — you have the source; use it. This +beats a blind crawl. + +### 2. Create the project (FE must have a URL) + +Frontend: + +```bash +testsprite project create --type frontend --name "" --url \ + [--username --password-file ] +``` + +Backend: + +```bash +testsprite project create --type backend --name "" +``` + +Capture the returned `projectId`. + +> **Critical for FE**: a frontend test with no resolvable target URL fails immediately with +> `No environment URL configured` — the suite goes all-red. Always pass `--url`. If flows need +> login, pass `--username/--password-file` now so authenticated pages are reachable. + +#### 2b. FE: register the app's test-hook attribute + +If the source tags elements with something other than `data-testid` (e.g. `data-element`), +run `testsprite project update --test-id-attributes data-element,data-testid` +once; exported locators then use the tag (check: `project get` → `testIdAttrs:`). + +### 3. Get the tests — try generation first, author by hand if it isn't available + +#### 3a. Preferred: generate → review → accept + +TestSprite proposes the cases; proposals stage **on the server** (nothing lands in the +repo) and you accept the ones worth keeping. + +**API projects need an API spec first** — with none, generation stops at +`no_processed_inputs`. Upload the spec (the file is only read). A PRD is optional and goes +**alongside** the spec, not instead of it: endpoints are read from the spec, and the PRD +shapes the feature map (`--role prd`, 0.5 credits). A PRD alone can charge the strategy +stage and then fail with no endpoints found. Frontend projects skip this, since exploring +the live app creates their inputs. + +```bash +testsprite project docs upload ./openapi.yaml --project --role api-doc +testsprite project docs upload ./prd.md --project --role prd # optional, with the spec +``` + +```bash +testsprite test plan generate --project +``` + +It runs only the stages the project is missing and prints proposals with stable ids. A +fresh frontend project takes minutes (browser agents visit the app) — that's normal; +Ctrl-C only detaches, the work continues. If it says inputs are still processing, wait +and re-run. + +**Review the table before accepting — that's the quality gate, and it's your job.** Check +titles and steps against what you learned in step 1; drop anything testing a flow the repo +doesn't have, duplicating another, or asserting something vague. + +```bash +testsprite test plan accept --project # all of them +testsprite test plan accept --project --only prop_2 prop_5 # or a subset +``` + +A subset accept **discards the rest**, so name every proposal you want in that one call. +Then `testsprite test list --project ` for the ids, and go to step 5 +(**skip step 4** — that's the hand-authoring path). + +**If generation isn't available, fall back to 3b — don't stall.** That means an unknown +`test plan generate` command (older CLI), an account not on the V3 platform (exit 6), or +no reachable URL and no source to read. Say which happened, then author the tests +yourself; don't ask the user to upgrade or migrate first. + +#### 3b. Fallback: author the tests by hand (quality over quantity) + +**Frontend** — one JSON plan file per flow, in a directory (e.g. `./testsprite-plans/`). +Each file is a COMPLETE plan and must include `projectId` (from step 2), `type: "frontend"`, +`name`, and `planSteps` — `create-batch` reads the project from each file, not from a flag: + +```json +{ + "projectId": "", + "type": "frontend", + "name": "Checkout — guest can complete a purchase", + "planSteps": [ + { "type": "action", "description": "Navigate to /products and open the first product" }, + { "type": "action", "description": "Click 'Add to cart', then go to /cart" }, + { + "type": "assertion", + "description": "The cart shows exactly 1 line item with the product's name and price" + }, + { "type": "action", "description": "Proceed to checkout as guest and submit the test payment" }, + { "type": "assertion", "description": "A confirmation page appears showing an order number" } + ] +} +``` + +**Backend** — one `.py` file per endpoint, using `requests` with concrete assertions on +status code and response body. + +**Backend auth — read the injected `__AUTH_HEADERS__`, NEVER hardcode any credential.** This +covers **every** secret the API needs — Bearer/JWT tokens **and** API keys (`sk-…`, +`x-api-key`), basic-auth blobs, cookies. TestSprite prepends a managed credential block +(`__AUTH_CREDENTIAL__` / `__AUTH_TYPE__` / `__AUTH_HEADERS__`) to every backend test from the +project's Authentication settings, and `__AUTH_HEADERS__` already holds the right header(s) for +the configured type (Bearer → `{"Authorization": "Bearer …"}`; API key → `{"X-API-Key": "…"}`; +basic → `{"Authorization": "Basic …"}`). Spread it into your request headers — never paste a +literal `Bearer …` / `sk-…` / key value into the script: + +```python +r = requests.get(f"{TARGET_URL}/orders", headers={**__AUTH_HEADERS__}) +``` + +Configure the credential once on the project (ask the user for the value — never invent it or +reuse a key you happened to see): a static credential with +`testsprite project credential --type "Bearer token"|"API key"|"basic token" --credential `, +or an auto-refreshing login with `testsprite project auto-auth …` so scheduled/repeat +runs keep working after the token expires. A hardcoded token expires within hours and a hardcoded +key can't be rotated centrally — `test create` emits a `[warn]` on an inlined credential; treat it +as a must-fix. + +**Assertion rule (this is the whole game for FE):** every `assertion` step must name a +**concrete, observable** outcome — an element, text, URL, count, or status. Never write +`"verify it works"`, `"check the page loads"`, or other narrative that an AI judge can +rubber-stamp. Vague assertions are how false-PASS sneaks in. + +Aim for ~8–15 tests covering the core flows. Don't pad. + +### 4. Batch-create (hand-authored path only — skip if you accepted generated proposals) + +Frontend (one call, up to 50 plans from the directory — `create-batch` is FE-only and has +**no `--project` flag**; the project comes from each plan file's `projectId`): + +```bash +testsprite test create-batch --plan-from-dir ./testsprite-plans +``` + +Backend (one call per file — `create-batch` is FE-only; `--name` is required): + +```bash +testsprite test create --type backend --name "" \ + --code-file ./tests/.py --project +``` + +Capture the created `testId`s from the output. + +### 5. Smoke-run a few — NOT all (protect credits) + +Pick the **2–3 highest-value happy-path** tests (prefer ones you're most confident are green) +and run only those: + +```bash +testsprite test run --wait +``` + +Do **not** run the whole suite automatically — a 20-test FE suite is ~40 credits and a free +account only has 150. Running the full suite is the user's explicit choice. + +### 6. Report + +Tell the user, plainly: + +- "Your project now has **N** tests covering: ." +- "I smoke-ran **M** — here's the result: ." +- "To run the rest (≈X credits — state the cost so they choose knowingly): + - frontend — run each remaining test by id: `testsprite test run --wait` (there is + **no `--all` for frontend**); + - backend — `testsprite test run --all --project ` (wave-ordered, runs every BE test)." + +## Quality checklist (self-check before reporting done) + +- [ ] FE project has a real `--url`; login configured if the app needs it. +- [ ] API project: an API spec uploaded before generating (a PRD is optional, alongside it) — or you used path 3b. +- [ ] If you generated: you **read the proposals** and dropped the ones that don't fit, + rather than accepting the batch unseen. +- [ ] Every FE assertion names a concrete, observable outcome (no "verify it works"). +- [ ] Tests cover the core flows you found in the code, not just one page. +- [ ] Smoke-ran 2–3 happy-path tests, not the whole suite. +- [ ] Reported test count, smoke result + dashboard link, and the cost to run the rest. + +## Don'ts + +- Don't auto-run the full suite (credit wall / surprise 402). +- Don't write narrative assertions an AI judge can't fail. +- Don't call backend endpoints directly — only the `testsprite` CLI. +- Don't create a FE project without a URL. +- Don't re-seed a project that already has tests — that's not this skill's job. +- Don't accept a generated batch unread — reviewing it is the point of the staging step. +- Don't stall when generation isn't available — say so and hand-author instead. +- Don't re-run `test plan generate` hoping for a different batch: with proposals already + staged it starts nothing, and regenerating is a Portal action today. + +## Hand off to verify + +This skill's job ends once the project has a seeded suite and a first green run. From here on, +the **`testsprite-verify`** skill takes over: after the user changes code, it runs the tests +covering that change before they report the work done. Onboard once; verify continuously. + diff --git a/.agents/skills/testsprite-verify/SKILL.md b/.agents/skills/testsprite-verify/SKILL.md new file mode 100644 index 0000000..90b2f55 --- /dev/null +++ b/.agents/skills/testsprite-verify/SKILL.md @@ -0,0 +1,505 @@ +--- +name: testsprite-verify +description: TestSprite verification loop — after finishing a feature or fix in a TestSprite-tested repo, use the `testsprite` CLI to run the relevant TestSprite tests against the change and inspect any failure artifacts before reporting the work as done. Use whenever code has changed outside docs/config and is about to be reported complete — by running an existing test that covers the change, or by creating a new TestSprite test (a frontend plan, or a backend Python assertion) and running it to a terminal verdict. +--- + + +# TestSprite Verification Loop + +The verification loop that flies your just-shipped feature through the +TestSprite CLI and reports back. + +You just finished a piece of work in a TestSprite-tested repo. Before you report +it done, **actually run the relevant TestSprite test(s)** through the `testsprite` +CLI and read the result. Spec review and unit tests catch correctness; only +running the test catches what breaks for a real user. + +## When to run + +Run after a feature or fix lands — one feature → one test run, at the moment it +lands, not batched at the end. Tests you create this way accumulate into the +project's TestSprite suite; before writing a new one, check `testsprite test list` +for an existing test that already covers the behavior and extend it instead of +duplicating. + +The CLI tests either a **deployed** URL or a frontend test running on this +machine — it doesn't build or host your environment either way. For a deployed +change, wait until it's live somewhere reachable (e.g. open the PR, let CI +deploy the preview/staging environment) and pass that URL as `--target-url`. +Running earlier verifies the previous build, not your change. + +For a change that is only running locally, don't wait for a deployment: run +`testsprite test run --local ` instead. It tunnels this +machine's own loopback address (`localhost` / `127.0.0.1` / `::1` — not a LAN +or RFC1918 address, and not a general local-network escape hatch) to the test +runner. Two constraints: frontend tests only (a backend test's target is baked +into its generated code, so run it normally), and it needs an API key with the +`run:tunnel` scope — a 403 there means mint a new key. + +If the user explicitly named a tool (the CLI or the MCP), honor that choice +regardless of which one the change's reachability would otherwise suggest. + +## When to skip + +The skip list is narrow: + +- Docs-only edits (`docs/**`, `*.md`, comments). +- Pure build/config edits (`tsconfig*`, lint/prettier config, lockfile bumps with + no behavior change). +- This repo isn't actually wired to TestSprite (no project linked, no creds). + Don't pull the user into a setup flow they didn't ask for — say so and stop. + +Otherwise, run it. + +## The one-test minimum + +Every shipped feature gets **at least one** TestSprite run to a terminal verdict +(`passed` / `failed` / `blocked` / `inconclusive`) before you call it done. What +counts: + +- `testsprite test create … --run --wait` returning a terminal verdict, **or** +- `testsprite test run --wait` against an existing test, **or** +- `testsprite test create-batch --plans plans.jsonl --run --wait` (or + two-step: create-batch, then `test run --wait`) on at least one + test returning a terminal verdict. + +What does **not** count: unit tests / typecheck / lint; drafting a plan without +`--run`; asking the user to run it for you. + +If the project has **no tests at all**, that's the `testsprite-onboard` skill's +job, not this one — seed a suite first (it can generate the proposals for you +with `testsprite test plan generate` / `test plan accept`, or author them by +hand). Seeding is a deliberate setup pass, not part of the verify loop. + +If you can't satisfy this — no creds, no valid target URL, repo not linked — +**say so explicitly**: "Feature shipped but I could not run any TestSprite test +because . Treat this as unverified until that's resolved." Don't claim done. + +## 1. Preflight + +```bash +testsprite --version # CLI installed? +testsprite auth status # credentials configured? +``` + +- `--version` fails → the CLI isn't installed. Tell the user to install the + TestSprite CLI (see the TestSprite docs) and stop; don't install it for them. +- `auth status` fails → no credentials. Tell the user they can run + `testsprite setup`, then stop. + +## 2. Find the project + +In priority order: + +1. `$TESTSPRITE_PROJECT_ID` if set. +2. `.testsprite/config.json` in the repo root, if it has a `projectId`. +3. `testsprite project list --output json` → match a project whose `name` looks + like this repo (e.g. a `Portal` repo → the `Portal` project). +4. Still ambiguous → list the candidates and ask the user which to use (one short + question; picking the wrong project wastes a run). + +## 3. Decide what to test + +Look at the diff (`git diff --stat`, then the changed files) to understand what +user-facing behavior changed. Pick one sub-mode. For a brand-new feature the +right default is almost always (b) or (c); (a) is for tweaks to behavior an +existing test already covers. + +### (a) An existing test covers the change + +```bash +testsprite test list --project --output json +testsprite test list --project --status failed --output json # what's already red +``` + +Heuristic: a change to `src/components/CheckoutForm.tsx` is more likely covered +by "Checkout happy path" than "Login flow." Frontend change → `type: frontend`; +backend → `type: backend`. + +### (b) A new test for the change (most common) + +**Frontend — draft a `plan.json`.** You name the behavior and list steps in plain +language; you don't write browser code. + +```jsonc +{ + "projectId": "prj_abc", + "type": "frontend", + "name": "Booking date range change updates the estimated total", + "description": "When a user opens a listing and extends the booking date range, the booking-panel estimated total updates to reflect the new dates before payment.", + "priority": "p1", + "planSteps": [ + { "type": "action", "description": "Navigate to the homepage" }, + { "type": "action", "description": "Search for stays with a valid destination and date range" }, + { "type": "action", "description": "Open a listing from the search results" }, + { + "type": "action", + "description": "Select an initial short date range to view the estimated total", + }, + { "type": "action", "description": "Change the date range to a longer stay" }, + { + "type": "assertion", + "description": "Verify the estimated total on the booking panel updates from the initial value to reflect the new longer dates", + }, + ], +} +``` + +- `name` — an assertable behavior statement (subject + verb + outcome), not a noun + fragment — e.g. "Booking date range change updates the estimated total" tells + the testing agent what to verify; "date range" tells it nothing. +- `description` — the condition + expected outcome in one sentence; disambiguates + a short name. +- `priority` — `p0` (must-pass) / `p1` (important paths) / `p2` (edge) / `p3` + (cosmetic). Pick honestly. +- `planSteps` — `Array<{ type: 'action' | 'assertion', description: string }>`, + max 200 steps / 256 KB. Describe user intent, not selectors. + +**Backend — write the Python yourself and use `--code-file`.** There is no +server-side codegen on the CLI. Read the API surface that changed (OpenAPI, the +route handler, request/response shapes) and write a pytest-style assertion script +to a tempfile. **End the file by calling your `test_*` function(s)** — the runner +executes the file top-to-bottom and does NOT auto-discover/collect test functions +the way `pytest` does, so a test that is only _defined_ (never called) silently +passes regardless of its assertions: + +```python +# /tmp/login-empty-password.py — runs against the project's target URL, creds injected. +import requests + +def test_login_rejects_empty_password(): + r = requests.post(f"{TARGET_URL}/login", json={"email": "a@b.c", "password": ""}) + assert r.status_code == 400 + assert r.json().get("error") == "invalid password" + +# Required: actually invoke the test so its assertions run. +test_login_rejects_empty_password() +``` + +**Execution environment (backend).** The code runs in a locked-down sandbox with +only the Python **standard library + `requests` + `pytest` + `numpy` + `scipy`** +(plus `requests`' own deps like `urllib3`). So: + +- **Test the API over HTTP** with `requests` against the target URL — that's what a + backend test verifies. +- **Do NOT `import` the project's own source modules** (e.g. `from app.services import …`, + `import core`, `import model`) or other third-party/ML packages (e.g. `torch`, + `pandas`, `django`). They are not installed, so the test fails to even run. +- Get values from the API's responses (and captured variables), not by importing and + calling the app's internals. + +**Authentication — read the injected credential, NEVER hardcode any credential.** This +applies to **every** secret the API needs — Bearer/JWT tokens **and** API keys, basic-auth +blobs, session cookies. Do not paste a literal `Bearer …`, `sk-…`, `x-api-key` value, or any +other credential into the test. Before your script runs, TestSprite prepends a managed +credential block built from the project's Authentication settings, and `__AUTH_HEADERS__` +already contains the right header(s) for the configured auth type: + +```python +# Auto-injected credentials — do not modify +__AUTH_CREDENTIAL__ = "..." +__AUTH_TYPE__ = "Bearer token" # or "API key" / "basic token" / "public" +__AUTH_HEADERS__ = {"Authorization": "Bearer ..."} # API key → {"X-API-Key": "..."}; basic → {"Authorization": "Basic ..."} +``` + +Spread `__AUTH_HEADERS__` into every authenticated request — it adapts to whatever auth type +the project is configured for, so the same line works for Bearer, API-key, or basic auth: + +```python +r = requests.get(f"{TARGET_URL}/profile", headers={**__AUTH_HEADERS__}) +``` + +Configure the credential **once on the project** (ask the user for the value — never invent +or reuse a key you happened to see), and the block stays correct + refreshable: + +- **Bearer / API key / basic (static):** + `testsprite project credential --type "Bearer token"|"API key"|"basic token" --credential ` +- **Auto-refreshing login (recurring token):** `testsprite project auto-auth …` + +A hardcoded token expires within hours (and a hardcoded key can't be rotated centrally), so +the test breaks on later runs; the managed block is rewritten with a fresh value each run. +`test create` emits a `[warn]` when it detects an inlined credential literal — treat that as +a must-fix, not a nuisance. + +**Backend tests that share state declare dependencies at create time.** For a +one-off verification, prefer a single self-contained script (log in inside the +same file). But when the coverage set splits naturally into producer → consumer +→ cleanup — one test captures an auth token or created-resource id that others +reuse — declare the graph with the dependency flags instead of duplicating setup +in every file: + +```bash +# producer — captures a variable for later waves +testsprite test create --type backend --project --name "login issues an auth token" \ + --code-file /tmp/login.py --produces auth_token + +# consumer — scheduled in a wave after every producer it names +testsprite test create --type backend --project --name "profile update accepts the issued token" \ + --code-file /tmp/profile.py --needs auth_token + +# cleanup — always scheduled in the final wave +testsprite test create --type backend --project --name "fixture user is deleted" \ + --code-file /tmp/cleanup.py --category teardown +``` + +- `--produces ` / `--needs ` are repeatable. All three flags are + **backend-only** — combined with `--type frontend` the CLI exits 5. +- **Don't hand-sequence `test run` calls to fake ordering.** The wave engine owns + ordering: trigger the set with `test run --all` (§4) and producers run before + consumers, `teardown` last. Chaining `run A --wait && run B --wait` yourself + loses the engine's variable passing and conflicts with concurrent runs. +- **Declarations are editable.** `test update` amends them (`--produces` / + `--needs` / `--category`, repeatable) and `test get` echoes them back — + still declare the graph at create time when you can, so wave ordering is + right on the first run. + +**Show the user the drafted plan / code before creating it** — creating writes to +their project. One short confirmation; let them edit the tempfile first. + +#### Authoring planSteps the testing agent will execute reliably + +Execution reliability tracks plan wording. A loose plan produces a +confidently-wrong `passed` (bare visibility assertions) or a thrashing +`blocked`. Write to these rules first: + +- **One verb per step.** `and` / `then` between two verbs → split — e.g. + "Search for stays and open the first result" becomes two steps. +- **Describe outcomes, not selectors.** The testing agent locates targets + semantically — describe the intent and the match stays robust across copy + changes; a guessed literal label defeats that. E.g. write `"Submit the form"`, + not `"Click the blue 'Submit' button"`. If the app tags elements with its own + attribute (`data-element`, `data-cy`, …), make sure the project knows — + `testsprite project get ` shows `testIdAttrs:`; set it once with + `project update --test-id-attributes ,data-testid` — and the + exported code will locate tagged elements by that attribute instead of text. +- **`Navigate to` only on step 1** (or a login page). Use clicks for every later + transition — direct URLs break SPA routing. +- **FE plans narrate a user journey through their actions.** Each action is + what a real user does (click, type, navigate, hover, scroll), forming a + sequence that exercises what gives the feature its value. The final assertion + verifies what the journey produced — the state the user arrived at, a + comparison against an earlier state, a derived count — not just that the + starting page rendered. +- **Name the target entity type, not a fuzzy noun.** If a page has several + look-alike row kinds, "open a thing" lets the testing agent pick the wrong + kind. Name the type and the page/view you expect to land on. +- **1–2 assertions, at the end, on whether the content is present _and actually + works_** (see _presence ≠ working_ below) rather than UI copy / formatting. + (Quoting a literal you submitted earlier in the same plan, to verify it + round-trips, is fine.) +- **Presence ≠ working.** A node can exist yet be broken or wrong — e.g. an + `` whose `src` 404s renders a broken-image box but still passes "element + present / has alt." Assert the thing actually **works and is correct**, not + just that the tag exists; trust the testing agent to judge correctness rather + than hard-coding the expected answer into the assertion. +- **Assertion targets name the specific page region** (panel / tab / output area). + Otherwise the testing agent settles for "some element with that text is + visible anywhere," which passes for wrong reasons. +- **For visual / CSS / layout-sensitive features, content-presence-only + assertions are dangerous.** "Verify the methodology section is visible" passes + even when the stylesheet is missing and three cards render as flat unstyled + text stacked vertically — the strings exist on the page, and a content-presence + assertion constrains nothing about layout. For any feature whose value depends on + layout, include at least one assertion that names geometry or relative + position (row, column, side-by-side, stacked, grid, above/below, span, card + background, border), not just content existence: + + ```jsonc + // BEFORE — content-presence-only (passes even on broken CSS) + { "type": "assertion", "description": "Verify the methodology section with three sub-score formulas is visible" } + + // AFTER — content + layout + { "type": "assertion", "description": "Verify the methodology section shows three card cells laid out side-by-side in a single horizontal row, each with a distinct card background and a heading; the three cards together span the full content width" } + ``` + +- **Keep `description` and `planSteps` in scope agreement** — the testing agent + reads `description` as the test's purpose and shrinks execution to match. If + you change the steps, re-align the description. +- **Keep flows that depend on state outside the test's control out of scope:** + third-party auth (OAuth/SSO/2FA), OS-native surfaces (file upload/download, + drag-and-drop, native dialogs), cross-context state (iframes, multi-tab, + external services). Pick a different verification. +- **Test data must be self-contained** — create what you need within the plan, or + don't write the plan. + +### (c) A coverage set — multiple FE plans as a batch + +When a FE feature has distinct paths (happy + error + edge), draft a +`plans.jsonl`, one spec per line. Aim for 2–5 plans; more only with explicit user +confirmation. Max 50 plans / 5 MB per batch. + +```jsonc +// plans.jsonl — FE only +{"projectId":"prj_abc","type":"frontend","name":"login happy path","planSteps":[...]} +{"projectId":"prj_abc","type":"frontend","name":"login wrong password","planSteps":[...]} +{"projectId":"prj_abc","type":"frontend","name":"login empty email","planSteps":[...]} +``` + +Batch is **FE-only.** For 3 backend tests, run `test create --type backend +--project --code-file ` three times with three Python files. + +### (d) Refine an existing test + +- **FE** — replace the steps, then re-run: + ```bash + testsprite test plan put --steps refined.json + ``` +- **BE** — write updated Python and replace the code (optimistic concurrency): + ```bash + testsprite test code put --code-file refined.py --expected-version + ``` + +## 4. Run + +All variants use `--wait` for a synchronous verdict, `--target-url ` for +the deployment under test, and `--timeout 600` as a sane default. + +```bash +# (a) existing test +testsprite test run --target-url --wait --timeout 600 --output json + +# (a-rerun) cheap replay of an existing test. FE: replays the saved script (auto-heal on — more +# lenient than a fresh run; for strict verification of a new change prefer `test run`). +# BE: dispatches the WHOLE dependency closure — producers and teardowns run too, not just , +# so expect their side effects (fixtures re-created, teardown deletes) and extra runs in history. +testsprite test rerun --wait --timeout 600 --output json +testsprite test rerun --skip-dependencies --wait --timeout 600 # BE: named test only + +# (b-FE) new FE test from plan +testsprite test create --plan-from plan.json --run --wait --target-url --timeout 600 + +# (b-BE) new BE test from Python (backend create needs --project) +testsprite test create --type backend --name "..." --project --code-file foo.py --run --wait --target-url --timeout 600 + +# (b-BE coverage set with dependencies) create each test without --run, then one wave-ordered batch +testsprite test run --all --project --wait --timeout 600 --output json +testsprite test run --all --project --filter --wait --timeout 600 # subset by name + +# (c) FE coverage set — single-call create + run (FE-only) +testsprite test create-batch --plans plans.jsonl --run --wait \ + --target-url --max-concurrency 3 --timeout 600 --output json +# Two-step alternative (inspect before running): +# testsprite test create-batch --plans plans.jsonl --output json +# then trigger each id: testsprite test run --wait --target-url --timeout 600 + +# (d-FE) refine + re-run +testsprite test plan put --steps refined.json && \ +testsprite test run --target-url --wait --timeout 600 + +# (d-BE) refine BE code + re-run. NOTE: if you reach for `test rerun` here instead, a BE rerun +# dispatches the full producer/teardown closure — use --skip-dependencies while iterating on one +# script (producers already verified this round), then finish with a closure run before reporting. +testsprite test code put --code-file refined.py --expected-version && \ +testsprite test run --target-url --wait --timeout 600 +``` + +Key behaviors: + +- `--target-url` must be an allowed project/environment URL. The CLI rejects + `localhost` / RFC1918 / link-local there. If the feature is only running + locally, use `--local ` instead of `--target-url` (frontend tests + only, see "When to run" above) — don't skip the run over this. +- `--wait` long-polls until terminal and handles its own backoff — don't wrap it + in a retry loop. +- Exit codes: `0` = passed; `1` = failed / blocked / cancelled; `7` = timeout. + Treat `7` as inconclusive (resume with `testsprite test wait `), not a + regression — except a `--local` run: its exit 7 already cancelled the run + (the tunnel closes with the process, so there is nothing to resume), so + don't suggest `test wait` there; re-run with `--local` again instead. +- Batch: `create-batch --run --wait` creates the tests (FE-only) and fans + out triggers in one call (bounded by `--max-concurrency`), emitting + `{ results: [...] }` that mirrors the single-test `test run --wait` + envelope. Exit `0` if every run passed; `1` for any failed/blocked/ + cancelled or trigger error; `7` only when EVERY run timed out. Drop + `--run` if you want to inspect the created tests before triggering. +- Run-trigger rate limit is 60/min/key, server-enforced; the CLI self-throttles + to 50/min. `--max-concurrency` (default 50) does NOT raise the server cap — + excess triggers return `RATE_LIMITED` (per-spec in batch JSON; exit 11 for + single `test run`). The test row stays created, the run never started. A full + `create-batch` (≤50 specs) fires all at once under the cap. The 50/min throttle + is per-invocation — separate batches/processes don't share it — so for >50 specs + in a minute you lean on the server's 60/min cap + `RATE_LIMITED` retries, not + client queuing. Re-list and check `draft` rows — "tests created" is + not the same as "runs triggered". +- **Backend execution is dependency-aware; frontend is not.** `test run --all +--project ` triggers a fresh wave-ordered batch over the project's backend + tests (producers → consumers → `teardown` last); FE tests in the project are + skipped with an advisory, and everything not dispatched is enumerated + (`conflicts` / `deferred` / `skippedFrontend`) so don't count `accepted[]` + alone. `test rerun ` expands the producer/teardown closure by default — + stderr summarizes `Reran N tests: 1 selected + P producer(s) + T teardown(s)`, + and failed members surface as `closureFailures[]` without flipping the exit + code. Pass `--skip-dependencies` only when this round already verified the + producers and you're iterating fast on one script. +- `test code put` needs `--expected-version `; stale etag → exit 6, + re-fetch via `test get ` and retry. `--force` bypasses but is audit-logged. +- Idempotency: the CLI auto-mints an `Idempotency-Key`; replays within 24h return + the original test/run. + +## 4a. Read the result — plan, or product? + +Don't take the verdict at face value. After a run, pull the steps +(`testsprite test steps --output json`) and ask: **plan quality, or +actual product behavior?** + +The plan is the problem (most common — check first) when: + +- recorded action count < plan action count → steps the plan left ambiguous were + skipped; +- assertions degraded to bare "Verify element is visible" with no subject; +- 5+ consecutive click attempts on similar targets with no progress. + +The product/environment is the problem (believe these) when: + +- `cause` / `error` names a concrete app observation ("the panel renders + read-only", "page 404s"); +- the trace blames infra (deploy lag, auth gate, missing fixture). + +Scope step counts to the **current run** — `test steps` is cumulative across runs; +filter on the run-id before counting. + +**Read the testing agent's failure summary skeptically — it can conflate two +failure phases.** When a flow produces an artifact that then runs against an external +target, "the backend returned an error" may mean the action endpoint itself +failed (feature broken) **or** the action succeeded and the produced artifact +failed later at runtime (orthogonal to your feature). Cross-check the step trace +and runtime output: if the runtime output references a literal you submitted +earlier in the plan, the action succeeded and the error is runtime-phase. + +**BE closure runs: root-cause the earliest failed wave, not the selected test.** +When a rerun or `run --all` expanded a dependency closure and a **producer** +failed, every consumer downstream of it fails or blocks by starvation (missing +token / missing fixture). The selected test's red verdict does not implicate +your feature — report it as failed-downstream, pull the producer's artifact +first, and only blame the consumer once its producers pass in the same run. + +If it's the plan: tighten via `test plan put` and re-run **once** (two runs total), +then stop. Don't grind. If it's the product/env: report the verdict with the +testing agent's observation; don't auto-fix on the recommendation alone. If you +genuinely can't tell: report `inconclusive` with the signal that triggered the +call and ask. + +## 5. On failure → download the artifact + +```bash +testsprite test artifact get --out ./.testsprite/runs// +``` + +Inspect the failure bundle (result, failed step + neighbors, video, root-cause +hypothesis, recommended fix target) before deciding whether your change caused it. + +## 6. Report + +When you tell the user the feature is done, include: + +- Which test(s) you ran — one line each: id, name, verdict. At least one terminal + verdict is required; zero means the feature is **not** done — surface that. +- The verdict. Don't report `passed` if §4a's sanity check tripped — surface as + `inconclusive` with the specific signal. +- If the user wants to inspect a test or run themselves, point them at the + dashboard link from the CLI output (`dashboardUrl` in JSON; a `Dashboard:` line + in text mode) — `test create` and `--wait` terminal output carry one. +- If failed, a one-line summary of the bundle's root-cause hypothesis and + recommended fix target. **Don't auto-fix** on that alone — the recommendation + can be wrong; the human should look. + diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..b6192cf --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "css.lint.propertyIgnoredDueToDisplay": "ignore" +} diff --git a/README.md b/README.md new file mode 100644 index 0000000..c1ccd3b --- /dev/null +++ b/README.md @@ -0,0 +1,72 @@ +# OurApp + +Imaginary creatures. Real fun. + +OurApp is a playful web app for generating one-of-a-kind AI "critters." Pick an adjective, an animal, an action, and a location — OurApp combines them into a prompt and uses AI image generation to bring your creature to life, ready to save, favorite, remix, and share. + +![OurApp dashboard](docs/dashboard-screenshot.png) + +## Features + +- **Critter creation** — combine an adjective, noun, verb, and location into a prompt and generate a unique AI image via Replicate (flux-schnell), with a playful animated loading screen while it's created +- **My Critters dashboard** — a searchable, sortable, filterable grid of everything you've created, with live stat tiles (total / favourites / archived), pagination, and quick status tabs +- **Critter detail popup** — click any critter for a card-style detail view with its recipe, a generated flavor description, the exact AI prompt used, real image metadata (resolution, file size, created date), and Download / Share / Create Similar actions +- **Favorites & archive** — toggle either from the dashboard grid, the detail popup, or the critter's own page, all kept in sync +- **Credits & payments** — new accounts start with credits; more are purchased through Paddle Checkout, applied automatically via a signed webhook +- **Accounts** — register, log in, log out, and reset a forgotten password, all with an emailed confirmation (PHPMailer + SMTP) +- **Guest marketing homepage** — a full-bleed hero, a "how it works" walkthrough, a recently-created carousel, and a call to action for signed-out visitors +- **Responsive, branded UI** — built with Tailwind CSS and a consistent playful visual language (Poppins, a warm gradient palette, Lucide icons) across every page + +## Tech stack + +| Layer | Technology | +|---|---| +| Language / runtime | PHP 8.5 | +| Database | SQLite (via PDO) | +| Frontend styling | Tailwind CSS v4 | +| Icons | [Lucide](https://lucide.dev) | +| Fonts | Poppins (Google Fonts) | +| AI image generation | [Replicate](https://replicate.com) — `black-forest-labs/flux-schnell` | +| Payments | [Paddle](https://www.paddle.com) Billing (Checkout + webhooks) | +| Email | [PHPMailer](https://github.com/PHPMailer/PHPMailer) over SMTP | +| Local development | [Local by Flywheel](https://localwp.com) (nginx + PHP-FPM) | + +## Project structure + +``` +public/ +├── index.php Guest homepage / signed-in dashboard +├── login.php, register.php, logout.php +├── forgot-password.php, reset-password.php +├── create-critter.php Critter creation form + AI generation +├── single-critter.php Standalone critter page +├── processing.php Credit purchase processing screen +├── receive-purchase.php Paddle webhook handler +├── api/ JSON endpoints (critter details, purchase status) +├── lib/ Shared partials (header, footer, hero, mailer, PHPMailer, etc.) +├── media/ Tailwind input/output CSS +├── assets/ Marketing images +└── critter-images/ Generated critter images +``` + +## Getting started + +This project is built to run on [Local by Flywheel](https://localwp.com), using its bundled PHP and nginx. + +1. Clone this repo into a Local site's `app/public` folder. +2. Install frontend dependencies and build the CSS: + ``` + npm install + npm run dev + ``` +3. Configure the following environment variables (set as `env[...]` entries in the site's PHP-FPM pool config): + + | Variable | Purpose | + |---|---| + | `REPLICATE_API_TOKEN` | Replicate API token for image generation | + | `HOOK_SECRET` | Verifies incoming Paddle webhook signatures | + | `TICKET_SECRET` | Signs short-lived tokens (checkout linking, password reset) | + | `SMTP_HOST`, `SMTP_PORT`, `SMTP_USERNAME`, `SMTP_PASSWORD` | SMTP credentials for outgoing email | + | `SMTP_FROM_EMAIL`, `SMTP_FROM_NAME` | Sender identity for outgoing email | + +4. Start the site in Local and visit it in your browser. diff --git a/api/critter-details.php b/api/critter-details.php new file mode 100644 index 0000000..2cde178 --- /dev/null +++ b/api/critter-details.php @@ -0,0 +1,137 @@ + 'Not authenticated']); + exit; +} + +function fetchOwnedCritter(PDO $pdo, int $userId, int $critterId): array|false +{ + $stmt = $pdo->prepare(' + SELECT c.id AS id, c.isFavorite AS isFavorite, c.isArchived AS isArchived, + c.adjective_id AS adjective_id, c.noun_id AS noun_id, c.verb_id AS verb_id, c.location_id AS location_id, + a.value AS adjective, n.value AS noun, v.value AS verb, l.value AS location, c.image AS image + FROM critters c + JOIN adjectives a ON a.id = c.adjective_id + JOIN nouns n ON n.id = c.noun_id + JOIN verbs v ON v.id = c.verb_id + JOIN locations l ON l.id = c.location_id + WHERE c.id = :id AND c.author_id = :author_id + '); + $stmt->execute(['id' => $critterId, 'author_id' => $userId]); + return $stmt->fetch(PDO::FETCH_ASSOC); +} + +$pdo = getDbConnection(); +$method = $_SERVER['REQUEST_METHOD']; +$critterId = $method === 'POST' + ? filter_input(INPUT_POST, 'id', FILTER_VALIDATE_INT) + : filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT); + +if (!$critterId) { + http_response_code(400); + echo json_encode(['error' => 'Invalid critter id']); + exit; +} + +$critter = fetchOwnedCritter($pdo, (int) $_SESSION['user_id'], $critterId); + +if (!$critter) { + http_response_code(404); + echo json_encode(['error' => 'Critter not found']); + exit; +} + +if ($method === 'POST') { + $action = $_POST['action'] ?? ''; + + if ($action === 'toggle_favorite') { + $newValue = $critter['isFavorite'] ? 0 : 1; + $stmt = $pdo->prepare('UPDATE critters SET isFavorite = :value WHERE id = :id'); + $stmt->execute(['value' => $newValue, 'id' => $critterId]); + $critter['isFavorite'] = $newValue; + } elseif ($action === 'toggle_archived') { + $newValue = $critter['isArchived'] ? 0 : 1; + $stmt = $pdo->prepare('UPDATE critters SET isArchived = :value WHERE id = :id'); + $stmt->execute(['value' => $newValue, 'id' => $critterId]); + $critter['isArchived'] = $newValue; + } +} + +$flourishes = [ + 'Always up for a new adventure!', + 'This one has a real personality.', + 'Ready to make new friends.', + "There's never a dull moment with this critter.", + 'One of a kind, through and through.', + 'A firm favorite in the collection.', + 'Full of charm and curiosity.', +]; +$flourish = $flourishes[array_rand($flourishes)]; +$description = 'A ' . $critter['adjective'] . ' ' . $critter['noun'] . ' who ' . $critter['verb'] . ' ' . $critter['location'] . '. ' . $flourish; +$prompt = "A {$critter['adjective']} {$critter['noun']} {$critter['verb']} {$critter['location']} in a high quality 3d animation art style. The image should be vibrant and colorful, capturing the essence of the action and setting."; + +$rarityTiers = [ + ['label' => 'Common', 'classes' => 'bg-pink-100 text-pink-700'], + ['label' => 'Rare', 'classes' => 'bg-blue-100 text-blue-700'], + ['label' => 'Legendary', 'classes' => 'bg-amber-100 text-amber-700'], +]; +$rarityRoll = $critter['id'] % 10; +if ($rarityRoll >= 9) { + $rarity = $rarityTiers[2]; +} elseif ($rarityRoll >= 6) { + $rarity = $rarityTiers[1]; +} else { + $rarity = $rarityTiers[0]; +} + +$resolution = null; +$fileSize = null; +$createdAt = null; + +if (!empty($critter['image'])) { + $imagePath = __DIR__ . '/../critter-images/' . $critter['image']; + if (is_file($imagePath)) { + $dimensions = @getimagesize($imagePath); + if ($dimensions) { + $resolution = $dimensions[0] . ' × ' . $dimensions[1]; + } + $bytes = @filesize($imagePath); + if ($bytes !== false) { + $fileSize = round($bytes / 1024) . ' KB'; + } + $mtime = @filemtime($imagePath); + if ($mtime !== false) { + $createdAt = date('j M Y, H:i', $mtime); + } + } +} + +echo json_encode([ + 'id' => (int) $critter['id'], + 'title' => ucwords($critter['adjective'] . ' ' . $critter['noun']), + 'adjective' => ucfirst($critter['adjective']), + 'noun' => ucfirst($critter['noun']), + 'verb' => ucfirst($critter['verb']), + 'location' => ucfirst($critter['location']), + 'isFavorite' => (bool) $critter['isFavorite'], + 'isArchived' => (bool) $critter['isArchived'], + 'rarity' => $rarity, + 'description' => $description, + 'prompt' => $prompt, + 'createdAt' => $createdAt, + 'resolution' => $resolution, + 'fileSize' => $fileSize, + 'imageUrl' => $critter['image'] ? 'critter-images/' . $critter['image'] : null, + 'shareUrl' => 'single-critter.php?id=' . $critter['id'], + 'createSimilarUrl' => 'create-critter.php?adjective_id=' . $critter['adjective_id'] + . '&noun_id=' . $critter['noun_id'] + . '&verb_id=' . $critter['verb_id'] + . '&location_id=' . $critter['location_id'], +]); diff --git a/api/purchase-boolean.php b/api/purchase-boolean.php new file mode 100644 index 0000000..ca8efa8 --- /dev/null +++ b/api/purchase-boolean.php @@ -0,0 +1,27 @@ +query("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'transactions'")->fetch(); + + if ($tableExists) { + $stmt = $pdo->prepare(" + SELECT 1 FROM transactions + WHERE user_id = :user_id + AND created_at >= datetime('now', '-40 seconds') + LIMIT 1 + "); + $stmt->execute(['user_id' => (int) $userId]); + $result = (bool) $stmt->fetch(); + } +} + +echo json_encode(['result' => $result]); diff --git a/assets/hero-image.png b/assets/hero-image.png new file mode 100644 index 0000000..e3a41cb Binary files /dev/null and b/assets/hero-image.png differ diff --git a/assets/hero-refference.png b/assets/hero-refference.png new file mode 100644 index 0000000..d6213e3 Binary files /dev/null and b/assets/hero-refference.png differ diff --git a/assets/logo.png b/assets/logo.png new file mode 100644 index 0000000..d15f978 Binary files /dev/null and b/assets/logo.png differ diff --git a/assets/recently1.webp b/assets/recently1.webp new file mode 100644 index 0000000..c301b2c Binary files /dev/null and b/assets/recently1.webp differ diff --git a/assets/recently2.webp b/assets/recently2.webp new file mode 100644 index 0000000..dcc2ebc Binary files /dev/null and b/assets/recently2.webp differ diff --git a/assets/recently3.webp b/assets/recently3.webp new file mode 100644 index 0000000..b6e95c7 Binary files /dev/null and b/assets/recently3.webp differ diff --git a/assets/recently4.webp b/assets/recently4.webp new file mode 100644 index 0000000..df177fd Binary files /dev/null and b/assets/recently4.webp differ diff --git a/create-critter.php b/create-critter.php index f7a483d..d62db8f 100644 --- a/create-critter.php +++ b/create-critter.php @@ -8,8 +8,17 @@ if (!isset($_SESSION['username']) || !isset($_SESSION['user_id'])) { exit; } +$isLoggedIn = isset($_SESSION['username']) && isset($_SESSION['user_id']); + +const DAILY_CRITTER_LIMIT = 30; +const CRITTER_COOLDOWN_SECONDS = 15; + $pdo = getDbConnection(); +$creditsStmt = $pdo->prepare('SELECT credits FROM users WHERE id = :id'); +$creditsStmt->execute(['id' => $_SESSION['user_id']]); +$userCredits = (int) $creditsStmt->fetchColumn(); + $pdo->exec('CREATE TABLE IF NOT EXISTS critters ( id INTEGER PRIMARY KEY AUTOINCREMENT, noun_id INTEGER NOT NULL REFERENCES nouns(id), @@ -17,7 +26,10 @@ $pdo->exec('CREATE TABLE IF NOT EXISTS critters ( verb_id INTEGER NOT NULL REFERENCES verbs(id), location_id INTEGER NOT NULL REFERENCES locations(id), author_id INTEGER NOT NULL REFERENCES users(id), - image TEXT + image TEXT, + isFavorite INTEGER NOT NULL DEFAULT 0, + isArchived INTEGER NOT NULL DEFAULT 0, + datetime TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP )'); $critterColumns = $pdo->query('PRAGMA table_info(critters)')->fetchAll(PDO::FETCH_COLUMN, 1); @@ -27,6 +39,16 @@ if (!in_array('author_id', $critterColumns, true)) { if (!in_array('image', $critterColumns, true)) { $pdo->exec('ALTER TABLE critters ADD COLUMN image TEXT'); } +if (!in_array('isFavorite', $critterColumns, true)) { + $pdo->exec('ALTER TABLE critters ADD COLUMN isFavorite INTEGER NOT NULL DEFAULT 0'); +} +if (!in_array('isArchived', $critterColumns, true)) { + $pdo->exec('ALTER TABLE critters ADD COLUMN isArchived INTEGER NOT NULL DEFAULT 0'); +} +if (!in_array('datetime', $critterColumns, true)) { + $pdo->exec('ALTER TABLE critters ADD COLUMN datetime TEXT'); + $pdo->exec("UPDATE critters SET datetime = CURRENT_TIMESTAMP WHERE datetime IS NULL"); +} $pdo->exec('CREATE INDEX IF NOT EXISTS idx_critters_noun_id ON critters (noun_id)'); $pdo->exec('CREATE INDEX IF NOT EXISTS idx_critters_adjective_id ON critters (adjective_id)'); @@ -34,11 +56,39 @@ $pdo->exec('CREATE INDEX IF NOT EXISTS idx_critters_verb_id ON critters (verb_id $pdo->exec('CREATE INDEX IF NOT EXISTS idx_critters_location_id ON critters (location_id)'); $pdo->exec('CREATE INDEX IF NOT EXISTS idx_critters_author_id ON critters (author_id)'); -function rowExistsById(PDO $pdo, string $table, $id): bool +function countCrittersCreatedToday(PDO $pdo): int { - $stmt = $pdo->prepare("SELECT 1 FROM {$table} WHERE id = :id"); - $stmt->execute(['id' => $id]); - return (bool) $stmt->fetch(); + return (int) $pdo->query("SELECT COUNT(*) FROM critters WHERE date(datetime) = date('now')")->fetchColumn(); +} + +function secondsSinceLastCritterByAuthor(PDO $pdo, int $authorId): ?int +{ + $stmt = $pdo->prepare("SELECT CAST(strftime('%s', 'now') - strftime('%s', datetime) AS INTEGER) FROM critters WHERE author_id = :author_id ORDER BY datetime DESC LIMIT 1"); + $stmt->execute(['author_id' => $authorId]); + $seconds = $stmt->fetchColumn(); + return $seconds === false ? null : (int) $seconds; +} + +$dailyLimitReached = countCrittersCreatedToday($pdo) >= DAILY_CRITTER_LIMIT; + +$cooldownRemaining = 0; +if ($_SERVER['REQUEST_METHOD'] === 'POST') { + $secondsSinceLast = secondsSinceLastCritterByAuthor($pdo, (int) $_SESSION['user_id']); + if ($secondsSinceLast !== null && $secondsSinceLast < CRITTER_COOLDOWN_SECONDS) { + $cooldownRemaining = CRITTER_COOLDOWN_SECONDS - $secondsSinceLast; + } +} + +function isAllowedReplicateUrl(string $url): bool +{ + $parts = parse_url($url); + if ($parts === false || ($parts['scheme'] ?? '') !== 'https' || empty($parts['host'])) { + return false; + } + $host = strtolower($parts['host']); + return $host === 'api.replicate.com' + || $host === 'replicate.delivery' + || substr($host, -strlen('.replicate.delivery')) === '.replicate.delivery'; } function getValueById(PDO $pdo, string $table, $id): string @@ -53,6 +103,13 @@ $nouns = $pdo->query('SELECT id, value FROM nouns ORDER BY value')->fetchAll(PDO $verbs = $pdo->query('SELECT id, value FROM verbs ORDER BY value')->fetchAll(PDO::FETCH_ASSOC); $locations = $pdo->query('SELECT id, value FROM locations ORDER BY value')->fetchAll(PDO::FETCH_ASSOC); +$fields = [ + 'adjective_id' => ['table' => 'adjectives', 'label' => 'adjective'], + 'noun_id' => ['table' => 'nouns', 'label' => 'noun'], + 'verb_id' => ['table' => 'verbs', 'label' => 'verb'], + 'location_id' => ['table' => 'locations', 'label' => 'location'], +]; + $errors = []; $selected = [ 'adjective_id' => '', @@ -61,14 +118,36 @@ $selected = [ 'location_id' => '', ]; -if ($_SERVER['REQUEST_METHOD'] === 'POST') { - $fields = [ - 'adjective_id' => ['table' => 'adjectives', 'label' => 'adjective'], - 'noun_id' => ['table' => 'nouns', 'label' => 'noun'], - 'verb_id' => ['table' => 'verbs', 'label' => 'verb'], - 'location_id' => ['table' => 'locations', 'label' => 'location'], - ]; +if ($_SERVER['REQUEST_METHOD'] !== 'POST') { + foreach ($fields as $field => $info) { + $value = $_GET[$field] ?? ''; + if ($value !== '' && ctype_digit((string) $value) && rowExistsById($pdo, $info['table'], $value)) { + $selected[$field] = (int) $value; + } + } + $hasRemixParams = $selected['adjective_id'] !== '' + || $selected['noun_id'] !== '' + || $selected['verb_id'] !== '' + || $selected['location_id'] !== ''; + + if (!$hasRemixParams) { + $optionLists = [ + 'adjective_id' => $adjectives, + 'noun_id' => $nouns, + 'verb_id' => $verbs, + 'location_id' => $locations, + ]; + + foreach ($optionLists as $field => $rows) { + if (!empty($rows)) { + $selected[$field] = (int) $rows[array_rand($rows)]['id']; + } + } + } +} + +if ($_SERVER['REQUEST_METHOD'] === 'POST' && $userCredits > 0 && !$dailyLimitReached) { foreach ($fields as $field => $info) { $value = $_POST[$field] ?? ''; $selected[$field] = $value; @@ -78,7 +157,33 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') { } } - if (empty($errors)) { + if (empty($errors) && countCrittersCreatedToday($pdo) >= DAILY_CRITTER_LIMIT) { + $dailyLimitReached = true; + } + + if (empty($errors) && $cooldownRemaining > 0) { + $errors['cooldown'] = "Please wait {$cooldownRemaining} more second(s) before creating another critter."; + } + + $creditReserved = false; + + if (empty($errors) && !$dailyLimitReached) { + // Atomically reserve one credit in the same statement that checks for it, so + // concurrent requests can't all read "1 credit" before any of them writes the + // deduction. SQLite serializes writes, so only as many of these UPDATEs can + // match "credits > 0" as there are credits actually available; everyone else + // gets 0 rows affected and is turned away before the expensive Replicate call. + $reserveStmt = $pdo->prepare('UPDATE users SET credits = credits - 1 WHERE id = :id AND credits > 0'); + $reserveStmt->execute(['id' => $_SESSION['user_id']]); + $creditReserved = $reserveStmt->rowCount() === 1; + + if (!$creditReserved) { + $userCredits = 0; + $errors['credits'] = 'You do not have enough credits to create a critter.'; + } + } + + if (empty($errors) && !$dailyLimitReached && $creditReserved) { $adjectiveValue = getValueById($pdo, 'adjectives', $selected['adjective_id']); $nounValue = getValueById($pdo, 'nouns', $selected['noun_id']); $verbValue = getValueById($pdo, 'verbs', $selected['verb_id']); @@ -90,6 +195,8 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') { curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_CAINFO, '/etc/ssl/certs/ca-certificates.crt'); + curl_setopt($ch, CURLOPT_PROTOCOLS, CURLPROTO_HTTPS); + curl_setopt($ch, CURLOPT_TIMEOUT, 30); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Authorization: Bearer ' . getenv('REPLICATE_API_TOKEN'), 'Content-Type: application/json', @@ -113,11 +220,19 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') { && !in_array($prediction['status'], ['succeeded', 'failed', 'canceled'], true) && $pollAttempt < 30 ) { + $pollUrl = $prediction['urls']['get'] ?? ''; + if (!is_string($pollUrl) || !isAllowedReplicateUrl($pollUrl)) { + $prediction['status'] = 'failed'; + break; + } + sleep(2); - $pollCh = curl_init($prediction['urls']['get']); + $pollCh = curl_init($pollUrl); curl_setopt($pollCh, CURLOPT_RETURNTRANSFER, true); curl_setopt($pollCh, CURLOPT_CAINFO, '/etc/ssl/certs/ca-certificates.crt'); + curl_setopt($pollCh, CURLOPT_PROTOCOLS, CURLPROTO_HTTPS); + curl_setopt($pollCh, CURLOPT_TIMEOUT, 15); curl_setopt($pollCh, CURLOPT_HTTPHEADER, [ 'Authorization: Bearer ' . getenv('REPLICATE_API_TOKEN'), ]); @@ -134,28 +249,40 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') { $output = $prediction['output'] ?? null; $imageUrl = is_array($output) ? ($output[0] ?? null) : $output; } + } else { + // The Replicate request never went through, so give the reserved credit back. + $refundStmt = $pdo->prepare('UPDATE users SET credits = credits + 1 WHERE id = :id'); + $refundStmt->execute(['id' => $_SESSION['user_id']]); } $imageFilename = null; - if ($imageUrl !== null) { + if (is_string($imageUrl) && isAllowedReplicateUrl($imageUrl)) { $imageCh = curl_init($imageUrl); curl_setopt($imageCh, CURLOPT_RETURNTRANSFER, true); curl_setopt($imageCh, CURLOPT_CAINFO, '/etc/ssl/certs/ca-certificates.crt'); + curl_setopt($imageCh, CURLOPT_PROTOCOLS, CURLPROTO_HTTPS); + curl_setopt($imageCh, CURLOPT_TIMEOUT, 30); + curl_setopt($imageCh, CURLOPT_MAXFILESIZE, 15 * 1024 * 1024); $imageData = curl_exec($imageCh); - if ($imageData !== false) { - $imagesDir = __DIR__ . '/critter-images'; - if (!is_dir($imagesDir)) { - mkdir($imagesDir, 0755, true); - } + if ($imageData !== false && strlen($imageData) > 0 && strlen($imageData) <= 15 * 1024 * 1024) { + $imageInfo = @getimagesizefromstring($imageData); + $allowedImageTypes = ['image/webp', 'image/png', 'image/jpeg']; - $imageFilename = bin2hex(random_bytes(16)) . '.webp'; - file_put_contents($imagesDir . '/' . $imageFilename, $imageData); + if ($imageInfo !== false && in_array($imageInfo['mime'] ?? '', $allowedImageTypes, true)) { + $imagesDir = __DIR__ . '/critter-images'; + if (!is_dir($imagesDir)) { + mkdir($imagesDir, 0755, true); + } + + $imageFilename = bin2hex(random_bytes(16)) . '.webp'; + file_put_contents($imagesDir . '/' . $imageFilename, $imageData); + } } } - $stmt = $pdo->prepare('INSERT INTO critters (noun_id, adjective_id, verb_id, location_id, author_id, image) VALUES (:noun_id, :adjective_id, :verb_id, :location_id, :author_id, :image)'); + $stmt = $pdo->prepare('INSERT INTO critters (noun_id, adjective_id, verb_id, location_id, author_id, image, datetime) VALUES (:noun_id, :adjective_id, :verb_id, :location_id, :author_id, :image, :datetime)'); $stmt->execute([ 'noun_id' => $selected['noun_id'], 'adjective_id' => $selected['adjective_id'], @@ -163,6 +290,7 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') { 'location_id' => $selected['location_id'], 'author_id' => $_SESSION['user_id'], 'image' => $imageFilename, + 'datetime' => gmdate('Y-m-d H:i:s'), ]); header('Location: /'); @@ -179,57 +307,171 @@ function renderOptions(array $rows, $selectedId): void . ''; } } + +$pageTitle = 'Create Critter'; ?> - - - Create Critter - - -

Create Your New Critter

-
-
- - - -
- + + + +
+ +
+
+ +
+

Critter limit reached for the day

+

Critter limit reached for the day, please come back tomorrow.

-
- - - -
- + +
+
+ +
+

Out of credits

+

You have 0 credits remaining, so you can't create a new critter right now.

+ + Buy Credits +
-
- - - -
- + +
+
+

Imagine · Mix · Create

+

Create Your New Critter

+

Pick a recipe and we'll bring it to life.

-
- - - -
+ +
+ +
+ +
+ +
+ +
+ + + +
+ +
+ +
+
+ +
+ + + +
+ +
+ +
+
+ +
+ + + +
+ +
+ +
+
+ +
+ + + +
+ +
+ +
+ +
- - +
+ + + + + + + +
+ diff --git a/critter-images/096dbda97f1289fba5cfb3ff5570c8a5.webp b/critter-images/096dbda97f1289fba5cfb3ff5570c8a5.webp new file mode 100644 index 0000000..503ffb1 Binary files /dev/null and b/critter-images/096dbda97f1289fba5cfb3ff5570c8a5.webp differ diff --git a/critter-images/14a0c1efbd60853310a009beecc2fdde.webp b/critter-images/14a0c1efbd60853310a009beecc2fdde.webp new file mode 100644 index 0000000..9739091 Binary files /dev/null and b/critter-images/14a0c1efbd60853310a009beecc2fdde.webp differ diff --git a/critter-images/1575274060d59f9543cb9e2f8e514701.webp b/critter-images/1575274060d59f9543cb9e2f8e514701.webp new file mode 100644 index 0000000..60a2902 Binary files /dev/null and b/critter-images/1575274060d59f9543cb9e2f8e514701.webp differ diff --git a/critter-images/1715835777148daa9fbdf68ee38edf35.webp b/critter-images/1715835777148daa9fbdf68ee38edf35.webp new file mode 100644 index 0000000..5c40e05 Binary files /dev/null and b/critter-images/1715835777148daa9fbdf68ee38edf35.webp differ diff --git a/critter-images/24192799244733aa61d5cd898f329f8b.webp b/critter-images/24192799244733aa61d5cd898f329f8b.webp new file mode 100644 index 0000000..82904a7 Binary files /dev/null and b/critter-images/24192799244733aa61d5cd898f329f8b.webp differ diff --git a/critter-images/29b2159161164bcae1414957d20222d4.webp b/critter-images/29b2159161164bcae1414957d20222d4.webp new file mode 100644 index 0000000..c301b2c Binary files /dev/null and b/critter-images/29b2159161164bcae1414957d20222d4.webp differ diff --git a/critter-images/2bae3ff71cfdb400fd3b6683b59c9690.webp b/critter-images/2bae3ff71cfdb400fd3b6683b59c9690.webp new file mode 100644 index 0000000..673bd4a Binary files /dev/null and b/critter-images/2bae3ff71cfdb400fd3b6683b59c9690.webp differ diff --git a/critter-images/33b755357ef9b929ede516504ee85648.webp b/critter-images/33b755357ef9b929ede516504ee85648.webp new file mode 100644 index 0000000..36a3e2a Binary files /dev/null and b/critter-images/33b755357ef9b929ede516504ee85648.webp differ diff --git a/critter-images/35474668fa1052916b2de071dece1de4.webp b/critter-images/35474668fa1052916b2de071dece1de4.webp new file mode 100644 index 0000000..1f1c5e9 Binary files /dev/null and b/critter-images/35474668fa1052916b2de071dece1de4.webp differ diff --git a/critter-images/35ec1d35cdec00e54a4e512b32bd2e06.webp b/critter-images/35ec1d35cdec00e54a4e512b32bd2e06.webp new file mode 100644 index 0000000..c73fde0 Binary files /dev/null and b/critter-images/35ec1d35cdec00e54a4e512b32bd2e06.webp differ diff --git a/critter-images/3f9335fd68d477391881275ff928ee45.webp b/critter-images/3f9335fd68d477391881275ff928ee45.webp new file mode 100644 index 0000000..e3a41cb Binary files /dev/null and b/critter-images/3f9335fd68d477391881275ff928ee45.webp differ diff --git a/critter-images/471b33054df8e3e2dc08e86f6aeb0d31.webp b/critter-images/471b33054df8e3e2dc08e86f6aeb0d31.webp new file mode 100644 index 0000000..cee5738 Binary files /dev/null and b/critter-images/471b33054df8e3e2dc08e86f6aeb0d31.webp differ diff --git a/critter-images/5afb94472f02abe9f3941d3ce858ebfa.webp b/critter-images/5afb94472f02abe9f3941d3ce858ebfa.webp new file mode 100644 index 0000000..8f5af7a Binary files /dev/null and b/critter-images/5afb94472f02abe9f3941d3ce858ebfa.webp differ diff --git a/critter-images/70ef6a31dbc9205031f9e2aa5829902a.webp b/critter-images/70ef6a31dbc9205031f9e2aa5829902a.webp new file mode 100644 index 0000000..8579c42 Binary files /dev/null and b/critter-images/70ef6a31dbc9205031f9e2aa5829902a.webp differ diff --git a/critter-images/75a8a55476cc010520bf6dd8b8a0f43b.webp b/critter-images/75a8a55476cc010520bf6dd8b8a0f43b.webp new file mode 100644 index 0000000..1235c7f Binary files /dev/null and b/critter-images/75a8a55476cc010520bf6dd8b8a0f43b.webp differ diff --git a/critter-images/804a210111966287409ea92569f94959.webp b/critter-images/804a210111966287409ea92569f94959.webp new file mode 100644 index 0000000..026c52c Binary files /dev/null and b/critter-images/804a210111966287409ea92569f94959.webp differ diff --git a/critter-images/8a2473153516d6df8831bd82a1fe92cd.webp b/critter-images/8a2473153516d6df8831bd82a1fe92cd.webp new file mode 100644 index 0000000..079e8e1 Binary files /dev/null and b/critter-images/8a2473153516d6df8831bd82a1fe92cd.webp differ diff --git a/critter-images/8ce0f65317a6354c88cfc0ea0580e454.webp b/critter-images/8ce0f65317a6354c88cfc0ea0580e454.webp new file mode 100644 index 0000000..d28a558 Binary files /dev/null and b/critter-images/8ce0f65317a6354c88cfc0ea0580e454.webp differ diff --git a/critter-images/a2473cb4c0c677968691aa7e9ca42fd0.webp b/critter-images/a2473cb4c0c677968691aa7e9ca42fd0.webp new file mode 100644 index 0000000..c1dcb07 Binary files /dev/null and b/critter-images/a2473cb4c0c677968691aa7e9ca42fd0.webp differ diff --git a/critter-images/a2f6b9d7cf7c76300c70a53be27a6544.webp b/critter-images/a2f6b9d7cf7c76300c70a53be27a6544.webp new file mode 100644 index 0000000..277f180 Binary files /dev/null and b/critter-images/a2f6b9d7cf7c76300c70a53be27a6544.webp differ diff --git a/critter-images/a70e02c97eb1f9a588589ec73317a4a8.webp b/critter-images/a70e02c97eb1f9a588589ec73317a4a8.webp new file mode 100644 index 0000000..569bee7 Binary files /dev/null and b/critter-images/a70e02c97eb1f9a588589ec73317a4a8.webp differ diff --git a/critter-images/b1ef62377a325861abcab6c885d3008d.webp b/critter-images/b1ef62377a325861abcab6c885d3008d.webp new file mode 100644 index 0000000..23e5723 Binary files /dev/null and b/critter-images/b1ef62377a325861abcab6c885d3008d.webp differ diff --git a/critter-images/b5fce87f533862e171d550def536ca89.webp b/critter-images/b5fce87f533862e171d550def536ca89.webp new file mode 100644 index 0000000..e179435 Binary files /dev/null and b/critter-images/b5fce87f533862e171d550def536ca89.webp differ diff --git a/critter-images/b7e02f759b0674fca2c62b0454a3eb9a.webp b/critter-images/b7e02f759b0674fca2c62b0454a3eb9a.webp new file mode 100644 index 0000000..941444b Binary files /dev/null and b/critter-images/b7e02f759b0674fca2c62b0454a3eb9a.webp differ diff --git a/critter-images/bd436d13c78805947f1f316f721a416a.webp b/critter-images/bd436d13c78805947f1f316f721a416a.webp new file mode 100644 index 0000000..df177fd Binary files /dev/null and b/critter-images/bd436d13c78805947f1f316f721a416a.webp differ diff --git a/critter-images/c89bf40acc8a921bad341e0ca166abc5.webp b/critter-images/c89bf40acc8a921bad341e0ca166abc5.webp new file mode 100644 index 0000000..1efd219 Binary files /dev/null and b/critter-images/c89bf40acc8a921bad341e0ca166abc5.webp differ diff --git a/critter-images/cc6e1c7bd942a6a65c68b91d51a89614.webp b/critter-images/cc6e1c7bd942a6a65c68b91d51a89614.webp new file mode 100644 index 0000000..7e9201d Binary files /dev/null and b/critter-images/cc6e1c7bd942a6a65c68b91d51a89614.webp differ diff --git a/critter-images/f094abcc06c5b38cebfe8e68d79be29f.webp b/critter-images/f094abcc06c5b38cebfe8e68d79be29f.webp new file mode 100644 index 0000000..88679d8 Binary files /dev/null and b/critter-images/f094abcc06c5b38cebfe8e68d79be29f.webp differ diff --git a/critter-images/index.php b/critter-images/index.php new file mode 100644 index 0000000..5ad69b7 --- /dev/null +++ b/critter-images/index.php @@ -0,0 +1,3 @@ +setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $pdo->exec('PRAGMA foreign_keys = ON'); + $pdo->exec('PRAGMA busy_timeout = 5000'); $pdo->exec('CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL UNIQUE, email TEXT NOT NULL UNIQUE, - password TEXT NOT NULL + password TEXT NOT NULL, + credits INTEGER NOT NULL DEFAULT 0 )'); + + $userColumns = $pdo->query('PRAGMA table_info(users)')->fetchAll(PDO::FETCH_COLUMN, 1); + if (!in_array('credits', $userColumns, true)) { + $pdo->exec('ALTER TABLE users ADD COLUMN credits INTEGER NOT NULL DEFAULT 0'); + } } return $pdo; } + +function rowExistsById(PDO $pdo, string $table, $id): bool +{ + $stmt = $pdo->prepare("SELECT 1 FROM {$table} WHERE id = :id"); + $stmt->execute(['id' => $id]); + return (bool) $stmt->fetch(); +} diff --git a/docs/dashboard-screenshot.png b/docs/dashboard-screenshot.png new file mode 100644 index 0000000..8b0c993 Binary files /dev/null and b/docs/dashboard-screenshot.png differ diff --git a/forgot-password.php b/forgot-password.php new file mode 100644 index 0000000..98faed8 --- /dev/null +++ b/forgot-password.php @@ -0,0 +1,100 @@ +prepare('SELECT id, username FROM users WHERE email = :email'); + $stmt->execute(['email' => $email]); + $user = $stmt->fetch(PDO::FETCH_ASSOC); + + if ($user) { + $token = createTicket((int) $user['id'], 'password_reset'); + $appUrl = rtrim(getenv('APP_URL') ?: 'https://ourapp.local', '/'); + $resetLink = $appUrl . '/reset-password.php?token=' . urlencode($token); + sendPasswordResetEmail($email, $user['username'], $resetLink); + } + + // Always show the same success state, whether or not the email matched an account, + // so this page can't be used to check which emails are registered. + $submitted = true; + } +} + +$pageTitle = 'Forgot Password'; +?> + + + + + +
+
+ +
+ +
+

Check your inbox

+

+ If an account exists for , + we've sent instructions to reset your password. The link expires in 20 minutes. +

+

+ Back to log in +

+ +
+ +
+

Forgot your password?

+

Enter your email and we'll send you a link to reset it.

+ +
+
+ +
+ + +
+ +

+ +
+ +
+ +

+ Remembered it? Log in +

+ +
+
+ + + diff --git a/index.php b/index.php index 6a214fe..a498867 100644 --- a/index.php +++ b/index.php @@ -60,67 +60,442 @@ if (!$tableExists) { } } -$dayOfWeek = date('l'); $isLoggedIn = isset($_SESSION['username']) && isset($_SESSION['user_id']); +if ($isLoggedIn && $_SERVER['REQUEST_METHOD'] === 'POST') { + $action = $_POST['action'] ?? ''; + $postedCritterId = $_POST['critter_id'] ?? ''; + + if (in_array($action, ['toggle_favorite', 'toggle_archived'], true) && ctype_digit((string) $postedCritterId)) { + $stmt = $pdo->prepare('SELECT author_id, isFavorite, isArchived FROM critters WHERE id = :id'); + $stmt->execute(['id' => $postedCritterId]); + $target = $stmt->fetch(PDO::FETCH_ASSOC); + + if ($target && (int) $target['author_id'] === (int) $_SESSION['user_id']) { + if ($action === 'toggle_favorite') { + $newValue = $target['isFavorite'] ? 0 : 1; + $update = $pdo->prepare('UPDATE critters SET isFavorite = :value WHERE id = :id'); + } else { + $newValue = $target['isArchived'] ? 0 : 1; + $update = $pdo->prepare('UPDATE critters SET isArchived = :value WHERE id = :id'); + } + $update->execute(['value' => $newValue, 'id' => $postedCritterId]); + } + } + + $redirectQuery = $_SERVER['QUERY_STRING'] ?? ''; + header('Location: /' . ($redirectQuery !== '' ? '?' . $redirectQuery : '')); + exit; +} + +function renderOptions(array $rows, $selectedId): void +{ + foreach ($rows as $row) { + $isSelected = (string) $selectedId === (string) $row['id']; + echo ''; + } +} + +function buildCritterUrl(array $overrides, array $filters, string $statusFilter, string $search, string $sort, int $page): string +{ + $params = []; + foreach ($filters as $key => $value) { + if ($value !== '') { + $params[$key] = $value; + } + } + if ($statusFilter !== 'any') { + $params['status'] = $statusFilter; + } + if ($search !== '') { + $params['q'] = $search; + } + if ($sort !== 'newest') { + $params['sort'] = $sort; + } + $params['page'] = $page; + + foreach ($overrides as $key => $value) { + if ($value === null) { + unset($params[$key]); + } else { + $params[$key] = $value; + } + } + + return '?' . http_build_query($params); +} + $myCritters = []; +$adjectives = []; +$nouns = []; +$verbs = []; +$locations = []; +$filters = [ + 'filter_adjective' => '', + 'filter_noun' => '', + 'filter_verb' => '', + 'filter_location' => '', +]; +$statusFilter = 'any'; +$search = ''; +$sort = 'newest'; +$perPage = 8; +$page = 1; +$totalPages = 1; +$totalCrittersCount = 0; +$favoritesCount = 0; +$archivedCount = 0; + if ($isLoggedIn) { + $adjectives = $pdo->query('SELECT id, value FROM adjectives ORDER BY value')->fetchAll(PDO::FETCH_ASSOC); + $nouns = $pdo->query('SELECT id, value FROM nouns ORDER BY value')->fetchAll(PDO::FETCH_ASSOC); + $verbs = $pdo->query('SELECT id, value FROM verbs ORDER BY value')->fetchAll(PDO::FETCH_ASSOC); + $locations = $pdo->query('SELECT id, value FROM locations ORDER BY value')->fetchAll(PDO::FETCH_ASSOC); + + $filterFields = [ + 'filter_adjective' => ['column' => 'adjective_id', 'table' => 'adjectives'], + 'filter_noun' => ['column' => 'noun_id', 'table' => 'nouns'], + 'filter_verb' => ['column' => 'verb_id', 'table' => 'verbs'], + 'filter_location' => ['column' => 'location_id', 'table' => 'locations'], + ]; + + foreach ($filterFields as $field => $info) { + $value = $_GET[$field] ?? ''; + if ($value !== '' && ctype_digit((string) $value) && rowExistsById($pdo, $info['table'], $value)) { + $filters[$field] = (int) $value; + } + } + + $allowedStatuses = ['any', 'favorited', 'archived']; + $requestedStatus = $_GET['status'] ?? 'any'; + if (in_array($requestedStatus, $allowedStatuses, true)) { + $statusFilter = $requestedStatus; + } + + $search = trim((string) ($_GET['q'] ?? '')); + if (strlen($search) > 100) { + $search = substr($search, 0, 100); + } + + $requestedSort = $_GET['sort'] ?? 'newest'; + if (in_array($requestedSort, ['newest', 'oldest'], true)) { + $sort = $requestedSort; + } + + $requestedPage = $_GET['page'] ?? '1'; + if (ctype_digit((string) $requestedPage) && (int) $requestedPage >= 1) { + $page = (int) $requestedPage; + } + $crittersTableExists = $pdo->query("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'critters'")->fetch(); if ($crittersTableExists) { - $stmt = $pdo->prepare(' - SELECT a.value AS adjective, n.value AS noun, v.value AS verb, l.value AS location, c.image AS image + $countAllStmt = $pdo->prepare('SELECT COUNT(*) FROM critters WHERE author_id = :author_id'); + $countAllStmt->execute(['author_id' => $_SESSION['user_id']]); + $totalCrittersCount = (int) $countAllStmt->fetchColumn(); + + $countFavStmt = $pdo->prepare('SELECT COUNT(*) FROM critters WHERE author_id = :author_id AND isFavorite = 1'); + $countFavStmt->execute(['author_id' => $_SESSION['user_id']]); + $favoritesCount = (int) $countFavStmt->fetchColumn(); + + $countArcStmt = $pdo->prepare('SELECT COUNT(*) FROM critters WHERE author_id = :author_id AND isArchived = 1'); + $countArcStmt->execute(['author_id' => $_SESSION['user_id']]); + $archivedCount = (int) $countArcStmt->fetchColumn(); + + $whereConditions = ['c.author_id = :author_id']; + $queryParams = ['author_id' => $_SESSION['user_id']]; + + foreach ($filters as $field => $value) { + if ($value !== '') { + $column = $filterFields[$field]['column']; + $whereConditions[] = "c.{$column} = :{$field}"; + $queryParams[$field] = $value; + } + } + + if ($statusFilter === 'favorited') { + $whereConditions[] = 'c.isFavorite = 1'; + } elseif ($statusFilter === 'archived') { + $whereConditions[] = 'c.isArchived = 1'; + } + + if ($search !== '') { + $escapedSearch = addcslashes($search, '%_\\'); + $whereConditions[] = "(a.value LIKE :search ESCAPE '\\' OR n.value LIKE :search ESCAPE '\\' OR v.value LIKE :search ESCAPE '\\' OR l.value LIKE :search ESCAPE '\\')"; + $queryParams['search'] = '%' . $escapedSearch . '%'; + } + + $whereSql = implode(' AND ', $whereConditions); + + $countStmt = $pdo->prepare(" + SELECT COUNT(*) FROM critters c JOIN adjectives a ON a.id = c.adjective_id JOIN nouns n ON n.id = c.noun_id JOIN verbs v ON v.id = c.verb_id JOIN locations l ON l.id = c.location_id - WHERE c.author_id = :author_id - ORDER BY c.id DESC - '); - $stmt->execute(['author_id' => $_SESSION['user_id']]); + WHERE {$whereSql} + "); + $countStmt->execute($queryParams); + $totalCritters = (int) $countStmt->fetchColumn(); + $totalPages = max(1, (int) ceil($totalCritters / $perPage)); + + if ($page > $totalPages) { + $page = $totalPages; + } + + $offset = ($page - 1) * $perPage; + $orderSql = $sort === 'oldest' ? 'c.id ASC' : 'c.id DESC'; + + $sql = " + SELECT c.id AS id, c.isFavorite AS isFavorite, c.isArchived AS isArchived, + a.value AS adjective, n.value AS noun, v.value AS verb, l.value AS location, c.image AS image + FROM critters c + JOIN adjectives a ON a.id = c.adjective_id + JOIN nouns n ON n.id = c.noun_id + JOIN verbs v ON v.id = c.verb_id + JOIN locations l ON l.id = c.location_id + WHERE {$whereSql} + ORDER BY {$orderSql} + LIMIT {$perPage} OFFSET {$offset} + "; + $stmt = $pdo->prepare($sql); + $stmt->execute($queryParams); $myCritters = $stmt->fetchAll(PDO::FETCH_ASSOC); } } + +$pageTitle = 'Welcome'; ?> - - - Welcome - - - + + +
-

Welcome

- -

Welcome guest

- -

Happy ! We're glad you're here.

- -

Create New Critter

-

Log out

-
-

My Critters

+ + + +
+
+ + +
+ + + + + +
+ + +
+ + +
+
+ -

You haven't created any critters yet.

+ -
+
- - AI-generated image of your critter - + +
+
+ +
+ + + +
+
+
+
+

+ # +
+
+ + +
+
+ +
+ + + +
+
+ + + +
+
+
+
+ + +
+
+ +
+

Ready for another critter?

+

Use your imagination and create something amazing!

+ + Create a Critter + +
+
+ + 1): ?> +
+ 1): ?> + Previous + + Previous + + + + + + + + + + + + Next + + Next + +
+ + +
+
+
+ +
+
+

Filter Your Critters

+

Find exactly what you're looking for.

+
+
+
+ + +
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ Clear + +
+
+
+ -

Sign Up

-

Log In

+ + + + +
+ diff --git a/lib/.htaccess b/lib/.htaccess new file mode 100644 index 0000000..7625314 --- /dev/null +++ b/lib/.htaccess @@ -0,0 +1,7 @@ + + Require all denied + + + Order allow,deny + Deny from all + diff --git a/lib/PHPMailer/LICENSE b/lib/PHPMailer/LICENSE new file mode 100644 index 0000000..f166cc5 --- /dev/null +++ b/lib/PHPMailer/LICENSE @@ -0,0 +1,502 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! \ No newline at end of file diff --git a/lib/PHPMailer/src/Exception.php b/lib/PHPMailer/src/Exception.php new file mode 100644 index 0000000..09c1a2c --- /dev/null +++ b/lib/PHPMailer/src/Exception.php @@ -0,0 +1,40 @@ + + * @author Jim Jagielski (jimjag) + * @author Andy Prevost (codeworxtech) + * @author Brent R. Matzelle (original founder) + * @copyright 2012 - 2020 Marcus Bointon + * @copyright 2010 - 2012 Jim Jagielski + * @copyright 2004 - 2009 Andy Prevost + * @license https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html GNU Lesser General Public License + * @note This program is distributed in the hope that it will be useful - WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. + */ + +namespace PHPMailer\PHPMailer; + +/** + * PHPMailer exception handler. + * + * @author Marcus Bointon + */ +class Exception extends \Exception +{ + /** + * Prettify error message output. + * + * @return string + */ + public function errorMessage() + { + return '' . htmlspecialchars($this->getMessage(), ENT_COMPAT | ENT_HTML401) . "
\n"; + } +} diff --git a/lib/PHPMailer/src/PHPMailer.php b/lib/PHPMailer/src/PHPMailer.php new file mode 100644 index 0000000..4900cbc --- /dev/null +++ b/lib/PHPMailer/src/PHPMailer.php @@ -0,0 +1,5586 @@ + + * @author Jim Jagielski (jimjag) + * @author Andy Prevost (codeworxtech) + * @author Brent R. Matzelle (original founder) + * @copyright 2012 - 2020 Marcus Bointon + * @copyright 2010 - 2012 Jim Jagielski + * @copyright 2004 - 2009 Andy Prevost + * @license https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html GNU Lesser General Public License + * @note This program is distributed in the hope that it will be useful - WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. + */ + +namespace PHPMailer\PHPMailer; + +/** + * PHPMailer - PHP email creation and transport class. + * + * @author Marcus Bointon (Synchro/coolbru) + * @author Jim Jagielski (jimjag) + * @author Andy Prevost (codeworxtech) + * @author Brent R. Matzelle (original founder) + */ +class PHPMailer +{ + const CHARSET_ASCII = 'us-ascii'; + const CHARSET_ISO88591 = 'iso-8859-1'; + const CHARSET_UTF8 = 'utf-8'; + + const CONTENT_TYPE_PLAINTEXT = 'text/plain'; + const CONTENT_TYPE_TEXT_CALENDAR = 'text/calendar'; + const CONTENT_TYPE_TEXT_HTML = 'text/html'; + const CONTENT_TYPE_MULTIPART_ALTERNATIVE = 'multipart/alternative'; + const CONTENT_TYPE_MULTIPART_MIXED = 'multipart/mixed'; + const CONTENT_TYPE_MULTIPART_RELATED = 'multipart/related'; + + const ENCODING_7BIT = '7bit'; + const ENCODING_8BIT = '8bit'; + const ENCODING_BASE64 = 'base64'; + const ENCODING_BINARY = 'binary'; + const ENCODING_QUOTED_PRINTABLE = 'quoted-printable'; + + const ENCRYPTION_STARTTLS = 'tls'; + const ENCRYPTION_SMTPS = 'ssl'; + + const ICAL_METHOD_REQUEST = 'REQUEST'; + const ICAL_METHOD_PUBLISH = 'PUBLISH'; + const ICAL_METHOD_REPLY = 'REPLY'; + const ICAL_METHOD_ADD = 'ADD'; + const ICAL_METHOD_CANCEL = 'CANCEL'; + const ICAL_METHOD_REFRESH = 'REFRESH'; + const ICAL_METHOD_COUNTER = 'COUNTER'; + const ICAL_METHOD_DECLINECOUNTER = 'DECLINECOUNTER'; + const RFC822_DATE_FORMAT = 'D, j M Y H:i:s O'; + + /** + * Email priority. + * Options: null (default), 1 = High, 3 = Normal, 5 = low. + * When null, the header is not set at all. + * + * @var int|null + */ + public $Priority; + + /** + * The character set of the message. + * + * @var string + */ + public $CharSet = self::CHARSET_ISO88591; + + /** + * The MIME Content-Type of the message. + * + * @var string + */ + public $ContentType = self::CONTENT_TYPE_PLAINTEXT; + + /** + * The message encoding. + * Options: "8bit", "7bit", "binary", "base64", and "quoted-printable". + * + * @var string + */ + public $Encoding = self::ENCODING_8BIT; + + /** + * Holds the most recent mailer error message. + * + * @var string + */ + public $ErrorInfo = ''; + + /** + * The From email address for the message. + * + * @var string + */ + public $From = ''; + + /** + * The From name of the message. + * + * @var string + */ + public $FromName = ''; + + /** + * The envelope sender of the message. + * This will usually be turned into a Return-Path header by the receiver, + * and is the address that bounces will be sent to. + * If not empty, will be passed via `-f` to sendmail or as the 'MAIL FROM' value over SMTP. + * + * @var string + */ + public $Sender = ''; + + /** + * The Subject of the message. + * + * @var string + */ + public $Subject = ''; + + /** + * An HTML or plain text message body. + * If HTML then call isHTML(true). + * + * @var string + */ + public $Body = ''; + + /** + * The plain-text message body. + * This body can be read by mail clients that do not have HTML email + * capability such as mutt & Eudora. + * Clients that can read HTML will view the normal Body. + * + * @var string + */ + public $AltBody = ''; + + /** + * An iCal message part body. + * Only supported in simple alt or alt_inline message types + * To generate iCal event structures, use classes like EasyPeasyICS or iCalcreator. + * + * @see https://kigkonsult.se/iCalcreator/ + * + * @var string + */ + public $Ical = ''; + + /** + * Value-array of "method" in Content-Type header "text/calendar" + * + * @var string[] + */ + protected static $IcalMethods = [ + self::ICAL_METHOD_REQUEST, + self::ICAL_METHOD_PUBLISH, + self::ICAL_METHOD_REPLY, + self::ICAL_METHOD_ADD, + self::ICAL_METHOD_CANCEL, + self::ICAL_METHOD_REFRESH, + self::ICAL_METHOD_COUNTER, + self::ICAL_METHOD_DECLINECOUNTER, + ]; + + /** + * The complete compiled MIME message body. + * + * @var string + */ + protected $MIMEBody = ''; + + /** + * The complete compiled MIME message headers. + * + * @var string + */ + protected $MIMEHeader = ''; + + /** + * Extra headers that createHeader() doesn't fold in. + * + * @var string + */ + protected $mailHeader = ''; + + /** + * Word-wrap the message body to this number of chars. + * Set to 0 to not wrap. A useful value here is 78, for RFC2822 section 2.1.1 compliance. + * + * @see static::STD_LINE_LENGTH + * + * @var int + */ + public $WordWrap = 0; + + /** + * Which method to use to send mail. + * Options: "mail", "sendmail", or "smtp". + * + * @var string + */ + public $Mailer = 'mail'; + + /** + * The path to the sendmail program. + * + * @var string + */ + public $Sendmail = '/usr/sbin/sendmail'; + + /** + * Whether mail() uses a fully sendmail-compatible MTA. + * One which supports sendmail's "-oi -f" options. + * + * @var bool + */ + public $UseSendmailOptions = true; + + /** + * The email address that a reading confirmation should be sent to, also known as read receipt. + * + * @var string + */ + public $ConfirmReadingTo = ''; + + /** + * The hostname to use in the Message-ID header and as default HELO string. + * If empty, PHPMailer attempts to find one with, in order, + * $_SERVER['SERVER_NAME'], gethostname(), php_uname('n'), or the value + * 'localhost.localdomain'. + * + * @see PHPMailer::$Helo + * + * @var string + */ + public $Hostname = ''; + + /** + * An ID to be used in the Message-ID header. + * If empty, a unique id will be generated. + * You can set your own, but it must be in the format "", + * as defined in RFC5322 section 3.6.4 or it will be ignored. + * + * @see https://www.rfc-editor.org/rfc/rfc5322#section-3.6.4 + * + * @var string + */ + public $MessageID = ''; + + /** + * The message Date to be used in the Date header. + * If empty, the current date will be added. + * + * @var string + */ + public $MessageDate = ''; + + /** + * SMTP hosts. + * Either a single hostname or multiple semicolon-delimited hostnames. + * You can also specify a different port + * for each host by using this format: [hostname:port] + * (e.g. "smtp1.example.com:25;smtp2.example.com"). + * You can also specify encryption type, for example: + * (e.g. "tls://smtp1.example.com:587;ssl://smtp2.example.com:465"). + * Hosts will be tried in order. + * + * @var string + */ + public $Host = 'localhost'; + + /** + * The default SMTP server port. + * + * @var int + */ + public $Port = 25; + + /** + * The SMTP HELO/EHLO name used for the SMTP connection. + * Default is $Hostname. If $Hostname is empty, PHPMailer attempts to find + * one with the same method described above for $Hostname. + * + * @see PHPMailer::$Hostname + * + * @var string + */ + public $Helo = ''; + + /** + * What kind of encryption to use on the SMTP connection. + * Options: '', static::ENCRYPTION_STARTTLS, or static::ENCRYPTION_SMTPS. + * + * @var string + */ + public $SMTPSecure = ''; + + /** + * Whether to enable TLS encryption automatically if a server supports it, + * even if `SMTPSecure` is not set to 'tls'. + * Be aware that in PHP >= 5.6 this requires that the server's certificates are valid. + * + * @var bool + */ + public $SMTPAutoTLS = true; + + /** + * Whether to use SMTP authentication. + * Uses the Username and Password properties. + * + * @see PHPMailer::$Username + * @see PHPMailer::$Password + * + * @var bool + */ + public $SMTPAuth = false; + + /** + * Options array passed to stream_context_create when connecting via SMTP. + * + * @var array + */ + public $SMTPOptions = []; + + /** + * SMTP username. + * + * @var string + */ + public $Username = ''; + + /** + * SMTP password. + * + * @var string + */ + public $Password = ''; + + /** + * SMTP authentication type. Options are CRAM-MD5, LOGIN, PLAIN, XOAUTH2. + * If not specified, the first one from that list that the server supports will be selected. + * + * @var string + */ + public $AuthType = ''; + + /** + * SMTP SMTPXClient command attributes + * + * @var array + */ + protected $SMTPXClient = []; + + /** + * An implementation of the PHPMailer OAuthTokenProvider interface. + * + * @var OAuthTokenProvider + */ + protected $oauth; + + /** + * The SMTP server timeout in seconds. + * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2. + * + * @var int + */ + public $Timeout = 300; + + /** + * Comma separated list of DSN notifications + * 'NEVER' under no circumstances a DSN must be returned to the sender. + * If you use NEVER all other notifications will be ignored. + * 'SUCCESS' will notify you when your mail has arrived at its destination. + * 'FAILURE' will arrive if an error occurred during delivery. + * 'DELAY' will notify you if there is an unusual delay in delivery, but the actual + * delivery's outcome (success or failure) is not yet decided. + * + * @see https://www.rfc-editor.org/rfc/rfc3461.html#section-4.1 for more information about NOTIFY + */ + public $dsn = ''; + + /** + * SMTP class debug output mode. + * Debug output level. + * Options: + * @see SMTP::DEBUG_OFF: No output + * @see SMTP::DEBUG_CLIENT: Client messages + * @see SMTP::DEBUG_SERVER: Client and server messages + * @see SMTP::DEBUG_CONNECTION: As SERVER plus connection status + * @see SMTP::DEBUG_LOWLEVEL: Noisy, low-level data output, rarely needed + * + * @see SMTP::$do_debug + * + * @var int + */ + public $SMTPDebug = 0; + + /** + * How to handle debug output. + * Options: + * * `echo` Output plain-text as-is, appropriate for CLI + * * `html` Output escaped, line breaks converted to `
`, appropriate for browser output + * * `error_log` Output to error log as configured in php.ini + * By default PHPMailer will use `echo` if run from a `cli` or `cli-server` SAPI, `html` otherwise. + * Alternatively, you can provide a callable expecting two params: a message string and the debug level: + * + * ```php + * $mail->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";}; + * ``` + * + * Alternatively, you can pass in an instance of a PSR-3 compatible logger, though only `debug` + * level output is used: + * + * ```php + * $mail->Debugoutput = new myPsr3Logger; + * ``` + * + * @see SMTP::$Debugoutput + * + * @var string|callable|\Psr\Log\LoggerInterface + */ + public $Debugoutput = 'echo'; + + /** + * Whether to keep the SMTP connection open after each message. + * If this is set to true then the connection will remain open after a send, + * and closing the connection will require an explicit call to smtpClose(). + * It's a good idea to use this if you are sending multiple messages as it reduces overhead. + * See the mailing list example for how to use it. + * + * @var bool + */ + public $SMTPKeepAlive = false; + + /** + * Whether to split multiple to addresses into multiple messages + * or send them all in one message. + * Only supported in `mail` and `sendmail` transports, not in SMTP. + * + * @var bool + * + * @deprecated 6.0.0 PHPMailer isn't a mailing list manager! + */ + public $SingleTo = false; + + /** + * Storage for addresses when SingleTo is enabled. + * + * @var array + */ + protected $SingleToArray = []; + + /** + * Whether to generate VERP addresses on send. + * Only applicable when sending via SMTP. + * + * @see https://en.wikipedia.org/wiki/Variable_envelope_return_path + * @see https://www.postfix.org/VERP_README.html Postfix VERP info + * + * @var bool + */ + public $do_verp = false; + + /** + * Whether to allow sending messages with an empty body. + * + * @var bool + */ + public $AllowEmpty = false; + + /** + * DKIM selector. + * + * @var string + */ + public $DKIM_selector = ''; + + /** + * DKIM Identity. + * Usually the email address used as the source of the email. + * + * @var string + */ + public $DKIM_identity = ''; + + /** + * DKIM passphrase. + * Used if your key is encrypted. + * + * @var string + */ + public $DKIM_passphrase = ''; + + /** + * DKIM signing domain name. + * + * @example 'example.com' + * + * @var string + */ + public $DKIM_domain = ''; + + /** + * DKIM Copy header field values for diagnostic use. + * + * @var bool + */ + public $DKIM_copyHeaderFields = true; + + /** + * DKIM Extra signing headers. + * + * @example ['List-Unsubscribe', 'List-Help'] + * + * @var array + */ + public $DKIM_extraHeaders = []; + + /** + * DKIM private key file path. + * + * @var string + */ + public $DKIM_private = ''; + + /** + * DKIM private key string. + * + * If set, takes precedence over `$DKIM_private`. + * + * @var string + */ + public $DKIM_private_string = ''; + + /** + * Callback Action function name. + * + * The function that handles the result of the send email action. + * It is called out by send() for each email sent. + * + * Value can be any php callable: https://www.php.net/is_callable + * + * Parameters: + * bool $result result of the send action + * array $to email addresses of the recipients + * array $cc cc email addresses + * array $bcc bcc email addresses + * string $subject the subject + * string $body the email body + * string $from email address of sender + * string $extra extra information of possible use + * 'smtp_transaction_id' => last smtp transaction id + * + * @var callable|callable-string + */ + public $action_function = ''; + + /** + * What to put in the X-Mailer header. + * Options: An empty string for PHPMailer default, whitespace/null for none, or a string to use. + * + * @var string|null + */ + public $XMailer = ''; + + /** + * Which validator to use by default when validating email addresses. + * May be a callable to inject your own validator, but there are several built-in validators. + * The default validator uses PHP's FILTER_VALIDATE_EMAIL filter_var option. + * + * If CharSet is UTF8, the validator is left at the default value, + * and you send to addresses that use non-ASCII local parts, then + * PHPMailer automatically changes to the 'eai' validator. + * + * @see PHPMailer::validateAddress() + * + * @var string|callable + */ + public static $validator = 'php'; + + /** + * An instance of the SMTP sender class. + * + * @var SMTP + */ + protected $smtp; + + /** + * The array of 'to' names and addresses. + * + * @var array + */ + protected $to = []; + + /** + * The array of 'cc' names and addresses. + * + * @var array + */ + protected $cc = []; + + /** + * The array of 'bcc' names and addresses. + * + * @var array + */ + protected $bcc = []; + + /** + * The array of reply-to names and addresses. + * + * @var array + */ + protected $ReplyTo = []; + + /** + * An array of all kinds of addresses. + * Includes all of $to, $cc, $bcc. + * + * @see PHPMailer::$to + * @see PHPMailer::$cc + * @see PHPMailer::$bcc + * + * @var array + */ + protected $all_recipients = []; + + /** + * An array of names and addresses queued for validation. + * In send(), valid and non duplicate entries are moved to $all_recipients + * and one of $to, $cc, or $bcc. + * This array is used only for addresses with IDN. + * + * @see PHPMailer::$to + * @see PHPMailer::$cc + * @see PHPMailer::$bcc + * @see PHPMailer::$all_recipients + * + * @var array + */ + protected $RecipientsQueue = []; + + /** + * An array of reply-to names and addresses queued for validation. + * In send(), valid and non duplicate entries are moved to $ReplyTo. + * This array is used only for addresses with IDN. + * + * @see PHPMailer::$ReplyTo + * + * @var array + */ + protected $ReplyToQueue = []; + + /** + * Whether the need for SMTPUTF8 has been detected. Set by + * preSend() if necessary. + * + * @var bool + */ + public $UseSMTPUTF8 = false; + + /** + * The array of attachments. + * + * @var array + */ + protected $attachment = []; + + /** + * The array of custom headers. + * + * @var array + */ + protected $CustomHeader = []; + + /** + * The most recent Message-ID (including angular brackets). + * + * @var string + */ + protected $lastMessageID = ''; + + /** + * The message's MIME type. + * + * @var string + */ + protected $message_type = ''; + + /** + * The array of MIME boundary strings. + * + * @var array + */ + protected $boundary = []; + + /** + * The array of available text strings for the current language. + * + * @var array + */ + protected static $language = []; + + /** + * The number of errors encountered. + * + * @var int + */ + protected $error_count = 0; + + /** + * The S/MIME certificate file path. + * + * @var string + */ + protected $sign_cert_file = ''; + + /** + * The S/MIME key file path. + * + * @var string + */ + protected $sign_key_file = ''; + + /** + * The optional S/MIME extra certificates ("CA Chain") file path. + * + * @var string + */ + protected $sign_extracerts_file = ''; + + /** + * The S/MIME password for the key. + * Used only if the key is encrypted. + * + * @var string + */ + protected $sign_key_pass = ''; + + /** + * Whether to throw exceptions for errors. + * + * @var bool + */ + protected $exceptions = false; + + /** + * Unique ID used for message ID and boundaries. + * + * @var string + */ + protected $uniqueid = ''; + + /** + * The PHPMailer Version number. + * + * @var string + */ + const VERSION = '7.1.1'; + + /** + * Error severity: message only, continue processing. + * + * @var int + */ + const STOP_MESSAGE = 0; + + /** + * Error severity: message, likely ok to continue processing. + * + * @var int + */ + const STOP_CONTINUE = 1; + + /** + * Error severity: message, plus full stop, critical error reached. + * + * @var int + */ + const STOP_CRITICAL = 2; + + /** + * The SMTP standard CRLF line break. + * If you want to change line break format, change static::$LE, not this. + */ + const CRLF = "\r\n"; + + /** + * "Folding White Space" a white space string used for line folding. + */ + const FWS = ' '; + + /** + * SMTP RFC standard line ending; Carriage Return, Line Feed. + * + * @var string + */ + protected static $LE = self::CRLF; + + /** + * The maximum line length supported by mail(). + * + * Background: mail() will sometimes corrupt messages + * with headers longer than 65 chars, see #818. + * + * @var int + */ + const MAIL_MAX_LINE_LENGTH = 63; + + /** + * The maximum line length allowed by RFC 2822 section 2.1.1. + * + * @var int + */ + const MAX_LINE_LENGTH = 998; + + /** + * The lower maximum line length allowed by RFC 2822 section 2.1.1. + * This length does NOT include the line break + * 76 means that lines will be 77 or 78 chars depending on whether + * the line break format is LF or CRLF; both are valid. + * + * @var int + */ + const STD_LINE_LENGTH = 76; + + /** + * Constructor. + * + * @param bool $exceptions Should we throw external exceptions? + */ + public function __construct($exceptions = null) + { + if (null !== $exceptions) { + $this->exceptions = (bool) $exceptions; + } + //Pick an appropriate debug output format automatically + $this->Debugoutput = (strpos(PHP_SAPI, 'cli') !== false ? 'echo' : 'html'); + } + + /** + * Destructor. + */ + public function __destruct() + { + //Close any open SMTP connection nicely + $this->smtpClose(); + } + + /** + * Call mail() in a safe_mode-aware fashion. + * Also, unless sendmail_path points to sendmail (or something that + * claims to be sendmail), don't pass params (not a perfect fix, + * but it will do). + * + * @param string $to To + * @param string $subject Subject + * @param string $body Message Body + * @param string $header Additional Header(s) + * @param string|null $params Params + * + * @return bool + */ + private function mailPassthru($to, $subject, $body, $header, $params) + { + //Check overloading of mail function to avoid double-encoding + // phpcs:ignore PHPCompatibility.IniDirectives.RemovedIniDirectives.mbstring_func_overloadDeprecatedRemoved + if ((int)ini_get('mbstring.func_overload') & 1) { + $subject = $this->secureHeader($subject); + } else { + $subject = $this->encodeHeader($this->secureHeader($subject)); + } + //Calling mail() with null params breaks + $this->edebug('Sending with mail()'); + $this->edebug('Sendmail path: ' . ini_get('sendmail_path')); + $this->edebug("Envelope sender: {$this->Sender}"); + $this->edebug("To: {$to}"); + $this->edebug("Subject: {$subject}"); + $this->edebug("Headers: {$header}"); + if (!$this->UseSendmailOptions || null === $params) { + $result = @mail($to, $subject, $body, $header); + } else { + $this->edebug("Additional params: {$params}"); + $result = @mail($to, $subject, $body, $header, $params); + } + $this->edebug('Result: ' . ($result ? 'true' : 'false')); + return $result; + } + + /** + * Output debugging info via a user-defined method. + * Only generates output if debug output is enabled. + * + * @see PHPMailer::$Debugoutput + * @see PHPMailer::$SMTPDebug + * + * @param string $str + */ + protected function edebug($str) + { + if ($this->SMTPDebug <= 0) { + return; + } + //Is this a PSR-3 logger? + if ($this->Debugoutput instanceof \Psr\Log\LoggerInterface) { + $this->Debugoutput->debug(rtrim($str, "\r\n")); + + return; + } + //Avoid clash with built-in function names + if (is_callable($this->Debugoutput) && !in_array($this->Debugoutput, ['error_log', 'html', 'echo'])) { + call_user_func($this->Debugoutput, $str, $this->SMTPDebug); + + return; + } + switch ($this->Debugoutput) { + case 'error_log': + //Don't output, just log + /** @noinspection ForgottenDebugOutputInspection */ + error_log($str); + break; + case 'html': + //Cleans up output a bit for a better looking, HTML-safe output + echo htmlentities( + preg_replace('/[\r\n]+/', '', $str), + ENT_QUOTES, + 'UTF-8' + ), "
\n"; + break; + case 'echo': + default: + //Normalize line breaks + $str = preg_replace('/\r\n|\r/m', "\n", $str); + echo gmdate('Y-m-d H:i:s'), + "\t", + //Trim trailing space + trim( + //Indent for readability, except for trailing break + str_replace( + "\n", + "\n \t ", + trim($str) + ) + ), + "\n"; + } + } + + /** + * Sets message type to HTML or plain. + * + * @param bool $isHtml True for HTML mode + */ + public function isHTML($isHtml = true) + { + if ($isHtml) { + $this->ContentType = static::CONTENT_TYPE_TEXT_HTML; + } else { + $this->ContentType = static::CONTENT_TYPE_PLAINTEXT; + } + } + + /** + * Send messages using SMTP. + */ + public function isSMTP() + { + $this->Mailer = 'smtp'; + } + + /** + * Send messages using PHP's mail() function. + */ + public function isMail() + { + $this->Mailer = 'mail'; + } + + /** + * Extract sendmail path and parse to deal with known parameters. + * + * @param string $sendmailPath The sendmail path as set in php.ini + * + * @return string The sendmail path without the known parameters + */ + private function parseSendmailPath($sendmailPath) + { + $sendmailPath = trim((string)$sendmailPath); + if ($sendmailPath === '') { + return $sendmailPath; + } + + $parts = preg_split('/\s+/', $sendmailPath); + if (empty($parts)) { + return $sendmailPath; + } + + $command = array_shift($parts); + $remainder = []; + + // Parse only -t, -i, -oi and -f parameters. + for ($i = 0; $i < count($parts); ++$i) { + $part = $parts[$i]; + if (preg_match('/^-(i|oi|t)$/', $part, $matches)) { + continue; + } + if (preg_match('/^-f(.*)$/', $part, $matches)) { + $address = $matches[1]; + if ($address === '' && isset($parts[$i + 1]) && strpos($parts[$i + 1], '-') !== 0) { + $address = $parts[++$i]; + } + $this->Sender = $address; + continue; + } + + $remainder[] = $part; + } + + // The params that are not parsed are added back to the command. + if (!empty($remainder)) { + $command .= ' ' . implode(' ', $remainder); + } + + return $command; + } + + /** + * Send messages using $Sendmail. + */ + public function isSendmail() + { + $ini_sendmail_path = ini_get('sendmail_path'); + + if (false === stripos($ini_sendmail_path, 'sendmail')) { + $ini_sendmail_path = '/usr/sbin/sendmail'; + } + $this->Sendmail = $this->parseSendmailPath($ini_sendmail_path); + $this->Mailer = 'sendmail'; + } + + /** + * Send messages using qmail. + */ + public function isQmail() + { + $ini_sendmail_path = ini_get('sendmail_path'); + + if (false === stripos($ini_sendmail_path, 'qmail')) { + $ini_sendmail_path = '/var/qmail/bin/qmail-inject'; + } + $this->Sendmail = $this->parseSendmailPath($ini_sendmail_path); + $this->Mailer = 'qmail'; + } + + /** + * Add a "To" address. + * + * @param string $address The email address to send to + * @param string $name + * + * @throws Exception + * + * @return bool true on success, false if address already used or invalid in some way + */ + public function addAddress($address, $name = '') + { + return $this->addOrEnqueueAnAddress('to', $address, $name); + } + + /** + * Add a "CC" address. + * + * @param string $address The email address to send to + * @param string $name + * + * @throws Exception + * + * @return bool true on success, false if address already used or invalid in some way + */ + public function addCC($address, $name = '') + { + return $this->addOrEnqueueAnAddress('cc', $address, $name); + } + + /** + * Add a "BCC" address. + * + * @param string $address The email address to send to + * @param string $name + * + * @throws Exception + * + * @return bool true on success, false if address already used or invalid in some way + */ + public function addBCC($address, $name = '') + { + return $this->addOrEnqueueAnAddress('bcc', $address, $name); + } + + /** + * Add a "Reply-To" address. + * + * @param string $address The email address to reply to + * @param string $name + * + * @throws Exception + * + * @return bool true on success, false if address already used or invalid in some way + */ + public function addReplyTo($address, $name = '') + { + return $this->addOrEnqueueAnAddress('Reply-To', $address, $name); + } + + /** + * Add an address to one of the recipient arrays or to the ReplyTo array. Because PHPMailer + * can't validate addresses with an IDN without knowing the PHPMailer::$CharSet (that can still + * be modified after calling this function), addition of such addresses is delayed until send(). + * Addresses that have been added already return false, but do not throw exceptions. + * + * @param string $kind One of 'to', 'cc', 'bcc', or 'Reply-To' + * @param string $address The email address + * @param string $name An optional username associated with the address + * + * @throws Exception + * + * @return bool true on success, false if address already used or invalid in some way + */ + protected function addOrEnqueueAnAddress($kind, $address, $name) + { + $pos = false; + if ($address !== null) { + $address = trim($address); + $pos = strrpos($address, '@'); + } + if (false === $pos) { + //At-sign is missing. + $error_message = sprintf( + '%s (%s): %s', + self::lang('invalid_address'), + $kind, + $address + ); + $this->setError($error_message); + $this->edebug($error_message); + if ($this->exceptions) { + throw new Exception($error_message); + } + + return false; + } + if ($name !== null && is_string($name)) { + $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim + } else { + $name = ''; + } + $params = [$kind, $address, $name]; + //Enqueue addresses with IDN until we know the PHPMailer::$CharSet. + //Domain is assumed to be whatever is after the last @ symbol in the address + if ($this->has8bitChars(substr($address, ++$pos))) { + if (static::idnSupported()) { + if ('Reply-To' !== $kind) { + if (!array_key_exists($address, $this->RecipientsQueue)) { + $this->RecipientsQueue[$address] = $params; + + return true; + } + } elseif (!array_key_exists($address, $this->ReplyToQueue)) { + $this->ReplyToQueue[$address] = $params; + + return true; + } + } + //We have an 8-bit domain, but we are missing the necessary extensions to support it + //Or we are already sending to this address + return false; + } + + //Immediately add standard addresses without IDN. + return call_user_func_array([$this, 'addAnAddress'], $params); + } + + /** + * Set the boundaries to use for delimiting MIME parts. + * If you override this, ensure you set all 3 boundaries to unique values. + * The default boundaries include a "=_" sequence which cannot occur in quoted-printable bodies, + * as suggested by https://www.rfc-editor.org/rfc/rfc2045#section-6.7 + * + * @return void + */ + public function setBoundaries() + { + $this->uniqueid = $this->generateId(); + $this->boundary[1] = 'b1=_' . $this->uniqueid; + $this->boundary[2] = 'b2=_' . $this->uniqueid; + $this->boundary[3] = 'b3=_' . $this->uniqueid; + } + + /** + * Add an address to one of the recipient arrays or to the ReplyTo array. + * Addresses that have been added already return false, but do not throw exceptions. + * + * @param string $kind One of 'to', 'cc', 'bcc', or 'ReplyTo' + * @param string $address The email address to send, resp. to reply to + * @param string $name + * + * @throws Exception + * + * @return bool true on success, false if address already used or invalid in some way + */ + protected function addAnAddress($kind, $address, $name = '') + { + if ( + self::$validator === 'php' && + ((bool) preg_match('/[\x80-\xFF]/', $address)) + ) { + //The caller has not altered the validator and is sending to an address + //with UTF-8, so assume that they want UTF-8 support instead of failing + $this->CharSet = self::CHARSET_UTF8; + self::$validator = 'eai'; + } + if (!in_array($kind, ['to', 'cc', 'bcc', 'Reply-To'])) { + $error_message = sprintf( + '%s: %s', + self::lang('Invalid recipient kind'), + $kind + ); + $this->setError($error_message); + $this->edebug($error_message); + if ($this->exceptions) { + throw new Exception($error_message); + } + + return false; + } + if (!static::validateAddress($address)) { + $error_message = sprintf( + '%s (%s): %s', + self::lang('invalid_address'), + $kind, + $address + ); + $this->setError($error_message); + $this->edebug($error_message); + if ($this->exceptions) { + throw new Exception($error_message); + } + + return false; + } + if ('Reply-To' !== $kind) { + if (!array_key_exists(strtolower($address), $this->all_recipients)) { + $this->{$kind}[] = [$address, $name]; + $this->all_recipients[strtolower($address)] = true; + + return true; + } + } else { + foreach ($this->ReplyTo as $replyTo) { + if (0 === strcasecmp($replyTo[0], $address)) { + return false; + } + } + $this->ReplyTo[] = [$address, $name]; + + return true; + } + return false; + } + + /** + * Parse and validate a string containing one or more RFC822-style comma-separated email addresses + * of the form "display name
" into an array of name/address pairs. + * Uses the imap_rfc822_parse_adrlist function if the IMAP extension is available and + * the deprecated $useimap argument is truthy. + * Note that quotes in the name part are removed. + * + * @see https://www.andrew.cmu.edu/user/agreen1/testing/mrbs/web/Mail/RFC822.php A more careful implementation + * + * @param string $addrstr The address list string + * @param bool|null $useimap Deprecated in PHPMailer 6.11.0. + * Truthy values request the deprecated IMAP parser + * and trigger a deprecation warning. + * @param string $charset The charset to use when decoding the address list string. + * + * @return array + */ + public static function parseAddresses($addrstr, $useimap = null, $charset = self::CHARSET_ISO88591) + { + if ($useimap == true) { + trigger_error(self::lang('deprecated_argument') . '$useimap', E_USER_DEPRECATED); + } + $addresses = []; + if ($useimap == true && function_exists('imap_rfc822_parse_adrlist')) { + //Use this built-in parser if it's available + // phpcs:ignore PHPCompatibility.FunctionUse.RemovedFunctions.imap_rfc822_parse_adrlistRemoved -- wrapped in function_exists() + $list = imap_rfc822_parse_adrlist($addrstr, ''); + // Clear any potential IMAP errors to get rid of notices being thrown at end of script. + // phpcs:ignore PHPCompatibility.FunctionUse.RemovedFunctions.imap_errorsRemoved -- wrapped in function_exists() + imap_errors(); + foreach ($list as $address) { + if ( + '.SYNTAX-ERROR.' !== $address->host && + static::validateAddress($address->mailbox . '@' . $address->host) + ) { + //Decode the name part if it's present and maybe encoded + if ( + property_exists($address, 'personal') + && is_string($address->personal) + && $address->personal !== '' + ) { + $address->personal = static::decodeHeader($address->personal, $charset); + } + + $addresses[] = [ + 'name' => (property_exists($address, 'personal') ? $address->personal : ''), + 'address' => $address->mailbox . '@' . $address->host, + ]; + } + } + } else { + //Use this simpler parser + $addresses = static::parseSimplerAddresses($addrstr, $charset); + } + + return $addresses; + } + + /** + * Parse a string containing one or more RFC822-style comma-separated email addresses + * with the form "display name
" into an array of name/address pairs. + * Uses a simpler parser that does not require the IMAP extension but doesnt support + * the full RFC822 spec. For full RFC822 support, use the PHP IMAP extension. + * + * @param string $addrstr The address list string + * @param string $charset The charset to use when decoding the address list string. + * + * @return array + */ + protected static function parseSimplerAddresses($addrstr, $charset) + { + // Emit a runtime notice to recommend using the IMAP extension for full RFC822 parsing + trigger_error(self::lang('imap_recommended'), E_USER_NOTICE); + + $addresses = []; + $list = explode(',', $addrstr); + foreach ($list as $address) { + $address = trim($address); + //Is there a separate name part? + if (strpos($address, '<') === false) { + //No separate name, just use the whole thing + if (static::validateAddress($address)) { + $addresses[] = [ + 'name' => '', + 'address' => $address, + ]; + } + } else { + $parsed = static::parseEmailString($address); + $email = $parsed['email']; + if (static::validateAddress($email)) { + $name = static::decodeHeader($parsed['name'], $charset); + $addresses[] = [ + //Remove any surrounding quotes and spaces from the name + 'name' => trim($name, '\'" '), + 'address' => $email, + ]; + } + } + } + + return $addresses; + } + + /** + * Parse a string containing an email address with an optional name + * and divide it into a name and email address. + * + * @param string $input The email with name. + * + * @return array{name: string, email: string} + */ + private static function parseEmailString($input) + { + $input = trim((string)$input); + + if ($input === '') { + return ['name' => '', 'email' => '']; + } + + $pattern = '/^\s*(?:(?:"([^"]*)"|\'([^\']*)\'|([^<]*?))\s*)?<\s*([^>]+)\s*>\s*$/'; + if (preg_match($pattern, $input, $matches)) { + $name = ''; + // Double quotes including special scenarios. + if (isset($matches[1]) && $matches[1] !== '') { + $name = $matches[1]; + // Single quotes including special scenarios. + } elseif (isset($matches[2]) && $matches[2] !== '') { + $name = $matches[2]; + // Simplest scenario, name and email are in the format "Name ". + } elseif (isset($matches[3])) { + $name = trim($matches[3]); + } + + return ['name' => $name, 'email' => trim($matches[4])]; + } + + return ['name' => '', 'email' => $input]; + } + + /** + * Set the From and FromName properties. + * + * @param string $address + * @param string $name + * @param bool $auto Whether to also set the Sender address, defaults to true + * + * @throws Exception + * + * @return bool + */ + public function setFrom($address, $name = '', $auto = true) + { + if (is_null($name)) { + //Helps avoid a deprecation warning in the preg_replace() below + $name = ''; + } + $address = trim((string)$address); + $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim + //Don't validate now addresses with IDN. Will be done in send(). + $pos = strrpos($address, '@'); + if ( + (false === $pos) + || ((!$this->has8bitChars(substr($address, ++$pos)) || !static::idnSupported()) + && !static::validateAddress($address)) + ) { + $error_message = sprintf( + '%s (From): %s', + self::lang('invalid_address'), + $address + ); + $this->setError($error_message); + $this->edebug($error_message); + if ($this->exceptions) { + throw new Exception($error_message); + } + + return false; + } + $this->From = $address; + $this->FromName = $name; + if ($auto && empty($this->Sender)) { + $this->Sender = $address; + } + + return true; + } + + /** + * Return the Message-ID header of the last email. + * Technically this is the value from the last time the headers were created, + * but it's also the message ID of the last sent message except in + * pathological cases. + * + * @return string + */ + public function getLastMessageID() + { + return $this->lastMessageID; + } + + /** + * Check that a string looks like an email address. + * Validation patterns supported: + * * `auto` Pick best pattern automatically; + * * `pcre8` Use the squiloople.com pattern, requires PCRE > 8.0; + * * `pcre` Use old PCRE implementation; + * * `php` Use PHP built-in FILTER_VALIDATE_EMAIL; + * * `html5` Use the pattern given by the HTML5 spec for 'email' type form input elements. + * * `eai` Use a pattern similar to the HTML5 spec for 'email' and to firefox, extended to support EAI (RFC6530). + * * `noregex` Don't use a regex: super fast, really dumb. + * Alternatively you may pass in a callable to inject your own validator, for example: + * + * ```php + * PHPMailer::validateAddress('user@example.com', function($address) { + * return (strpos($address, '@') !== false); + * }); + * ``` + * + * You can also set the PHPMailer::$validator static to a callable, allowing built-in methods to use your validator. + * + * @param string $address The email address to check + * @param string|callable $patternselect Which pattern to use + * + * @return bool + */ + public static function validateAddress($address, $patternselect = null) + { + if (null === $patternselect) { + $patternselect = static::$validator; + } + //Don't allow strings as callables, see SECURITY.md and CVE-2021-3603 + if (is_callable($patternselect) && !is_string($patternselect)) { + return call_user_func($patternselect, $address); + } + //Reject line breaks in addresses; it's valid RFC5322, but not RFC5321 + if (strpos($address, "\n") !== false || strpos($address, "\r") !== false) { + return false; + } + switch ($patternselect) { + case 'pcre': //Kept for BC + case 'pcre8': + /* + * A more complex and more permissive version of the RFC5322 regex on which FILTER_VALIDATE_EMAIL + * is based. + * In addition to the addresses allowed by filter_var, also permits: + * * dotless domains: `a@b` + * * comments: `1234 @ local(blah) .machine .example` + * * quoted elements: `'"test blah"@example.org'` + * * numeric TLDs: `a@b.123` + * * unbracketed IPv4 literals: `a@192.168.0.1` + * * IPv6 literals: 'first.last@[IPv6:a1::]' + * Not all of these will necessarily work for sending! + * + * @copyright 2009-2010 Michael Rushton + * Feel free to use and redistribute this code. But please keep this copyright notice. + */ + return (bool) preg_match( + '/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)' . + '((?>(?>(?>((?>(?>(?>\x0D\x0A)?[\t ])+|(?>[\t ]*\x0D\x0A)?[\t ]+)?)(\((?>(?2)' . + '(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)' . + '([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*' . + '(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)' . + '(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}' . + '|(?!(?:.*[a-f0-9][:\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:' . + '|(?!(?:.*[a-f0-9]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}' . + '|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD', + $address + ); + case 'html5': + /* + * This is the pattern used in the HTML5 spec for validation of 'email' type form input elements. + * + * @see https://html.spec.whatwg.org/#e-mail-state-(type=email) + */ + return (bool) preg_match( + '/^[a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}' . + '[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/sD', + $address + ); + case 'eai': + /* + * This is the pattern used in the HTML5 spec for validation of 'email' type + * form input elements (as above), modified to accept Unicode email addresses. + * This is also more lenient than Firefox' html5 spec, in order to make the regex faster. + * 'eai' is an acronym for Email Address Internationalization. + * This validator is selected automatically if you attempt to use recipient addresses + * that contain Unicode characters in the local part. + * + * @see https://html.spec.whatwg.org/#e-mail-state-(type=email) + * @see https://en.wikipedia.org/wiki/International_email + */ + return (bool) preg_match( + '/^[-\p{L}\p{N}\p{M}.!#$%&\'*+\/=?^_`{|}~]+@[\p{L}\p{N}\p{M}](?:[\p{L}\p{N}\p{M}-]{0,61}' . + '[\p{L}\p{N}\p{M}])?(?:\.[\p{L}\p{N}\p{M}]' . + '(?:[-\p{L}\p{N}\p{M}]{0,61}[\p{L}\p{N}\p{M}])?)*$/usD', + $address + ); + case 'php': + default: + return filter_var($address, FILTER_VALIDATE_EMAIL) !== false; + } + } + + /** + * Tells whether IDNs (Internationalized Domain Names) are supported or not. This requires the + * `intl` and `mbstring` PHP extensions. + * + * @return bool `true` if required functions for IDN support are present + */ + public static function idnSupported() + { + return function_exists('idn_to_ascii') && function_exists('mb_convert_encoding'); + } + + /** + * Converts IDN in given email address to its ASCII form, also known as punycode, if possible. + * Important: Address must be passed in same encoding as currently set in PHPMailer::$CharSet. + * This function silently returns unmodified address if: + * - No conversion is necessary (i.e. domain name is not an IDN, or is already in ASCII form) + * - Conversion to punycode is impossible (e.g. required PHP functions are not available) + * or fails for any reason (e.g. domain contains characters not allowed in an IDN). + * + * @see PHPMailer::$CharSet + * + * @param string $address The email address to convert + * + * @return string The encoded address in ASCII form + */ + public function punyencodeAddress($address) + { + //Verify we have required functions, CharSet, and at-sign. + $pos = strrpos($address, '@'); + if ( + !empty($this->CharSet) && + false !== $pos && + static::idnSupported() + ) { + $domain = substr($address, ++$pos); + //Verify CharSet string is a valid one, and domain properly encoded in this CharSet. + if ($this->has8bitChars($domain) && @mb_check_encoding($domain, $this->CharSet)) { + //Convert the domain from whatever charset it's in to UTF-8 + $domain = mb_convert_encoding($domain, self::CHARSET_UTF8, $this->CharSet); + //Ignore IDE complaints about this line - method signature changed in PHP 5.4 + $errorcode = 0; + if (defined('INTL_IDNA_VARIANT_UTS46')) { + //Use the current punycode standard (appeared in PHP 7.2) + $punycode = idn_to_ascii( + $domain, + \IDNA_DEFAULT | \IDNA_USE_STD3_RULES | \IDNA_CHECK_BIDI | + \IDNA_CHECK_CONTEXTJ | \IDNA_NONTRANSITIONAL_TO_ASCII, + \INTL_IDNA_VARIANT_UTS46 + ); + } elseif (defined('INTL_IDNA_VARIANT_2003')) { + //Fall back to this old, deprecated/removed encoding + // phpcs:ignore PHPCompatibility.Constants.RemovedConstants.intl_idna_variant_2003DeprecatedRemoved + $punycode = idn_to_ascii($domain, $errorcode, \INTL_IDNA_VARIANT_2003); + } else { + //Fall back to a default we don't know about + // phpcs:ignore PHPCompatibility.ParameterValues.NewIDNVariantDefault.NotSet + $punycode = idn_to_ascii($domain, $errorcode); + } + if (false !== $punycode) { + return substr($address, 0, $pos) . $punycode; + } + } + } + + return $address; + } + + /** + * Create a message and send it. + * Uses the sending method specified by $Mailer. + * + * @throws Exception + * + * @return bool false on error - See the ErrorInfo property for details of the error + */ + public function send() + { + try { + if (!$this->preSend()) { + return false; + } + + return $this->postSend(); + } catch (Exception $exc) { + $this->mailHeader = ''; + $this->setError($exc->getMessage()); + if ($this->exceptions) { + throw $exc; + } + + return false; + } + } + + /** + * Prepare a message for sending. + * + * @throws Exception + * + * @return bool + */ + public function preSend() + { + if ( + 'smtp' === $this->Mailer + || ('mail' === $this->Mailer && (\PHP_VERSION_ID >= 80000 || stripos(PHP_OS, 'WIN') === 0)) + ) { + //SMTP mandates RFC-compliant line endings + //and it's also used with mail() on Windows + static::setLE(self::CRLF); + } else { + //Maintain backward compatibility with legacy Linux command line mailers + static::setLE(PHP_EOL); + } + //Check for buggy PHP versions that add a header with an incorrect line break + if ( + 'mail' === $this->Mailer + && ((\PHP_VERSION_ID >= 70000 && \PHP_VERSION_ID < 70017) + || (\PHP_VERSION_ID >= 70100 && \PHP_VERSION_ID < 70103)) + && ini_get('mail.add_x_header') === '1' + && stripos(PHP_OS, 'WIN') === 0 + ) { + trigger_error(self::lang('buggy_php'), E_USER_WARNING); + } + + try { + $this->error_count = 0; //Reset errors + $this->mailHeader = ''; + + //The code below tries to support full use of Unicode, + //while remaining compatible with legacy SMTP servers to + //the greatest degree possible: If the message uses + //Unicode in the local parts of any addresses, it is sent + //using SMTPUTF8. If not, it it sent using + //punycode-encoded domains and plain SMTP. + if ( + static::CHARSET_UTF8 === strtolower($this->CharSet) && + ($this->anyAddressHasUnicodeLocalPart($this->RecipientsQueue) || + $this->anyAddressHasUnicodeLocalPart(array_keys($this->all_recipients)) || + $this->anyAddressHasUnicodeLocalPart($this->ReplyToQueue) || + $this->addressHasUnicodeLocalPart($this->From)) + ) { + $this->UseSMTPUTF8 = true; + } + //Dequeue recipient and Reply-To addresses with IDN + foreach (array_merge($this->RecipientsQueue, $this->ReplyToQueue) as $params) { + if (!$this->UseSMTPUTF8) { + $params[1] = $this->punyencodeAddress($params[1]); + } + call_user_func_array([$this, 'addAnAddress'], $params); + } + if (count($this->to) + count($this->cc) + count($this->bcc) < 1) { + throw new Exception(self::lang('provide_address'), self::STOP_CRITICAL); + } + + //Validate From, Sender, and ConfirmReadingTo addresses + foreach (['From', 'Sender', 'ConfirmReadingTo'] as $address_kind) { + if ($this->{$address_kind} === null) { + $this->{$address_kind} = ''; + continue; + } + $this->{$address_kind} = trim($this->{$address_kind}); + if (empty($this->{$address_kind})) { + continue; + } + $this->{$address_kind} = $this->punyencodeAddress($this->{$address_kind}); + if (!static::validateAddress($this->{$address_kind})) { + $error_message = sprintf( + '%s (%s): %s', + self::lang('invalid_address'), + $address_kind, + $this->{$address_kind} + ); + $this->setError($error_message); + $this->edebug($error_message); + if ($this->exceptions) { + throw new Exception($error_message); + } + + return false; + } + } + + //Set whether the message is multipart/alternative + if ($this->alternativeExists()) { + $this->ContentType = static::CONTENT_TYPE_MULTIPART_ALTERNATIVE; + } + + $this->setMessageType(); + //Refuse to send an empty message unless we are specifically allowing it + if (!$this->AllowEmpty && empty($this->Body)) { + throw new Exception(self::lang('empty_message'), self::STOP_CRITICAL); + } + + //Trim subject consistently + $this->Subject = trim($this->Subject); + + + //Create body before headers in case body makes changes to headers (e.g. altering transfer encoding) + $this->MIMEHeader = ''; + $this->MIMEBody = $this->createBody(); + //createBody may have added some headers, so retain them + $tempheaders = $this->MIMEHeader; + $this->MIMEHeader = $this->createHeader(); + $this->MIMEHeader .= $tempheaders; + + //To capture the complete message when using mail(), create + //an extra header list which createHeader() doesn't fold in + if ('mail' === $this->Mailer) { + if (count($this->to) > 0) { + $this->mailHeader .= $this->addrAppend('To', $this->to); + } else { + $this->mailHeader .= $this->headerLine('To', 'undisclosed-recipients:;'); + } + $this->mailHeader .= $this->headerLine( + 'Subject', + $this->encodeHeader($this->secureHeader($this->Subject)) + ); + } + + //Sign with DKIM if enabled + if ( + !empty($this->DKIM_domain) + && !empty($this->DKIM_selector) + && (!empty($this->DKIM_private_string) + || (!empty($this->DKIM_private) + && static::isPermittedPath($this->DKIM_private) + && file_exists($this->DKIM_private) + ) + ) + ) { + $header_dkim = $this->DKIM_Add( + $this->MIMEHeader . $this->mailHeader, + $this->encodeHeader($this->secureHeader($this->Subject)), + $this->MIMEBody + ); + $this->MIMEHeader = static::stripTrailingWSP($this->MIMEHeader) . static::$LE . + static::normalizeBreaks($header_dkim) . static::$LE; + } + + return true; + } catch (Exception $exc) { + $this->setError($exc->getMessage()); + if ($this->exceptions) { + throw $exc; + } + + return false; + } + } + + /** + * Actually send a message via the selected mechanism. + * + * @throws Exception + * + * @return bool + */ + public function postSend() + { + try { + //Choose the mailer and send through it + switch ($this->Mailer) { + case 'sendmail': + case 'qmail': + return $this->sendmailSend($this->MIMEHeader, $this->MIMEBody); + case 'smtp': + return $this->smtpSend($this->MIMEHeader, $this->MIMEBody); + case 'mail': + return $this->mailSend($this->MIMEHeader, $this->MIMEBody); + default: + $sendMethod = $this->Mailer . 'Send'; + if (!empty($this->Mailer) && method_exists($this, $sendMethod)) { + return $this->{$sendMethod}($this->MIMEHeader, $this->MIMEBody); + } + + return $this->mailSend($this->MIMEHeader, $this->MIMEBody); + } + } catch (Exception $exc) { + $this->setError($exc->getMessage()); + $this->edebug($exc->getMessage()); + if ($this->Mailer === 'smtp' && $this->SMTPKeepAlive == true && $this->smtp->connected()) { + $this->smtp->reset(); + } + if ($this->exceptions) { + throw $exc; + } + } + + return false; + } + + /** + * Send mail using the $Sendmail program. + * + * @see PHPMailer::$Sendmail + * + * @param string $header The message headers + * @param string $body The message body + * + * @throws Exception + * + * @return bool + */ + protected function sendmailSend($header, $body) + { + if ($this->Mailer === 'qmail') { + $this->edebug('Sending with qmail'); + } else { + $this->edebug('Sending with sendmail'); + } + $header = static::stripTrailingWSP($header) . static::$LE . static::$LE; + //This sets the SMTP envelope sender which gets turned into a return-path header by the receiver + //A space after `-f` is optional, but there is a long history of its presence + //causing problems, so we don't use one + //Exim docs: https://www.exim.org/exim-html-current/doc/html/spec_html/ch-the_exim_command_line.html + //Sendmail docs: https://www.sendmail.org/~ca/email/man/sendmail.html + //Example problem: https://www.drupal.org/node/1057954 + + //PHP 5.6 workaround + $sendmail_from_value = ini_get('sendmail_from'); + if (empty($this->Sender) && !empty($sendmail_from_value)) { + //PHP config has a sender address we can use + $this->Sender = ini_get('sendmail_from'); + } + + $sendmailArgs = []; + + // CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped. + // Also don't add the -f automatically unless it has been set either via Sender + // or sendmail_path. Otherwise, it can introduce new problems. + // @see http://github.com/PHPMailer/PHPMailer/issues/2298 + if (!empty($this->Sender) && static::validateAddress($this->Sender) && self::isShellSafe($this->Sender)) { + $sendmailArgs[] = '-f' . $this->Sender; + } + + // Qmail doesn't accept all the sendmail parameters + // @see https://github.com/PHPMailer/PHPMailer/issues/3189 + if ($this->Mailer !== 'qmail') { + $sendmailArgs[] = '-i'; + $sendmailArgs[] = '-t'; + } + + $resultArgs = (empty($sendmailArgs) ? '' : ' ' . implode(' ', $sendmailArgs)); + + $sendmail = trim(escapeshellcmd($this->Sendmail) . $resultArgs); + $this->edebug('Sendmail path: ' . $this->Sendmail); + $this->edebug('Sendmail command: ' . $sendmail); + $this->edebug('Envelope sender: ' . $this->Sender); + $this->edebug("Headers: {$header}"); + + if ($this->SingleTo) { + foreach ($this->SingleToArray as $toAddr) { + $mail = @popen($sendmail, 'w'); + if (!$mail) { + throw new Exception(self::lang('execute') . $this->Sendmail, self::STOP_CRITICAL); + } + $this->edebug("To: {$toAddr}"); + fwrite($mail, 'To: ' . $toAddr . "\n"); + fwrite($mail, $header); + fwrite($mail, $body); + $result = pclose($mail); + $addrinfo = static::parseAddresses($toAddr, null, $this->CharSet); + foreach ($addrinfo as $addr) { + $this->doCallback( + ($result === 0), + [[$addr['address'], $addr['name']]], + $this->cc, + $this->bcc, + $this->Subject, + $body, + $this->From, + [] + ); + } + $this->edebug("Result: " . ($result === 0 ? 'true' : 'false')); + if (0 !== $result) { + throw new Exception(self::lang('execute') . $this->Sendmail, self::STOP_CRITICAL); + } + } + } else { + $mail = @popen($sendmail, 'w'); + if (!$mail) { + throw new Exception(self::lang('execute') . $this->Sendmail, self::STOP_CRITICAL); + } + fwrite($mail, $header); + fwrite($mail, $body); + $result = pclose($mail); + $this->doCallback( + ($result === 0), + $this->to, + $this->cc, + $this->bcc, + $this->Subject, + $body, + $this->From, + [] + ); + $this->edebug("Result: " . ($result === 0 ? 'true' : 'false')); + if (0 !== $result) { + throw new Exception(self::lang('execute') . $this->Sendmail, self::STOP_CRITICAL); + } + } + + return true; + } + + /** + * Fix CVE-2016-10033 and CVE-2016-10045 by disallowing potentially unsafe shell characters. + * Note that escapeshellarg and escapeshellcmd are inadequate for our purposes, especially on Windows. + * + * @see https://github.com/PHPMailer/PHPMailer/issues/924 CVE-2016-10045 bug report + * + * @param string $string The string to be validated + * + * @return bool + */ + protected static function isShellSafe($string) + { + //It's not possible to use shell commands safely (which includes the mail() function) without escapeshellarg, + //but some hosting providers disable it, creating a security problem that we don't want to have to deal with, + //so we don't. + if (!function_exists('escapeshellarg') || !function_exists('escapeshellcmd')) { + return false; + } + + if ( + escapeshellcmd($string) !== $string + || !in_array(escapeshellarg($string), ["'$string'", "\"$string\""]) + ) { + return false; + } + + $length = strlen($string); + + for ($i = 0; $i < $length; ++$i) { + $c = $string[$i]; + + //All other characters have a special meaning in at least one common shell, including = and +. + //Full stop (.) has a special meaning in cmd.exe, but its impact should be negligible here. + //Note that this does permit non-Latin alphanumeric characters based on the current locale. + if (!ctype_alnum($c) && strpos('@_-.', $c) === false) { + return false; + } + } + + return true; + } + + /** + * Check whether a file path is of a permitted type. + * Used to reject URLs and phar files from functions that access local file paths, + * such as addAttachment. + * + * @param string $path A relative or absolute path to a file + * + * @return bool + */ + protected static function isPermittedPath($path) + { + //Matches scheme definition from https://www.rfc-editor.org/rfc/rfc3986#section-3.1 + return !preg_match('#^[a-z][a-z\d+.-]*://#i', $path); + } + + /** + * Check whether a file path is safe, accessible, and readable. + * + * @param string $path A relative or absolute path to a file + * + * @return bool + */ + protected static function fileIsAccessible($path) + { + if (!static::isPermittedPath($path)) { + return false; + } + $readable = is_file($path); + //If not a UNC path (expected to start with \\), check read permission, see #2069 + if (strpos($path, '\\\\') !== 0) { + $readable = $readable && is_readable($path); + } + return $readable; + } + + /** + * Send mail using the PHP mail() function. + * + * @see https://www.php.net/manual/en/book.mail.php + * + * @param string $header The message headers + * @param string $body The message body + * + * @throws Exception + * + * @return bool + */ + protected function mailSend($header, $body) + { + $header = static::stripTrailingWSP($header) . static::$LE . static::$LE; + + $toArr = []; + foreach ($this->to as $toaddr) { + $toArr[] = $this->addrFormat($toaddr); + } + $to = trim(implode(', ', $toArr)); + + //If there are no To-addresses (e.g. when sending only to BCC-addresses) + //the following should be added to get a correct DKIM-signature. + //Compare with $this->preSend() + if ($to === '') { + $to = 'undisclosed-recipients:;'; + } + + $params = null; + //This sets the SMTP envelope sender which gets turned into a return-path header by the receiver + //A space after `-f` is optional, but there is a long history of its presence + //causing problems, so we don't use one + //Exim docs: https://www.exim.org/exim-html-current/doc/html/spec_html/ch-the_exim_command_line.html + //Sendmail docs: https://www.sendmail.org/~ca/email/man/sendmail.html + //Example problem: https://www.drupal.org/node/1057954 + //CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped. + + //PHP 5.6 workaround + $sendmail_from_value = ini_get('sendmail_from'); + if (empty($this->Sender) && !empty($sendmail_from_value)) { + //PHP config has a sender address we can use + $this->Sender = ini_get('sendmail_from'); + } + if (!empty($this->Sender) && static::validateAddress($this->Sender)) { + $phpmailer_path = ini_get('sendmail_path'); + if (self::isShellSafe($this->Sender) && strpos($phpmailer_path, ' -f') === false) { + $params = sprintf('-f%s', $this->Sender); + } + $old_from = ini_get('sendmail_from'); + ini_set('sendmail_from', $this->Sender); + } + $result = false; + if ($this->SingleTo && count($toArr) > 1) { + foreach ($toArr as $toAddr) { + $result = $this->mailPassthru($toAddr, $this->Subject, $body, $header, $params); + $addrinfo = static::parseAddresses($toAddr, null, $this->CharSet); + foreach ($addrinfo as $addr) { + $this->doCallback( + $result, + [[$addr['address'], $addr['name']]], + $this->cc, + $this->bcc, + $this->Subject, + $body, + $this->From, + [] + ); + } + } + } else { + $result = $this->mailPassthru($to, $this->Subject, $body, $header, $params); + $this->doCallback($result, $this->to, $this->cc, $this->bcc, $this->Subject, $body, $this->From, []); + } + if (isset($old_from)) { + ini_set('sendmail_from', $old_from); + } + if (!$result) { + throw new Exception(self::lang('instantiate'), self::STOP_CRITICAL); + } + + return true; + } + + /** + * Get an instance to use for SMTP operations. + * Override this function to load your own SMTP implementation, + * or set one with setSMTPInstance. + * + * @return SMTP + */ + public function getSMTPInstance() + { + if (!is_object($this->smtp)) { + $this->smtp = new SMTP(); + } + + return $this->smtp; + } + + /** + * Provide an instance to use for SMTP operations. + * + * @return SMTP + */ + public function setSMTPInstance(SMTP $smtp) + { + $this->smtp = $smtp; + + return $this->smtp; + } + + /** + * Provide SMTP XCLIENT attributes + * + * @param string $name Attribute name + * @param ?string $value Attribute value + * + * @return bool + */ + public function setSMTPXclientAttribute($name, $value) + { + if (!in_array($name, SMTP::$xclient_allowed_attributes)) { + return false; + } + if (isset($this->SMTPXClient[$name]) && $value === null) { + unset($this->SMTPXClient[$name]); + } elseif ($value !== null) { + $this->SMTPXClient[$name] = $value; + } + + return true; + } + + /** + * Get SMTP XCLIENT attributes + * + * @return array + */ + public function getSMTPXclientAttributes() + { + return $this->SMTPXClient; + } + + /** + * Send mail via SMTP. + * Returns false if there is a bad MAIL FROM, RCPT, or DATA input. + * + * @see PHPMailer::setSMTPInstance() to use a different class. + * + * @uses \PHPMailer\PHPMailer\SMTP + * + * @param string $header The message headers + * @param string $body The message body + * + * @throws Exception + * + * @return bool + */ + protected function smtpSend($header, $body) + { + $header = static::stripTrailingWSP($header) . static::$LE . static::$LE; + $bad_rcpt = []; + if (!$this->smtpConnect($this->SMTPOptions)) { + throw new Exception(self::lang('smtp_connect_failed'), self::STOP_CRITICAL); + } + //If we have recipient addresses that need Unicode support, + //but the server doesn't support it, stop here + if ($this->UseSMTPUTF8 && !$this->smtp->getServerExt('SMTPUTF8')) { + throw new Exception(self::lang('no_smtputf8'), self::STOP_CRITICAL); + } + //Sender already validated in preSend() + if ('' === $this->Sender) { + $smtp_from = $this->From; + } else { + $smtp_from = $this->Sender; + } + if (count($this->SMTPXClient)) { + $this->smtp->xclient($this->SMTPXClient); + } + if (!$this->smtp->mail($smtp_from)) { + $this->setError(self::lang('from_failed') . $smtp_from . ' : ' . implode(',', $this->smtp->getError())); + throw new Exception($this->ErrorInfo, self::STOP_CRITICAL); + } + + $callbacks = []; + //Attempt to send to all recipients + foreach ([$this->to, $this->cc, $this->bcc] as $togroup) { + foreach ($togroup as $to) { + if (!$this->smtp->recipient($to[0], $this->dsn)) { + $error = $this->smtp->getError(); + $bad_rcpt[] = ['to' => $to[0], 'error' => $error['detail']]; + $isSent = false; + } else { + $isSent = true; + } + + $callbacks[] = ['issent' => $isSent, 'to' => $to[0], 'name' => $to[1]]; + } + } + + //Only send the DATA command if we have viable recipients + if ((count($this->all_recipients) > count($bad_rcpt)) && !$this->smtp->data($header . $body)) { + throw new Exception(self::lang('data_not_accepted'), self::STOP_CRITICAL); + } + + $smtp_transaction_id = $this->smtp->getLastTransactionID(); + + if ($this->SMTPKeepAlive) { + $this->smtp->reset(); + } else { + $this->smtp->quit(); + $this->smtp->close(); + } + + foreach ($callbacks as $cb) { + $this->doCallback( + $cb['issent'], + [[$cb['to'], $cb['name']]], + [], + [], + $this->Subject, + $body, + $this->From, + ['smtp_transaction_id' => $smtp_transaction_id] + ); + } + + //Create error message for any bad addresses + if (count($bad_rcpt) > 0) { + $errstr = ''; + foreach ($bad_rcpt as $bad) { + $errstr .= $bad['to'] . ': ' . $bad['error']; + } + throw new Exception(self::lang('recipients_failed') . $errstr, self::STOP_CONTINUE); + } + + return true; + } + + /** + * Initiate a connection to an SMTP server. + * Returns false if the operation failed. + * + * @param array $options An array of options compatible with stream_context_create() + * + * @throws Exception + * + * @uses \PHPMailer\PHPMailer\SMTP + * + * @return bool + */ + public function smtpConnect($options = null) + { + if (null === $this->smtp) { + $this->smtp = $this->getSMTPInstance(); + } + + //If no options are provided, use whatever is set in the instance + if (null === $options) { + $options = $this->SMTPOptions; + } + + //Already connected? + if ($this->smtp->connected()) { + return true; + } + + $this->smtp->setTimeout($this->Timeout); + $this->smtp->setDebugLevel($this->SMTPDebug); + $this->smtp->setDebugOutput($this->Debugoutput); + $this->smtp->setVerp($this->do_verp); + $this->smtp->setSMTPUTF8($this->UseSMTPUTF8); + if ($this->Host === null) { + $this->Host = 'localhost'; + } + $hosts = explode(';', $this->Host); + $lastexception = null; + + foreach ($hosts as $hostentry) { + $hostinfo = []; + if ( + !preg_match( + '/^(?:(ssl|tls):\/\/)?(.+?)(?::(\d+))?$/', + trim($hostentry), + $hostinfo + ) + ) { + $this->edebug(self::lang('invalid_hostentry') . ' ' . trim($hostentry)); + //Not a valid host entry + continue; + } + //$hostinfo[1]: optional ssl or tls prefix + //$hostinfo[2]: the hostname + //$hostinfo[3]: optional port number + //The host string prefix can temporarily override the current setting for SMTPSecure + //If it's not specified, the default value is used + + //Check the host name is a valid name or IP address before trying to use it + if (!static::isValidHost($hostinfo[2])) { + $this->edebug(self::lang('invalid_host') . ' ' . $hostinfo[2]); + continue; + } + $prefix = ''; + $secure = $this->SMTPSecure; + $tls = (static::ENCRYPTION_STARTTLS === $this->SMTPSecure); + if ('ssl' === $hostinfo[1] || ('' === $hostinfo[1] && static::ENCRYPTION_SMTPS === $this->SMTPSecure)) { + $prefix = 'ssl://'; + $tls = false; //Can't have SSL and TLS at the same time + $secure = static::ENCRYPTION_SMTPS; + } elseif ('tls' === $hostinfo[1]) { + $tls = true; + //TLS doesn't use a prefix + $secure = static::ENCRYPTION_STARTTLS; + } + //Do we need the OpenSSL extension? + $sslext = defined('OPENSSL_ALGO_SHA256'); + if (static::ENCRYPTION_STARTTLS === $secure || static::ENCRYPTION_SMTPS === $secure) { + //Check for an OpenSSL constant rather than using extension_loaded, which is sometimes disabled + if (!$sslext) { + throw new Exception(self::lang('extension_missing') . 'openssl', self::STOP_CRITICAL); + } + } + $host = $hostinfo[2]; + $port = $this->Port; + if ( + array_key_exists(3, $hostinfo) && + is_numeric($hostinfo[3]) && + $hostinfo[3] > 0 && + $hostinfo[3] < 65536 + ) { + $port = (int) $hostinfo[3]; + } + if ($this->smtp->connect($prefix . $host, $port, $this->Timeout, $options)) { + try { + if ($this->Helo) { + $hello = $this->Helo; + } else { + $hello = $this->serverHostname(); + } + $this->smtp->hello($hello); + //Automatically enable TLS encryption if: + //* it's not disabled + //* we are not connecting to localhost + //* we have openssl extension + //* we are not already using SSL + //* the server offers STARTTLS + if ( + $this->SMTPAutoTLS && + $this->Host !== 'localhost' && + $sslext && + $secure !== 'ssl' && + $this->smtp->getServerExt('STARTTLS') + ) { + $tls = true; + } + if ($tls) { + if (!$this->smtp->startTLS()) { + $message = $this->getSmtpErrorMessage('connect_host'); + throw new Exception($message); + } + //We must resend EHLO after TLS negotiation + $this->smtp->hello($hello); + } + if ( + $this->SMTPAuth && !$this->smtp->authenticate( + $this->Username, + $this->Password, + $this->AuthType, + $this->oauth + ) + ) { + throw new Exception(self::lang('authenticate')); + } + + return true; + } catch (Exception $exc) { + $lastexception = $exc; + $this->edebug($exc->getMessage()); + //We must have connected, but then failed TLS or Auth, so close connection nicely + $this->smtp->quit(); + } + } + } + //If we get here, all connection attempts have failed, so close connection hard + $this->smtp->close(); + //As we've caught all exceptions, just report whatever the last one was + if ($this->exceptions && null !== $lastexception) { + throw $lastexception; + } + if ($this->exceptions) { + // no exception was thrown, likely $this->smtp->connect() failed + $message = $this->getSmtpErrorMessage('connect_host'); + throw new Exception($message); + } + + return false; + } + + /** + * Close the active SMTP session if one exists. + */ + public function smtpClose() + { + if ((null !== $this->smtp) && $this->smtp->connected()) { + $this->smtp->quit(); + $this->smtp->close(); + } + } + + /** + * Set the language for error messages. + * The default language is English. + * + * @param string $langcode ISO 639-1 2-character language code (e.g. French is "fr") + * Optionally, the language code can be enhanced with a 4-character + * script annotation and/or a 2-character country annotation. + * @param string $lang_path Path to the language file directory, with trailing separator (slash) + * Do not set this from user input! + * + * @return bool Returns true if the requested language was loaded, false otherwise. + */ + public static function setLanguage($langcode = 'en', $lang_path = '') + { + //Backwards compatibility for renamed language codes + $renamed_langcodes = [ + 'br' => 'pt_br', + 'cz' => 'cs', + 'dk' => 'da', + 'no' => 'nb', + 'se' => 'sv', + 'rs' => 'sr', + 'tg' => 'tl', + 'am' => 'hy', + ]; + + if (array_key_exists($langcode, $renamed_langcodes)) { + $langcode = $renamed_langcodes[$langcode]; + } + + //Define full set of translatable strings in English + $PHPMAILER_LANG = [ + 'authenticate' => 'SMTP Error: Could not authenticate.', + 'buggy_php' => 'Your version of PHP is affected by a bug that may result in corrupted messages.' . + ' To fix it, switch to sending using SMTP, disable the mail.add_x_header option in' . + ' your php.ini, switch to macOS or Linux, or upgrade your PHP to version 7.0.17+ or 7.1.3+.', + 'connect_host' => 'SMTP Error: Could not connect to SMTP host.', + 'data_not_accepted' => 'SMTP Error: data not accepted.', + 'empty_message' => 'Message body empty', + 'encoding' => 'Unknown encoding: ', + 'execute' => 'Could not execute: ', + 'extension_missing' => 'Extension missing: ', + 'file_access' => 'Could not access file: ', + 'file_open' => 'File Error: Could not open file: ', + 'from_failed' => 'The following From address failed: ', + 'instantiate' => 'Could not instantiate mail function.', + 'invalid_address' => 'Invalid address: ', + 'invalid_header' => 'Invalid header name or value', + 'invalid_hostentry' => 'Invalid hostentry: ', + 'invalid_host' => 'Invalid host: ', + 'mailer_not_supported' => ' mailer is not supported.', + 'provide_address' => 'You must provide at least one recipient email address.', + 'recipients_failed' => 'SMTP Error: The following recipients failed: ', + 'signing' => 'Signing Error: ', + 'smtp_code' => 'SMTP code: ', + 'smtp_code_ex' => 'Additional SMTP info: ', + 'smtp_connect_failed' => 'SMTP connect() failed.', + 'smtp_detail' => 'Detail: ', + 'smtp_error' => 'SMTP server error: ', + 'variable_set' => 'Cannot set or reset variable: ', + 'no_smtputf8' => 'Server does not support SMTPUTF8 needed to send to Unicode addresses', + 'imap_recommended' => 'Using simplified address parser is not recommended. ' . + 'Install the PHP IMAP extension for full RFC822 parsing.', + 'deprecated_argument' => 'Deprecated Argument: ', + ]; + if (empty($lang_path)) { + //Calculate an absolute path so it can work if CWD is not here + $lang_path = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'language' . DIRECTORY_SEPARATOR; + } + + //Validate $langcode + $foundlang = true; + $langcode = strtolower($langcode); + if ( + !preg_match('/^(?P[a-z]{2})(?P diff --git a/lib/critters-hero.php b/lib/critters-hero.php new file mode 100644 index 0000000..0963dc1 --- /dev/null +++ b/lib/critters-hero.php @@ -0,0 +1,48 @@ +
+
+
+
+

My Critters

+

+ unique critter and counting! +

+

Create, explore and manage your collection of AI-generated critters.

+
+
+ One of your critters + +
+
+
+
+
+
+ +
+

+

Total Critters

+
+
+
+ +
+

+

Favourites

+
+
+
+ +
+

+

Archived

+
+
+ + Create a Critter + +
+
+
diff --git a/lib/cta.php b/lib/cta.php new file mode 100644 index 0000000..e1a5efb --- /dev/null +++ b/lib/cta.php @@ -0,0 +1,9 @@ +
+
+

Ready to meet your first critter?

+

It only takes a few clicks to bring your imagination to life.

+ + Get Started Free + +
+
diff --git a/lib/footer.php b/lib/footer.php new file mode 100644 index 0000000..bc03e03 --- /dev/null +++ b/lib/footer.php @@ -0,0 +1,33 @@ + + + diff --git a/lib/head.php b/lib/head.php new file mode 100644 index 0000000..c474bb6 --- /dev/null +++ b/lib/head.php @@ -0,0 +1,42 @@ + + + + + <?php echo htmlspecialchars($pageTitle ?? 'OurApp', ENT_QUOTES, 'UTF-8'); ?> + + + + + + + + diff --git a/lib/header.php b/lib/header.php new file mode 100644 index 0000000..3bb5f36 --- /dev/null +++ b/lib/header.php @@ -0,0 +1,77 @@ + prepare('SELECT credits FROM users WHERE id = :id'); + $stmt->execute(['id' => $_SESSION['user_id']]); + $userCredits = (int) $stmt->fetchColumn(); + } + ?> + + +
+
+ + + + + +
+ Login + Sign up +
+ +
+
diff --git a/lib/hero.php b/lib/hero.php new file mode 100644 index 0000000..ccbb3d0 --- /dev/null +++ b/lib/hero.php @@ -0,0 +1,66 @@ +
+
+
+ + + +
+
+

Imagine · Mix · Create

+

+ Bring your + imagination + to life. +

+

+ Create unique, AI-generated critters from your favorite combinations. Choose an + adjective, + animal, + action, + and place — and discover something completely new. +

+ +
+
+ + Unique creations +
+
+ + Save your favorites +
+
+ + Remix and explore +
+
+
+ +
+ +
+ A cute AI-generated critter +
+
+
+

Fluffy Pig

+

Building · On the Farm

+
+ +
+
+
+
diff --git a/lib/how-it-works.php b/lib/how-it-works.php new file mode 100644 index 0000000..d02fcd9 --- /dev/null +++ b/lib/how-it-works.php @@ -0,0 +1,41 @@ +
+
+
+

How it works

+

Create your perfect critter in four simple steps.

+
+
+
+
+ +
+

1. Choose an Adjective

+

Set the mood

+
+ +
+
+ +
+

2. Pick an Animal

+

From cute to wild

+
+ +
+
+ +
+

3. Add an Action

+

What are they doing?

+
+ +
+
+ +
+

4. Select a Location

+

Where do they live?

+
+
+
+
diff --git a/lib/mailer.php b/lib/mailer.php new file mode 100644 index 0000000..d08ef84 --- /dev/null +++ b/lib/mailer.php @@ -0,0 +1,106 @@ +isSMTP(); + $mail->Host = getenv('SMTP_HOST'); + $mail->SMTPAuth = true; + $mail->Port = (int) getenv('SMTP_PORT'); + $mail->Username = getenv('SMTP_USERNAME'); + $mail->Password = getenv('SMTP_PASSWORD'); + $mail->SMTPOptions = [ + 'ssl' => [ + 'cafile' => '/etc/ssl/certs/ca-certificates.crt', + 'verify_peer' => true, + 'verify_peer_name' => true, + ], + ]; + + $mail->setFrom(getenv('SMTP_FROM_EMAIL'), getenv('SMTP_FROM_NAME')); + $mail->isHTML(true); + + return $mail; +} + +function sendRegistrationConfirmationEmail(string $toEmail, string $username): bool +{ + try { + $mail = configureAppMailer(); + $mail->addAddress($toEmail, $username); + $mail->Subject = 'Welcome to OurApp!'; + + $safeUsername = htmlspecialchars($username, ENT_QUOTES, 'UTF-8'); + + $mail->Body = ' +
+

Welcome, ' . $safeUsername . '! 🐾

+

+ Your OurApp account has been created. You are ready to start creating unique, AI-generated critters — pick an adjective, animal, action, and location, and watch your imagination come to life. +

+

+ + Start Creating + +

+

+ If you didn’t create this account, you can safely ignore this email. +

+
+ '; + $mail->AltBody = "Welcome, {$username}!\n\nYour OurApp account has been created. Start creating unique, AI-generated critters at https://ourapp.local/\n\nIf you didn't create this account, you can safely ignore this email."; + + $mail->send(); + + return true; + } catch (PHPMailerException $e) { + error_log('Registration confirmation email failed: ' . (isset($mail) ? $mail->ErrorInfo : $e->getMessage())); + + return false; + } +} + +function sendPasswordResetEmail(string $toEmail, string $username, string $resetLink): bool +{ + try { + $mail = configureAppMailer(); + $mail->addAddress($toEmail, $username); + $mail->Subject = 'Reset your OurApp password'; + + $safeUsername = htmlspecialchars($username, ENT_QUOTES, 'UTF-8'); + $safeResetLink = htmlspecialchars($resetLink, ENT_QUOTES, 'UTF-8'); + + $mail->Body = ' +
+

Reset your password

+

+ Hi ' . $safeUsername . ', we received a request to reset your OurApp password. Click the button below to choose a new one. This link expires in 20 minutes. +

+

+ + Reset Password + +

+

+ If you didn’t request a password reset, you can safely ignore this email — your password will not be changed. +

+
+ '; + $mail->AltBody = "Hi {$username},\n\nWe received a request to reset your OurApp password. Visit the link below to choose a new one. This link expires in 20 minutes.\n\n{$resetLink}\n\nIf you didn't request a password reset, you can safely ignore this email."; + + $mail->send(); + + return true; + } catch (PHPMailerException $e) { + error_log('Password reset email failed: ' . (isset($mail) ? $mail->ErrorInfo : $e->getMessage())); + + return false; + } +} diff --git a/lib/recent-critters.php b/lib/recent-critters.php new file mode 100644 index 0000000..5229443 --- /dev/null +++ b/lib/recent-critters.php @@ -0,0 +1,48 @@ +
+
+

Recently Created Critters

+

A peek at what other creators just dreamed up.

+
+ +
+
+
+
+ A recently created critter +
+
+
+
+ A recently created critter +
+
+
+
+ A recently created critter +
+
+
+
+ A recently created critter +
+
+
+ + + +
+
diff --git a/lib/ticket.php b/lib/ticket.php new file mode 100644 index 0000000..0e8556b --- /dev/null +++ b/lib/ticket.php @@ -0,0 +1,60 @@ +prepare('SELECT * FROM users WHERE username = :username'); - $stmt->execute(['username' => $username]); + $stmt = $pdo->prepare('SELECT * FROM users WHERE email = :email'); + $stmt->execute(['email' => $email]); $user = $stmt->fetch(PDO::FETCH_ASSOC); if (!$user || !password_verify($password, $user['password'])) { - $errors['login'] = 'Invalid username or password.'; + $errors['login'] = 'Invalid email or password.'; } else { start_app_session(); session_regenerate_id(true); @@ -44,33 +44,107 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') { } } } +$pageTitle = 'Log In'; ?> - - - Log In - - - -
- -
-
- - - -
- + + + +
+
+ -
- - - -
+ +
+

Welcome back, explorer.

+

Your critters have been waiting.

+ + +
+ +
+ + +
+ Your password has been reset. You can now log in. +
+ + + +
+ +
+ + +
+ +

+ +
+
+
+ + Forgot password? +
+
+ + + +
+ +

+ +
+ + + +

+ New to OurApp? Create an account +

- - +
+
+ + + diff --git a/media/input.css b/media/input.css index f1d8c73..1933ee0 100644 --- a/media/input.css +++ b/media/input.css @@ -1 +1,5 @@ @import "tailwindcss"; + +@theme { + --font-sans: "Poppins", ui-sans-serif, system-ui, sans-serif; +} diff --git a/media/output.css b/media/output.css index 77989eb..95936fc 100644 --- a/media/output.css +++ b/media/output.css @@ -3,18 +3,105 @@ @layer theme, base, components, utilities; @layer theme { :root, :host { - --font-sans: -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-sans: "Poppins", ui-sans-serif, system-ui, sans-serif; --font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; + --color-red-50: oklch(97.1% 0.013 17.38); + --color-red-500: oklch(63.7% 0.237 25.331); + --color-red-600: oklch(57.7% 0.245 27.325); + --color-red-700: oklch(50.5% 0.213 27.518); + --color-amber-50: oklch(98.7% 0.022 95.277); + --color-amber-100: oklch(96.2% 0.059 95.617); + --color-amber-200: oklch(92.4% 0.12 95.746); + --color-amber-300: oklch(87.9% 0.169 91.605); + --color-amber-500: oklch(76.9% 0.188 70.08); + --color-amber-600: oklch(66.6% 0.179 58.318); + --color-amber-700: oklch(55.5% 0.163 48.998); + --color-amber-900: oklch(41.4% 0.112 45.904); + --color-yellow-400: oklch(85.2% 0.199 91.936); + --color-yellow-500: oklch(79.5% 0.184 86.047); + --color-yellow-950: oklch(28.6% 0.066 53.813); + --color-green-50: oklch(98.2% 0.018 155.826); + --color-green-100: oklch(96.2% 0.044 156.743); + --color-green-500: oklch(72.3% 0.219 149.579); + --color-green-600: oklch(62.7% 0.194 149.214); + --color-green-700: oklch(52.7% 0.154 150.069); + --color-blue-50: oklch(97% 0.014 254.604); + --color-blue-100: oklch(93.2% 0.032 255.585); + --color-blue-300: oklch(80.9% 0.105 251.813); + --color-blue-400: oklch(70.7% 0.165 254.624); + --color-blue-500: oklch(62.3% 0.214 259.815); + --color-blue-600: oklch(54.6% 0.245 262.881); + --color-blue-700: oklch(48.8% 0.243 264.376); + --color-purple-50: oklch(97.7% 0.014 308.299); + --color-purple-100: oklch(94.6% 0.033 307.174); + --color-purple-200: oklch(90.2% 0.063 306.703); + --color-purple-300: oklch(82.7% 0.119 306.383); + --color-purple-400: oklch(71.4% 0.203 305.504); + --color-purple-500: oklch(62.7% 0.265 303.9); + --color-purple-600: oklch(55.8% 0.288 302.321); + --color-purple-700: oklch(49.6% 0.265 301.924); + --color-pink-50: oklch(97.1% 0.014 343.198); + --color-pink-100: oklch(94.8% 0.028 342.258); + --color-pink-200: oklch(89.9% 0.061 343.231); + --color-pink-500: oklch(65.6% 0.241 354.308); + --color-pink-600: oklch(59.2% 0.249 0.584); + --color-pink-700: oklch(52.5% 0.223 3.958); + --color-gray-50: oklch(98.5% 0.002 247.839); + --color-gray-100: oklch(96.7% 0.003 264.542); --color-gray-200: oklch(92.8% 0.006 264.531); + --color-gray-300: oklch(87.2% 0.01 258.338); + --color-gray-400: oklch(70.7% 0.022 261.325); + --color-gray-500: oklch(55.1% 0.027 264.364); + --color-gray-600: oklch(44.6% 0.03 256.802); + --color-gray-700: oklch(37.3% 0.034 259.733); + --color-gray-800: oklch(27.8% 0.033 256.848); + --color-gray-900: oklch(21% 0.034 264.665); + --color-black: #000; + --color-white: #fff; --spacing: 0.25rem; + --container-sm: 24rem; + --container-md: 28rem; + --container-lg: 32rem; + --container-xl: 36rem; + --container-2xl: 42rem; --container-4xl: 56rem; + --text-xs: 0.75rem; + --text-xs--line-height: calc(1 / 0.75); + --text-sm: 0.875rem; + --text-sm--line-height: calc(1.25 / 0.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); + --text-4xl: 2.25rem; + --text-4xl--line-height: calc(2.5 / 2.25); + --text-5xl: 3rem; + --text-5xl--line-height: 1; + --font-weight-medium: 500; --font-weight-semibold: 600; + --font-weight-bold: 700; + --font-weight-extrabold: 800; + --tracking-tight: -0.025em; + --tracking-wide: 0.025em; + --tracking-widest: 0.1em; + --leading-tight: 1.25; + --leading-snug: 1.375; + --leading-relaxed: 1.625; + --radius-md: 0.375rem; --radius-lg: 0.5rem; + --radius-xl: 0.75rem; + --radius-2xl: 1rem; + --radius-3xl: 1.5rem; + --ease-in-out: cubic-bezier(0.4, 0, 0.2, 1); + --animate-spin: spin 1s linear infinite; + --blur-3xl: 64px; + --default-transition-duration: 150ms; + --default-transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); --default-font-family: var(--font-sans); --default-mono-font-family: var(--font-mono); } @@ -168,80 +255,1499 @@ } } @layer utilities { + .pointer-events-none { + pointer-events: none; + } + .visible { + visibility: visible; + } + .sr-only { + position: absolute; + width: 1px; + height: 1px; + padding: 0; + margin: -1px; + overflow: hidden; + clip-path: inset(50%); + white-space: nowrap; + border-width: 0; + } + .absolute { + position: absolute; + } + .fixed { + position: fixed; + } + .relative { + position: relative; + } .static { position: static; } - .m-1 { - margin: var(--spacing); + .inset-0 { + inset: 0px; + } + .-top-8 { + top: calc(var(--spacing) * -8); + } + .-top-24 { + top: calc(var(--spacing) * -24); + } + .top-1 { + top: var(--spacing); + } + .top-1\/2 { + top: calc(1 / 2 * 100%); + } + .top-3 { + top: calc(var(--spacing) * 3); + } + .top-4 { + top: calc(var(--spacing) * 4); + } + .top-40 { + top: calc(var(--spacing) * 40); + } + .-right-5 { + right: calc(var(--spacing) * -5); + } + .-right-24 { + right: calc(var(--spacing) * -24); + } + .right-0 { + right: 0px; + } + .right-3 { + right: calc(var(--spacing) * 3); + } + .right-4 { + right: calc(var(--spacing) * 4); + } + .-bottom-4 { + bottom: calc(var(--spacing) * -4); + } + .-bottom-6 { + bottom: calc(var(--spacing) * -6); + } + .-left-4 { + left: calc(var(--spacing) * -4); + } + .-left-5 { + left: calc(var(--spacing) * -5); + } + .-left-24 { + left: calc(var(--spacing) * -24); + } + .left-3 { + left: calc(var(--spacing) * 3); + } + .left-6 { + left: calc(var(--spacing) * 6); + } + .left-8 { + left: calc(var(--spacing) * 8); + } + .z-10 { + z-index: 10; + } + .z-20 { + z-index: 20; + } + .z-30 { + z-index: 30; + } + .z-50 { + z-index: 50; + } + .-mx-6 { + margin-inline: calc(var(--spacing) * -6); } .mx-auto { margin-inline: auto; } + .mt-1 { + margin-top: var(--spacing); + } + .mt-2 { + margin-top: calc(var(--spacing) * 2); + } + .mt-3 { + margin-top: calc(var(--spacing) * 3); + } + .mt-4 { + margin-top: calc(var(--spacing) * 4); + } + .mt-5 { + margin-top: calc(var(--spacing) * 5); + } + .mt-6 { + margin-top: calc(var(--spacing) * 6); + } + .mt-8 { + margin-top: calc(var(--spacing) * 8); + } + .mt-10 { + margin-top: calc(var(--spacing) * 10); + } + .mb-1 { + margin-bottom: var(--spacing); + } + .mb-2 { + margin-bottom: calc(var(--spacing) * 2); + } + .mb-3 { + margin-bottom: calc(var(--spacing) * 3); + } .mb-4 { margin-bottom: calc(var(--spacing) * 4); } + .mb-5 { + margin-bottom: calc(var(--spacing) * 5); + } + .mb-8 { + margin-bottom: calc(var(--spacing) * 8); + } + .mb-12 { + margin-bottom: calc(var(--spacing) * 12); + } + .ml-auto { + margin-left: auto; + } + .block { + display: block; + } + .contents { + display: contents; + } + .flex { + display: flex; + } .grid { display: grid; } + .hidden { + display: none; + } + .inline { + display: inline; + } + .inline-flex { + display: inline-flex; + } .table { display: table; } .aspect-square { aspect-ratio: 1 / 1; } + .h-2 { + height: calc(var(--spacing) * 2); + } + .h-4 { + height: calc(var(--spacing) * 4); + } + .h-5 { + height: calc(var(--spacing) * 5); + } + .h-6 { + height: calc(var(--spacing) * 6); + } + .h-7 { + height: calc(var(--spacing) * 7); + } + .h-8 { + height: calc(var(--spacing) * 8); + } + .h-9 { + height: calc(var(--spacing) * 9); + } + .h-10 { + height: calc(var(--spacing) * 10); + } + .h-12 { + height: calc(var(--spacing) * 12); + } + .h-14 { + height: calc(var(--spacing) * 14); + } + .h-16 { + height: calc(var(--spacing) * 16); + } + .h-72 { + height: calc(var(--spacing) * 72); + } + .h-full { + height: 100%; + } + .max-h-\[90vh\] { + max-height: 90vh; + } + .min-h-\[1\.5em\] { + min-height: 1.5em; + } + .min-h-\[60vh\] { + min-height: 60vh; + } + .min-h-screen { + min-height: 100vh; + } + .w-1 { + width: var(--spacing); + } + .w-1\/3 { + width: calc(1 / 3 * 100%); + } + .w-4 { + width: calc(var(--spacing) * 4); + } + .w-5 { + width: calc(var(--spacing) * 5); + } + .w-6 { + width: calc(var(--spacing) * 6); + } + .w-7 { + width: calc(var(--spacing) * 7); + } + .w-8 { + width: calc(var(--spacing) * 8); + } + .w-9 { + width: calc(var(--spacing) * 9); + } + .w-10 { + width: calc(var(--spacing) * 10); + } + .w-12 { + width: calc(var(--spacing) * 12); + } + .w-14 { + width: calc(var(--spacing) * 14); + } + .w-16 { + width: calc(var(--spacing) * 16); + } + .w-20 { + width: calc(var(--spacing) * 20); + } + .w-52 { + width: calc(var(--spacing) * 52); + } + .w-56 { + width: calc(var(--spacing) * 56); + } + .w-64 { + width: calc(var(--spacing) * 64); + } + .w-72 { + width: calc(var(--spacing) * 72); + } + .w-auto { + width: auto; + } .w-full { width: 100%; } + .w-px { + width: 1px; + } + .max-w-2xl { + max-width: var(--container-2xl); + } .max-w-4xl { max-width: var(--container-4xl); } + .max-w-\[85\%\] { + max-width: 85%; + } + .max-w-\[1400px\] { + max-width: 1400px; + } + .max-w-full { + max-width: 100%; + } + .max-w-lg { + max-width: var(--container-lg); + } + .max-w-md { + max-width: var(--container-md); + } + .max-w-sm { + max-width: var(--container-sm); + } + .max-w-xl { + max-width: var(--container-xl); + } + .min-w-5 { + min-width: calc(var(--spacing) * 5); + } + .flex-1 { + flex: 1; + } + .flex-shrink { + flex-shrink: 1; + } + .shrink-0 { + flex-shrink: 0; + } + .border-collapse { + border-collapse: collapse; + } + .-translate-y-1 { + --tw-translate-y: calc(var(--spacing) * -1); + translate: var(--tw-translate-x) var(--tw-translate-y); + } + .-translate-y-1\/2 { + --tw-translate-y: calc(calc(1 / 2 * 100%) * -1); + translate: var(--tw-translate-x) var(--tw-translate-y); + } + .-rotate-6 { + rotate: calc(6deg * -1); + } + .transform { + transform: var(--tw-rotate-x,) var(--tw-rotate-y,) var(--tw-rotate-z,) var(--tw-skew-x,) var(--tw-skew-y,); + } + .animate-spin { + animation: var(--animate-spin); + } + .cursor-not-allowed { + cursor: not-allowed; + } + .resize { + resize: both; + } + .snap-x { + scroll-snap-type: x var(--tw-scroll-snap-strictness); + } + .snap-mandatory { + --tw-scroll-snap-strictness: mandatory; + } + .snap-center { + scroll-snap-align: center; + } + .\[scrollbar-width\:none\] { + scrollbar-width: none; + } + .appearance-none { + appearance: none; + } + .grid-cols-2 { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } + .grid-cols-3 { + grid-template-columns: repeat(3, minmax(0, 1fr)); + } .grid-cols-4 { grid-template-columns: repeat(4, minmax(0, 1fr)); } + .flex-col { + flex-direction: column; + } + .flex-wrap { + flex-wrap: wrap; + } + .items-center { + align-items: center; + } + .items-end { + align-items: flex-end; + } + .items-start { + align-items: flex-start; + } + .justify-between { + justify-content: space-between; + } + .justify-center { + justify-content: center; + } + .gap-1 { + gap: var(--spacing); + } + .gap-1\.5 { + gap: calc(var(--spacing) * 1.5); + } + .gap-2 { + gap: calc(var(--spacing) * 2); + } + .gap-3 { + gap: calc(var(--spacing) * 3); + } .gap-4 { gap: calc(var(--spacing) * 4); } + .gap-6 { + gap: calc(var(--spacing) * 6); + } + .gap-8 { + gap: calc(var(--spacing) * 8); + } + .gap-10 { + gap: calc(var(--spacing) * 10); + } + .gap-12 { + gap: calc(var(--spacing) * 12); + } + :where(.space-y-2 > :not(:last-child)) { + --tw-space-y-reverse: 0; + margin-block-start: calc(calc(var(--spacing) * 2) * var(--tw-space-y-reverse)); + margin-block-end: calc(calc(var(--spacing) * 2) * calc(1 - var(--tw-space-y-reverse))); + } + :where(.space-y-4 > :not(:last-child)) { + --tw-space-y-reverse: 0; + margin-block-start: calc(calc(var(--spacing) * 4) * var(--tw-space-y-reverse)); + margin-block-end: calc(calc(var(--spacing) * 4) * calc(1 - var(--tw-space-y-reverse))); + } + :where(.space-y-5 > :not(:last-child)) { + --tw-space-y-reverse: 0; + margin-block-start: calc(calc(var(--spacing) * 5) * var(--tw-space-y-reverse)); + margin-block-end: calc(calc(var(--spacing) * 5) * calc(1 - var(--tw-space-y-reverse))); + } + .gap-x-6 { + column-gap: calc(var(--spacing) * 6); + } + .gap-y-2 { + row-gap: calc(var(--spacing) * 2); + } + :where(.divide-y > :not(:last-child)) { + --tw-divide-y-reverse: 0; + border-bottom-style: var(--tw-border-style); + border-top-style: var(--tw-border-style); + border-top-width: calc(1px * var(--tw-divide-y-reverse)); + border-bottom-width: calc(1px * calc(1 - var(--tw-divide-y-reverse))); + } + :where(.divide-gray-100 > :not(:last-child)) { + border-color: var(--color-gray-100); + } + .truncate { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + .overflow-hidden { + overflow: hidden; + } + .overflow-x-auto { + overflow-x: auto; + } + .overflow-y-auto { + overflow-y: auto; + } + .scroll-smooth { + scroll-behavior: smooth; + } + .rounded { + border-radius: 0.25rem; + } + .rounded-2xl { + border-radius: var(--radius-2xl); + } + .rounded-3xl { + border-radius: var(--radius-3xl); + } + .rounded-full { + border-radius: calc(infinity * 1px); + } .rounded-lg { border-radius: var(--radius-lg); } + .rounded-md { + border-radius: var(--radius-md); + } + .rounded-xl { + border-radius: var(--radius-xl); + } .border { border-style: var(--tw-border-style); border-width: 1px; } + .border-2 { + border-style: var(--tw-border-style); + border-width: 2px; + } + .border-4 { + border-style: var(--tw-border-style); + border-width: 4px; + } + .border-y { + border-block-style: var(--tw-border-style); + border-block-width: 1px; + } + .border-t { + border-top-style: var(--tw-border-style); + border-top-width: 1px; + } + .border-b-2 { + border-bottom-style: var(--tw-border-style); + border-bottom-width: 2px; + } + .border-dashed { + --tw-border-style: dashed; + border-style: dashed; + } + .border-blue-600 { + border-color: var(--color-blue-600); + } + .border-gray-100 { + border-color: var(--color-gray-100); + } .border-gray-200 { border-color: var(--color-gray-200); } + .border-gray-300 { + border-color: var(--color-gray-300); + } + .border-gray-800 { + border-color: var(--color-gray-800); + } + .border-transparent { + border-color: transparent; + } + .border-yellow-400 { + border-color: var(--color-yellow-400); + } + .border-t-gray-900 { + border-top-color: var(--color-gray-900); + } + .bg-amber-50 { + background-color: var(--color-amber-50); + } + .bg-amber-100 { + background-color: var(--color-amber-100); + } + .bg-amber-100\/70 { + background-color: color-mix(in srgb, oklch(96.2% 0.059 95.617) 70%, transparent); + @supports (color: color-mix(in lab, red, red)) { + background-color: color-mix(in oklab, var(--color-amber-100) 70%, transparent); + } + } + .bg-amber-300 { + background-color: var(--color-amber-300); + } + .bg-black { + background-color: var(--color-black); + } + .bg-black\/50 { + background-color: color-mix(in srgb, #000 50%, transparent); + @supports (color: color-mix(in lab, red, red)) { + background-color: color-mix(in oklab, var(--color-black) 50%, transparent); + } + } + .bg-blue-50 { + background-color: var(--color-blue-50); + } + .bg-blue-50\/60 { + background-color: color-mix(in srgb, oklch(97% 0.014 254.604) 60%, transparent); + @supports (color: color-mix(in lab, red, red)) { + background-color: color-mix(in oklab, var(--color-blue-50) 60%, transparent); + } + } + .bg-blue-100 { + background-color: var(--color-blue-100); + } + .bg-gray-100 { + background-color: var(--color-gray-100); + } + .bg-gray-300 { + background-color: var(--color-gray-300); + } + .bg-gray-300\/70 { + background-color: color-mix(in srgb, oklch(87.2% 0.01 258.338) 70%, transparent); + @supports (color: color-mix(in lab, red, red)) { + background-color: color-mix(in oklab, var(--color-gray-300) 70%, transparent); + } + } + .bg-gray-800 { + background-color: var(--color-gray-800); + } + .bg-gray-900 { + background-color: var(--color-gray-900); + } + .bg-green-50 { + background-color: var(--color-green-50); + } + .bg-green-100 { + background-color: var(--color-green-100); + } + .bg-pink-50 { + background-color: var(--color-pink-50); + } + .bg-pink-100 { + background-color: var(--color-pink-100); + } + .bg-purple-50 { + background-color: var(--color-purple-50); + } + .bg-purple-100 { + background-color: var(--color-purple-100); + } + .bg-purple-300 { + background-color: var(--color-purple-300); + } + .bg-red-50 { + background-color: var(--color-red-50); + } + .bg-transparent { + background-color: transparent; + } + .bg-white { + background-color: var(--color-white); + } + .bg-white\/70 { + background-color: color-mix(in srgb, #fff 70%, transparent); + @supports (color: color-mix(in lab, red, red)) { + background-color: color-mix(in oklab, var(--color-white) 70%, transparent); + } + } + .bg-white\/90 { + background-color: color-mix(in srgb, #fff 90%, transparent); + @supports (color: color-mix(in lab, red, red)) { + background-color: color-mix(in oklab, var(--color-white) 90%, transparent); + } + } + .bg-yellow-400 { + background-color: var(--color-yellow-400); + } + .bg-gradient-to-b { + --tw-gradient-position: to bottom in oklab; + background-image: linear-gradient(var(--tw-gradient-stops)); + } + .bg-gradient-to-br { + --tw-gradient-position: to bottom right in oklab; + background-image: linear-gradient(var(--tw-gradient-stops)); + } + .bg-gradient-to-r { + --tw-gradient-position: to right in oklab; + background-image: linear-gradient(var(--tw-gradient-stops)); + } + .from-amber-50 { + --tw-gradient-from: var(--color-amber-50); + --tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position)); + } + .from-black { + --tw-gradient-from: var(--color-black); + --tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position)); + } + .from-black\/10 { + --tw-gradient-from: color-mix(in srgb, #000 10%, transparent); + @supports (color: color-mix(in lab, red, red)) { + --tw-gradient-from: color-mix(in oklab, var(--color-black) 10%, transparent); + } + --tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position)); + } + .from-blue-50 { + --tw-gradient-from: var(--color-blue-50); + --tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position)); + } + .from-pink-50 { + --tw-gradient-from: var(--color-pink-50); + --tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position)); + } + .from-purple-600 { + --tw-gradient-from: var(--color-purple-600); + --tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position)); + } + .via-pink-50 { + --tw-gradient-via: var(--color-pink-50); + --tw-gradient-via-stops: var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-via) var(--tw-gradient-via-position), var(--tw-gradient-to) var(--tw-gradient-to-position); + --tw-gradient-stops: var(--tw-gradient-via-stops); + } + .via-pink-500 { + --tw-gradient-via: var(--color-pink-500); + --tw-gradient-via-stops: var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-via) var(--tw-gradient-via-position), var(--tw-gradient-to) var(--tw-gradient-to-position); + --tw-gradient-stops: var(--tw-gradient-via-stops); + } + .via-transparent { + --tw-gradient-via: transparent; + --tw-gradient-via-stops: var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-via) var(--tw-gradient-via-position), var(--tw-gradient-to) var(--tw-gradient-to-position); + --tw-gradient-stops: var(--tw-gradient-via-stops); + } + .via-white { + --tw-gradient-via: var(--color-white); + --tw-gradient-via-stops: var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-via) var(--tw-gradient-via-position), var(--tw-gradient-to) var(--tw-gradient-to-position); + --tw-gradient-stops: var(--tw-gradient-via-stops); + } + .to-amber-50 { + --tw-gradient-to: var(--color-amber-50); + --tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position)); + } + .to-amber-500 { + --tw-gradient-to: var(--color-amber-500); + --tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position)); + } + .to-black { + --tw-gradient-to: var(--color-black); + --tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position)); + } + .to-black\/40 { + --tw-gradient-to: color-mix(in srgb, #000 40%, transparent); + @supports (color: color-mix(in lab, red, red)) { + --tw-gradient-to: color-mix(in oklab, var(--color-black) 40%, transparent); + } + --tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position)); + } + .to-pink-500 { + --tw-gradient-to: var(--color-pink-500); + --tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position)); + } + .to-purple-50 { + --tw-gradient-to: var(--color-purple-50); + --tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position)); + } + .to-white { + --tw-gradient-to: var(--color-white); + --tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position)); + } + .bg-clip-text { + background-clip: text; + } + .fill-pink-500 { + fill: var(--color-pink-500); + } .object-cover { object-fit: cover; } + .p-2 { + padding: calc(var(--spacing) * 2); + } + .p-3 { + padding: calc(var(--spacing) * 3); + } + .p-4 { + padding: calc(var(--spacing) * 4); + } + .p-6 { + padding: calc(var(--spacing) * 6); + } + .p-8 { + padding: calc(var(--spacing) * 8); + } + .px-1 { + padding-inline: var(--spacing); + } + .px-2 { + padding-inline: calc(var(--spacing) * 2); + } + .px-2\.5 { + padding-inline: calc(var(--spacing) * 2.5); + } + .px-3 { + padding-inline: calc(var(--spacing) * 3); + } .px-4 { padding-inline: calc(var(--spacing) * 4); } + .px-5 { + padding-inline: calc(var(--spacing) * 5); + } + .px-6 { + padding-inline: calc(var(--spacing) * 6); + } + .px-8 { + padding-inline: calc(var(--spacing) * 8); + } + .py-1 { + padding-block: var(--spacing); + } + .py-1\.5 { + padding-block: calc(var(--spacing) * 1.5); + } + .py-2 { + padding-block: calc(var(--spacing) * 2); + } + .py-2\.5 { + padding-block: calc(var(--spacing) * 2.5); + } + .py-3 { + padding-block: calc(var(--spacing) * 3); + } + .py-10 { + padding-block: calc(var(--spacing) * 10); + } + .py-12 { + padding-block: calc(var(--spacing) * 12); + } + .py-14 { + padding-block: calc(var(--spacing) * 14); + } + .py-16 { + padding-block: calc(var(--spacing) * 16); + } + .py-20 { + padding-block: calc(var(--spacing) * 20); + } + .pt-3 { + padding-top: calc(var(--spacing) * 3); + } + .pt-5 { + padding-top: calc(var(--spacing) * 5); + } + .pt-6 { + padding-top: calc(var(--spacing) * 6); + } + .pt-8 { + padding-top: calc(var(--spacing) * 8); + } + .pr-3 { + padding-right: calc(var(--spacing) * 3); + } + .pr-9 { + padding-right: calc(var(--spacing) * 9); + } + .pr-10 { + padding-right: calc(var(--spacing) * 10); + } + .pb-1 { + padding-bottom: var(--spacing); + } + .pb-4 { + padding-bottom: calc(var(--spacing) * 4); + } + .pl-9 { + padding-left: calc(var(--spacing) * 9); + } + .pl-10 { + padding-left: calc(var(--spacing) * 10); + } + .text-center { + text-align: center; + } + .text-2xl { + font-size: var(--text-2xl); + line-height: var(--tw-leading, var(--text-2xl--line-height)); + } + .text-3xl { + font-size: var(--text-3xl); + line-height: var(--tw-leading, var(--text-3xl--line-height)); + } + .text-4xl { + font-size: var(--text-4xl); + line-height: var(--tw-leading, var(--text-4xl--line-height)); + } + .text-lg { + font-size: var(--text-lg); + line-height: var(--tw-leading, var(--text-lg--line-height)); + } + .text-sm { + font-size: var(--text-sm); + line-height: var(--tw-leading, var(--text-sm--line-height)); + } .text-xl { font-size: var(--text-xl); line-height: var(--tw-leading, var(--text-xl--line-height)); } + .text-xs { + font-size: var(--text-xs); + line-height: var(--tw-leading, var(--text-xs--line-height)); + } + .text-\[11px\] { + font-size: 11px; + } + .leading-relaxed { + --tw-leading: var(--leading-relaxed); + line-height: var(--leading-relaxed); + } + .leading-snug { + --tw-leading: var(--leading-snug); + line-height: var(--leading-snug); + } + .leading-tight { + --tw-leading: var(--leading-tight); + line-height: var(--leading-tight); + } + .font-bold { + --tw-font-weight: var(--font-weight-bold); + font-weight: var(--font-weight-bold); + } + .font-extrabold { + --tw-font-weight: var(--font-weight-extrabold); + font-weight: var(--font-weight-extrabold); + } + .font-medium { + --tw-font-weight: var(--font-weight-medium); + font-weight: var(--font-weight-medium); + } .font-semibold { --tw-font-weight: var(--font-weight-semibold); font-weight: var(--font-weight-semibold); } + .tracking-tight { + --tw-tracking: var(--tracking-tight); + letter-spacing: var(--tracking-tight); + } + .tracking-wide { + --tw-tracking: var(--tracking-wide); + letter-spacing: var(--tracking-wide); + } + .tracking-widest { + --tw-tracking: var(--tracking-widest); + letter-spacing: var(--tracking-widest); + } + .text-amber-500 { + color: var(--color-amber-500); + } + .text-amber-600 { + color: var(--color-amber-600); + } + .text-amber-700 { + color: var(--color-amber-700); + } + .text-amber-900 { + color: var(--color-amber-900); + } + .text-blue-300 { + color: var(--color-blue-300); + } + .text-blue-400 { + color: var(--color-blue-400); + } + .text-blue-500 { + color: var(--color-blue-500); + } + .text-blue-600 { + color: var(--color-blue-600); + } + .text-blue-700 { + color: var(--color-blue-700); + } + .text-gray-300 { + color: var(--color-gray-300); + } + .text-gray-400 { + color: var(--color-gray-400); + } + .text-gray-500 { + color: var(--color-gray-500); + } + .text-gray-600 { + color: var(--color-gray-600); + } + .text-gray-700 { + color: var(--color-gray-700); + } + .text-gray-800 { + color: var(--color-gray-800); + } + .text-gray-900 { + color: var(--color-gray-900); + } + .text-green-500 { + color: var(--color-green-500); + } + .text-green-600 { + color: var(--color-green-600); + } + .text-green-700 { + color: var(--color-green-700); + } + .text-pink-500 { + color: var(--color-pink-500); + } + .text-pink-600 { + color: var(--color-pink-600); + } + .text-pink-700 { + color: var(--color-pink-700); + } + .text-purple-300 { + color: var(--color-purple-300); + } + .text-purple-500 { + color: var(--color-purple-500); + } + .text-purple-600 { + color: var(--color-purple-600); + } + .text-purple-700 { + color: var(--color-purple-700); + } + .text-red-500 { + color: var(--color-red-500); + } + .text-red-600 { + color: var(--color-red-600); + } + .text-red-700 { + color: var(--color-red-700); + } + .text-transparent { + color: transparent; + } + .text-white { + color: var(--color-white); + } + .text-white\/90 { + color: color-mix(in srgb, #fff 90%, transparent); + @supports (color: color-mix(in lab, red, red)) { + color: color-mix(in oklab, var(--color-white) 90%, transparent); + } + } + .text-yellow-950 { + color: var(--color-yellow-950); + } .lowercase { text-transform: lowercase; } + .uppercase { + text-transform: uppercase; + } + .italic { + font-style: italic; + } + .underline { + text-decoration-line: underline; + } + .opacity-30 { + opacity: 30%; + } + .shadow { + --tw-shadow: 0 1px 3px 0 var(--tw-shadow-color, rgb(0 0 0 / 0.1)), 0 1px 2px -1px var(--tw-shadow-color, rgb(0 0 0 / 0.1)); + box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow); + } + .shadow-2xl { + --tw-shadow: 0 25px 50px -12px var(--tw-shadow-color, rgb(0 0 0 / 0.25)); + box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow); + } + .shadow-lg { + --tw-shadow: 0 10px 15px -3px var(--tw-shadow-color, rgb(0 0 0 / 0.1)), 0 4px 6px -4px var(--tw-shadow-color, rgb(0 0 0 / 0.1)); + box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow); + } + .shadow-md { + --tw-shadow: 0 4px 6px -1px var(--tw-shadow-color, rgb(0 0 0 / 0.1)), 0 2px 4px -2px var(--tw-shadow-color, rgb(0 0 0 / 0.1)); + box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow); + } .shadow-sm { --tw-shadow: 0 1px 3px 0 var(--tw-shadow-color, rgb(0 0 0 / 0.1)), 0 1px 2px -1px var(--tw-shadow-color, rgb(0 0 0 / 0.1)); box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow); } + .shadow-xl { + --tw-shadow: 0 20px 25px -5px var(--tw-shadow-color, rgb(0 0 0 / 0.1)), 0 8px 10px -6px var(--tw-shadow-color, rgb(0 0 0 / 0.1)); + box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow); + } + .ring-1 { + --tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor); + box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow); + } + .ring-amber-200 { + --tw-ring-color: var(--color-amber-200); + } + .ring-blue-100 { + --tw-ring-color: var(--color-blue-100); + } + .ring-gray-100 { + --tw-ring-color: var(--color-gray-100); + } + .ring-gray-200 { + --tw-ring-color: var(--color-gray-200); + } + .ring-pink-200 { + --tw-ring-color: var(--color-pink-200); + } + .outline { + outline-style: var(--tw-outline-style); + outline-width: 1px; + } + .blur-3xl { + --tw-blur: blur(var(--blur-3xl)); + filter: var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,); + } + .drop-shadow { + --tw-drop-shadow-size: drop-shadow(0 1px 2px var(--tw-drop-shadow-color, rgb(0 0 0 / 0.1))) drop-shadow(0 1px 1px var(--tw-drop-shadow-color, rgb(0 0 0 / 0.06))); + --tw-drop-shadow: drop-shadow(0 1px 2px rgb(0 0 0 / 0.1)) drop-shadow( 0 1px 1px rgb(0 0 0 / 0.06)); + filter: var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,); + } + .filter { + filter: var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,); + } + .backdrop-blur { + --tw-backdrop-blur: blur(8px); + -webkit-backdrop-filter: var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,); + backdrop-filter: var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,); + } + .backdrop-filter { + -webkit-backdrop-filter: var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,); + backdrop-filter: var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,); + } + .transition { + transition-property: color, background-color, border-color, outline-color, text-decoration-color, fill, stroke, --tw-gradient-from, --tw-gradient-via, --tw-gradient-to, opacity, box-shadow, transform, translate, scale, rotate, filter, -webkit-backdrop-filter, backdrop-filter, display, content-visibility, overlay, pointer-events; + transition-timing-function: var(--tw-ease, var(--default-transition-timing-function)); + transition-duration: var(--tw-duration, var(--default-transition-duration)); + } + .transition-all { + transition-property: all; + transition-timing-function: var(--tw-ease, var(--default-transition-timing-function)); + transition-duration: var(--tw-duration, var(--default-transition-duration)); + } + .transition-colors { + transition-property: color, background-color, border-color, outline-color, text-decoration-color, fill, stroke, --tw-gradient-from, --tw-gradient-via, --tw-gradient-to; + transition-timing-function: var(--tw-ease, var(--default-transition-timing-function)); + transition-duration: var(--tw-duration, var(--default-transition-duration)); + } + .transition-shadow { + transition-property: box-shadow; + transition-timing-function: var(--tw-ease, var(--default-transition-timing-function)); + transition-duration: var(--tw-duration, var(--default-transition-duration)); + } + .transition-transform { + transition-property: transform, translate, scale, rotate; + transition-timing-function: var(--tw-ease, var(--default-transition-timing-function)); + transition-duration: var(--tw-duration, var(--default-transition-duration)); + } + .duration-150 { + --tw-duration: 150ms; + transition-duration: 150ms; + } + .duration-200 { + --tw-duration: 200ms; + transition-duration: 200ms; + } + .duration-300 { + --tw-duration: 300ms; + transition-duration: 300ms; + } + .ease-in-out { + --tw-ease: var(--ease-in-out); + transition-timing-function: var(--ease-in-out); + } + .\[hostname\:port\] { + hostname: port; + } + @media (hover: hover) { + .group-hover\:scale-105:is(:where(.group):hover *) { + --tw-scale-x: 105%; + --tw-scale-y: 105%; + --tw-scale-z: 105%; + scale: var(--tw-scale-x) var(--tw-scale-y); + } + .group-hover\:scale-\[1\.02\]:is(:where(.group):hover *) { + scale: 1.02; + } + .hover\:-translate-y-0\.5:hover { + --tw-translate-y: calc(var(--spacing) * -0.5); + translate: var(--tw-translate-x) var(--tw-translate-y); + } + .hover\:-translate-y-1:hover { + --tw-translate-y: calc(var(--spacing) * -1); + translate: var(--tw-translate-x) var(--tw-translate-y); + } + .hover\:scale-110:hover { + --tw-scale-x: 110%; + --tw-scale-y: 110%; + --tw-scale-z: 110%; + scale: var(--tw-scale-x) var(--tw-scale-y); + } + .hover\:border-purple-200:hover { + border-color: var(--color-purple-200); + } + .hover\:bg-gray-50:hover { + background-color: var(--color-gray-50); + } + .hover\:bg-gray-100:hover { + background-color: var(--color-gray-100); + } + .hover\:bg-gray-200:hover { + background-color: var(--color-gray-200); + } + .hover\:bg-gray-700:hover { + background-color: var(--color-gray-700); + } + .hover\:bg-gray-800:hover { + background-color: var(--color-gray-800); + } + .hover\:bg-purple-50\/30:hover { + background-color: color-mix(in srgb, oklch(97.7% 0.014 308.299) 30%, transparent); + } + @supports (color: color-mix(in lab, red, red)) { + .hover\:bg-purple-50\/30:hover { + background-color: color-mix(in oklab, var(--color-purple-50) 30%, transparent); + } + } + .hover\:bg-white:hover { + background-color: var(--color-white); + } + .hover\:bg-yellow-500:hover { + background-color: var(--color-yellow-500); + } + .hover\:from-purple-700:hover { + --tw-gradient-from: var(--color-purple-700); + --tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position)); + } + .hover\:to-pink-600:hover { + --tw-gradient-to: var(--color-pink-600); + --tw-gradient-stops: var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position)); + } + .hover\:text-blue-600:hover { + color: var(--color-blue-600); + } + .hover\:text-gray-600:hover { + color: var(--color-gray-600); + } + .hover\:text-gray-700:hover { + color: var(--color-gray-700); + } + .hover\:text-gray-900:hover { + color: var(--color-gray-900); + } + .hover\:text-green-600:hover { + color: var(--color-green-600); + } + .hover\:text-pink-500:hover { + color: var(--color-pink-500); + } + .hover\:text-purple-600:hover { + color: var(--color-purple-600); + } + .hover\:underline:hover { + text-decoration-line: underline; + } + .hover\:shadow-lg:hover { + --tw-shadow: 0 10px 15px -3px var(--tw-shadow-color, rgb(0 0 0 / 0.1)), 0 4px 6px -4px var(--tw-shadow-color, rgb(0 0 0 / 0.1)); + box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow); + } + .hover\:shadow-md:hover { + --tw-shadow: 0 4px 6px -1px var(--tw-shadow-color, rgb(0 0 0 / 0.1)), 0 2px 4px -2px var(--tw-shadow-color, rgb(0 0 0 / 0.1)); + box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow); + } + } + .focus\:border-transparent:focus { + border-color: transparent; + } + .focus\:ring-2:focus { + --tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor); + box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow); + } + .focus\:ring-purple-400:focus { + --tw-ring-color: var(--color-purple-400); + } + .focus\:outline-none:focus { + --tw-outline-style: none; + outline-style: none; + } + .focus-visible\:ring-2:focus-visible { + --tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor); + box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow); + } + .focus-visible\:ring-purple-400:focus-visible { + --tw-ring-color: var(--color-purple-400); + } + .focus-visible\:ring-offset-2:focus-visible { + --tw-ring-offset-width: 2px; + --tw-ring-offset-shadow: var(--tw-ring-inset,) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color); + } + .focus-visible\:ring-inset:focus-visible { + --tw-ring-inset: inset; + } + .active\:scale-\[0\.98\]:active { + scale: 0.98; + } + @media (width >= 40rem) { + .sm\:block { + display: block; + } + .sm\:flex { + display: flex; + } + .sm\:hidden { + display: none; + } + .sm\:inline { + display: inline; + } + .sm\:inline-flex { + display: inline-flex; + } + .sm\:w-72 { + width: calc(var(--spacing) * 72); + } + .sm\:grid-cols-2 { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } + .sm\:grid-cols-3 { + grid-template-columns: repeat(3, minmax(0, 1fr)); + } + .sm\:flex-row { + flex-direction: row; + } + .sm\:items-end { + align-items: flex-end; + } + .sm\:items-start { + align-items: flex-start; + } + .sm\:justify-between { + justify-content: space-between; + } + .sm\:gap-4 { + gap: calc(var(--spacing) * 4); + } + .sm\:p-8 { + padding: calc(var(--spacing) * 8); + } + .sm\:p-10 { + padding: calc(var(--spacing) * 10); + } + .sm\:px-12 { + padding-inline: calc(var(--spacing) * 12); + } + .sm\:text-4xl { + font-size: var(--text-4xl); + line-height: var(--tw-leading, var(--text-4xl--line-height)); + } + .sm\:text-5xl { + font-size: var(--text-5xl); + line-height: var(--tw-leading, var(--text-5xl--line-height)); + } + } + @media (width >= 48rem) { + .md\:block { + display: block; + } + .md\:flex { + display: flex; + } + .md\:grid-cols-2 { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } + } + @media (width >= 64rem) { + .lg\:col-span-2 { + grid-column: span 2 / span 2; + } + .lg\:grid-cols-2 { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } + .lg\:grid-cols-3 { + grid-template-columns: repeat(3, minmax(0, 1fr)); + } + .lg\:grid-cols-4 { + grid-template-columns: repeat(4, minmax(0, 1fr)); + } + .lg\:flex-row { + flex-direction: row; + } + .lg\:items-center { + align-items: center; + } + .lg\:justify-between { + justify-content: space-between; + } + .lg\:py-24 { + padding-block: calc(var(--spacing) * 24); + } + } + .\[\&\:\:-webkit-scrollbar\]\:hidden::-webkit-scrollbar { + display: none; + } +} +@property --tw-translate-x { + syntax: "*"; + inherits: false; + initial-value: 0; +} +@property --tw-translate-y { + syntax: "*"; + inherits: false; + initial-value: 0; +} +@property --tw-translate-z { + syntax: "*"; + inherits: false; + initial-value: 0; +} +@property --tw-rotate-x { + syntax: "*"; + inherits: false; +} +@property --tw-rotate-y { + syntax: "*"; + inherits: false; +} +@property --tw-rotate-z { + syntax: "*"; + inherits: false; +} +@property --tw-skew-x { + syntax: "*"; + inherits: false; +} +@property --tw-skew-y { + syntax: "*"; + inherits: false; +} +@property --tw-scroll-snap-strictness { + syntax: "*"; + inherits: false; + initial-value: proximity; +} +@property --tw-space-y-reverse { + syntax: "*"; + inherits: false; + initial-value: 0; +} +@property --tw-divide-y-reverse { + syntax: "*"; + inherits: false; + initial-value: 0; } @property --tw-border-style { syntax: "*"; inherits: false; initial-value: solid; } +@property --tw-gradient-position { + syntax: "*"; + inherits: false; +} +@property --tw-gradient-from { + syntax: ""; + inherits: false; + initial-value: #0000; +} +@property --tw-gradient-via { + syntax: ""; + inherits: false; + initial-value: #0000; +} +@property --tw-gradient-to { + syntax: ""; + inherits: false; + initial-value: #0000; +} +@property --tw-gradient-stops { + syntax: "*"; + inherits: false; +} +@property --tw-gradient-via-stops { + syntax: "*"; + inherits: false; +} +@property --tw-gradient-from-position { + syntax: ""; + inherits: false; + initial-value: 0%; +} +@property --tw-gradient-via-position { + syntax: ""; + inherits: false; + initial-value: 50%; +} +@property --tw-gradient-to-position { + syntax: ""; + inherits: false; + initial-value: 100%; +} +@property --tw-leading { + syntax: "*"; + inherits: false; +} @property --tw-font-weight { syntax: "*"; inherits: false; } +@property --tw-tracking { + syntax: "*"; + inherits: false; +} @property --tw-shadow { syntax: "*"; inherits: false; @@ -307,11 +1813,155 @@ inherits: false; initial-value: 0 0 #0000; } +@property --tw-outline-style { + syntax: "*"; + inherits: false; + initial-value: solid; +} +@property --tw-blur { + syntax: "*"; + inherits: false; +} +@property --tw-brightness { + syntax: "*"; + inherits: false; +} +@property --tw-contrast { + syntax: "*"; + inherits: false; +} +@property --tw-grayscale { + syntax: "*"; + inherits: false; +} +@property --tw-hue-rotate { + syntax: "*"; + inherits: false; +} +@property --tw-invert { + syntax: "*"; + inherits: false; +} +@property --tw-opacity { + syntax: "*"; + inherits: false; +} +@property --tw-saturate { + syntax: "*"; + inherits: false; +} +@property --tw-sepia { + syntax: "*"; + inherits: false; +} +@property --tw-drop-shadow { + syntax: "*"; + inherits: false; +} +@property --tw-drop-shadow-color { + syntax: "*"; + inherits: false; +} +@property --tw-drop-shadow-alpha { + syntax: ""; + inherits: false; + initial-value: 100%; +} +@property --tw-drop-shadow-size { + syntax: "*"; + inherits: false; +} +@property --tw-backdrop-blur { + syntax: "*"; + inherits: false; +} +@property --tw-backdrop-brightness { + syntax: "*"; + inherits: false; +} +@property --tw-backdrop-contrast { + syntax: "*"; + inherits: false; +} +@property --tw-backdrop-grayscale { + syntax: "*"; + inherits: false; +} +@property --tw-backdrop-hue-rotate { + syntax: "*"; + inherits: false; +} +@property --tw-backdrop-invert { + syntax: "*"; + inherits: false; +} +@property --tw-backdrop-opacity { + syntax: "*"; + inherits: false; +} +@property --tw-backdrop-saturate { + syntax: "*"; + inherits: false; +} +@property --tw-backdrop-sepia { + syntax: "*"; + inherits: false; +} +@property --tw-duration { + syntax: "*"; + inherits: false; +} +@property --tw-ease { + syntax: "*"; + inherits: false; +} +@property --tw-scale-x { + syntax: "*"; + inherits: false; + initial-value: 1; +} +@property --tw-scale-y { + syntax: "*"; + inherits: false; + initial-value: 1; +} +@property --tw-scale-z { + syntax: "*"; + inherits: false; + initial-value: 1; +} +@keyframes spin { + to { + transform: rotate(360deg); + } +} @layer properties { @supports ((-webkit-hyphens: none) and (not (margin-trim: inline))) 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-rotate-x: initial; + --tw-rotate-y: initial; + --tw-rotate-z: initial; + --tw-skew-x: initial; + --tw-skew-y: initial; + --tw-scroll-snap-strictness: proximity; + --tw-space-y-reverse: 0; + --tw-divide-y-reverse: 0; --tw-border-style: solid; + --tw-gradient-position: initial; + --tw-gradient-from: #0000; + --tw-gradient-via: #0000; + --tw-gradient-to: #0000; + --tw-gradient-stops: initial; + --tw-gradient-via-stops: initial; + --tw-gradient-from-position: 0%; + --tw-gradient-via-position: 50%; + --tw-gradient-to-position: 100%; + --tw-leading: initial; --tw-font-weight: initial; + --tw-tracking: initial; --tw-shadow: 0 0 #0000; --tw-shadow-color: initial; --tw-shadow-alpha: 100%; @@ -326,6 +1976,34 @@ --tw-ring-offset-width: 0px; --tw-ring-offset-color: #fff; --tw-ring-offset-shadow: 0 0 #0000; + --tw-outline-style: solid; + --tw-blur: initial; + --tw-brightness: initial; + --tw-contrast: initial; + --tw-grayscale: initial; + --tw-hue-rotate: initial; + --tw-invert: initial; + --tw-opacity: initial; + --tw-saturate: initial; + --tw-sepia: initial; + --tw-drop-shadow: initial; + --tw-drop-shadow-color: initial; + --tw-drop-shadow-alpha: 100%; + --tw-drop-shadow-size: initial; + --tw-backdrop-blur: initial; + --tw-backdrop-brightness: initial; + --tw-backdrop-contrast: initial; + --tw-backdrop-grayscale: initial; + --tw-backdrop-hue-rotate: initial; + --tw-backdrop-invert: initial; + --tw-backdrop-opacity: initial; + --tw-backdrop-saturate: initial; + --tw-backdrop-sepia: initial; + --tw-duration: initial; + --tw-ease: initial; + --tw-scale-x: 1; + --tw-scale-y: 1; + --tw-scale-z: 1; } } } diff --git a/processing.php b/processing.php new file mode 100644 index 0000000..fa4400f --- /dev/null +++ b/processing.php @@ -0,0 +1,36 @@ + + + + + + +
+

Your credits are being processed. Please wait.

+
+
+ + + + diff --git a/receive-purchase.php b/receive-purchase.php new file mode 100644 index 0000000..cfaccb2 --- /dev/null +++ b/receive-purchase.php @@ -0,0 +1,128 @@ + 'Method not allowed']); +} + +$rawBody = file_get_contents('php://input'); +if ($rawBody === false || $rawBody === '') { + respond(400, ['error' => 'Empty request body']); +} + +$signatureHeader = $_SERVER['HTTP_PADDLE_SIGNATURE'] ?? ''; +if ($signatureHeader === '') { + respond(400, ['error' => 'Missing Paddle-Signature header']); +} + +$signatureParts = []; +foreach (explode(';', $signatureHeader) as $part) { + $pair = explode('=', $part, 2); + if (count($pair) === 2) { + $signatureParts[trim($pair[0])] = trim($pair[1]); + } +} + +$timestamp = $signatureParts['ts'] ?? ''; +$providedHash = $signatureParts['h1'] ?? ''; + +if ($timestamp === '' || $providedHash === '' || !ctype_digit($timestamp)) { + respond(400, ['error' => 'Malformed Paddle-Signature header']); +} + +$webhookSecret = getenv('HOOK_SECRET'); +if ($webhookSecret === false || $webhookSecret === '') { + error_log('receive-purchase.php: HOOK_SECRET is not configured'); + respond(500, ['error' => 'Server misconfiguration']); +} + +$signedPayload = $timestamp . ':' . $rawBody; +$expectedHash = hash_hmac('sha256', $signedPayload, $webhookSecret); + +if (!hash_equals($expectedHash, $providedHash)) { + respond(401, ['error' => 'Invalid signature']); +} + +$maxTimestampAgeSeconds = 300; +if (abs(time() - (int) $timestamp) > $maxTimestampAgeSeconds) { + respond(401, ['error' => 'Signature timestamp outside allowed window']); +} + +$event = json_decode($rawBody, true); +if (!is_array($event)) { + respond(400, ['error' => 'Invalid JSON payload']); +} + +$eventId = $event['event_id'] ?? null; +if (!is_string($eventId) || $eventId === '') { + respond(400, ['error' => 'Missing event_id']); +} + +$pdo = getDbConnection(); + +$pdo->exec('CREATE TABLE IF NOT EXISTS processed_webhook_events ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + event_id TEXT NOT NULL UNIQUE, + created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP +)'); + +$pdo->exec('CREATE TABLE IF NOT EXISTS transactions ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + user_id INTEGER NOT NULL REFERENCES users(id), + credits_added INTEGER NOT NULL, + created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP +)'); +$pdo->exec('CREATE INDEX IF NOT EXISTS idx_transactions_user_id ON transactions (user_id)'); + +$existingStmt = $pdo->prepare('SELECT 1 FROM processed_webhook_events WHERE event_id = :event_id'); +$existingStmt->execute(['event_id' => $eventId]); +if ($existingStmt->fetch()) { + respond(200, ['status' => 'already_processed']); +} + +$creditsPerPrice = [ + 'pri_01m1v28mknf5pjm5c99cvxa5k4' => 20, + 'pri_01m1v2aegbrdvwhw1jf7b0s6va' => 50, +]; + +if (($event['event_type'] ?? '') === 'transaction.completed') { + $data = $event['data'] ?? []; + $ticket = $data['custom_data']['user_id'] ?? null; + $userId = is_string($ticket) ? decodeTicket($ticket, 'purchase') : null; + $items = is_array($data['items'] ?? null) ? $data['items'] : []; + + $creditsToAdd = 0; + foreach ($items as $item) { + $priceId = $item['price']['id'] ?? null; + if (is_string($priceId) && isset($creditsPerPrice[$priceId])) { + $creditsToAdd += $creditsPerPrice[$priceId]; + } + } + + if ($creditsToAdd > 0 && $userId !== null) { + $userExistsStmt = $pdo->prepare('SELECT 1 FROM users WHERE id = :id'); + $userExistsStmt->execute(['id' => $userId]); + + if ($userExistsStmt->fetch()) { + $creditStmt = $pdo->prepare('UPDATE users SET credits = credits + :credits WHERE id = :id'); + $creditStmt->execute(['credits' => $creditsToAdd, 'id' => $userId]); + + $transactionStmt = $pdo->prepare('INSERT INTO transactions (user_id, credits_added) VALUES (:user_id, :credits_added)'); + $transactionStmt->execute(['user_id' => $userId, 'credits_added' => $creditsToAdd]); + } + } +} + +$pdo->prepare('INSERT INTO processed_webhook_events (event_id) VALUES (:event_id)')->execute(['event_id' => $eventId]); + +respond(200, ['status' => 'ok']); diff --git a/register.php b/register.php index 69ffce8..7101fc2 100644 --- a/register.php +++ b/register.php @@ -1,6 +1,7 @@ prepare('SELECT 1 FROM users WHERE email = :email'); $stmt->execute(['email' => $email]); if ($stmt->fetch()) { - $errors['email'] = 'That email address is already registered.'; + $errors['email'] = "We couldn't create your account with those details. If you already have an account, try logging in instead."; } } if ($password === '') { $errors['password'] = 'Password is required.'; - } elseif (strlen($password) > 100) { - $errors['password'] = 'Password cannot exceed 100 characters.'; - } elseif (strlen($password) < 6 || strlen($password) > 12) { - $errors['password'] = 'Password must be between 6 and 12 characters long.'; + } elseif (strlen($password) < 8) { + $errors['password'] = 'Password must be at least 8 characters long.'; + } elseif (strlen($password) > 72) { + $errors['password'] = 'Password cannot exceed 72 characters.'; } if (empty($errors)) { $hashedPassword = password_hash($password, PASSWORD_DEFAULT); - $stmt = $pdo->prepare('INSERT INTO users (username, email, password) VALUES (:username, :email, :password)'); - $stmt->execute([ - 'username' => $username, - 'email' => $email, - 'password' => $hashedPassword, - ]); + try { + $stmt = $pdo->prepare('INSERT INTO users (username, email, password, credits) VALUES (:username, :email, :password, :credits)'); + $stmt->execute([ + 'username' => $username, + 'email' => $email, + 'password' => $hashedPassword, + 'credits' => STARTING_CREDITS, + ]); + } catch (PDOException $e) { + if (str_contains($e->getMessage(), 'UNIQUE constraint failed: users.username')) { + $errors['username'] = 'That username is not available.'; + } elseif (str_contains($e->getMessage(), 'UNIQUE constraint failed: users.email')) { + $errors['email'] = "We couldn't create your account with those details. If you already have an account, try logging in instead."; + } else { + throw $e; + } + } - start_app_session(); - session_regenerate_id(true); - $_SESSION['user_id'] = (int) $pdo->lastInsertId(); - $_SESSION['username'] = $username; + if (empty($errors)) { + start_app_session(); + session_regenerate_id(true); + $_SESSION['user_id'] = (int) $pdo->lastInsertId(); + $_SESSION['username'] = $username; - header('Location: /'); - exit; + sendRegistrationConfirmationEmail($email, $username); + + header('Location: /'); + exit; + } } } + +$pageTitle = 'Register'; ?> - - - Register - - -
-
- - - -
- + + + +
+
+ -
- - - -
- + +
+

Start your collection.

+

Create an account and bring your imagination to life.

+ + +
+ +
+ + +
+ +

+ +
+
+ +
+ + +
+ +

+ +
+
+ +
+ + + +
+ +

+ +
+ + + +

+ Already have an account? Log in +

-
- - - -
- -
- - +
+
+ + + diff --git a/reset-password.php b/reset-password.php new file mode 100644 index 0000000..11d3778 --- /dev/null +++ b/reset-password.php @@ -0,0 +1,110 @@ + 100) { + $errors['password'] = 'Password cannot exceed 100 characters.'; + } elseif (strlen($password) < 6 || strlen($password) > 12) { + $errors['password'] = 'Password must be between 6 and 12 characters long.'; + } + + if (empty($errors)) { + $pdo = getDbConnection(); + $hashedPassword = password_hash($password, PASSWORD_DEFAULT); + $stmt = $pdo->prepare('UPDATE users SET password = :password WHERE id = :id'); + $stmt->execute(['password' => $hashedPassword, 'id' => $userId]); + + header('Location: login.php?reset=success'); + exit; + } +} + +$pageTitle = 'Reset Password'; +?> + + + + + +
+
+ +
+ +
+

Link expired

+

+ This password reset link is invalid or has expired. Request a new one below. +

+ + Request New Link + + +
+ +
+

Choose a new password

+

Make it something you'll remember.

+ +
+ +
+ +
+ + + +
+ +

+ +
+ +
+ +
+
+ + + + + diff --git a/session.php b/session.php index f311d54..d0353e6 100644 --- a/session.php +++ b/session.php @@ -4,9 +4,14 @@ function start_app_session(): void if (session_status() === PHP_SESSION_ACTIVE) { return; } + $isHttps = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') + || (($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https') + || (($_SERVER['SERVER_PORT'] ?? '') === '443'); + session_set_cookie_params([ 'lifetime' => 0, 'path' => '/', + 'secure' => $isHttps, 'httponly' => true, 'samesite' => 'Strict', ]); diff --git a/single-critter.php b/single-critter.php new file mode 100644 index 0000000..45888c4 --- /dev/null +++ b/single-critter.php @@ -0,0 +1,187 @@ +prepare(' + SELECT c.id AS id, c.author_id AS author_id, c.isFavorite AS isFavorite, c.isArchived AS isArchived, + c.adjective_id AS adjective_id, c.noun_id AS noun_id, c.verb_id AS verb_id, c.location_id AS location_id, + a.value AS adjective, n.value AS noun, v.value AS verb, l.value AS location, c.image AS image + FROM critters c + JOIN adjectives a ON a.id = c.adjective_id + JOIN nouns n ON n.id = c.noun_id + JOIN verbs v ON v.id = c.verb_id + JOIN locations l ON l.id = c.location_id + WHERE c.id = :id AND c.author_id = :author_id + '); + $stmt->execute(['id' => $critterId, 'author_id' => $userId]); + return $stmt->fetch(PDO::FETCH_ASSOC); +} + +$critter = null; +if ($critterId !== null && $critterId !== false) { + $critter = fetchOwnedCritter($pdo, (int) $_SESSION['user_id'], $critterId); +} + +$isOwner = (bool) $critter; + +$relatedCritters = []; +if ($critter) { + $relatedStmt = $pdo->prepare(' + SELECT id, image FROM critters + WHERE author_id = :author_id + AND adjective_id = :adjective_id + AND noun_id = :noun_id + AND verb_id = :verb_id + AND location_id = :location_id + AND id != :current_id + ORDER BY id DESC + '); + $relatedStmt->execute([ + 'author_id' => $critter['author_id'], + 'adjective_id' => $critter['adjective_id'], + 'noun_id' => $critter['noun_id'], + 'verb_id' => $critter['verb_id'], + 'location_id' => $critter['location_id'], + 'current_id' => $critter['id'], + ]); + $relatedCritters = array_values(array_filter( + $relatedStmt->fetchAll(PDO::FETCH_ASSOC), + fn($row) => !empty($row['image']) + )); +} + +if ($_SERVER['REQUEST_METHOD'] === 'POST' && $critter && $isOwner) { + $action = $_POST['action'] ?? ''; + + if ($action === 'toggle_favorite') { + $newValue = $critter['isFavorite'] ? 0 : 1; + $stmt = $pdo->prepare('UPDATE critters SET isFavorite = :value WHERE id = :id'); + $stmt->execute(['value' => $newValue, 'id' => $critterId]); + } elseif ($action === 'toggle_archived') { + $newValue = $critter['isArchived'] ? 0 : 1; + $stmt = $pdo->prepare('UPDATE critters SET isArchived = :value WHERE id = :id'); + $stmt->execute(['value' => $newValue, 'id' => $critterId]); + } + + header('Location: single-critter.php?id=' . $critterId); + exit; +} + +$pageTitle = 'View Critter'; +?> + + + + + +
+ + + AI-generated image of this critter + +

+ +

+

+ The +

+
+ +
+ + +
+
+ + +
+ +
+ + + + + +
+
+ + +
+

Other critters with this same recipe

+
+ + + AI-generated image of a matching critter + + +
+
+ + +

Critter not found.

+ +
+ + + diff --git a/skills-lock.json b/skills-lock.json new file mode 100644 index 0000000..59bbf54 --- /dev/null +++ b/skills-lock.json @@ -0,0 +1,11 @@ +{ + "version": 1, + "skills": { + "frontend-design": { + "source": "anthropics/skills", + "sourceType": "github", + "skillPath": "skills/frontend-design/SKILL.md", + "computedHash": "89496d5dd00f4810205f351759594fc2742bf8eea85a2f2b2d1de59f4bd91576" + } + } +}