📝 Markdown Document Manager

Upload markdown files and organize them in a tree structure

Add Document
Document Tree
Delete Document
View Document

Add New Document


Or Upload Markdown File

Max file size: 2M | Supported: .md, .txt, .markdown files | Content limit: 5MB

Document Tree Structure

🗑️ Delete Document

⚠️ Warning: This action cannot be undone!

PAGES_CONTROLLER_API_DOCUMENTATION

Created: 2025-08-09 10:48:05 | Updated: 2025-08-09 10:48:05

▶ Pages Controller API Documentation

■ Overview

The Pages Controller manages a Content Management System (CMS) for static pages within the ERP system. It supports bilingual content (Arabic/English), internal HTML content, external links, and image uploads.
  • Controller File: controllers/pages.php
  • Module: General Properties / CMS Module
  • Database Table: pages
  • Line Count: 265 lines
  • Complexity: Simple
  • Dependencies:
  • → Authentication: public/impOpreation.php
  • → Image Upload: library/uploadImages.php
  • → YouTube Integration: YoutubeLink models
  • → CURL/API Support: initiateStaticSessionCommingWithCurl.php

■ Business Logic Analysis

• Core Operations

  1. Page Creation - Add new pages with bilingual content
  2. Content Management - Support for HTML content or external links
  3. Image Management - Upload and manage page images/logos
  4. Activation Control - Enable/disable pages
  5. YouTube Integration - Link pages with YouTube videos

• Data Validation

  • → Title required in both languages (Arabic and English)
  • → Content type selection (internal content vs external link)
  • → Image upload validation
  • → User session validation for all operations
  • → External link URL validation when link type selected

• Business Rules

  • → Pages can be either internal content or external links (not both)
  • → External links can specify target window (new tab or same tab)
  • → Images are stored in upload/pages/ directory
  • → All pages track creation user and timestamp
  • → No soft delete implemented - uses hard delete with file cleanup

• Security Requirements

  • → Session-based authentication required
  • → User ID tracking for all operations
  • → CURL post support with JSON responses for external integrations
  • → File upload security through uploadImages library

■ Database Schema

• Primary Table: pages


CREATE TABLE IF NOT EXISTS pages (
  id int(11) NOT NULL AUTO_INCREMENT,
  title varchar(255) NOT NULL,                    -- Arabic title

  titleEn varchar(255) NOT NULL,                  -- English title

  contentOrExternalLink tinyint(4) NOT NULL,      -- 0=content, 1=external link

  externalLink varchar(500) NOT NULL,             -- External URL

  openTarget tinyint(4) NOT NULL,                 -- 0=new tab, 1=same tab

  content text NOT NULL,                          -- Arabic HTML content

  contentEn text NOT NULL,                        -- English HTML content

  isActive tinyint(4) NOT NULL,                   -- 0=inactive, 1=active

  image varchar(255) NOT NULL,                    -- Image filename

  sysDate datetime NOT NULL,                      -- Creation/update timestamp

  userid int(11) NOT NULL,                        -- User who created/updated

  isdel tinyint(4) NOT NULL,                     -- Deletion flag (not used)

  PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;

• Related Tables

  • youtubelink - YouTube video associations (referenced but not directly joined)

• Indexes and Constraints

  • → Primary Key: id
  • → No foreign key constraints defined
  • → No additional indexes

■ Current Implementation Analysis

• Request Methods

  • GET Parameters:
  • do - Action parameter (empty, show, edit, deleteFinaly)
  • id - Page ID for edit/delete operations
  • POST Parameters:
  • → Form submissions for add/update operations
  • curlpost - Flag for API mode responses

• Input Parameters

▪ Add/Update Page


$_POST['title']                    // Arabic title

$_POST['titleEn']                  // English title

$_POST['contentOrExternalLink']    // 0=content, 1=link

$_POST['content']                  // Arabic content (if type=0)

">$_POST['contentEn']                // English content (if type=0)

$_POST['externalLink']             // External URL (if type=1)

$_POST['openTarget']               // Link target (if type=1)

$_POST['isActive']                 // Active status

$_FILES['logo']                    // Page image upload

">$_POST['oldlogo']                  // Existing image (for updates)

• Output Formats

  1. HTML Views (via Smarty templates):
    - pagesview/add.html - Add page form
    - pagesview/show.html - List all pages
    - pagesview/edit.html - Edit page form
    - succes.html - Success message
    - error.html - Error message
  1. JSON Responses (when curlpost=1):
    
    
    {
    "status": 1, // 1=success, 2=error
    "message": "تمت العمليه بنجاح",
    "message_en": "Success"
    }
  1. Redirects:
    - Success: location:?do=sucess
    - Error: location:?do=error

• Error Handling

  • → Try-catch blocks around all database operations
  • → Generic error responses (no detailed error messages)
  • → Image deletion on page deletion
  • → No validation error messages to user

■ SQL Operations from Current Controller

• Create Operation


-- Add new page

INSERT INTO pages (
  title, titleEn, contentOrExternalLink, content, contentEn, 
  externalLink, openTarget, isActive, image, sysDate, userid, isdel
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0)

• Read Operations


-- List all active pages

SELECT * FROM pages WHERE isdel = 0

-- Load single page for editing

SELECT * FROM pages WHERE id = ?

-- Get all YouTube links (for show page)

SELECT * FROM youtubelink

• Update Operation


-- Update existing page

UPDATE pages SET 
  title = ?, titleEn = ?, contentOrExternalLink = ?,
  content = ?, contentEn = ?, externalLink = ?,
  openTarget = ?, isActive = ?, image = ?,
  sysDate = ?, userid = ?, isdel = 0
WHERE id = ?

• Delete Operation


-- Hard delete (with file cleanup)

DELETE FROM pages WHERE id = ?
-- Also: unlink('../upload/pages/' . $pages->image)

■ API Endpoint to SQL Mapping

• Proposed RESTful Endpoints

  • GET /api/v1/pagesSELECT * FROM pages WHERE isdel = 0
  • GET /api/v1/pages/{id}SELECT * FROM pages WHERE id = ?
  • POST /api/v1/pagesINSERT INTO pages (...) VALUES (...)
  • PUT /api/v1/pages/{id}UPDATE pages SET ... WHERE id = ?
  • DELETE /api/v1/pages/{id}DELETE FROM pages WHERE id = ?
  • GET /api/v1/pages/activeSELECT * FROM pages WHERE isdel = 0 AND isActive = 1

■ API Specification

• Base URL


/api/v1/pages

• Resources

  • Pages Resource: /pages - Static page management
  • Active Pages: /pages/active - Only active pages
  • Page Content: /pages/{id}/content - Get page content by language

• HTTP Methods

| Method | Endpoint | Description | |--------|----------|-------------| | GET | /pages | List all pages | | GET | /pages/{id} | Get single page | | POST | /pages | Create new page | | PUT | /pages/{id} | Update existing page | | DELETE | /pages/{id} | Delete page | | GET | /pages/active | List active pages only |

• Request/Response Formats

▪ Create Page Request


{
  "title": "عن الشركة",
  "title_en": "About Us",
  "content_type": "internal",  // "internal" or "external"

  "content": "<p>محتوى الصفحة</p>",
  "content_en": "<p>Page content</p>",
  "external_link": null,
  "open_target": null,
  "is_active": true,
  "image": "base64_encoded_image_data"
}

▪ Page Response


{
  "success": true,
  "data": {
    "id": 1,
    "title": "عن الشركة",
    "title_en": "About Us",
    "content_type": "internal",
    "content": "<p>محتوى الصفحة</p>",
    "content_en": "<p>Page content</p>",
    "external_link": null,
    "open_target": null,
    "is_active": true,
    "image_url": "/upload/pages/page_1.jpg",
    "created_at": "2024-01-20 10:30:00",
    "created_by": 1,
    "youtube_links": []
  }
}

• Status Codes

  • 200 OK - Successful GET, PUT
  • 201 Created - Successful POST
  • 204 No Content - Successful DELETE
  • 400 Bad Request - Invalid input
  • 401 Unauthorized - Authentication required
  • 404 Not Found - Page not found
  • 500 Internal Server Error - Server error

• Error Response Format


{
  "success": false,
  "error": {
    "code": "PAGE_NOT_FOUND",
    "message": "Page with ID 123 not found",
    "details": {}
  }
}

■ Authentication & Authorization

• Current Implementation

  • → Session-based authentication via impOpreation.php
  • → User ID stored in $_SESSION['userid']
  • → No role-based permissions (all authenticated users can manage pages)

• Proposed API Authentication

  • → JWT token authentication
  • → Bearer token in Authorization header
  • → Token payload should include user_id and permissions

• Required Permissions

  • pages:read - View pages
  • pages:write - Create/update pages
  • pages:delete - Delete pages
  • pages:manage - Full page management

■ Implementation Guidelines

• Migration Path

  1. Phase 1: Add API mode to existing controller
    - Check for Accept: application/json header
    - Return JSON instead of HTML views
    - Maintain backward compatibility
  1. Phase 2: Create dedicated API controller
    - Implement RESTful endpoints
    - Add proper validation and error handling
    - Implement file upload via base64 or multipart
  1. Phase 3: Add advanced features
    - Pagination for page lists
    - Search/filter capabilities
    - Version history
    - SEO metadata support

• Backward Compatibility

  • → Keep existing controller for legacy UI
  • → Add API flag detection (api_mode parameter)
  • → Gradual migration of frontend to use API

• Testing Strategy

  1. Unit Tests:
    - Page CRUD operations
    - Content type switching logic
    - Image upload/deletion
    - Input validation
  1. Integration Tests:
    - Full page lifecycle
    - Image file management
    - YouTube link associations
    - Authentication flow

• Performance Considerations

  • → Implement pagination for page lists
  • → Cache active pages for frontend
  • → Optimize image delivery (CDN/lazy loading)
  • → Add database indexes for common queries

■ Examples

• Create Page with Internal Content


curl -X POST http://erp.local/api/v1/pages \

  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d &#039;{

    "title": "سياسة الخصوصية",
    "title_en": "Privacy Policy",
    "content_type": "internal",
    "content": "<h1>سياسة الخصوصية</h1><p>...</p>",
    "content_en": "<h1>Privacy Policy</h1><p>...</p>",
    "is_active": true
  }&#039;

• Create Page with External Link


curl -X POST http://erp.local/api/v1/pages \

  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d &#039;{

    "title": "موقعنا الخارجي",
    "title_en": "Our External Site",
    "content_type": "external",
    "external_link": "https://example.com",

    "open_target": "new_tab",
    "is_active": true
  }&#039;

• Get Active Pages


curl -X GET http://erp.local/api/v1/pages/active \

  -H "Authorization: Bearer YOUR_TOKEN"

• Update Page Status


curl -X PATCH http://erp.local/api/v1/pages/5/status \

  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d &#039;{

    "is_active": false
  }&#039;

■ Future Enhancements

• Planned Features

  1. Content Versioning - Track page content changes
  2. SEO Metadata - Add meta descriptions, keywords
  3. Content Blocks - Reusable content components
  4. Multi-language Support - Beyond Arabic/English
  5. Preview Mode - Preview before publishing
  6. Scheduled Publishing - Set publish dates
  7. Content Templates - Predefined page layouts
  8. Rich Media Support - Video, gallery components
  9. Access Control - Page-level permissions
  10. Soft Delete - Implement proper soft deletion

• API Versioning

  • → Current: v1
  • → Version in URL path: /api/v1/pages
  • → Deprecation notices in headers
  • → Sunset dates for old versions

• Scalability Considerations

  • → Implement caching layer (Redis/Memcached)
  • → CDN for static content and images
  • → Database read replicas for high traffic
  • → Full-text search for content (Elasticsearch)
  • → Content delivery optimization

■ Integration Points

• Current Integrations

  1. YouTube Links - Associate videos with pages
  2. CURL Support - External system integration
  3. Image Management - Upload library integration

• Potential Integrations

  1. Search System - Full-text search across pages
  2. Analytics - Page view tracking
  3. Workflow System - Content approval process
  4. Translation Service - Auto-translate content
  5. CDN Service - Image/content delivery

■ Security Considerations

• Current Security

  • → Session-based authentication
  • → File upload through validated library
  • → No SQL injection (using DAO pattern)
  • → No XSS protection for content (allows HTML)

• Recommended Security Enhancements

  1. Content Sanitization - HTML purifier for content
  2. CSRF Protection - Token validation
  3. Rate Limiting - Prevent abuse
  4. Input Validation - Comprehensive validation rules
  5. File Type Validation - Restrict upload types
  6. Content Security Policy - XSS prevention
  7. Audit Logging - Track all changes

■ Code Quality Observations

• Strengths

  • → Clean DAO/DTO pattern
  • → Separation of concerns
  • → CURL/API support built-in
  • → Proper error handling structure

• Areas for Improvement

  1. No soft delete - Uses hard delete
  2. Generic error messages - No specific validation feedback
  3. No pagination - Lists all pages at once
  4. Mixed concerns - YouTube logic in pages controller
  5. No caching - Direct database queries
  6. Limited validation - Basic input checking
  7. No transaction support - File+DB operations not atomic

■ Conclusion

The Pages Controller is a simple yet functional CMS component of the ERP system. While it handles basic page management well, it would benefit from:
  • → Proper soft delete implementation
  • → Enhanced validation and error messages
  • → Pagination and search capabilities
  • → Content versioning and workflow
  • → Better security measures for content handling
The controller is ready for API conversion with minimal effort due to its existing CURL support and clean data structure. --- Documentation Status: ✅ Complete Prepared By: Claude Code Assistant Date: 2024-01-20 Controller Complexity: Simple (265 lines) API Readiness: High - CURL support already implemented