# Expiry Tokens Cleanup CLI

This document explains the behavior and operations of `cli/expiry_tokens_cleanup.php`.

## Purpose

Token files are written under:

- `DOI_UPLOAD_TOKEN_PATH/{portal}/{user_id}/{token}.json`

Where `{portal}` usually comes from `X-Portal` (for example `frontend`).

The cleanup CLI does two things in one run:

1. Finds idle-expired active token files and moves them to:
   - `DOI_UPLOAD_TOKEN_PATH/expired_tokens/{portal}/`
2. Deletes all `*.json` files found under:
   - `DOI_UPLOAD_TOKEN_PATH/expired_tokens/`

Anything under `expired_tokens` is treated as invalid and is removed. No JSON `expiry` parsing is used there.

## Idle Expiry Rule (Move Condition)

Idle timeout uses the same rule as runtime token validation:

- `time() - filemtime(token_file) > getSessionExpireMinutes() * 60`

If true, token is moved to `expired_tokens/{portal}/`.

## Timezone Behavior

The cleanup logic is timezone-safe:

- `time()` and `filemtime()` are Unix epoch seconds.
- Epoch comparisons are not affected by server display timezone.

## Command

Run from any directory:

```bash
php /var/www/doi_public_pages_api/cli/expiry_tokens_cleanup.php
```

## Cron Recommendation

Run as web user (`www-data`) so move/delete permissions match token ownership.

Example (every 15 minutes):

```cron
*/15 * * * * /usr/bin/php /var/www/doi_public_pages_api/cli/expiry_tokens_cleanup.php >/dev/null 2>&1
```

If added in root crontab, execute as `www-data`.

## Exit Code and Logging

- Exit `0`: completed without operational errors.
- Exit `1`: one or more filesystem operations failed (for example `rename`/`unlink`).

Logs are written via `ssloger` using standard project log settings.
