Fix issues identified by Davidson CI
pauljd/davidson-ci: Davidson CI / quality (push) Successful in 14s
pauljd/davidson-ci: Davidson CI / ai-review (push) Successful in 1m24s

This commit is contained in:
2026-09-09 19:15:05 +01:00
parent aab614f811
commit 8630b6133e
75 changed files with 13016 additions and 180 deletions
+177
View File
@@ -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
+71
View File
@@ -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.
+252
View File
@@ -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-skill: testsprite-onboard v0.10.0 sha256:a1f983745370 -->
<!--
User-facing content for `testsprite agent install` (skill: testsprite-onboard).
Body only — name + description frontmatter is emitted by the install wrapper.
The cursor (.mdc), cline (.clinerules), and antigravity (experimental)
wrappers reuse this body verbatim and swap only the frontmatter/header.
-->
# 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 "<repo name>" --url <app-url> \
[--username <user> --password-file <path-to-secret>]
```
Backend:
```bash
testsprite project create --type backend --name "<repo 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 <projectId> --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 <projectId> --role api-doc
testsprite project docs upload ./prd.md --project <projectId> --role prd # optional, with the spec
```
```bash
testsprite test plan generate --project <projectId>
```
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 <projectId> # all of them
testsprite test plan accept --project <projectId> --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 <projectId>` 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": "<projectId from step 2>",
"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 <projectId> --type "Bearer token"|"API key"|"basic token" --credential <value>`,
or an auto-refreshing login with `testsprite project auto-auth <projectId> …` 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 "<behavior being tested>" \
--code-file ./tests/<endpoint>.py --project <projectId>
```
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 <testId> --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: <list the flows>."
- "I smoke-ran **M** — here's the result: <pass/fail + the dashboard link from the run output>."
- "To run the rest (≈X credits — state the cost so they choose knowingly):
- frontend — run each remaining test by id: `testsprite test run <testId> --wait` (there is
**no `--all` for frontend**);
- backend — `testsprite test run --all --project <id>` (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.
+505
View File
@@ -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-skill: testsprite-verify v0.10.0 sha256:8d5ca7f47da6 -->
# 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 <test-id> --local <port>` 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 <id> --wait` against an existing test, **or**
- `testsprite test create-batch --plans plans.jsonl --run --wait` (or
two-step: create-batch, then `test run <id> --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 <X>. 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 <projectId> --output json
testsprite test list --project <projectId> --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 <projectId> --type "Bearer token"|"API key"|"basic token" --credential <value>`
- **Auto-refreshing login (recurring token):** `testsprite project auto-auth <projectId> …`
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 <projectId> --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 <projectId> --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 <projectId> --name "fixture user is deleted" \
--code-file /tmp/cleanup.py --category teardown
```
- `--produces <var>` / `--needs <var>` 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 <projectId>` shows `testIdAttrs:`; set it once with
`project update <projectId> --test-id-attributes <attr>,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
`<img>` 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 <projectId> --code-file <file>` three times with three Python files.
### (d) Refine an existing test
- **FE** — replace the steps, then re-run:
```bash
testsprite test plan put <test-id> --steps refined.json
```
- **BE** — write updated Python and replace the code (optimistic concurrency):
```bash
testsprite test code put <test-id> --code-file refined.py --expected-version <current-version>
```
## 4. Run
All variants use `--wait` for a synchronous verdict, `--target-url <env-url>` for
the deployment under test, and `--timeout 600` as a sane default.
```bash
# (a) existing test
testsprite test run <test-id> --target-url <env-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 <test-id>,
# so expect their side effects (fixtures re-created, teardown deletes) and extra runs in history.
testsprite test rerun <test-id> --wait --timeout 600 --output json
testsprite test rerun <test-id> --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 <env-url> --timeout 600
# (b-BE) new BE test from Python (backend create needs --project)
testsprite test create --type backend --name "..." --project <projectId> --code-file foo.py --run --wait --target-url <env-url> --timeout 600
# (b-BE coverage set with dependencies) create each test without --run, then one wave-ordered batch
testsprite test run --all --project <projectId> --wait --timeout 600 --output json
testsprite test run --all --project <projectId> --filter <name-substr> --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 <env-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 <test-id> --wait --target-url <env-url> --timeout 600
# (d-FE) refine + re-run
testsprite test plan put <test-id> --steps refined.json && \
testsprite test run <test-id> --target-url <env-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 <test-id> --code-file refined.py --expected-version <current-version> && \
testsprite test run <test-id> --target-url <env-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 <port>` 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 <run-id>`), 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 <id>` 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 <be-id>` 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 <codeVersion>`; stale etag → exit 6,
re-fetch via `test get <id>` 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 <test-id> --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 <run-id> --out ./.testsprite/runs/<run-id>/
```
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.
+3
View File
@@ -0,0 +1,3 @@
{
"css.lint.propertyIgnoredDueToDisplay": "ignore"
}
+72
View File
@@ -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.
+137
View File
@@ -0,0 +1,137 @@
<?php
require __DIR__ . '/../session.php';
require __DIR__ . '/../db.php';
start_app_session();
header('Content-Type: application/json');
if (!isset($_SESSION['user_id'])) {
http_response_code(401);
echo json_encode(['error' => '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'],
]);
+27
View File
@@ -0,0 +1,27 @@
<?php
require __DIR__ . '/../session.php';
require __DIR__ . '/../db.php';
start_app_session();
header('Content-Type: application/json');
$userId = $_SESSION['user_id'] ?? null;
$result = false;
if ($userId !== null) {
$pdo = getDbConnection();
$tableExists = $pdo->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]);
Binary file not shown.

After

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 161 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

+309 -67
View File
@@ -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
. '</option>';
}
}
$pageTitle = 'Create Critter';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Create Critter</title>
</head>
<body>
<h1>Create Your New Critter</h1>
<form action="create-critter.php" method="post" novalidate>
<div>
<label for="adjective_id">Adjective</label>
<select id="adjective_id" name="adjective_id">
<option value="">-- Select an adjective --</option>
<?php renderOptions($adjectives, $selected['adjective_id']); ?>
</select>
<?php if (isset($errors['adjective_id'])): ?>
<div><?php echo htmlspecialchars($errors['adjective_id'], ENT_QUOTES, 'UTF-8'); ?></div>
<?php endif; ?>
<?php require __DIR__ . '/lib/head.php'; ?>
<body class="bg-amber-50 min-h-screen flex flex-col">
<?php require __DIR__ . '/lib/header.php'; ?>
<main class="flex-1">
<?php if ($dailyLimitReached): ?>
<div class="max-w-md mx-auto px-6 py-20 text-center">
<div class="flex h-16 w-16 items-center justify-center rounded-full bg-purple-50 text-purple-300 mx-auto mb-4">
<i data-lucide="calendar-clock" class="h-8 w-8"></i>
</div>
<h1 class="text-2xl font-extrabold text-gray-900 mb-2">Critter limit reached for the day</h1>
<p class="text-gray-600">Critter limit reached for the day, please come back tomorrow.</p>
</div>
<div>
<label for="noun_id">Noun</label>
<select id="noun_id" name="noun_id">
<option value="">-- Select a noun --</option>
<?php renderOptions($nouns, $selected['noun_id']); ?>
</select>
<?php if (isset($errors['noun_id'])): ?>
<div><?php echo htmlspecialchars($errors['noun_id'], ENT_QUOTES, 'UTF-8'); ?></div>
<?php endif; ?>
<?php elseif ($userCredits <= 0): ?>
<div class="max-w-md mx-auto px-6 py-20 text-center">
<div class="flex h-16 w-16 items-center justify-center rounded-full bg-purple-50 text-purple-300 mx-auto mb-4">
<i data-lucide="coins" class="h-8 w-8"></i>
</div>
<h1 class="text-2xl font-extrabold text-gray-900 mb-2">Out of credits</h1>
<p class="text-gray-600">You have 0 credits remaining, so you can't create a new critter right now.</p>
<a href="#" onClick="openCheckout(itemsList)" class="mt-6 inline-flex items-center gap-2 rounded-xl bg-gradient-to-r from-purple-600 to-pink-500 text-white font-semibold px-5 py-2.5 shadow-sm hover:from-purple-700 hover:to-pink-600">
<i data-lucide="shopping-cart" class="h-4 w-4"></i> Buy Credits
</a>
</div>
<div>
<label for="verb_id">Verb</label>
<select id="verb_id" name="verb_id">
<option value="">-- Select a verb --</option>
<?php renderOptions($verbs, $selected['verb_id']); ?>
</select>
<?php if (isset($errors['verb_id'])): ?>
<div><?php echo htmlspecialchars($errors['verb_id'], ENT_QUOTES, 'UTF-8'); ?></div>
<?php endif; ?>
<?php else: ?>
<div class="max-w-xl mx-auto px-6 py-12">
<div class="text-center mb-8">
<p class="text-sm font-semibold tracking-widest text-purple-600 uppercase mb-2">Imagine &middot; Mix &middot; Create</p>
<h1 class="text-3xl sm:text-4xl font-extrabold text-gray-900">Create Your New Critter</h1>
<p class="mt-2 text-gray-500">Pick a recipe and we'll bring it to life.</p>
</div>
<div>
<label for="location_id">Location</label>
<select id="location_id" name="location_id">
<option value="">-- Select a location --</option>
<?php renderOptions($locations, $selected['location_id']); ?>
</select>
<?php if (isset($errors['location_id'])): ?>
<div><?php echo htmlspecialchars($errors['location_id'], ENT_QUOTES, 'UTF-8'); ?></div>
<div class="rounded-3xl bg-white ring-1 ring-gray-100 shadow-sm p-6 sm:p-8">
<?php if (isset($errors['credits']) || isset($errors['cooldown'])): ?>
<div class="mb-5 rounded-lg bg-red-50 text-red-700 text-sm px-4 py-3">
<?php echo htmlspecialchars($errors['credits'] ?? $errors['cooldown'], ENT_QUOTES, 'UTF-8'); ?>
</div>
<?php endif; ?>
<form id="createCritterForm" action="create-critter.php" method="post" novalidate class="space-y-5">
<div>
<label for="adjective_id" class="block text-sm font-medium text-gray-700 mb-1">Adjective</label>
<div class="relative">
<i data-lucide="wand" class="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-pink-500"></i>
<select id="adjective_id" name="adjective_id" class="w-full appearance-none rounded-xl border border-gray-300 pl-10 pr-9 py-2.5 text-gray-900 focus:outline-none focus:ring-2 focus:ring-purple-400 transition-shadow">
<option value="">-- Select an adjective --</option>
<?php renderOptions($adjectives, $selected['adjective_id']); ?>
</select>
<i data-lucide="chevron-down" class="pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400"></i>
</div>
<?php if (isset($errors['adjective_id'])): ?>
<div class="text-sm text-red-600 mt-1"><?php echo htmlspecialchars($errors['adjective_id'], ENT_QUOTES, 'UTF-8'); ?></div>
<?php endif; ?>
</div>
<div>
<label for="noun_id" class="block text-sm font-medium text-gray-700 mb-1">Animal</label>
<div class="relative">
<i data-lucide="paw-print" class="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-blue-500"></i>
<select id="noun_id" name="noun_id" class="w-full appearance-none rounded-xl border border-gray-300 pl-10 pr-9 py-2.5 text-gray-900 focus:outline-none focus:ring-2 focus:ring-purple-400 transition-shadow">
<option value="">-- Select a noun --</option>
<?php renderOptions($nouns, $selected['noun_id']); ?>
</select>
<i data-lucide="chevron-down" class="pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400"></i>
</div>
<?php if (isset($errors['noun_id'])): ?>
<div class="text-sm text-red-600 mt-1"><?php echo htmlspecialchars($errors['noun_id'], ENT_QUOTES, 'UTF-8'); ?></div>
<?php endif; ?>
</div>
<div>
<label for="verb_id" class="block text-sm font-medium text-gray-700 mb-1">Action</label>
<div class="relative">
<i data-lucide="play" class="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-green-500"></i>
<select id="verb_id" name="verb_id" class="w-full appearance-none rounded-xl border border-gray-300 pl-10 pr-9 py-2.5 text-gray-900 focus:outline-none focus:ring-2 focus:ring-purple-400 transition-shadow">
<option value="">-- Select a verb --</option>
<?php renderOptions($verbs, $selected['verb_id']); ?>
</select>
<i data-lucide="chevron-down" class="pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400"></i>
</div>
<?php if (isset($errors['verb_id'])): ?>
<div class="text-sm text-red-600 mt-1"><?php echo htmlspecialchars($errors['verb_id'], ENT_QUOTES, 'UTF-8'); ?></div>
<?php endif; ?>
</div>
<div>
<label for="location_id" class="block text-sm font-medium text-gray-700 mb-1">Location</label>
<div class="relative">
<i data-lucide="map-pin" class="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-purple-500"></i>
<select id="location_id" name="location_id" class="w-full appearance-none rounded-xl border border-gray-300 pl-10 pr-9 py-2.5 text-gray-900 focus:outline-none focus:ring-2 focus:ring-purple-400 transition-shadow">
<option value="">-- Select a location --</option>
<?php renderOptions($locations, $selected['location_id']); ?>
</select>
<i data-lucide="chevron-down" class="pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400"></i>
</div>
<?php if (isset($errors['location_id'])): ?>
<div class="text-sm text-red-600 mt-1"><?php echo htmlspecialchars($errors['location_id'], ENT_QUOTES, 'UTF-8'); ?></div>
<?php endif; ?>
</div>
<button type="submit" id="createCritterSubmit" class="w-full inline-flex items-center justify-center gap-2 rounded-xl bg-gradient-to-r from-purple-600 to-pink-500 text-white font-semibold py-3 shadow-sm hover:from-purple-700 hover:to-pink-600 focus:outline-none focus-visible:ring-2 focus-visible:ring-purple-400 focus-visible:ring-offset-2">
<i data-lucide="sparkles" class="h-4 w-4"></i> Create Critter
</button>
</form>
</div>
<button type="submit">Create Critter</button>
</form>
</div>
<div id="creatingOverlay" class="hidden fixed inset-0 z-50 flex items-center justify-center bg-gradient-to-br from-purple-600 via-pink-500 to-amber-500 p-6">
<div class="w-full max-w-sm rounded-3xl bg-white shadow-2xl p-8 text-center">
<div class="mx-auto flex h-16 w-16 items-center justify-center rounded-full bg-pink-50 text-pink-500 mb-5" style="animation: critter-bounce 1.1s ease-in-out infinite;">
<i data-lucide="paw-print" class="h-8 w-8"></i>
</div>
<h2 class="text-xl font-extrabold text-gray-900">Creating your critter&hellip;</h2>
<p id="creatingMessage" class="mt-2 text-gray-500 min-h-[1.5em]">Mixing colors&hellip;</p>
<div class="mt-6 h-2 w-full rounded-full bg-gray-100 overflow-hidden">
<div class="h-full w-1/3 rounded-full bg-gradient-to-r from-purple-600 via-pink-500 to-amber-500" style="animation: critter-progress 1.4s ease-in-out infinite;"></div>
</div>
<p class="mt-5 text-xs text-gray-400">This can take up to a minute &mdash; hang tight!</p>
</div>
</div>
<style>
@keyframes critter-bounce {
0%, 100% { transform: translateY(0) scale(1); }
50% { transform: translateY(-10px) scale(1.08); }
}
@keyframes critter-progress {
0% { transform: translateX(-110%); }
50% { transform: translateX(60%); }
100% { transform: translateX(310%); }
}
</style>
<script>
(function () {
const form = document.getElementById('createCritterForm');
if (!form) return;
const messages = [
'Mixing colors…',
'Sketching whiskers…',
'Adding a sprinkle of magic…',
'Choosing the perfect pose…',
'Bringing your critter to life…',
'Almost there…',
];
form.addEventListener('submit', function () {
const overlay = document.getElementById('creatingOverlay');
const messageEl = document.getElementById('creatingMessage');
const submitBtn = document.getElementById('createCritterSubmit');
overlay.classList.remove('hidden');
if (window.lucide) lucide.createIcons();
if (submitBtn) submitBtn.disabled = true;
let index = 0;
setInterval(function () {
index = (index + 1) % messages.length;
messageEl.textContent = messages[index];
}, 2200);
});
})();
</script>
<?php endif; ?>
</main>
<?php require __DIR__ . '/lib/footer.php'; ?>
</body>
</html>
Binary file not shown.

After

Width:  |  Height:  |  Size: 82 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 57 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 69 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 69 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 87 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 99 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 70 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 68 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 99 KiB

+3
View File
@@ -0,0 +1,3 @@
<?php
header('Location: /');
exit;
+15 -1
View File
@@ -8,13 +8,27 @@ function getDbConnection(): PDO
$pdo = new PDO('sqlite:' . $dbPath);
$pdo->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();
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 823 KiB

+100
View File
@@ -0,0 +1,100 @@
<?php
require __DIR__ . '/session.php';
require __DIR__ . '/db.php';
require __DIR__ . '/lib/ticket.php';
require __DIR__ . '/lib/mailer.php';
start_app_session();
if (isset($_SESSION['username'])) {
header('Location: /');
exit;
}
$errors = [];
$email = '';
$submitted = false;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$email = trim($_POST['email'] ?? '');
if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors['email'] = 'Please enter a valid email address.';
}
if (empty($errors)) {
$pdo = getDbConnection();
$stmt = $pdo->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';
?>
<!DOCTYPE html>
<html lang="en">
<?php require __DIR__ . '/lib/head.php'; ?>
<body class="bg-amber-50 min-h-screen flex flex-col">
<?php require __DIR__ . '/lib/header.php'; ?>
<div class="flex-1 flex items-center justify-center bg-gradient-to-b from-amber-50 via-pink-50 to-white p-4 py-12">
<div class="w-full max-w-md bg-white rounded-3xl shadow-xl ring-1 ring-gray-100 p-8 sm:p-10">
<?php if ($submitted): ?>
<div class="flex h-14 w-14 items-center justify-center rounded-full bg-green-50 text-green-500 mx-auto mb-4">
<i data-lucide="mail-check" class="h-7 w-7"></i>
</div>
<h1 class="text-2xl font-extrabold text-gray-900 text-center">Check your inbox</h1>
<p class="mt-2 text-gray-500 text-sm text-center">
If an account exists for <span class="font-medium text-gray-700"><?php echo htmlspecialchars($email, ENT_QUOTES, 'UTF-8'); ?></span>,
we've sent instructions to reset your password. The link expires in 20 minutes.
</p>
<p class="mt-6 text-center text-sm text-gray-600">
<a href="login.php" class="text-purple-600 font-semibold hover:underline">Back to log in</a>
</p>
<?php else: ?>
<div class="flex h-14 w-14 items-center justify-center rounded-full bg-purple-50 text-purple-500 mx-auto mb-4">
<i data-lucide="key-round" class="h-7 w-7"></i>
</div>
<h1 class="text-2xl font-extrabold text-gray-900 text-center">Forgot your password?</h1>
<p class="mt-2 text-gray-500 text-sm text-center">Enter your email and we'll send you a link to reset it.</p>
<form action="forgot-password.php" method="post" novalidate class="mt-6 space-y-4">
<div>
<label for="email" class="block text-sm font-medium text-gray-700 mb-1">Email</label>
<div class="relative">
<i data-lucide="mail" class="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400"></i>
<input
type="email" id="email" name="email"
value="<?php echo htmlspecialchars($email, ENT_QUOTES, 'UTF-8'); ?>"
placeholder="you@example.com"
class="w-full rounded-xl border border-gray-300 pl-10 pr-3 py-2.5 focus:outline-none focus:ring-2 focus:ring-purple-400"
>
</div>
<?php if (isset($errors['email'])): ?>
<p class="mt-1 text-sm text-red-600"><?php echo htmlspecialchars($errors['email'], ENT_QUOTES, 'UTF-8'); ?></p>
<?php endif; ?>
</div>
<button type="submit" class="w-full inline-flex items-center justify-center gap-2 rounded-xl bg-gray-900 text-white font-semibold py-3 hover:bg-gray-800">
Send Reset Link <i data-lucide="arrow-right" class="h-4 w-4"></i>
</button>
</form>
<p class="mt-6 text-center text-sm text-gray-600">
Remembered it? <a href="login.php" class="text-purple-600 font-semibold hover:underline">Log in</a>
</p>
<?php endif; ?>
</div>
</div>
<?php require __DIR__ . '/lib/footer.php'; ?>
</body>
</html>
+409 -34
View File
@@ -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 '<option value="' . (int) $row['id'] . '"' . ($isSelected ? ' selected' : '') . '>'
. htmlspecialchars($row['value'], ENT_QUOTES, 'UTF-8')
. '</option>';
}
}
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';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Welcome</title>
<link rel="stylesheet" href="/media/output.css">
</head>
<body>
<?php require __DIR__ . '/lib/head.php'; ?>
<body class="<?php echo $isLoggedIn ? 'bg-amber-50' : ''; ?> min-h-screen flex flex-col">
<main class="flex-1">
<?php if ($isLoggedIn): ?>
<h1>Welcome <?php echo htmlspecialchars($_SESSION['username'], ENT_QUOTES, 'UTF-8'); ?></h1>
<?php else: ?>
<h1>Welcome guest</h1>
<?php endif; ?>
<p>Happy <?php echo $dayOfWeek; ?>! We're glad you're here.</p>
<?php if ($isLoggedIn): ?>
<p><a href="create-critter.php">Create New Critter</a></p>
<p><a href="logout.php">Log out</a></p>
<div class="max-w-4xl mx-auto px-4">
<h2 class="text-xl font-semibold mb-4">My Critters</h2>
<?php require __DIR__ . '/lib/header.php'; ?>
<?php require __DIR__ . '/lib/critters-hero.php'; ?>
<div class="max-w-[1400px] mx-auto px-6 mt-8">
<div class="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4">
<div class="flex flex-wrap items-center gap-2">
<a href="<?php echo htmlspecialchars(buildCritterUrl(['status' => null, 'page' => 1], $filters, $statusFilter, $search, $sort, $page), ENT_QUOTES, 'UTF-8'); ?>"
class="inline-flex items-center gap-2 rounded-xl px-4 py-2 text-sm font-medium transition-colors duration-150 focus:outline-none focus-visible:ring-2 focus-visible:ring-purple-400 <?php echo $statusFilter === 'any' ? 'bg-blue-100 text-blue-700' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'; ?>">
<i data-lucide="layout-grid" class="h-4 w-4"></i> All Critters
<span class="inline-flex items-center justify-center h-5 min-w-5 px-1 rounded-full bg-white/70 text-xs font-semibold"><?php echo $totalCrittersCount; ?></span>
</a>
<a href="<?php echo htmlspecialchars(buildCritterUrl(['status' => 'favorited', 'page' => 1], $filters, $statusFilter, $search, $sort, $page), ENT_QUOTES, 'UTF-8'); ?>"
class="inline-flex items-center gap-2 rounded-xl px-4 py-2 text-sm font-medium transition-colors duration-150 focus:outline-none focus-visible:ring-2 focus-visible:ring-purple-400 <?php echo $statusFilter === 'favorited' ? 'bg-pink-100 text-pink-700' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'; ?>">
<i data-lucide="heart" class="h-4 w-4"></i> Favourites
<span class="inline-flex items-center justify-center h-5 min-w-5 px-1 rounded-full bg-white/70 text-xs font-semibold"><?php echo $favoritesCount; ?></span>
</a>
<a href="<?php echo htmlspecialchars(buildCritterUrl(['status' => 'archived', 'page' => 1], $filters, $statusFilter, $search, $sort, $page), ENT_QUOTES, 'UTF-8'); ?>"
class="inline-flex items-center gap-2 rounded-xl px-4 py-2 text-sm font-medium transition-colors duration-150 focus:outline-none focus-visible:ring-2 focus-visible:ring-purple-400 <?php echo $statusFilter === 'archived' ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'; ?>">
<i data-lucide="archive" class="h-4 w-4"></i> Archived
<span class="inline-flex items-center justify-center h-5 min-w-5 px-1 rounded-full bg-white/70 text-xs font-semibold"><?php echo $archivedCount; ?></span>
</a>
</div>
<form action="" method="get" class="flex flex-wrap items-center gap-3">
<input type="hidden" name="filter_adjective" value="<?php echo htmlspecialchars((string) $filters['filter_adjective'], ENT_QUOTES, 'UTF-8'); ?>">
<input type="hidden" name="filter_noun" value="<?php echo htmlspecialchars((string) $filters['filter_noun'], ENT_QUOTES, 'UTF-8'); ?>">
<input type="hidden" name="filter_verb" value="<?php echo htmlspecialchars((string) $filters['filter_verb'], ENT_QUOTES, 'UTF-8'); ?>">
<input type="hidden" name="filter_location" value="<?php echo htmlspecialchars((string) $filters['filter_location'], ENT_QUOTES, 'UTF-8'); ?>">
<input type="hidden" name="status" value="<?php echo htmlspecialchars($statusFilter, ENT_QUOTES, 'UTF-8'); ?>">
<div class="relative">
<i data-lucide="search" class="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400"></i>
<input
type="text" name="q" value="<?php echo htmlspecialchars($search, ENT_QUOTES, 'UTF-8'); ?>"
placeholder="Search your critters..."
class="rounded-xl border border-gray-300 pl-9 pr-3 py-2 text-sm w-56 transition-shadow focus:outline-none focus:ring-2 focus:ring-purple-400 focus:border-transparent"
>
</div>
<label class="flex items-center gap-2 text-sm text-gray-600">
Sort by
<select name="sort" onchange="this.form.submit()" class="rounded-xl border border-gray-300 px-3 py-2 text-sm transition-shadow focus:outline-none focus:ring-2 focus:ring-purple-400 focus:border-transparent">
<option value="newest" <?php echo $sort === 'newest' ? 'selected' : ''; ?>>Newest</option>
<option value="oldest" <?php echo $sort === 'oldest' ? 'selected' : ''; ?>>Oldest</option>
</select>
</label>
<button type="submit" class="sr-only">Search</button>
</form>
</div>
<?php if (empty($myCritters)): ?>
<p>You haven't created any critters yet.</p>
<div class="mt-10 flex flex-col items-center text-center py-12">
<div class="flex h-16 w-16 items-center justify-center rounded-full bg-purple-50 text-purple-300 mb-4">
<i data-lucide="paw-print" class="h-8 w-8"></i>
</div>
<p class="text-gray-500">
<?php echo $totalCrittersCount === 0 ? "You haven't created any critters yet." : 'No critters match your current filters.'; ?>
</p>
<?php if ($totalCrittersCount === 0): ?>
<a href="create-critter.php" class="mt-4 inline-flex items-center gap-2 rounded-xl bg-gradient-to-r from-purple-600 to-pink-500 text-white text-sm font-semibold px-5 py-2.5 shadow-sm transition-all duration-200 hover:from-purple-700 hover:to-pink-600 hover:shadow-md active:scale-[0.98]">
<i data-lucide="plus" class="h-4 w-4"></i> Create your first critter
</a>
<?php endif; ?>
</div>
<?php else: ?>
<div class="grid grid-cols-4 gap-4">
<div class="mt-6 grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-6">
<?php foreach ($myCritters as $critter): ?>
<?php if (!empty($critter['image'])): ?>
<img
src="critter-images/<?php echo htmlspecialchars($critter['image'], ENT_QUOTES, 'UTF-8'); ?>"
alt="AI-generated image of your critter"
class="w-full aspect-square object-cover rounded-lg border border-gray-200 shadow-sm m-1"
>
<?php endif; ?>
<?php if (empty($critter['image'])) continue; ?>
<div class="group rounded-2xl bg-white ring-1 ring-gray-100 shadow-sm overflow-hidden transition-all duration-200 hover:shadow-lg hover:-translate-y-1" data-critter-card="<?php echo (int) $critter['id']; ?>">
<div class="relative overflow-hidden">
<button type="button" onclick="openCritterModal(<?php echo (int) $critter['id']; ?>)" class="block w-full focus:outline-none focus-visible:ring-2 focus-visible:ring-purple-400 focus-visible:ring-inset">
<img
src="critter-images/<?php echo htmlspecialchars($critter['image'], ENT_QUOTES, 'UTF-8'); ?>"
alt="AI-generated image of your critter"
class="w-full aspect-square object-cover transition-transform duration-300 group-hover:scale-105"
>
</button>
<form action="" method="post" class="absolute top-3 right-3">
<input type="hidden" name="action" value="toggle_favorite">
<input type="hidden" name="critter_id" value="<?php echo (int) $critter['id']; ?>">
<button type="submit" aria-label="<?php echo $critter['isFavorite'] ? 'Unfavorite' : 'Favorite'; ?>" class="flex h-8 w-8 items-center justify-center rounded-full bg-white/90 shadow-sm transition-transform duration-150 hover:bg-white hover:scale-110">
<i data-lucide="heart" data-favorite-icon class="h-4 w-4 <?php echo $critter['isFavorite'] ? 'text-pink-500 fill-pink-500' : 'text-gray-400'; ?>"></i>
</button>
</form>
</div>
<div class="p-4">
<div class="flex items-center justify-between gap-2">
<h3 class="font-semibold text-gray-900 truncate"><?php echo htmlspecialchars(ucwords($critter['adjective'] . ' ' . $critter['noun']), ENT_QUOTES, 'UTF-8'); ?></h3>
<span class="shrink-0 text-xs text-gray-400">#<?php echo str_pad((string) $critter['id'], 4, '0', STR_PAD_LEFT); ?></span>
</div>
<div class="mt-2 flex flex-wrap gap-1.5">
<span class="inline-flex items-center rounded-full bg-blue-50 text-blue-700 text-xs font-medium px-2 py-1 truncate max-w-full"><?php echo htmlspecialchars(ucfirst($critter['verb']), ENT_QUOTES, 'UTF-8'); ?></span>
<span class="inline-flex items-center rounded-full bg-green-50 text-green-700 text-xs font-medium px-2 py-1 truncate max-w-full"><?php echo htmlspecialchars(ucfirst($critter['location']), ENT_QUOTES, 'UTF-8'); ?></span>
</div>
<div class="mt-3 flex items-center gap-2 border-t border-gray-100 pt-3">
<button type="button" onclick="openCritterModal(<?php echo (int) $critter['id']; ?>)" aria-label="View critter" class="flex h-8 w-8 items-center justify-center rounded-lg text-gray-500 transition-colors duration-150 hover:bg-gray-100 hover:text-purple-600">
<i data-lucide="eye" class="h-4 w-4"></i>
</button>
<form action="" method="post">
<input type="hidden" name="action" value="toggle_favorite">
<input type="hidden" name="critter_id" value="<?php echo (int) $critter['id']; ?>">
<button type="submit" aria-label="<?php echo $critter['isFavorite'] ? 'Unfavorite' : 'Favorite'; ?>" class="flex h-8 w-8 items-center justify-center rounded-lg text-gray-500 transition-colors duration-150 hover:bg-gray-100 hover:text-pink-500">
<i data-lucide="heart" data-favorite-icon class="h-4 w-4 <?php echo $critter['isFavorite'] ? 'text-pink-500 fill-pink-500' : ''; ?>"></i>
</button>
</form>
<form action="" method="post">
<input type="hidden" name="action" value="toggle_archived">
<input type="hidden" name="critter_id" value="<?php echo (int) $critter['id']; ?>">
<button type="submit" aria-label="<?php echo $critter['isArchived'] ? 'Unarchive' : 'Archive'; ?>" class="flex h-8 w-8 items-center justify-center rounded-lg text-gray-500 transition-colors duration-150 hover:bg-gray-100 hover:text-green-600">
<i data-lucide="<?php echo $critter['isArchived'] ? 'archive-restore' : 'archive'; ?>" class="h-4 w-4"></i>
</button>
</form>
</div>
</div>
</div>
<?php endforeach; ?>
<?php if (count($myCritters) < $perPage): ?>
<div class="rounded-2xl border-2 border-dashed border-gray-200 flex flex-col items-center justify-center text-center p-6 transition-colors duration-200 hover:border-purple-200 hover:bg-purple-50/30">
<div class="flex h-12 w-12 items-center justify-center rounded-full bg-blue-50 text-blue-300 mb-3">
<i data-lucide="paw-print" class="h-6 w-6"></i>
</div>
<h3 class="font-semibold text-gray-900">Ready for another critter?</h3>
<p class="mt-1 text-sm text-gray-500">Use your imagination and create something amazing!</p>
<a href="create-critter.php" class="mt-4 inline-flex items-center gap-2 rounded-xl bg-gradient-to-r from-purple-600 to-pink-500 text-white text-sm font-semibold px-4 py-2 shadow-sm transition-all duration-200 hover:from-purple-700 hover:to-pink-600 hover:shadow-md active:scale-[0.98]">
<i data-lucide="plus" class="h-4 w-4"></i> Create a Critter
</a>
</div>
<?php endif; ?>
</div>
<?php endif; ?>
<?php if ($totalPages > 1): ?>
<div class="mt-6 flex justify-center items-center gap-2">
<?php if ($page > 1): ?>
<a href="<?php echo htmlspecialchars(buildCritterUrl(['page' => $page - 1], $filters, $statusFilter, $search, $sort, $page), ENT_QUOTES, 'UTF-8'); ?>" class="px-3 py-2 rounded-md border border-gray-300 text-gray-700 transition-colors hover:bg-gray-100">Previous</a>
<?php else: ?>
<span class="px-3 py-2 rounded-md border border-gray-200 text-gray-400 cursor-not-allowed">Previous</span>
<?php endif; ?>
<?php for ($i = 1; $i <= $totalPages; $i++): ?>
<?php if ($i === $page): ?>
<span class="px-3 py-2 rounded-md bg-gray-900 text-white font-medium"><?php echo $i; ?></span>
<?php else: ?>
<a href="<?php echo htmlspecialchars(buildCritterUrl(['page' => $i], $filters, $statusFilter, $search, $sort, $page), ENT_QUOTES, 'UTF-8'); ?>" class="px-3 py-2 rounded-md border border-gray-300 text-gray-700 transition-colors hover:bg-gray-100"><?php echo $i; ?></a>
<?php endif; ?>
<?php endfor; ?>
<?php if ($page < $totalPages): ?>
<a href="<?php echo htmlspecialchars(buildCritterUrl(['page' => $page + 1], $filters, $statusFilter, $search, $sort, $page), ENT_QUOTES, 'UTF-8'); ?>" class="px-3 py-2 rounded-md border border-gray-300 text-gray-700 transition-colors hover:bg-gray-100">Next</a>
<?php else: ?>
<span class="px-3 py-2 rounded-md border border-gray-200 text-gray-400 cursor-not-allowed">Next</span>
<?php endif; ?>
</div>
<?php endif; ?>
<div class="mt-8 mb-12 rounded-2xl bg-blue-50/60 ring-1 ring-blue-100 p-6">
<div class="flex items-start gap-3 mb-4">
<div class="flex h-10 w-10 items-center justify-center rounded-full bg-blue-100 text-blue-600">
<i data-lucide="funnel" class="h-5 w-5"></i>
</div>
<div>
<h2 class="font-semibold text-gray-900">Filter Your Critters</h2>
<p class="text-sm text-gray-500">Find exactly what you're looking for.</p>
</div>
</div>
<form action="" method="get" class="flex flex-wrap items-end gap-4">
<input type="hidden" name="q" value="<?php echo htmlspecialchars($search, ENT_QUOTES, 'UTF-8'); ?>">
<input type="hidden" name="sort" value="<?php echo htmlspecialchars($sort, ENT_QUOTES, 'UTF-8'); ?>">
<div>
<label for="filter_adjective" class="block text-sm font-medium text-gray-700 mb-1">Adjective</label>
<select id="filter_adjective" name="filter_adjective" class="rounded-md border border-gray-300 px-3 py-2 text-gray-900 focus:outline-none focus:ring-2 focus:ring-purple-400 transition-shadow">
<option value="">Any</option>
<?php renderOptions($adjectives, $filters['filter_adjective']); ?>
</select>
</div>
<div>
<label for="filter_noun" class="block text-sm font-medium text-gray-700 mb-1">Noun (Animal)</label>
<select id="filter_noun" name="filter_noun" class="rounded-md border border-gray-300 px-3 py-2 text-gray-900 focus:outline-none focus:ring-2 focus:ring-purple-400 transition-shadow">
<option value="">Any</option>
<?php renderOptions($nouns, $filters['filter_noun']); ?>
</select>
</div>
<div>
<label for="filter_verb" class="block text-sm font-medium text-gray-700 mb-1">Verb (Action)</label>
<select id="filter_verb" name="filter_verb" class="rounded-md border border-gray-300 px-3 py-2 text-gray-900 focus:outline-none focus:ring-2 focus:ring-purple-400 transition-shadow">
<option value="">Any</option>
<?php renderOptions($verbs, $filters['filter_verb']); ?>
</select>
</div>
<div>
<label for="filter_location" class="block text-sm font-medium text-gray-700 mb-1">Location</label>
<select id="filter_location" name="filter_location" class="rounded-md border border-gray-300 px-3 py-2 text-gray-900 focus:outline-none focus:ring-2 focus:ring-purple-400 transition-shadow">
<option value="">Any</option>
<?php renderOptions($locations, $filters['filter_location']); ?>
</select>
</div>
<div>
<label for="status" class="block text-sm font-medium text-gray-700 mb-1">Status</label>
<select id="status" name="status" class="rounded-md border border-gray-300 px-3 py-2 text-gray-900 focus:outline-none focus:ring-2 focus:ring-purple-400 transition-shadow">
<option value="any" <?php echo $statusFilter === 'any' ? 'selected' : ''; ?>>Any</option>
<option value="favorited" <?php echo $statusFilter === 'favorited' ? 'selected' : ''; ?>>Favorited</option>
<option value="archived" <?php echo $statusFilter === 'archived' ? 'selected' : ''; ?>>Archived</option>
</select>
</div>
<div class="flex items-center gap-2">
<a href="<?php echo htmlspecialchars(buildCritterUrl(['filter_adjective' => null, 'filter_noun' => null, 'filter_verb' => null, 'filter_location' => null, 'status' => null, 'page' => 1], $filters, $statusFilter, $search, $sort, $page), ENT_QUOTES, 'UTF-8'); ?>" class="px-4 py-2 rounded-md border border-gray-300 text-gray-700 font-medium transition-colors hover:bg-gray-100">Clear</a>
<button type="submit" class="inline-flex items-center gap-2 bg-gray-900 text-white rounded-md px-4 py-2 font-medium transition-all duration-150 hover:bg-gray-700 active:scale-[0.98]">
<i data-lucide="search" class="h-4 w-4"></i> Apply Filters
</button>
</div>
</form>
</div>
</div>
<?php require __DIR__ . '/lib/critter-modal.php'; ?>
<?php else: ?>
<p><a href="register.php">Sign Up</a></p>
<p><a href="login.php">Log In</a></p>
<?php require __DIR__ . '/lib/hero.php'; ?>
<?php require __DIR__ . '/lib/how-it-works.php'; ?>
<?php require __DIR__ . '/lib/recent-critters.php'; ?>
<?php require __DIR__ . '/lib/cta.php'; ?>
<?php endif; ?>
</main>
<?php require __DIR__ . '/lib/footer.php'; ?>
</body>
</html>
+7
View File
@@ -0,0 +1,7 @@
<IfModule mod_authz_core.c>
Require all denied
</IfModule>
<IfModule !mod_authz_core.c>
Order allow,deny
Deny from all
</IfModule>
+502
View File
@@ -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.
<one line to give the library's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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.
<signature of Ty Coon>, 1 April 1990
Ty Coon, President of Vice
That's all there is to it!
+40
View File
@@ -0,0 +1,40 @@
<?php
/**
* PHPMailer Exception class.
* PHP Version 5.5.
*
* @see https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project
*
* @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
* @author Jim Jagielski (jimjag) <jimjag@gmail.com>
* @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
* @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 <phpmailer@synchromedia.co.uk>
*/
class Exception extends \Exception
{
/**
* Prettify error message output.
*
* @return string
*/
public function errorMessage()
{
return '<strong>' . htmlspecialchars($this->getMessage(), ENT_COMPAT | ENT_HTML401) . "</strong><br />\n";
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+254
View File
@@ -0,0 +1,254 @@
<div id="critterModalOverlay" class="hidden fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
<div class="relative w-full max-w-4xl max-h-[90vh] overflow-y-auto rounded-3xl bg-white shadow-2xl grid md:grid-cols-2">
<button type="button" onclick="closeCritterModal()" aria-label="Close" class="absolute top-4 right-4 z-10 flex h-9 w-9 items-center justify-center rounded-full bg-white/90 shadow hover:bg-white text-gray-500">
<i data-lucide="x" class="h-5 w-5"></i>
</button>
<div class="p-6 bg-gradient-to-br from-pink-50 via-white to-amber-50">
<div class="flex items-start justify-between mb-4 pr-10">
<div>
<h2 id="critterModalTitleLeft" class="text-2xl font-extrabold text-gray-900"></h2>
<p id="critterModalIdLeft" class="text-sm text-gray-400"></p>
</div>
<span id="critterModalRarityLeft" class="inline-flex items-center gap-1 rounded-full text-xs font-semibold px-3 py-1 shrink-0"></span>
</div>
<div class="rounded-2xl overflow-hidden ring-1 ring-gray-100 shadow-sm">
<img id="critterModalImage" src="" alt="" class="w-full aspect-square object-cover">
</div>
<div class="mt-4 grid grid-cols-4 gap-2 text-center">
<div>
<div class="mx-auto flex h-9 w-9 items-center justify-center rounded-full bg-pink-100 text-pink-600 mb-1"><i data-lucide="wand" class="h-4 w-4"></i></div>
<p id="critterModalAdjective" class="text-xs font-semibold text-gray-800 truncate"></p>
<p class="text-[11px] text-gray-400">Adjective</p>
</div>
<div>
<div class="mx-auto flex h-9 w-9 items-center justify-center rounded-full bg-blue-100 text-blue-600 mb-1"><i data-lucide="paw-print" class="h-4 w-4"></i></div>
<p id="critterModalNoun" class="text-xs font-semibold text-gray-800 truncate"></p>
<p class="text-[11px] text-gray-400">Animal</p>
</div>
<div>
<div class="mx-auto flex h-9 w-9 items-center justify-center rounded-full bg-green-100 text-green-600 mb-1"><i data-lucide="play" class="h-4 w-4"></i></div>
<p id="critterModalVerb" class="text-xs font-semibold text-gray-800 truncate"></p>
<p class="text-[11px] text-gray-400">Action</p>
</div>
<div>
<div class="mx-auto flex h-9 w-9 items-center justify-center rounded-full bg-purple-100 text-purple-600 mb-1"><i data-lucide="map-pin" class="h-4 w-4"></i></div>
<p id="critterModalLocation" class="text-xs font-semibold text-gray-800 truncate"></p>
<p class="text-[11px] text-gray-400">Location</p>
</div>
</div>
<p id="critterModalFlourish" class="mt-4 text-center italic text-sm text-pink-600"></p>
</div>
<div class="p-6">
<h2 id="critterModalTitleRight" class="text-2xl font-extrabold text-gray-900 pr-10"></h2>
<div class="mt-1 flex items-center gap-3">
<span id="critterModalIdRight" class="text-sm text-gray-400"></span>
<span id="critterModalRarityRight" class="inline-flex items-center gap-1 rounded-full text-xs font-semibold px-3 py-1"></span>
<button type="button" id="critterModalFavoriteBtn" onclick="toggleModalFavorite()" aria-label="Toggle favorite" class="ml-auto flex h-9 w-9 items-center justify-center rounded-full ring-1 ring-gray-200 text-gray-400 hover:bg-gray-50">
<i data-lucide="heart" class="h-4 w-4"></i>
</button>
</div>
<p id="critterModalDescription" class="mt-4 text-sm text-gray-600 leading-relaxed"></p>
<div class="mt-4 divide-y divide-gray-100 border-y border-gray-100">
<div class="flex items-center gap-2 py-2">
<i data-lucide="wand" class="h-4 w-4 text-pink-500 shrink-0"></i>
<span class="text-sm text-gray-500 w-20 shrink-0">Adjective</span>
<span id="critterModalAdjectivePill" class="inline-flex items-center rounded-full bg-pink-50 text-pink-700 text-xs font-medium px-2.5 py-1"></span>
</div>
<div class="flex items-center gap-2 py-2">
<i data-lucide="paw-print" class="h-4 w-4 text-blue-500 shrink-0"></i>
<span class="text-sm text-gray-500 w-20 shrink-0">Animal</span>
<span id="critterModalNounPill" class="inline-flex items-center rounded-full bg-blue-50 text-blue-700 text-xs font-medium px-2.5 py-1"></span>
</div>
<div class="flex items-center gap-2 py-2">
<i data-lucide="play" class="h-4 w-4 text-green-500 shrink-0"></i>
<span class="text-sm text-gray-500 w-20 shrink-0">Action</span>
<span id="critterModalVerbPill" class="inline-flex items-center rounded-full bg-green-50 text-green-700 text-xs font-medium px-2.5 py-1"></span>
</div>
<div class="flex items-center gap-2 py-2">
<i data-lucide="map-pin" class="h-4 w-4 text-purple-500 shrink-0"></i>
<span class="text-sm text-gray-500 w-20 shrink-0">Location</span>
<span id="critterModalLocationPill" class="inline-flex items-center rounded-full bg-purple-50 text-purple-700 text-xs font-medium px-2.5 py-1"></span>
</div>
</div>
<div class="mt-4 grid grid-cols-3 gap-3 text-xs text-gray-500">
<div class="flex items-center gap-1.5">
<i data-lucide="calendar" class="h-4 w-4 shrink-0"></i>
<div>
<p class="text-gray-400">Created</p>
<p id="critterModalCreated" class="text-gray-700 font-medium"></p>
</div>
</div>
<div class="flex items-center gap-1.5">
<i data-lucide="scaling" class="h-4 w-4 shrink-0"></i>
<div>
<p class="text-gray-400">Resolution</p>
<p id="critterModalResolution" class="text-gray-700 font-medium"></p>
</div>
</div>
<div class="flex items-center gap-1.5">
<i data-lucide="hard-drive" class="h-4 w-4 shrink-0"></i>
<div>
<p class="text-gray-400">File Size</p>
<p id="critterModalFileSize" class="text-gray-700 font-medium"></p>
</div>
</div>
</div>
<div class="mt-4 rounded-xl bg-blue-50 ring-1 ring-blue-100 p-3">
<div class="flex items-center justify-between mb-1">
<span class="inline-flex items-center gap-1.5 text-xs font-semibold text-blue-700">
<i data-lucide="sparkles" class="h-4 w-4"></i> Prompt Used
</span>
<button type="button" onclick="copyModalPrompt()" aria-label="Copy prompt" class="text-blue-400 hover:text-blue-600">
<i data-lucide="copy" class="h-4 w-4"></i>
</button>
</div>
<p id="critterModalPrompt" class="text-xs italic text-gray-600 leading-relaxed"></p>
</div>
<div class="mt-4 grid grid-cols-3 gap-2">
<a id="critterModalDownloadBtn" href="#" download class="flex items-center justify-center gap-1.5 rounded-xl bg-gray-900 text-white text-sm font-semibold py-2.5 hover:bg-gray-800">
<i data-lucide="download" class="h-4 w-4"></i> Download
</a>
<button type="button" id="critterModalShareBtn" onclick="shareModalCritter()" class="flex items-center justify-center gap-1.5 rounded-xl bg-gray-100 text-gray-700 text-sm font-semibold py-2.5 hover:bg-gray-200">
<i data-lucide="share-2" class="h-4 w-4"></i> Share
</button>
<a id="critterModalCreateSimilarBtn" href="#" class="flex items-center justify-center gap-1.5 rounded-xl bg-gray-100 text-gray-700 text-sm font-semibold py-2.5 hover:bg-gray-200">
<i data-lucide="refresh-cw" class="h-4 w-4"></i> Create Similar
</a>
</div>
</div>
</div>
</div>
<script>
let currentCritterModalId = null;
function updateModalFavoriteButton(isFavorite) {
const btn = document.getElementById('critterModalFavoriteBtn');
const icon = btn.querySelector('[data-lucide]');
icon.classList.toggle('text-pink-500', isFavorite);
icon.classList.toggle('fill-pink-500', isFavorite);
btn.classList.toggle('ring-pink-200', isFavorite);
}
function renderCritterModal(data) {
currentCritterModalId = data.id;
const idText = '#' + String(data.id).padStart(4, '0');
document.getElementById('critterModalTitleLeft').textContent = data.title;
document.getElementById('critterModalTitleRight').textContent = data.title;
document.getElementById('critterModalIdLeft').textContent = idText;
document.getElementById('critterModalIdRight').textContent = idText;
const rarityClasses = 'inline-flex items-center gap-1 rounded-full text-xs font-semibold px-3 py-1 shrink-0 ' + data.rarity.classes;
const rarityLeft = document.getElementById('critterModalRarityLeft');
const rarityRight = document.getElementById('critterModalRarityRight');
rarityLeft.textContent = data.rarity.label;
rarityRight.textContent = data.rarity.label;
rarityLeft.className = rarityClasses;
rarityRight.className = rarityClasses.replace(' shrink-0', '');
const img = document.getElementById('critterModalImage');
img.src = data.imageUrl || '';
img.alt = data.title;
document.getElementById('critterModalAdjective').textContent = data.adjective;
document.getElementById('critterModalNoun').textContent = data.noun;
document.getElementById('critterModalVerb').textContent = data.verb;
document.getElementById('critterModalLocation').textContent = data.location;
document.getElementById('critterModalAdjectivePill').textContent = data.adjective;
document.getElementById('critterModalNounPill').textContent = data.noun;
document.getElementById('critterModalVerbPill').textContent = data.verb;
document.getElementById('critterModalLocationPill').textContent = data.location;
const sentences = data.description.split('. ');
document.getElementById('critterModalFlourish').textContent = '"' + sentences[sentences.length - 1].replace(/\.$/, '') + '"';
document.getElementById('critterModalDescription').textContent = data.description;
document.getElementById('critterModalCreated').textContent = data.createdAt || '—';
document.getElementById('critterModalResolution').textContent = data.resolution || '—';
document.getElementById('critterModalFileSize').textContent = data.fileSize || '—';
document.getElementById('critterModalPrompt').textContent = data.prompt;
document.getElementById('critterModalDownloadBtn').href = data.imageUrl || '#';
document.getElementById('critterModalCreateSimilarBtn').href = data.createSimilarUrl;
updateModalFavoriteButton(data.isFavorite);
window.__critterModalShareUrl = window.location.origin + '/' + data.shareUrl;
window.__critterModalPromptText = data.prompt;
}
function openCritterModal(id) {
fetch('api/critter-details.php?id=' + encodeURIComponent(id))
.then((res) => res.json())
.then((data) => {
if (data.error) return;
renderCritterModal(data);
document.getElementById('critterModalOverlay').classList.remove('hidden');
if (window.lucide) lucide.createIcons();
});
}
function closeCritterModal() {
document.getElementById('critterModalOverlay').classList.add('hidden');
}
document.getElementById('critterModalOverlay').addEventListener('click', function (event) {
if (event.target === this) closeCritterModal();
});
document.addEventListener('keydown', function (event) {
if (event.key === 'Escape') closeCritterModal();
});
function toggleModalFavorite() {
if (!currentCritterModalId) return;
fetch('api/critter-details.php', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({ id: currentCritterModalId, action: 'toggle_favorite' }),
})
.then((res) => res.json())
.then((data) => {
if (data.error) return;
updateModalFavoriteButton(data.isFavorite);
const card = document.querySelector('[data-critter-card="' + currentCritterModalId + '"]');
if (card) {
card.querySelectorAll('[data-favorite-icon]').forEach((icon) => {
icon.classList.toggle('text-pink-500', data.isFavorite);
icon.classList.toggle('fill-pink-500', data.isFavorite);
});
}
});
}
function copyModalPrompt() {
if (window.__critterModalPromptText && navigator.clipboard) {
navigator.clipboard.writeText(window.__critterModalPromptText);
}
}
function shareModalCritter() {
const url = window.__critterModalShareUrl;
if (navigator.share) {
navigator.share({ title: 'Check out my critter!', url }).catch(() => {});
return;
}
if (navigator.clipboard) {
navigator.clipboard.writeText(url);
const btn = document.getElementById('critterModalShareBtn');
const original = btn.innerHTML;
btn.textContent = 'Link copied!';
setTimeout(() => {
btn.innerHTML = original;
if (window.lucide) lucide.createIcons();
}, 1500);
}
}
</script>
+48
View File
@@ -0,0 +1,48 @@
<section class="max-w-[1400px] mx-auto px-6 pt-8">
<div class="rounded-3xl bg-gradient-to-br from-blue-50 via-white to-purple-50 ring-1 ring-gray-100 p-6 sm:p-8 grid lg:grid-cols-3 gap-8 items-center">
<div class="lg:col-span-2 grid sm:grid-cols-2 gap-8 items-center">
<div>
<h1 class="text-4xl font-extrabold text-gray-900">My Critters</h1>
<p class="mt-2 text-lg text-gray-700">
<?php echo (int) $totalCrittersCount; ?> unique critter<?php echo $totalCrittersCount === 1 ? '' : 's'; ?> and counting!
</p>
<p class="mt-2 text-gray-500">Create, explore and manage your collection of AI-generated critters.</p>
</div>
<div class="relative group">
<img src="assets/recently3.webp" alt="One of your critters" class="w-full aspect-square object-cover rounded-2xl shadow-lg ring-1 ring-gray-100 transition-transform duration-300 group-hover:scale-[1.02]">
<div class="absolute -bottom-4 -left-4 hidden sm:flex items-center gap-2 rounded-xl bg-white px-3 py-2 shadow-md ring-1 ring-gray-100 text-sm max-w-[85%]">
<i data-lucide="heart" class="h-4 w-4 shrink-0 text-pink-500"></i>
<span class="text-gray-700 font-medium">Same critters. Bigger adventures!</span>
</div>
</div>
</div>
<div>
<div class="grid grid-cols-3 gap-3">
<div class="rounded-xl bg-white ring-1 ring-gray-100 shadow-sm p-4 text-center transition-all duration-200 hover:-translate-y-0.5 hover:shadow-md">
<div class="mx-auto flex h-9 w-9 items-center justify-center rounded-full bg-blue-100 text-blue-600 mb-2">
<i data-lucide="paw-print" class="h-4 w-4"></i>
</div>
<p class="text-xl font-bold text-gray-900"><?php echo (int) $totalCrittersCount; ?></p>
<p class="text-xs text-gray-500">Total Critters</p>
</div>
<div class="rounded-xl bg-white ring-1 ring-gray-100 shadow-sm p-4 text-center transition-all duration-200 hover:-translate-y-0.5 hover:shadow-md">
<div class="mx-auto flex h-9 w-9 items-center justify-center rounded-full bg-pink-100 text-pink-600 mb-2">
<i data-lucide="heart" class="h-4 w-4"></i>
</div>
<p class="text-xl font-bold text-gray-900"><?php echo (int) $favoritesCount; ?></p>
<p class="text-xs text-gray-500">Favourites</p>
</div>
<div class="rounded-xl bg-white ring-1 ring-gray-100 shadow-sm p-4 text-center transition-all duration-200 hover:-translate-y-0.5 hover:shadow-md">
<div class="mx-auto flex h-9 w-9 items-center justify-center rounded-full bg-green-100 text-green-600 mb-2">
<i data-lucide="archive" class="h-4 w-4"></i>
</div>
<p class="text-xl font-bold text-gray-900"><?php echo (int) $archivedCount; ?></p>
<p class="text-xs text-gray-500">Archived</p>
</div>
</div>
<a href="create-critter.php" class="mt-4 flex items-center justify-center gap-2 rounded-xl bg-gradient-to-r from-purple-600 to-pink-500 text-white font-semibold py-3 shadow-sm transition-all duration-200 hover:from-purple-700 hover:to-pink-600 hover:shadow-md active:scale-[0.98] focus:outline-none focus-visible:ring-2 focus-visible:ring-purple-400 focus-visible:ring-offset-2">
<i data-lucide="plus" class="h-4 w-4"></i> Create a Critter
</a>
</div>
</div>
</section>
+9
View File
@@ -0,0 +1,9 @@
<section class="bg-gradient-to-r from-purple-600 via-pink-500 to-amber-500">
<div class="max-w-4xl mx-auto px-6 py-14 text-center">
<h2 class="text-3xl font-extrabold text-white">Ready to meet your first critter?</h2>
<p class="mt-3 text-white/90">It only takes a few clicks to bring your imagination to life.</p>
<a href="register.php" class="mt-8 inline-flex items-center rounded-full bg-white px-8 py-3 font-semibold text-purple-700 shadow-md hover:bg-gray-50">
Get Started Free
</a>
</div>
</section>
+33
View File
@@ -0,0 +1,33 @@
<?php
$isLoggedIn = isset($_SESSION['username']);
?>
<footer class="border-t border-gray-200 bg-amber-50">
<div class="max-w-[1400px] mx-auto px-6 py-10 flex flex-col sm:flex-row sm:items-start sm:justify-between gap-8">
<div>
<a href="/" class="inline-flex items-center">
<img src="assets/logo.png" alt="OurApp" class="h-6 w-auto">
</a>
<p class="mt-1 text-sm text-gray-500">Imaginary creatures. Real fun.</p>
</div>
<div class="flex flex-col sm:items-end gap-4">
<div class="flex flex-wrap items-center gap-x-6 gap-y-2 text-sm text-gray-600">
<?php if ($isLoggedIn): ?>
<a href="/?status=favorited" class="hover:text-gray-900 hover:underline">Favorites</a>
<?php else: ?>
<a href="/" class="hover:text-gray-900 hover:underline">Home</a>
<a href="login.php" class="hover:text-gray-900 hover:underline">Login</a>
<a href="register.php" class="hover:text-gray-900 hover:underline">Sign up</a>
<?php endif; ?>
</div>
<div class="flex items-center gap-4 text-gray-400">
<a href="#" aria-label="GitHub" class="hover:text-gray-700"><i data-lucide="laptop" class="h-5 w-5"></i></a>
<a href="#" aria-label="Twitter" class="hover:text-gray-700"><i data-lucide="bird" class="h-5 w-5"></i></a>
<a href="#" aria-label="Discord" class="hover:text-gray-700"><i data-lucide="message-circle" class="h-5 w-5"></i></a>
<a href="#" aria-label="Instagram" class="hover:text-gray-700"><i data-lucide="camera" class="h-5 w-5"></i></a>
</div>
</div>
</div>
</footer>
<script>lucide.createIcons();</script>
+42
View File
@@ -0,0 +1,42 @@
<?php require_once __DIR__ . '/ticket.php'; ?>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?php echo htmlspecialchars($pageTitle ?? 'OurApp', ENT_QUOTES, 'UTF-8'); ?></title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<link rel="stylesheet" href="/media/output.css?v=<?php echo filemtime(__DIR__ . '/../media/output.css'); ?>">
<script src="https://unpkg.com/lucide@1.41.0/dist/umd/lucide.min.js"></script>
<script src="https://cdn.paddle.com/paddle/v2/paddle.js"></script>
<script type="text/javascript">
Paddle.Environment.set("sandbox");
Paddle.Initialize({
token: "test_4e37deb3ec9f5dbe68fef14fcf6",
eventCallback: function(data) {
if (data.name === "checkout.completed") {
setTimeout(function() {
window.location.href = "/processing.php";
}, 2000);
}
}
});
// define items
let itemsList = [
{
priceId: "pri_01m1v2aegbrdvwhw1jf7b0s6va",
quantity: 1
}
];
// open checkout
function openCheckout(items){
Paddle.Checkout.open({
items: items,
customData: JSON.stringify({user_id: "<?php echo htmlspecialchars(createTicket((int) ($_SESSION['user_id'] ?? 0), 'purchase'), ENT_QUOTES, 'UTF-8'); ?>"})
});
}
</script>
</head>
+77
View File
@@ -0,0 +1,77 @@
<?php
require_once __DIR__ . '/../db.php';
$isLoggedIn = isset($_SESSION['username']);
$userCredits = 0;
if ($isLoggedIn && isset($_SESSION['user_id'])) {
$stmt = getDbConnection()->prepare('SELECT credits FROM users WHERE id = :id');
$stmt->execute(['id' => $_SESSION['user_id']]);
$userCredits = (int) $stmt->fetchColumn();
}
?>
<?php $headerBgClass = $headerBgClass ?? 'bg-amber-50'; ?>
<?php $currentPage = basename($_SERVER['SCRIPT_NAME'] ?? ''); ?>
<header class="relative z-20 w-full <?php echo $headerBgClass; ?>">
<div class="px-6 py-3 flex items-center justify-between gap-6">
<div class="flex items-center gap-8">
<a href="/" class="inline-flex items-center shrink-0">
<img src="assets/logo.png" alt="OurApp" class="h-8 w-auto">
</a>
<?php if ($isLoggedIn): ?>
<nav class="hidden md:flex items-center gap-6 text-sm font-medium">
<a href="/" class="pb-1 border-b-2 <?php echo $currentPage === 'index.php' ? 'border-blue-600 text-blue-600' : 'border-transparent text-gray-600 hover:text-gray-900'; ?>">My Critters</a>
<a href="create-critter.php" class="pb-1 border-b-2 <?php echo $currentPage === 'create-critter.php' ? 'border-blue-600 text-blue-600' : 'border-transparent text-gray-600 hover:text-gray-900'; ?>">Create Critter</a>
</nav>
<?php endif; ?>
</div>
<?php if ($isLoggedIn): ?>
<div class="flex items-center gap-4">
<span class="hidden sm:inline-flex items-center gap-1.5 rounded-full bg-amber-100/70 ring-1 ring-amber-200 text-amber-900 text-sm font-semibold px-3 py-1.5">
<i data-lucide="coins" class="h-4 w-4 text-amber-500"></i>
Credits: <?php echo $userCredits; ?>
</span>
<a href="#" onClick="openCheckout(itemsList)" class="hidden sm:inline-flex items-center gap-2 rounded-xl bg-gray-900 text-white text-sm font-semibold px-4 py-2 transition-colors hover:bg-gray-800">
<i data-lucide="shopping-cart" class="h-4 w-4"></i> Buy 50 Credits
</a>
<span class="hidden sm:block h-6 w-px bg-gray-300/70"></span>
<div class="relative">
<button type="button" data-user-menu-toggle class="flex items-center gap-2">
<span class="flex h-8 w-8 items-center justify-center rounded-full bg-gradient-to-br from-purple-600 to-pink-500 text-white text-sm font-semibold">
<?php echo htmlspecialchars(strtoupper(substr($_SESSION['username'], 0, 1)), ENT_QUOTES, 'UTF-8'); ?>
</span>
<span class="hidden sm:inline text-sm font-medium text-gray-800"><?php echo htmlspecialchars($_SESSION['username'], ENT_QUOTES, 'UTF-8'); ?></span>
<i data-lucide="chevron-down" class="h-4 w-4 text-gray-500"></i>
</button>
<div id="userMenu" class="hidden absolute right-0 mt-2 w-52 rounded-xl bg-white shadow-lg ring-1 ring-gray-100 py-2 text-sm z-30">
<a href="create-critter.php" class="flex items-center gap-2 px-4 py-2 text-gray-700 hover:bg-gray-50 sm:hidden">
<i data-lucide="sparkles" class="h-4 w-4"></i> Create Critter
</a>
<a href="#" onClick="openCheckout(itemsList)" class="flex items-center gap-2 px-4 py-2 text-gray-700 hover:bg-gray-50 sm:hidden">
<i data-lucide="coins" class="h-4 w-4"></i> Buy 50 Credits
</a>
<a href="logout.php" class="flex items-center gap-2 px-4 py-2 text-gray-700 hover:bg-gray-50">
<i data-lucide="log-out" class="h-4 w-4"></i> Log out
</a>
</div>
</div>
</div>
<script>
document.addEventListener('click', function (event) {
const menu = document.getElementById('userMenu');
if (!menu) return;
if (event.target.closest('[data-user-menu-toggle]')) {
menu.classList.toggle('hidden');
return;
}
if (!menu.contains(event.target)) {
menu.classList.add('hidden');
}
});
</script>
<?php else: ?>
<div class="flex items-center gap-4">
<a href="login.php" class="font-medium text-gray-700 hover:text-gray-900">Login</a>
<a href="register.php" class="inline-flex items-center rounded-full bg-gradient-to-r from-purple-600 to-pink-500 px-5 py-2 font-semibold text-white shadow-sm hover:from-purple-700 hover:to-pink-600">Sign up</a>
</div>
<?php endif; ?>
</div>
</header>
+66
View File
@@ -0,0 +1,66 @@
<section class="relative overflow-hidden bg-gradient-to-b from-amber-50 via-pink-50 to-white">
<div class="pointer-events-none absolute -top-24 -left-24 h-72 w-72 rounded-full bg-purple-300 opacity-30 blur-3xl"></div>
<div class="pointer-events-none absolute top-40 -right-24 h-72 w-72 rounded-full bg-amber-300 opacity-30 blur-3xl"></div>
<?php $headerBgClass = 'bg-transparent'; require __DIR__ . '/header.php'; ?>
<div class="relative max-w-[1400px] mx-auto px-6 py-16 lg:py-24 grid lg:grid-cols-2 gap-12 items-center">
<div>
<p class="text-sm font-semibold tracking-widest text-purple-600 uppercase mb-4">Imagine &middot; Mix &middot; Create</p>
<h1 class="text-4xl sm:text-5xl font-extrabold tracking-tight text-gray-900 leading-tight">
Bring your
<span class="bg-gradient-to-r from-purple-600 via-pink-500 to-amber-500 bg-clip-text text-transparent">imagination</span>
to life.
</h1>
<p class="mt-6 text-lg text-gray-600 max-w-lg">
Create unique, AI-generated critters from your favorite combinations. Choose an
<span class="font-semibold text-gray-800">adjective</span>,
<span class="font-semibold text-gray-800">animal</span>,
<span class="font-semibold text-gray-800">action</span>,
and <span class="font-semibold text-gray-800">place</span> &mdash; and discover something completely new.
</p>
<div class="mt-8 flex flex-wrap gap-4">
<a href="register.php" class="inline-flex items-center rounded-full bg-gradient-to-r from-purple-600 to-pink-500 px-6 py-3 font-semibold text-white shadow-md hover:from-purple-700 hover:to-pink-600">
Sign Up Free
</a>
<a href="login.php" class="inline-flex items-center rounded-full bg-white px-6 py-3 font-semibold text-gray-800 shadow-sm ring-1 ring-gray-200 hover:bg-gray-50">
Log In
</a>
</div>
<div class="mt-10 flex flex-wrap gap-6 text-sm text-gray-600">
<div class="flex items-center gap-2">
<span class="flex h-8 w-8 items-center justify-center rounded-full bg-pink-100 text-pink-600"><i data-lucide="zap" class="h-4 w-4"></i></span>
Unique creations
</div>
<div class="flex items-center gap-2">
<span class="flex h-8 w-8 items-center justify-center rounded-full bg-amber-100 text-amber-600"><i data-lucide="sparkles" class="h-4 w-4"></i></span>
Save your favorites
</div>
<div class="flex items-center gap-2">
<span class="flex h-8 w-8 items-center justify-center rounded-full bg-purple-100 text-purple-600"><i data-lucide="rainbow" class="h-4 w-4"></i></span>
Remix and explore
</div>
</div>
</div>
<div class="relative">
<p class="hidden sm:block absolute -top-8 left-8 z-10 -rotate-6 font-semibold text-gray-700 italic">
<i data-lucide="arrow-up-right" class="inline h-4 w-4 text-purple-500"></i> Endless possibilities
</p>
<div class="relative rounded-3xl bg-white p-3 shadow-xl ring-1 ring-gray-100">
<img
src="assets/hero-image.png"
alt="A cute AI-generated critter"
class="w-full rounded-2xl object-cover"
>
</div>
<div class="absolute -bottom-6 left-6 flex items-center gap-3 rounded-2xl bg-white px-4 py-3 shadow-lg ring-1 ring-gray-100">
<div>
<p class="font-semibold text-gray-900">Fluffy Pig</p>
<p class="text-sm text-gray-500">Building &middot; On the Farm</p>
</div>
<i data-lucide="heart" class="h-4 w-4 text-pink-500"></i>
</div>
</div>
</div>
</section>
+41
View File
@@ -0,0 +1,41 @@
<section class="max-w-[1400px] mx-auto px-6 py-16 lg:py-24">
<div class="rounded-3xl bg-white/70 ring-1 ring-gray-100 shadow-sm px-6 py-12 sm:px-12">
<div class="text-center max-w-2xl mx-auto mb-12">
<h2 class="text-3xl font-extrabold text-gray-900">How it works</h2>
<p class="mt-3 text-gray-600">Create your perfect critter in four simple steps.</p>
</div>
<div class="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-10 sm:gap-4">
<div class="flex-1 text-center">
<div class="mx-auto flex h-14 w-14 items-center justify-center rounded-full bg-pink-100 text-pink-600">
<i data-lucide="wand" class="h-6 w-6"></i>
</div>
<h3 class="mt-4 font-semibold text-gray-900">1. Choose an Adjective</h3>
<p class="mt-1 text-gray-500 text-sm">Set the mood</p>
</div>
<div class="hidden sm:flex items-center justify-center text-gray-300 pt-5"><i data-lucide="arrow-right" class="h-5 w-5"></i></div>
<div class="flex-1 text-center">
<div class="mx-auto flex h-14 w-14 items-center justify-center rounded-full bg-blue-100 text-blue-600">
<i data-lucide="paw-print" class="h-6 w-6"></i>
</div>
<h3 class="mt-4 font-semibold text-gray-900">2. Pick an Animal</h3>
<p class="mt-1 text-gray-500 text-sm">From cute to wild</p>
</div>
<div class="hidden sm:flex items-center justify-center text-gray-300 pt-5"><i data-lucide="arrow-right" class="h-5 w-5"></i></div>
<div class="flex-1 text-center">
<div class="mx-auto flex h-14 w-14 items-center justify-center rounded-full bg-green-100 text-green-600">
<i data-lucide="play" class="h-6 w-6"></i>
</div>
<h3 class="mt-4 font-semibold text-gray-900">3. Add an Action</h3>
<p class="mt-1 text-gray-500 text-sm">What are they doing?</p>
</div>
<div class="hidden sm:flex items-center justify-center text-gray-300 pt-5"><i data-lucide="arrow-right" class="h-5 w-5"></i></div>
<div class="flex-1 text-center">
<div class="mx-auto flex h-14 w-14 items-center justify-center rounded-full bg-purple-100 text-purple-600">
<i data-lucide="map-pin" class="h-6 w-6"></i>
</div>
<h3 class="mt-4 font-semibold text-gray-900">4. Select a Location</h3>
<p class="mt-1 text-gray-500 text-sm">Where do they live?</p>
</div>
</div>
</div>
</section>
+106
View File
@@ -0,0 +1,106 @@
<?php
require_once __DIR__ . '/PHPMailer/src/Exception.php';
require_once __DIR__ . '/PHPMailer/src/PHPMailer.php';
require_once __DIR__ . '/PHPMailer/src/SMTP.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception as PHPMailerException;
function configureAppMailer(): PHPMailer
{
$mail = new PHPMailer(true);
$mail->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 = '
<div style="font-family: Arial, sans-serif; max-width: 480px; margin: 0 auto; padding: 32px 24px;">
<h1 style="color: #111827; font-size: 22px; margin-bottom: 8px;">Welcome, ' . $safeUsername . '! &#128062;</h1>
<p style="color: #4b5563; font-size: 15px; line-height: 1.6;">
Your OurApp account has been created. You are ready to start creating unique, AI-generated critters &mdash; pick an adjective, animal, action, and location, and watch your imagination come to life.
</p>
<p style="margin-top: 24px;">
<a href="https://ourapp.local/" style="display: inline-block; background: linear-gradient(to right, #9333ea, #ec4899); color: #ffffff; text-decoration: none; font-weight: 600; padding: 12px 24px; border-radius: 9999px;">
Start Creating
</a>
</p>
<p style="color: #9ca3af; font-size: 13px; margin-top: 32px;">
If you didn&rsquo;t create this account, you can safely ignore this email.
</p>
</div>
';
$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 = '
<div style="font-family: Arial, sans-serif; max-width: 480px; margin: 0 auto; padding: 32px 24px;">
<h1 style="color: #111827; font-size: 22px; margin-bottom: 8px;">Reset your password</h1>
<p style="color: #4b5563; font-size: 15px; line-height: 1.6;">
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.
</p>
<p style="margin-top: 24px;">
<a href="' . $safeResetLink . '" style="display: inline-block; background: linear-gradient(to right, #9333ea, #ec4899); color: #ffffff; text-decoration: none; font-weight: 600; padding: 12px 24px; border-radius: 9999px;">
Reset Password
</a>
</p>
<p style="color: #9ca3af; font-size: 13px; margin-top: 32px;">
If you didn&rsquo;t request a password reset, you can safely ignore this email &mdash; your password will not be changed.
</p>
</div>
';
$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;
}
}
+48
View File
@@ -0,0 +1,48 @@
<section class="max-w-[1400px] mx-auto px-6 py-16 lg:py-24">
<div class="text-center max-w-2xl mx-auto mb-12">
<h2 class="text-3xl font-extrabold text-gray-900">Recently Created Critters</h2>
<p class="mt-3 text-gray-600">A peek at what other creators just dreamed up.</p>
</div>
<div class="relative">
<div id="recent-critters-track" class="flex gap-6 overflow-x-auto snap-x snap-mandatory scroll-smooth pb-4 -mx-6 px-6 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
<div class="snap-center shrink-0 w-64 sm:w-72">
<div class="rounded-3xl bg-white p-2 shadow-md ring-1 ring-gray-100">
<img src="assets/recently1.webp" alt="A recently created critter" class="w-full aspect-square rounded-2xl object-cover">
</div>
</div>
<div class="snap-center shrink-0 w-64 sm:w-72">
<div class="rounded-3xl bg-white p-2 shadow-md ring-1 ring-gray-100">
<img src="assets/recently2.webp" alt="A recently created critter" class="w-full aspect-square rounded-2xl object-cover">
</div>
</div>
<div class="snap-center shrink-0 w-64 sm:w-72">
<div class="rounded-3xl bg-white p-2 shadow-md ring-1 ring-gray-100">
<img src="assets/recently3.webp" alt="A recently created critter" class="w-full aspect-square rounded-2xl object-cover">
</div>
</div>
<div class="snap-center shrink-0 w-64 sm:w-72">
<div class="rounded-3xl bg-white p-2 shadow-md ring-1 ring-gray-100">
<img src="assets/recently4.webp" alt="A recently created critter" class="w-full aspect-square rounded-2xl object-cover">
</div>
</div>
</div>
<button
type="button"
onclick="document.getElementById('recent-critters-track').scrollBy({left: -300, behavior: 'smooth'})"
class="hidden sm:flex absolute -left-5 top-1/2 -translate-y-1/2 h-10 w-10 items-center justify-center rounded-full bg-white text-gray-700 shadow-md ring-1 ring-gray-200 hover:bg-gray-50"
aria-label="Scroll left"
>
<i data-lucide="chevron-left" class="h-5 w-5"></i>
</button>
<button
type="button"
onclick="document.getElementById('recent-critters-track').scrollBy({left: 300, behavior: 'smooth'})"
class="hidden sm:flex absolute -right-5 top-1/2 -translate-y-1/2 h-10 w-10 items-center justify-center rounded-full bg-white text-gray-700 shadow-md ring-1 ring-gray-200 hover:bg-gray-50"
aria-label="Scroll right"
>
<i data-lucide="chevron-right" class="h-5 w-5"></i>
</button>
</div>
</section>
+60
View File
@@ -0,0 +1,60 @@
<?php
define('TICKET_LIFETIME_SECONDS', 20 * 60);
function getTicketSecret(): string
{
$secret = getenv('TICKET_SECRET');
if ($secret === false || $secret === '') {
error_log('ticket.php: TICKET_SECRET is not configured');
throw new RuntimeException('Server misconfiguration');
}
return $secret;
}
function createTicket(int $userId, string $purpose = 'default'): string
{
$expiresAt = time() + TICKET_LIFETIME_SECONDS;
$payload = $userId . '|' . $expiresAt . '|' . $purpose;
$signature = hash_hmac('sha256', $payload, getTicketSecret());
return base64_encode($payload . '.' . $signature);
}
function decodeTicket(string $ticket, string $purpose = 'default'): ?int
{
$decoded = base64_decode($ticket, true);
if ($decoded === false) {
return null;
}
$separatorPosition = strrpos($decoded, '.');
if ($separatorPosition === false) {
return null;
}
$payload = substr($decoded, 0, $separatorPosition);
$signature = substr($decoded, $separatorPosition + 1);
$expectedSignature = hash_hmac('sha256', $payload, getTicketSecret());
if (!hash_equals($expectedSignature, $signature)) {
return null;
}
$parts = explode('|', $payload, 3);
if (count($parts) !== 3 || !ctype_digit($parts[0]) || !ctype_digit($parts[1])) {
return null;
}
[$userId, $expiresAt, $ticketPurpose] = $parts;
if (!hash_equals($purpose, $ticketPurpose)) {
return null;
}
if ((int) $expiresAt < time()) {
return null;
}
return (int) $userId;
}
+103 -29
View File
@@ -9,16 +9,16 @@ if (isset($_SESSION['username'])) {
}
$errors = [];
$username = '';
$email = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
sleep(4);
$username = trim($_POST['username'] ?? '');
$email = trim($_POST['email'] ?? '');
$password = $_POST['password'] ?? '';
if ($username === '') {
$errors['username'] = 'Username is required.';
if ($email === '') {
$errors['email'] = 'Email is required.';
}
if ($password === '') {
@@ -27,12 +27,12 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (empty($errors)) {
$pdo = getDbConnection();
$stmt = $pdo->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';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Log In</title>
</head>
<body>
<?php if (isset($errors['login'])): ?>
<div><?php echo htmlspecialchars($errors['login'], ENT_QUOTES, 'UTF-8'); ?></div>
<?php endif; ?>
<form action="login.php" method="post" novalidate>
<div>
<label for="username">Username</label>
<input type="text" id="username" name="username" value="<?php echo htmlspecialchars($username, ENT_QUOTES, 'UTF-8'); ?>">
<?php if (isset($errors['username'])): ?>
<div><?php echo htmlspecialchars($errors['username'], ENT_QUOTES, 'UTF-8'); ?></div>
<?php endif; ?>
<?php require __DIR__ . '/lib/head.php'; ?>
<body class="bg-amber-50 min-h-screen flex flex-col">
<?php require __DIR__ . '/lib/header.php'; ?>
<div class="flex-1 flex items-center justify-center bg-gradient-to-b from-amber-50 via-pink-50 to-white p-4 py-12">
<div class="w-full max-w-4xl bg-white rounded-3xl shadow-xl ring-1 ring-gray-100 overflow-hidden grid md:grid-cols-2">
<div class="relative hidden md:block">
<img src="assets/recently2.webp" alt="" aria-hidden="true" class="absolute inset-0 h-full w-full object-cover">
<div class="absolute inset-0 bg-gradient-to-b from-black/10 via-transparent to-black/40"></div>
<div class="relative h-full flex flex-col justify-between p-8 text-white">
<p class="italic font-semibold text-xl leading-snug drop-shadow">
Good creatures.<br>Brighter days.
</p>
<div class="rounded-2xl bg-white/90 backdrop-blur text-gray-800 px-4 py-3 flex items-center gap-3 shadow-md">
<i data-lucide="paw-print" class="h-4 w-4"></i>
<span class="text-sm font-medium">Log in to continue your collection.</span>
</div>
</div>
</div>
<div>
<label for="password">Password</label>
<input type="password" id="password" name="password">
<?php if (isset($errors['password'])): ?>
<div><?php echo htmlspecialchars($errors['password'], ENT_QUOTES, 'UTF-8'); ?></div>
<div class="p-8 sm:p-10">
<h1 class="text-2xl font-extrabold text-gray-900">Welcome back, explorer.</h1>
<p class="mt-1 text-gray-500 text-sm">Your critters have been waiting.</p>
<?php if (isset($errors['login'])): ?>
<div class="mt-4 rounded-lg bg-red-50 text-red-700 text-sm px-4 py-3">
<?php echo htmlspecialchars($errors['login'], ENT_QUOTES, 'UTF-8'); ?>
</div>
<?php endif; ?>
<?php if (isset($_GET['reset']) && $_GET['reset'] === 'success'): ?>
<div class="mt-4 rounded-lg bg-green-50 text-green-700 text-sm px-4 py-3">
Your password has been reset. You can now log in.
</div>
<?php endif; ?>
<form action="login.php" method="post" novalidate class="mt-6 space-y-4">
<div>
<label for="email" class="block text-sm font-medium text-gray-700 mb-1">Email</label>
<div class="relative">
<i data-lucide="mail" class="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400"></i>
<input
type="email" id="email" name="email"
value="<?php echo htmlspecialchars($email, ENT_QUOTES, 'UTF-8'); ?>"
placeholder="you@example.com"
class="w-full rounded-xl border border-gray-300 pl-10 pr-3 py-2.5 focus:outline-none focus:ring-2 focus:ring-purple-400"
>
</div>
<?php if (isset($errors['email'])): ?>
<p class="mt-1 text-sm text-red-600"><?php echo htmlspecialchars($errors['email'], ENT_QUOTES, 'UTF-8'); ?></p>
<?php endif; ?>
</div>
<div>
<div class="flex items-center justify-between mb-1">
<label for="password" class="block text-sm font-medium text-gray-700">Password</label>
<a href="forgot-password.php" class="text-sm text-purple-600 font-medium hover:underline">Forgot password?</a>
</div>
<div class="relative">
<i data-lucide="lock" class="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400"></i>
<input
type="password" id="password" name="password"
placeholder="Enter your password"
class="w-full rounded-xl border border-gray-300 pl-10 pr-10 py-2.5 focus:outline-none focus:ring-2 focus:ring-purple-400"
>
<button
type="button"
onclick="togglePasswordVisibility('password', this)"
class="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
aria-label="Show password"
>
<i data-lucide="eye" class="h-4 w-4"></i>
<i data-lucide="eye-off" class="h-4 w-4 hidden"></i>
</button>
</div>
<?php if (isset($errors['password'])): ?>
<p class="mt-1 text-sm text-red-600"><?php echo htmlspecialchars($errors['password'], ENT_QUOTES, 'UTF-8'); ?></p>
<?php endif; ?>
</div>
<button type="submit" class="w-full inline-flex items-center justify-center gap-2 rounded-xl bg-gray-900 text-white font-semibold py-3 hover:bg-gray-800">
Log In <i data-lucide="arrow-right" class="h-4 w-4"></i>
</button>
</form>
<p class="mt-6 text-center text-sm text-gray-600">
New to OurApp? <a href="register.php" class="text-purple-600 font-semibold hover:underline">Create an account</a>
</p>
</div>
<button type="submit">Log In</button>
</form>
</div>
</div>
<script>
function togglePasswordVisibility(inputId, button) {
const input = document.getElementById(inputId);
const isPassword = input.type === 'password';
input.type = isPassword ? 'text' : 'password';
button.querySelectorAll('[data-lucide]').forEach((icon) => icon.classList.toggle('hidden'));
}
</script>
<?php require __DIR__ . '/lib/footer.php'; ?>
</body>
</html>
+4
View File
@@ -1 +1,5 @@
@import "tailwindcss";
@theme {
--font-sans: "Poppins", ui-sans-serif, system-ui, sans-serif;
}
+1683 -5
View File
File diff suppressed because it is too large Load Diff
+36
View File
@@ -0,0 +1,36 @@
<?php
require __DIR__ . '/session.php';
start_app_session();
$pageTitle = 'Processing';
?>
<!DOCTYPE html>
<html lang="en">
<?php require __DIR__ . '/lib/head.php'; ?>
<body class="bg-amber-50 min-h-screen flex flex-col">
<?php require __DIR__ . '/lib/header.php'; ?>
<div class="flex-1 flex flex-col items-center justify-center text-center px-4">
<p class="text-lg text-gray-700 mb-4">Your credits are being processed. Please wait.</p>
<div class="h-10 w-10 border-4 border-gray-300 border-t-gray-900 rounded-full animate-spin"></div>
</div>
<?php require __DIR__ . '/lib/footer.php'; ?>
<script>
function checkPurchaseStatus() {
fetch('/api/purchase-boolean.php')
.then(function (response) { return response.json(); })
.then(function (data) {
if (data.result) {
window.location.href = '/';
} else {
setTimeout(checkPurchaseStatus, 3000);
}
})
.catch(function () {
setTimeout(checkPurchaseStatus, 3000);
});
}
checkPurchaseStatus();
</script>
</body>
</html>
+128
View File
@@ -0,0 +1,128 @@
<?php
require __DIR__ . '/db.php';
require __DIR__ . '/lib/ticket.php';
header('Content-Type: application/json');
function respond(int $statusCode, array $body = []): void
{
http_response_code($statusCode);
echo json_encode($body);
exit;
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
respond(405, ['error' => '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']);
+133 -44
View File
@@ -1,6 +1,7 @@
<?php
require __DIR__ . '/session.php';
require __DIR__ . '/db.php';
require __DIR__ . '/lib/mailer.php';
start_app_session();
if (isset($_SESSION['username'])) {
@@ -8,6 +9,8 @@ if (isset($_SESSION['username'])) {
exit;
}
const STARTING_CREDITS = 3;
$errors = [];
$username = '';
$email = '';
@@ -45,68 +48,154 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$stmt = $pdo->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';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Register</title>
</head>
<body>
<form action="register.php" method="post" novalidate>
<div>
<label for="username">Username</label>
<input type="text" id="username" name="username" value="<?php echo htmlspecialchars($username, ENT_QUOTES, 'UTF-8'); ?>">
<?php if (isset($errors['username'])): ?>
<div><?php echo htmlspecialchars($errors['username'], ENT_QUOTES, 'UTF-8'); ?></div>
<?php endif; ?>
<?php require __DIR__ . '/lib/head.php'; ?>
<body class="bg-amber-50 min-h-screen flex flex-col">
<?php require __DIR__ . '/lib/header.php'; ?>
<div class="flex-1 flex items-center justify-center bg-gradient-to-b from-amber-50 via-pink-50 to-white p-4 py-12">
<div class="w-full max-w-4xl bg-white rounded-3xl shadow-xl ring-1 ring-gray-100 overflow-hidden grid md:grid-cols-2">
<div class="relative hidden md:block">
<img src="assets/recently3.webp" alt="" aria-hidden="true" class="absolute inset-0 h-full w-full object-cover">
<div class="absolute inset-0 bg-gradient-to-b from-black/10 via-transparent to-black/40"></div>
<div class="relative h-full flex flex-col justify-between p-8 text-white">
<p class="italic font-semibold text-xl leading-snug drop-shadow">
Create weird.<br>Wonderful critters.
</p>
<div class="rounded-2xl bg-white/90 backdrop-blur text-gray-800 px-4 py-3 flex items-center gap-3 shadow-md">
<i data-lucide="star" class="h-4 w-4"></i>
<span class="text-sm font-medium">Your next adventure is waiting.</span>
</div>
</div>
</div>
<div>
<label for="email">Email</label>
<input type="text" id="email" name="email" value="<?php echo htmlspecialchars($email, ENT_QUOTES, 'UTF-8'); ?>">
<?php if (isset($errors['email'])): ?>
<div><?php echo htmlspecialchars($errors['email'], ENT_QUOTES, 'UTF-8'); ?></div>
<?php endif; ?>
<div class="p-8 sm:p-10">
<h1 class="text-2xl font-extrabold text-gray-900">Start your collection.</h1>
<p class="mt-1 text-gray-500 text-sm">Create an account and bring your imagination to life.</p>
<form action="register.php" method="post" novalidate class="mt-6 space-y-4">
<div>
<label for="username" class="block text-sm font-medium text-gray-700 mb-1">Username</label>
<div class="relative">
<i data-lucide="user" class="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400"></i>
<input
type="text" id="username" name="username"
value="<?php echo htmlspecialchars($username, ENT_QUOTES, 'UTF-8'); ?>"
placeholder="CritterExplorer"
class="w-full rounded-xl border border-gray-300 pl-10 pr-3 py-2.5 focus:outline-none focus:ring-2 focus:ring-purple-400"
>
</div>
<?php if (isset($errors['username'])): ?>
<p class="mt-1 text-sm text-red-600"><?php echo htmlspecialchars($errors['username'], ENT_QUOTES, 'UTF-8'); ?></p>
<?php endif; ?>
</div>
<div>
<label for="email" class="block text-sm font-medium text-gray-700 mb-1">Email</label>
<div class="relative">
<i data-lucide="mail" class="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400"></i>
<input
type="text" id="email" name="email"
value="<?php echo htmlspecialchars($email, ENT_QUOTES, 'UTF-8'); ?>"
placeholder="you@example.com"
class="w-full rounded-xl border border-gray-300 pl-10 pr-3 py-2.5 focus:outline-none focus:ring-2 focus:ring-purple-400"
>
</div>
<?php if (isset($errors['email'])): ?>
<p class="mt-1 text-sm text-red-600"><?php echo htmlspecialchars($errors['email'], ENT_QUOTES, 'UTF-8'); ?></p>
<?php endif; ?>
</div>
<div>
<label for="password" class="block text-sm font-medium text-gray-700 mb-1">Password</label>
<div class="relative">
<i data-lucide="lock" class="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400"></i>
<input
type="password" id="password" name="password"
placeholder="At least 8 characters"
class="w-full rounded-xl border border-gray-300 pl-10 pr-10 py-2.5 focus:outline-none focus:ring-2 focus:ring-purple-400"
>
<button
type="button"
onclick="togglePasswordVisibility('password', this)"
class="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
aria-label="Show password"
>
<i data-lucide="eye" class="h-4 w-4"></i>
<i data-lucide="eye-off" class="h-4 w-4 hidden"></i>
</button>
</div>
<?php if (isset($errors['password'])): ?>
<p class="mt-1 text-sm text-red-600"><?php echo htmlspecialchars($errors['password'], ENT_QUOTES, 'UTF-8'); ?></p>
<?php endif; ?>
</div>
<button type="submit" class="w-full inline-flex items-center justify-center gap-2 rounded-xl bg-gray-900 text-white font-semibold py-3 hover:bg-gray-800">
Create my account <i data-lucide="arrow-right" class="h-4 w-4"></i>
</button>
</form>
<p class="mt-6 text-center text-sm text-gray-600">
Already have an account? <a href="login.php" class="text-purple-600 font-semibold hover:underline">Log in</a>
</p>
</div>
<div>
<label for="password">Password</label>
<input type="password" id="password" name="password">
<?php if (isset($errors['password'])): ?>
<div><?php echo htmlspecialchars($errors['password'], ENT_QUOTES, 'UTF-8'); ?></div>
<?php endif; ?>
</div>
<button type="submit">Sign Up</button>
</form>
</div>
</div>
<script>
function togglePasswordVisibility(inputId, button) {
const input = document.getElementById(inputId);
const isPassword = input.type === 'password';
input.type = isPassword ? 'text' : 'password';
button.querySelectorAll('[data-lucide]').forEach((icon) => icon.classList.toggle('hidden'));
}
</script>
<?php require __DIR__ . '/lib/footer.php'; ?>
</body>
</html>
+110
View File
@@ -0,0 +1,110 @@
<?php
require __DIR__ . '/session.php';
require __DIR__ . '/db.php';
require __DIR__ . '/lib/ticket.php';
start_app_session();
if (isset($_SESSION['username'])) {
header('Location: /');
exit;
}
$token = $_GET['token'] ?? ($_POST['token'] ?? '');
$userId = is_string($token) && $token !== '' ? decodeTicket($token, 'password_reset') : null;
$errors = [];
$success = false;
if ($userId !== null && $_SERVER['REQUEST_METHOD'] === 'POST') {
$password = $_POST['password'] ?? '';
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.';
}
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';
?>
<!DOCTYPE html>
<html lang="en">
<?php require __DIR__ . '/lib/head.php'; ?>
<body class="bg-amber-50 min-h-screen flex flex-col">
<?php require __DIR__ . '/lib/header.php'; ?>
<div class="flex-1 flex items-center justify-center bg-gradient-to-b from-amber-50 via-pink-50 to-white p-4 py-12">
<div class="w-full max-w-md bg-white rounded-3xl shadow-xl ring-1 ring-gray-100 p-8 sm:p-10">
<?php if ($userId === null): ?>
<div class="flex h-14 w-14 items-center justify-center rounded-full bg-red-50 text-red-500 mx-auto mb-4">
<i data-lucide="shield-alert" class="h-7 w-7"></i>
</div>
<h1 class="text-2xl font-extrabold text-gray-900 text-center">Link expired</h1>
<p class="mt-2 text-gray-500 text-sm text-center">
This password reset link is invalid or has expired. Request a new one below.
</p>
<a href="forgot-password.php" class="mt-6 w-full inline-flex items-center justify-center gap-2 rounded-xl bg-gray-900 text-white font-semibold py-3 hover:bg-gray-800">
Request New Link <i data-lucide="arrow-right" class="h-4 w-4"></i>
</a>
<?php else: ?>
<div class="flex h-14 w-14 items-center justify-center rounded-full bg-purple-50 text-purple-500 mx-auto mb-4">
<i data-lucide="key-round" class="h-7 w-7"></i>
</div>
<h1 class="text-2xl font-extrabold text-gray-900 text-center">Choose a new password</h1>
<p class="mt-2 text-gray-500 text-sm text-center">Make it something you'll remember.</p>
<form action="reset-password.php" method="post" novalidate class="mt-6 space-y-4">
<input type="hidden" name="token" value="<?php echo htmlspecialchars($token, ENT_QUOTES, 'UTF-8'); ?>">
<div>
<label for="password" class="block text-sm font-medium text-gray-700 mb-1">New Password</label>
<div class="relative">
<i data-lucide="lock" class="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400"></i>
<input
type="password" id="password" name="password"
placeholder="At least 6 characters"
class="w-full rounded-xl border border-gray-300 pl-10 pr-10 py-2.5 focus:outline-none focus:ring-2 focus:ring-purple-400"
>
<button
type="button"
onclick="togglePasswordVisibility('password', this)"
class="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
aria-label="Show password"
>
<i data-lucide="eye" class="h-4 w-4"></i>
<i data-lucide="eye-off" class="h-4 w-4 hidden"></i>
</button>
</div>
<?php if (isset($errors['password'])): ?>
<p class="mt-1 text-sm text-red-600"><?php echo htmlspecialchars($errors['password'], ENT_QUOTES, 'UTF-8'); ?></p>
<?php endif; ?>
</div>
<button type="submit" class="w-full inline-flex items-center justify-center gap-2 rounded-xl bg-gradient-to-r from-purple-600 to-pink-500 text-white font-semibold py-3 shadow-sm hover:from-purple-700 hover:to-pink-600">
Reset Password <i data-lucide="arrow-right" class="h-4 w-4"></i>
</button>
</form>
<?php endif; ?>
</div>
</div>
<script>
function togglePasswordVisibility(inputId, button) {
const input = document.getElementById(inputId);
const isPassword = input.type === 'password';
input.type = isPassword ? 'text' : 'password';
button.querySelectorAll('[data-lucide]').forEach((icon) => icon.classList.toggle('hidden'));
}
</script>
<?php require __DIR__ . '/lib/footer.php'; ?>
</body>
</html>
+5
View File
@@ -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',
]);
+187
View File
@@ -0,0 +1,187 @@
<?php
require __DIR__ . '/session.php';
require __DIR__ . '/db.php';
start_app_session();
if (!isset($_SESSION['username']) || !isset($_SESSION['user_id'])) {
header('Location: /');
exit;
}
$pdo = getDbConnection();
$critterId = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
function fetchOwnedCritter(PDO $pdo, int $userId, int $critterId)
{
$stmt = $pdo->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';
?>
<!DOCTYPE html>
<html lang="en">
<?php require __DIR__ . '/lib/head.php'; ?>
<body class="min-h-screen flex flex-col">
<?php require __DIR__ . '/lib/header.php'; ?>
<div class="flex-1 max-w-md mx-auto px-4 py-10 text-center">
<?php if ($critter): ?>
<?php if (!empty($critter['image'])): ?>
<img
src="critter-images/<?php echo htmlspecialchars($critter['image'], ENT_QUOTES, 'UTF-8'); ?>"
alt="AI-generated image of this critter"
class="w-full aspect-square object-cover rounded-lg border border-gray-200 shadow-sm mb-4"
>
<?php endif; ?>
<h1 class="text-2xl font-semibold mb-2">
<?php echo htmlspecialchars(ucwords($critter['adjective'] . ' ' . $critter['noun']), ENT_QUOTES, 'UTF-8'); ?>
</h1>
<p class="text-lg">
The <?php
echo htmlspecialchars($critter['adjective'], ENT_QUOTES, 'UTF-8') . ' '
. htmlspecialchars($critter['noun'], ENT_QUOTES, 'UTF-8') . ' '
. htmlspecialchars($critter['verb'], ENT_QUOTES, 'UTF-8') . ' '
. htmlspecialchars($critter['location'], ENT_QUOTES, 'UTF-8');
?>
</p>
<div class="flex justify-center gap-4 mt-6">
<?php if ($isOwner): ?>
<form action="single-critter.php?id=<?php echo (int) $critterId; ?>" method="post">
<input type="hidden" name="action" value="toggle_favorite">
<button
type="submit"
class="px-4 py-2 rounded-md font-medium border <?php echo $critter['isFavorite'] ? 'bg-yellow-400 border-yellow-400 text-yellow-950 hover:bg-yellow-500' : 'bg-white border-gray-300 text-gray-800 hover:bg-gray-100'; ?>"
>
<?php echo $critter['isFavorite'] ? 'Unfavorite' : 'Favorite'; ?>
</button>
</form>
<form action="single-critter.php?id=<?php echo (int) $critterId; ?>" method="post">
<input type="hidden" name="action" value="toggle_archived">
<button
type="submit"
class="px-4 py-2 rounded-md font-medium border <?php echo $critter['isArchived'] ? 'bg-gray-800 border-gray-800 text-white hover:bg-gray-700' : 'bg-white border-gray-300 text-gray-800 hover:bg-gray-100'; ?>"
>
<?php echo $critter['isArchived'] ? 'Unarchive' : 'Archive'; ?>
</button>
</form>
<?php endif; ?>
<form action="create-critter.php" method="get">
<input type="hidden" name="adjective_id" value="<?php echo (int) $critter['adjective_id']; ?>">
<input type="hidden" name="noun_id" value="<?php echo (int) $critter['noun_id']; ?>">
<input type="hidden" name="verb_id" value="<?php echo (int) $critter['verb_id']; ?>">
<input type="hidden" name="location_id" value="<?php echo (int) $critter['location_id']; ?>">
<button type="submit" class="px-4 py-2 rounded-md font-medium border bg-white border-gray-300 text-gray-800 hover:bg-gray-100">
Remix
</button>
</form>
</div>
<div class="mt-8 pt-6 border-t border-gray-200 text-center">
<h2 class="text-sm font-semibold text-gray-500 uppercase tracking-wide mb-3">Quick Filters</h2>
<ul class="space-y-2">
<li>
<a href="/?filter_noun=<?php echo (int) $critter['noun_id']; ?>" class="hover:underline">
Show me all my <?php echo htmlspecialchars($critter['noun'], ENT_QUOTES, 'UTF-8'); ?> critters
</a>
</li>
<li>
<a href="/?filter_adjective=<?php echo (int) $critter['adjective_id']; ?>" class="hover:underline">
Show me all my <?php echo htmlspecialchars($critter['adjective'], ENT_QUOTES, 'UTF-8'); ?> critters
</a>
</li>
<li>
<a href="/?filter_verb=<?php echo (int) $critter['verb_id']; ?>" class="hover:underline">
Show me any critter that I've created that <?php echo htmlspecialchars($critter['verb'], ENT_QUOTES, 'UTF-8'); ?>
</a>
</li>
<li>
<a href="/?filter_location=<?php echo (int) $critter['location_id']; ?>" class="hover:underline">
Show me all my critters <?php echo htmlspecialchars($critter['location'], ENT_QUOTES, 'UTF-8'); ?>
</a>
</li>
</ul>
</div>
<?php if (!empty($relatedCritters)): ?>
<div class="mt-8 pt-6 border-t border-gray-200 text-center">
<h2 class="text-sm font-semibold text-gray-500 uppercase tracking-wide mb-3">Other critters with this same recipe</h2>
<div class="grid grid-cols-4 gap-2">
<?php foreach ($relatedCritters as $related): ?>
<a href="single-critter.php?id=<?php echo (int) $related['id']; ?>">
<img
src="critter-images/<?php echo htmlspecialchars($related['image'], ENT_QUOTES, 'UTF-8'); ?>"
alt="AI-generated image of a matching critter"
class="w-full aspect-square object-cover rounded-lg border border-gray-200 shadow-sm"
>
</a>
<?php endforeach; ?>
</div>
</div>
<?php endif; ?>
<?php else: ?>
<p>Critter not found.</p>
<?php endif; ?>
</div>
<?php require __DIR__ . '/lib/footer.php'; ?>
</body>
</html>
+11
View File
@@ -0,0 +1,11 @@
{
"version": 1,
"skills": {
"frontend-design": {
"source": "anthropics/skills",
"sourceType": "github",
"skillPath": "skills/frontend-design/SKILL.md",
"computedHash": "89496d5dd00f4810205f351759594fc2742bf8eea85a2f2b2d1de59f4bd91576"
}
}
}