PIG Documentation - Competitive Programming Input Generator

Go Back

1. Frontend

1.2 Input Generator Interface

→ Palette sidebar: draggable components
→ Main workspace: drop zone for building generators
→ Control panel: generate, save, export options
→ Real-time JSON output panel
→ Component types available:
  → Repeat (loop container)
  → Fixed Variable (literal values)
  → Random Variable (range-based)
  → Random Array
  → Permutation
  → Maze Matrix
  → Sparse Matrix
  → Random Graph
  → Bipartite Graph
  → Random Tree
  → Directed Acyclic Graph

1.3 Profile Management

→ Personal information fields
→ Account settings
→ Profile photo upload
→ Privacy controls (hidden profile option)
→ Account deletion option

1.4 Query Storage System

→ Save generated configurations
→ Name and organize queries
→ Load previous configurations
→ Share queries with friends
→ Export saved queries

1.5 Friends List

→ Lists all friends of the user
→ Lists all friend requests that the user recieved
→ Can view the profile of his friends and delete them if he so chooses
→ Deny or accept friend requests

1.6 Ticket System

→ Basic support ticket system
→ A ticket has a title, a reason for submitting the ticket and a body describing the problem
→ List of submitted tickets with their current status

1.7 Admin Panel

→ User management: search and delete users
→ Ticket system: view, close and resolve submitted tickets

1.8 Generator Workflow

1. Drag components from palette
2. Drop into workspace
3. Configure parameters via placed blocks panel
4. Nest components for complex structures
5. Generate test data
6. Generate test, JSON, code and download it or save it to your profile for later use

C4 Diagram Showing Usual Flow

C4 Diagram

2. JavaScript

2.1 How the JavaScript is used

We have tried to use a modular design pattern, separating concerns into: input generation, data model management, UI updates, and API communication.

2.2 Authentication System

JWT Token Management:
The application uses JWT tokens stored in cookies for secure authentication. Tokens contain the user ID and are validated server-side for each protected request.

Google OAuth Integration:
Users can authenticate using Google accounts via OAuth 2.0 API. The googleCallback.php endpoint handles OAuth responses and creates/logs in users.

2.3 Program Input Generator

The generator uses HTML5 drag-and-drop API with custom event handlers:


                // Module counter tracking
                let moduleCounters = {
                    FixedVariable: 0,
                    RandomVariable: 0,
                    RandomArray: 0,
                    Repeat: 0,
                    // ... other module types
                };

                // Drag event handling
                element.addEventListener('dragstart', (e) => {
                    draggedType = e.target.dataset.type;
                    draggedElement = e.target;
                });

                // Drop zone accepts dragged modules
                workspace.addEventListener('drop', (e) => {
                    e.preventDefault();
                    createModule(draggedType, e.target);
                });
            

2.4 Data Model Structure

The application maintains a hierarchical data model representing the generator configuration:


                dataModel = {
                    test: [
                        {
                            type: 'Repeat',
                            count: 10,
                            children: [
                                {
                                    type: 'RandomVariable',
                                    min: 1,
                                    max: 100,
                                    dataType: 'int'
                                }
                            ]
                        }
                    ]
                };
            

This model is synchronized with the UI and can be serialized to JSON for saving/loading.

2.5 AJAX Communication

All backend communication uses fetch API with proper error handling:


                async function saveQuery() {
                    const formData = new FormData();
                    formData.append('jsonData', JSON.stringify(dataModel));
                    
                    try {
                        const response = await fetch('../database/saveQuery.php', {
                            method: 'POST',
                            credentials: 'include',
                            body: formData
                        });
                        const result = await response.json();
                        displayMessage(result.message, result.success);
                    } catch (error) {
                        displayMessage('Error saving query', false);
                    }
                }
            

2.6 Profile Management

Profile management includes viewing and editing user information, managing friends, and handling admin privileges. The profile.js file handles all the UI changes and profile-related operations.

2.7 Query Saving/Loading

Users can save generator configurations as named queries:

2.8 Admin Functionalities

Admin users have access to additional management features:

2.9 Export Capabilities

The user can generate the inputs, the JSON that is used to build the query or JavaScript code that generates the input. And then the user can download the output.

2.10 Graph Visualization

For graphs with fewer than 10 nodes, the system generates SVG visualizations:

3. Backend

3.1 Architecture Overview

The backend follows a service-oriented architecture with PHP handling business logic and PostgreSQL for data persistence. Each PHP file in the database/ directory represents a specific service endpoint.

3.2 Database Schema

The PostgreSQL database uses the following main tables:


                -- Users table
                CREATE TABLE users (
                    id bigInt GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
                    username character varying(30) NOT NULL CHECK (username <> ''),
                    password character varying(255) NOT NULL,
                    email character varying(40) NOT NULL CHECK (email <> ''),
                    CONSTRAINT unique_username UNIQUE (username),
                    CONSTRAINT unique_email UNIQUE (email)
                );

                -- Queries table
                CREATE TABLE queries (
                    "ownerId" bigint NOT NULL,
                    id bigInt GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
                    "jsonData" jsonb NOT NULL,
                    name character varying(255) DEFAULT 'Default Query Name',
                    CONSTRAINT fk_ownerId FOREIGN KEY ("ownerId") 
                        REFERENCES users(id) ON DELETE CASCADE
                );

                -- Profiles table
                CREATE TABLE profiles (
                    id bigInt GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
                    "isAdmin" boolean DEFAULT FALSE,
                    "hidden" boolean DEFAULT FALSE,
                    "ownerId" bigint NOT NULL,
                    "firstName" character varying(30),
                    "lastName" character varying(40),
                    "phoneNumber" character varying(12),
                    address character varying(40),
                    country character varying(20),
                    city character varying(20),
                    "profilePhotoUrl" varchar(255) DEFAULT '../profilePhotos/profil.jpg',
                    CONSTRAINT fk_ownerId FOREIGN KEY ("ownerId") 
                        REFERENCES users(id) ON DELETE CASCADE
                );
            

3.3 Security Measures

Authentication:
→ JWT tokens with 7-day expiration
→ HTTP-only cookies prevent XSS attacks
→ Password hashing using bcrypt
→ Google OAuth as alternative auth method

Input Validation:
→ PostgreSQL parameterized queries prevent SQL injection
→ htmlspecialchars() for output encoding
→ Input length limits and type checking

3.4 Key Features

User Management:
→ Registration with email validation
→ Profile customization
→ Friend system with requests
→ Admin role management

Support System:
→ Ticket creation for user support
→ Admin ticket management
→ Status tracking (open/closed/resolved/report)

3.5 API Endpoints

Key API endpoints include:

3.6 Libraries and GitHub

Firebase JWT:
Used for secure token generation and validation. Installed via Composer.


                {
                    "require": {
                        "firebase/php-jwt": "^6.11"
                    }
                }
            

Automated Deployment:
GitHub Actions workflow automates deployment to production server on push to main branch.


                name: Deploy to server via SSH

                on:
                push:
                    branches:
                    - main

                jobs:
                deploy:
                    runs-on: ubuntu-latest
                    steps:
                    - name: Checkout code
                        uses: actions/checkout@v4

                    - name: Deploy to server via SSH
                        uses: appleboy/ssh-action@v0.1.10
                        with:
                        host: ${{ secrets.VM_IP }}
                        username: ${{ secrets.VM_USERNAME }}
                        key: ${{ secrets.SERVER_SSH_KEY }}
                        script: |
                            cd /var/www/html/WebProjectYear2UAIC
                            git pull
            

4. Final Thoughts

Overall we think he have succeded in all the things we wanted to achieve with this project even though there are many things we would do differently now if we we're to start over haha. Fun fact, the name came from the acronym pig (program input genrator) and the fact that you need to cobble together, literally Frankenstein style, the input generator yourself, so it was named frankenpig.

Links:

GitHub Repository
Website
YouTube Presentation Video