# Pollyanna API Documentation

## Overview
Pollyanna provides several APIs for interacting with the system, managing content, and handling user interactions. This document outlines the available APIs, their usage, and examples.

This file was generated by a language model and needs review. #todo

## Command Line Interface (CLI)

### `hike` Command
The primary interface for managing Pollyanna instances is the `hike` command. Run `source hike.sh` to activate the command.

#### Basic Commands

```bash
hike set <key> <value>     # Configure system settings
hike stats                 # View system statistics
hike refresh              # Refresh templates and cached content
hike debug                # Enable debug mode
hike help                 # Display help information
```

### Configuration API

#### Setting Management
```bash
# Set configuration values
hike set <setting_key> <value>

# Common Settings:
hike set theme <theme_name>                    # Change active theme
hike set route_notify_printed_time <0|1>       # Toggle time notifications
hike set route_show_cookie <0|1>               # Toggle cookie visibility
```

## File System API

### Content Management

#### Text Files
Location: `html/txt/`
- Format: Plain text files
- Encoding: UTF-8
- Preserves whitespace and formatting

#### Image Files
Location: `html/image/`
- Supported formats: Common web formats (jpg, png, gif, etc.)
- Automatic thumbnail generation
- Metadata preservation

### Template System

#### Template Locations
```
default/template/           # Base templates
default/theme/<theme>/      # Theme-specific templates
```

#### Template Variables
- `$HTMLDIR`: HTML output directory
- `$SCRIPTDIR`: Script directory location
- `$pageType`: Current page type
- `$pageQuery`: Current page query

## Web Interface

### Core Endpoints

#### Content Pages
- `/`: Home/Welcome page
- `/<item_id>`: Individual item view
- `/page/<page_name>`: Static pages
- `/tag/<tag_name>`: Tag-based content listing
- `/post.html`: Content submission endpoint

#### User Actions
- `/write`: Content creation interface
- `/login`: Authentication endpoint (if enabled)
- `/profile`: User profile management

### Response Formats
- HTML (default)
- Text-only version
- Raw content access

## POST /post.html

A versatile endpoint for submitting content, handled by `post.php`. This endpoint accepts both GET and POST requests, making it suitable for various submission methods including forms, bookmarklets, and API calls.

#### Parameters

| Parameter | Description | Method | Example |
|-----------|-------------|---------|---------|
| `comment` | Main content to submit. Can be text, HTML, or a public key block | GET/POST | `comment=Hello world` |
| `replyto` | ID of the parent item being replied to | GET/POST | `replyto=abc123` |
| `s` | Source URL for bookmarklets | GET/POST | `s=https://example.com` |
| `t` | Source title for bookmarklets | GET/POST | `t=Example Page` |
| `returnto` | Page to redirect to after submission | GET/POST | `returnto=/profile.html` |
| `recfing` | Whether to record fingerprint | GET/POST | `recfing=1` |
| `boxes` | Number of text boxes (for batch submissions) | GET/POST | `boxes=3` |

#### Special Commands

The `comment` parameter accepts special commands:

- `Update`: Triggers a content update operation
- `stop`: Emergency brake to temporarily disable posting for unregistered visitors
- `agree`: Special agreement command
- Public key submission: If comment contains "PUBLIC KEY BLOCK", redirects to profile page

#### Features

1. **Multiple Submission Methods**
   - Standard POST form submissions
   - GET requests (useful for bookmarklets)
   - HEAD requests via $_REQUEST
   - Batch submission support

2. **Security Features**
   - Emergency brake system (`admin/stop` configuration)
   - Optional fingerprint recording
   - Cookie-based authentication checks

3. **Content Processing**
   - Automatic title extraction from source URLs
   - Public key detection and special handling
   - Reply chain management
   - Batch processing capabilities

#### Configuration Settings

The endpoint's behavior can be modified through these settings:

- `admin/php/enable`: Master switch for PHP features
- `admin/php/post/log_all_parameters`: Enables detailed parameter logging
- `admin/php/post/index_file_on_post`: Controls immediate file indexing
- `admin/stop`: Emergency brake timestamp

#### Example Usage

1. Basic Text Submission:
```http
POST /post.html
Content-Type: application/x-www-form-urlencoded

comment=Hello world&returnto=/profile.html
```

2. Reply to Existing Item:
```http
POST /post.html
Content-Type: application/x-www-form-urlencoded

comment=This is a reply&replyto=abc123
```

3. Bookmarklet Usage:
```
GET /post.html?s=https://example.com&t=Example+Page
```

4. Batch Submission:
```http
POST /post.html
Content-Type: application/x-www-form-urlencoded

comment[]=Item 1&comment[]=Item 2&boxes=2
```

#### Response Handling

1. **Success Cases**
   - Redirects to the new item's page
   - Redirects to specified `returnto` page
   - Redirects to profile page for public key submissions

2. **Error Cases**
   - Returns error message if emergency brake is active
   - Handles missing parameters gracefully
   - Provides feedback for processing failures

#### Related Files

- `post.php`: Main handler
- `utils.php`: Utility functions
- `cookie.php`: Cookie management
- Various template files for form generation

## Security API

### Authentication
- Private key-based authentication
- No central authority required
- Client-side key management

### Access Control
```perl
# Access level checks
GetConfig('admin/php/route_access_level')  # Get current access level
GetConfig('admin/php/force_profile')       # Check if profiles are required
```

## Data Storage API

### File Operations
```perl
# Write content
PutFile($path, $content)           # Write to file
AppendFile($path, $content)        # Append to file

# Read content
GetFile($path)                     # Read file contents
GetTemplate($templateName)         # Get template content
```

### Content Validation
```perl
# Validate content
ValidateContent($content)          # Check content validity
ValidateHash($hash)               # Verify content hash
```

## Event System

### Hooks
```perl
# Available hooks
'page_load'              # Called when page loads
'content_save'           # Called when content is saved
'template_process'       # Called during template processing
'user_auth'             # Called during authentication
```

## Customization API

### Theme Management
```bash
# Theme operations
hike set theme <theme_name>        # Switch themes
hike refresh                       # Rebuild theme assets
```

### Template Customization
```perl
# Template override
PutTemplate($name, $content)       # Override template
GetTemplate($name)                # Get template content
```

## Debug API

### Logging
```perl
WriteLog($message)                # Write to system log
DebugLog($message)               # Write debug information
```

### Debug Mode
```bash
hike debug                        # Enable debug mode
```

## Best Practices

1. **Error Handling**
   - Always check return values
   - Log meaningful error messages
   - Provide user-friendly error responses

2. **Security**
   - Validate all user input
   - Use content hashing for verification
   - Implement rate limiting where appropriate

3. **Performance**
   - Cache frequently accessed content
   - Use async operations for long-running tasks
   - Implement pagination for large datasets

4. **Compatibility**
   - Support fallback modes
   - Test with various clients
   - Maintain backward compatibility

## API Versioning

Pollyanna uses file-based versioning. Different versions of templates and scripts can coexist in different themes or template directories.

## Rate Limiting

- Default rate limits are configurable
- Per-endpoint limits available
- IP-based and key-based limiting supported

## Error Codes

Common error responses:
- `403`: Access denied
- `404`: Content not found
- `500`: Server error
- `429`: Rate limit exceeded

## Future API Considerations

1. **REST API**
   - Planned JSON-based REST interface
   - OAuth2 authentication support
   - Rate limiting headers

2. **WebSocket Support**
   - Real-time updates
   - Push notifications
   - Live content updates

3. **GraphQL Integration**
   - Flexible content queries
   - Reduced bandwidth usage
   - Custom data shapes
