Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 17 additions & 14 deletions .github/workflows/php.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ name: PHP package checks

on:
push:
branches: [main, master]
pull_request:
branches: [main, master]
workflow_dispatch:
Expand All @@ -12,12 +11,14 @@ permissions:

jobs:
verify:
name: PHP ${{ matrix.php }}
name: PHP ${{ matrix.php }} / ${{ matrix.dependencies }} dependencies
runs-on: ubuntu-24.04
timeout-minutes: 15
strategy:
fail-fast: false
matrix:
php: ['8.1', '8.5']
dependencies: ['lowest', 'latest']
steps:
- name: Checkout
uses: actions/checkout@v7
Expand All @@ -32,19 +33,21 @@ jobs:
coverage: none

- name: Validate Composer manifest and lock
run: composer validate --no-check-publish --no-interaction

- name: Install locked dependencies
run: composer install --prefer-dist --no-interaction --no-progress --no-scripts

- name: Check PHP syntax
run: find . -path './vendor' -prune -o -path './.git' -prune -o -name '*.php' -type f -print0 | xargs -0 -n1 php -l
run: composer validate --strict --no-check-publish --no-interaction

- name: Run declared tests
shell: bash
- name: Install dependencies
run: |
if php -r '$composer = json_decode(file_get_contents("composer.json"), true); exit(isset($composer["scripts"]["test"]) ? 0 : 1);'; then
composer test --no-interaction
if [ "${{ matrix.dependencies }}" = "lowest" ]; then
composer update --prefer-lowest --prefer-stable --prefer-dist --no-interaction --no-progress --no-scripts
else
echo 'No test script is declared for this package.'
composer update --prefer-dist --no-interaction --no-progress --no-scripts
fi

- name: Audit dependencies
run: composer audit --locked --no-interaction

- name: Check PHP syntax
run: composer lint

- name: Run tests
run: composer test --no-interaction
6 changes: 3 additions & 3 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,11 @@

Опорные файлы: `CONTRIBUTING.md`.

`composer.json`: triangle/media; runtime "^8.1"; triangle/engine.
`composer.json`: triangle/media; runtime "^8.1"; `triangle/engine:^9.0`.

Именованных test/lint/build-скриптов в проверенных JSON-манифестах нет. Перед запуском выбери существующую команду из CI, конфигурации тестов или Makefile; не выдавай предполагаемую команду за проверенную.
Проверки: `composer run lint`, `composer run test`, `composer run check`, `composer audit --locked`. Интеграционный запуск зависит от PHP extensions и сервисов Triangle Engine; перед утверждениями о runtime проверяй фактическое окружение.

Команды выше найдены в манифестах, а не проверены запуском. Перед выполнением прочитай их реализацию, нужные переменные и внешние зависимости. Не запускай нагрузочные, сетевые, deploy/migration-задачи или полный train как обычный smoke test.
Перед выполнением проверок читай их реализацию и нужные внешние зависимости. Не запускай нагрузочные, сетевые, deploy/migration-задачи или полный train как обычный smoke test.

### Ограничения реализации

Expand Down
19 changes: 19 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# Changelog

Notable changes are documented here. This project follows Semantic Versioning.

## 2.0.0 - Unreleased

### Changed

- Require Triangle Engine 9 and its Server 7 runtime.
- Expand CI to PHP 8.1 and 8.5 with lowest and latest dependency sets, Composer audit, lint, and executable tests.
- Add English and Russian installation, configuration, endpoint, and security guidance.
- Standardize PHP copyright and SPDX headers to AGPL-3.0-or-later.

### Fixed

- Enforce the project-registration setting and validate registration requests.
- Reject image identifiers that could escape the configured image directory.
- Enforce frame and pixel limits when processing previously stored images.
- Return transformed image bytes with the configured image MIME type.
39 changes: 15 additions & 24 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -1,34 +1,25 @@
# Contributing to the Project
[Документ на русском языке](CONTRIBUTING_ru.md)

We welcome you to our project and thank you for your interest in our code!

## Getting Started
# Contributing to Triangle Media

Before you begin, please familiarize yourself with our rules and guidelines:

- Code of Conduct
- Code Style Guide
[Документ на русском языке](CONTRIBUTING_ru.md)

## How to Contribute
Thank you for helping improve the Triangle Media plugin.

There are many ways you can contribute to the project:
Before opening a change, read the [Code of Conduct](CODE_OF_CONDUCT.md), [Security policy](SECURITY.md), and [project documentation](README.md).

- Suggest improvements or new features
- Submit bug fixes
- Improve documentation
## Local checks

## Creating a Pull Request
Use PHP 8.1 or newer with the required `curl`, `fileinfo`, and `imagick` extensions. Run:

1. Fork the repository.
2. Create a new branch.
3. Make your changes.
4. Submit a pull request.
```sh
composer validate --strict --no-check-publish --no-interaction
composer run check --no-interaction
composer audit --locked --no-interaction
```

Please ensure that your code adheres to our code style guide and all tests pass.
Changes to image upload, URL fetching, storage paths, or filters should include a focused regression test. Do not add credentials, production data, or generated image files to a pull request.

## Contact
## Pull requests

If you have any questions, feel free to reach out to us through the GitHub issues system.
Keep the change focused, describe any compatibility impact, and include the commands and results of the checks you ran. GitHub Actions tests PHP 8.1 and 8.5 with lowest and latest allowed dependencies.

Thank you for your contribution!
For general questions, use GitHub Issues. Report suspected vulnerabilities privately using GitHub's **Report a vulnerability** feature; do not publish exploit details in an issue.
38 changes: 15 additions & 23 deletions CONTRIBUTING_ru.md
Original file line number Diff line number Diff line change
@@ -1,33 +1,25 @@
# Вклад в проект
# Вклад в Triangle Media

Мы рады приветствовать вас в нашем проекте и благодарим за ваш интерес к нашему коду!
[English version](CONTRIBUTING.md)

## Как начать
Спасибо, что помогаете улучшать плагин Triangle Media.

Перед тем как начать, пожалуйста, ознакомьтесь с нашими правилами и руководствами:
Перед отправкой изменений прочитайте [Кодекс поведения](CODE_OF_CONDUCT_ru.md), [политику безопасности](SECURITY.ru.md) и [документацию проекта](README.ru.md).

- Кодекс поведения
- Руководство по стилю кода
## Локальные проверки

## Как внести свой вклад
Нужны PHP 8.1 или новее и расширения `curl`, `fileinfo`, `imagick`. Выполните:

Есть много способов внести свой вклад в проект:
```sh
composer validate --strict --no-check-publish --no-interaction
composer run check --no-interaction
composer audit --locked --no-interaction
```

- Предложить улучшения или новые функции
- Отправить исправления ошибок
- Улучшить документацию
Изменения загрузки, получения изображений по URL, путей хранения и фильтров должны сопровождаться регрессионным тестом. Не добавляйте в pull request учётные данные, production-данные и сгенерированные изображения.

## Создание запроса на слияние (Pull Request)
## Pull request

1. Сделайте форк репозитория.
2. Создайте новую ветку.
3. Внесите свои изменения.
4. Отправьте запрос на слияние.
Не расширяйте scope без необходимости, описывайте влияние на совместимость и указывайте команды с результатами проверок. GitHub Actions запускает PHP 8.1 и 8.5 с минимальными и последними допустимыми зависимостями.

Пожалуйста, убедитесь, что ваш код соответствует нашему руководству по стилю кода и все тесты проходят.

## Связь

Если у вас есть вопросы, не стесняйтесь обращаться к нам через систему вопросов GitHub.

Спасибо за ваш вклад!
Общие вопросы задавайте в GitHub Issues. О возможной уязвимости сообщайте приватно через функцию GitHub **Report a vulnerability**; не публикуйте подробности эксплуатации в issue.
91 changes: 91 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
# Triangle Media

Triangle Media is an image plugin for applications built with Triangle Engine. It accepts image uploads and remote image URLs, validates and converts accepted images to PNG, stores image metadata through the application's configured database connection, and can serve resized or transformed image responses.

## Compatibility

- PHP 8.1 or newer
- Triangle Engine 9
- PHP extensions: `curl`, `fileinfo`, and `imagick`
- A writable image directory and a database connection configured by the host application

The latest published package tag is `v1.1.0`, which requires Triangle Engine `^8.1`. This branch prepares the next major version for Triangle Engine 9 and its Server 7 runtime; that migration is not a published stable release yet. The next major version will not support the Engine 8 dependency line.

## Installation

For the currently published Engine 8 package:

```sh
composer require triangle/media:^1.1
```

After the Engine 9 compatible `2.0.0` release is published, install it with `composer require triangle/media:^2.0`.

Triangle Engine discovers the plugin controllers through Composer autoloading. The plugin's `Triangle\Media\Install::install()` method copies missing default settings from `src/Config` into `config/plugin/triangle/media`; it preserves existing application settings. The host application's plugin lifecycle should call it when installing the package.

The plugin does not include view templates. Install `triangle/view` to use the bundled view routes, then provide `index`, `form`, and `image` templates in the host application. The host may instead replace those controllers with its own presentation layer.

## Default controller paths

With Triangle Engine's default `app.plugin_uri` setting, the controllers are available at these paths:

| Path | Method | Behavior |
| --- | --- | --- |
| `/app/media` | `GET` | Renders the `index` view and sets a `token` cookie when the request includes a token. |
| `/app/media/project` | `GET`, `POST` | Returns `403` while project registration is disabled. When enabled, `GET` renders `form` and `POST` validates the fields, stores the project, and returns its token. |
| `/app/media/upload` | `POST` | Accepts an uploaded image or a remote image URL after checking the project token. |
| `/app/media/image/{image-id}` | `GET` | Renders the `image` view for an existing image. |
| `/app/media/processing/{image-id}/{filters...}` | `GET` | Applies the configured image filters and returns the generated image bytes. |

The prefix changes if the host application overrides `app.plugin_uri`. Configure the router, access control, and rate limits at the application or reverse-proxy boundary as appropriate for the deployment.

## Configuration

The defaults are installed at `config/plugin/triangle/media/app.php`:

| Setting | Default | Purpose |
| --- | --- | --- |
| `enable` | `true` | Enables plugin configuration. |
| `project_registration` | `false` | Allows project registration through the project controller when enabled. |
| `image_uri` | `https://example.ru/media/` | Public base URI returned for uploaded images; replace it with the deployed media URL. |
| `image_path` | `public_path() . '/media/upload/'` | Writable storage directory for converted images. |
| `max_file_size` | 15 MiB | Maximum accepted source-file size. |
| `max_image_pixels` | 40,000,000 | Maximum total decoded pixels across frames. |
| `max_image_frames` | 50 | Maximum number of frames in an input image. |
| `max_image_memory` | 256 MiB | ImageMagick memory and map resource limit. |
| `max_image_disk` | 512 MiB | ImageMagick disk resource limit. |
| `max_image_time` | 10 seconds | ImageMagick processing time limit. |
| `rate_limiter.enable` | `false` | Enables the configured request rate limiter. |
| `rate_limiter.quota` / `cycle` | `3` / `60` | Allowed requests per cycle when rate limiting is enabled. |

The accepted source MIME types, target PNG format, database collection names, and transformation patterns are also configurable in this file. Treat configuration values as application policy: verify the public URI, storage permissions, and resource limits before exposing upload routes.

Installation preserves an existing application configuration. After upgrading an older installation, check `project_registration` explicitly and set it to `false` if anonymous project creation is not intended.

The host application must provide compatible `db()` and `storage()` adapters. The database adapter must support `insert($table, $record)` and `where($field, $value)->getOne($table)`. The storage adapter must support `get($key)`, `set($key, $value, $ttl)` and `increment($key)`. Triangle Engine supplies `config()`, request IP resolution, and response helpers. `triangle/view` supplies `view()`; the host application supplies the `index`, `form`, and `image` templates. The package does not bundle database or storage adapters.

## Upload behavior

The upload controller accepts either a multipart file under the `file` field or a remote URL in the `link` field. Both paths validate the source MIME type and size. The uploader converts successful images to PNG, stores the image record through the Engine database helper, and returns the image identifier, URL, MIME type, dimensions, dominant color, and output size.

Remote image downloads use HTTP or HTTPS on standard ports, reject credentials and non-public IP addresses, pin DNS resolution to a validated address, do not follow redirects, and enforce a download byte limit and timeout. These controls reduce server-side request forgery risk; they do not replace outbound network policy at the host level.

The processing controller supports the configured `crop`, `resize`, `pixelize`, and `cover` filters. Results are cached through the host application's storage service.

## Development checks

```sh
composer validate --strict --no-check-publish --no-interaction
composer run check --no-interaction
composer audit --locked --no-interaction
```

The URL security test rejects local, reserved, and non-standard URL targets. Image decoding and conversion require the `imagick` extension; the repository's local test does not replace an end-to-end upload test against the host application's database, router, storage, and view configuration.

## License

AGPL-3.0-or-later. See [LICENSE](LICENSE).

## Documentation

The current project handbook is available at [server.localzet.com/projects/media](https://server.localzet.com/projects/media), with [English guides](https://server.localzet.com/projects/media/en).
Loading