Architecture
1. Introduction
UNA CMS is a modern, modular community management system designed with flexibility, scalability, and extensibility at its core. This document provides a comprehensive overview of UNA's architecture, explaining how its components interact to create a robust platform for building social networks, community sites, and collaborative environments.
The architecture of UNA CMS follows a modular approach based on the Model-View-Controller (MVC) pattern, allowing for clean separation of concerns, code reusability, and maintainable development. This document outlines the key architectural components, their relationships, and the underlying principles that make UNA a powerful platform for community building.
2. High-Level Architecture
UNA's architecture consists of several interconnected layers that work together to provide a complete community management solution:
- Client Layer: Web browsers or mobile applications that interact with UNA
- Web Server Layer: Handles HTTP requests and serves UNA content
- UNA Core: Contains foundational components and utilities
- Modules: Independent functional units that provide specific features
- Objects: Helper classes that encapsulate high-level interface functionalities
- Plugins: Third-party libraries that extend core functionality
- Database: Stores all content and configuration data
- Studio: Administrative interface for site configuration
- REST API: Enables external integration with UNA
2.1 Request Handling Flow
When a user interacts with a UNA-powered site, the request follows this processing flow:
- Routing: index.php routes requests using rewrite rules to the correct module/action
- Session & Authentication: Session is initialized; ACL checks the user's membership level
- Module Controller: The requested module loads, invokes its controller method (e.g., actionView)
- Model & Logic: The controller queries the database (via *Db.php), validates data, and applies permissions
- Template Rendering: The module's template merges data into .html files or block layouts
- Page Composition: Multiple blocks from various modules can be composed into one page (configured in Studio > Pages)
- Output: An HTML page or JSON response is sent to the user
- Alerts: If relevant, alerts fire so other modules can hook in (e.g., notifications)
3. Core Components
3.1 Core
The Core of UNA CMS contains the foundational components and utilities essential for the framework's functioning:
- Utilities: Standard functions and common utilities that provide necessary support across the infrastructure
- Base Classes: Generalized classes serving as the foundation for derived classes within the system
- Interfaces: Definitions for methods and properties that must be implemented by implementing classes
- Configs: Configuration files that define system-wide settings and parameters
- ACL (Access Control List): Defines the permissions and access levels for different users and roles
The Core components establish relationships with other parts of the system:
- Base Classes provide foundations for Modules
- Interfaces define contracts that Modules must implement
- Utilities support both Objects and Modules
- ACL controls the Permissions system
3.2 Objects
Objects in UNA CMS are helper classes that encapsulate high-level interface functionalities, simplifying operations across the system. The Core connects to Objects, which in turn connect to Modules.
Common objects include:
- User Interface Objects: Captcha, Editors, Forms, Grids, Lists, Menu, Pages, Views
- Content Management Objects: Categories, Comments, Metatags, Votes
- Communication Objects: Live Updates, Social Sharing
- Data Management Objects: Profiles, RSS, Storage, Uploaders
- Financial Objects: Payment
These objects provide reusable functionality that can be leveraged by different modules throughout the system.
3.3 Plugins
Plugins in UNA CMS are third-party libraries that provide extended functionalities and enhancements to the core system:
- jQuery: JavaScript library for HTML document traversing, event handling, and Ajax interactions
- TinyMCE: Rich text editor for content creation and editing
3.4 Modules
Modules are the basic building blocks of UNA CMS. They are complete, independent pieces of code that can be integrated into the system or removed without affecting core functionalities.
Module Types:
- Profile Modules: Handle user profiles (e.g., Persons)
- Context Modules: Provide organizational contexts (e.g., Groups, Spaces, Organizations, Channels)
- Content Modules: Manage different content types (e.g., Posts, Photos, Videos, Files)
- Service Modules: Provide system services (e.g., Notifications, Messenger)
3.4.1 Module Interfaces
Modules can inherit multiple interfaces, which define their capabilities and behavior:
- Profile: Check with
bx_srv('system', 'is_module_profile', $sModuleName)
- Context: Check with
bx_srv('system', 'is_module_context', $sModuleName)
- Content: Check with
bx_srv('system', 'is_module_content', $sModuleName)
3.4.2 Base Module Classes
These abstract classes contain common functions for inherited modules:
BxBaseModGeneralModule extends BxDolModule
BxBaseModGroupsModule extends BxBaseModProfileModule
BxBaseModNotificationsModule extends BxBaseModGeneralModule
BxBaseModProfileModule extends BxBaseModGeneralModule implements iBxDolContentInfoService, iBxDolProfileService
BxBaseModTextModule extends BxBaseModGeneralModule implements iBxDolContentInfoService
The inheritance hierarchy provides a structured approach to module development, with specialized base classes for different module types.
4. MVC Paradigm
UNA CMS follows the Model-View-Controller (MVC) architectural pattern, which segregates the codebase into three interconnected components:
- Model (M): Represents data structures and business logic, primarily implemented in
*Db
classes - View (V): Represents the UI and presentation layer, implemented in
*Templ*
classes and files in the/template/
folder - Controller (C): Handles user interactions and selects views, implemented in
*Module
classes
The Controller interacts with both the Model and View, while the Model provides data to the View for rendering. This separation of concerns enhances maintainability and allows for more flexible development.
5. Accounts and Profiles System
UNA implements a sophisticated accounts and profiles system that separates user authentication from user representation:
Account Structure:
- AccountID: Unique identifier
- Email: User's email address
- Password: Securely stored password
- Status: Account status (active, pending, etc.)
Profile Structure:
- ProfileID: Unique identifier
- AccountID: Reference to the parent account
- ContentID: Reference to the content that represents this profile
- Type: Profile type (person, organization, etc.)
- Status: Profile status
One account can have multiple profiles, allowing users to maintain different personas within the system.
5.1 Accounts (BxDolAccount)
Key BxDolAccount methods:
getInstance()
: Get account instancelogin()
: Log in an accountupdateEmailConfirmationCode()
: Update email confirmation codeupdatePassword()
: Update account password
5.2 Profiles (BxDolProfile)
Key BxDolProfile methods:
getInstance()
: Get profile instancecheckAllowedEdit()
: Check if editing is allowedcheckAllowedView()
: Check if viewing is allowedgetInfo()
: Get profile information
6. Internal APIs & Extensibility Hooks
UNA provides several mechanisms for extending functionality and enabling communication between components:
6.1 Service Calls
Modules declare public methods as "services" that can be called by other modules or pages:
bx_srv('module', 'method', [...])
This approach allows for calling services without direct class referencing, enhancing modularity. For example, a module can call a service from another module without needing to know the implementation details.
Example service call implementation:
// Declaring a service in a module class
public function serviceGetProfileInfo($iProfileId)
{
// Implementation
return $aProfileInfo;
}
// Calling the service from another module
$aProfileInfo = bx_srv('profiles', 'get_profile_info', [$iProfileId]);
6.2 Alerts (Hooks)
Modules can emit events that trigger custom logic in subscribed handlers:
bx_alert('type', 'action', $objectId, $profileId)
Common use cases include:
- Sending emails when specific actions occur
- Logging important actions for audit purposes
- Updating related data in other modules
- Triggering notifications
Example alert implementation:
// Emitting an alert when a post is created
bx_alert('bx_posts', 'add', $iPostId, $iProfileId, [
'content' => $sContent,
'title' => $sTitle,
'module' => $this->_oConfig->getName()
]);
// Handling an alert in a handler class
public function response($oAlert)
{
if ($oAlert->sUnit == 'bx_posts' && $oAlert->sAction == 'add') {
// Process the alert, e.g., send notification
$iPostId = $oAlert->iObject;
$iProfileId = $oAlert->iSender;
$aExtraParams = $oAlert->aExtras;
// Implementation
}
}
### 6.3 Inheritance/Overrides
Developers can extend base classes or override templates in higher-priority directories to customize behavior without modifying core code. This approach allows for:
* Adding new functionality to existing modules
* Modifying the behavior of core components
* Customizing the appearance of templates
* Creating specialized versions of base classes
Example of template override:
```php
// Original template location:
// modules/base/text/template/unit.html
// Override location (higher priority):
// template/base/text/unit.html
// The system will use the override file if it exists
Example of class extension:
// Extending a base module class
class BxCustomTextModule extends BxBaseModTextModule
{
// Override a method to customize behavior
public function serviceGetBlockView($aParams)
{
// Custom implementation
$aResult = parent::serviceGetBlockView($aParams);
// Modify the result
$aResult['content'] = $this->_oTemplate->parseHtmlByName('custom_block.html', [
'content' => $aResult['content'],
'custom_field' => $this->_oDb->getCustomData()
]);
return $aResult;
}
}
### 6.4 UNA REST API
The same service calls are exposed externally via OAuth2/API keys, enabling seamless integration with:
* Mobile applications
* CRM systems
* External user interfaces
* Third-party services
Example REST API call:
GET /api/module/method?param1=value1¶m2=value2 Authorization: Bearer {oauth_token}
Response format:
```json
{
"code": 0,
"message": "Success",
"data": {
"key1": "value1",
"key2": "value2",
"items": [
{"id": 1, "title": "Item 1"},
{"id": 2, "title": "Item 2"}
]
}
}
7. Cloud Deployment & Load Balancing
UNA CMS supports sophisticated deployment architectures for high-availability and scalability:
7.1 Docker/Containerization
Official UNA Docker images exist for easy scaling and portability. Best practices include:
- Separate containers for web servers, database, and cron tasks
- Shared storage volumes for persistent data
- Container orchestration for automated scaling
- Health checks for container monitoring
7.2 Load Balancing
For high-traffic sites, UNA can be deployed across multiple servers with load balancing:
- Distribute traffic across multiple UNA containers/servers
- Store sessions in DB/Redis for statelessness
- Use sticky sessions or session replication when needed
- Configure health checks for automatic failover
7.3 Caching Strategy
UNA employs multiple caching layers for optimal performance:
- OPcache (PHP): For code optimization
- Memory caching (Redis/Memcached): For data caching
- Page caching: Can be enabled in Studio for heavier pages
- Browser caching: For static assets
7.4 Autoscaling & Monitoring
For enterprise deployments, UNA supports:
- Standard infrastructure monitoring integration
- UNA-specific logs and profiling
- Scaling based on CPU, memory, or request rates
- Automated backup and recovery procedures
8. Security Considerations
UNA implements multiple security layers to protect data and functionality:
8.1 Roles & Permissions
- Fine-tuned membership levels control access to features
- Operator roles manage administrative access
- Form-based validations enforce data integrity
- Context-aware permissions restrict content access
8.2 CSRF & XSS Prevention
- Built-in tokens for forms protect against CSRF attacks
- Output escaping in templates prevents XSS vulnerabilities
- Content sanitization removes potentially harmful markup
- Security headers enhance browser protection
8.3 SQL Injection Defense
- Parameterized queries via
*Db
classes prevent SQL injection - Direct string concatenation in queries is avoided
- Database access is abstracted through secure methods
- Input validation occurs before database operations
8.4 HTTPS Everywhere
- SSL is recommended site-wide for all UNA installations
- The operator (Studio) interface must be secured with HTTPS
- Secure cookies prevent session hijacking
- HTTP to HTTPS redirects enforce secure connections
8.5 File Security
- Safe folder structures (
/storage/
) with restricted direct access - File type validation prevents upload of malicious files
- Optional remote storage integration (S3, etc.)
- Access control for file downloads
8.6 2FA & SSO
- Two-Factor Authentication module for admins or all users
- Integration with enterprise SSO solutions
- Password policy enforcement
- Account lockout after failed attempts
8.7 Auditing & Logging
- Debug logs can be enabled for troubleshooting
- Activity logs track user actions
- Integration with external log/audit systems for compliance
- Configurable log retention policies
9. Developer Workflow & Best Practices
UNA supports a structured development workflow with best practices for customization and extension:
9.1 No-Code in Studio
Many changes can be implemented without coding:
- Page layouts and content blocks
- Form fields and validation rules
- Navigation menus and items
- Permission settings and user levels
9.2 Module Creation
Best practices for creating new modules:
- Duplicate an existing module as a starting point
- Register service calls for inter-module communication
- Define database schema in installation files
- Implement standard interfaces for consistency
9.3 Test & Staging
Recommended testing approach:
- Use a staging environment for development
- Test upgrades before applying to production
- Verify compatibility with other modules
- Perform user acceptance testing
9.4 Version Control
Code management recommendations:
- Keep UNA core and custom modules in Git
- Read release notes before updating
- Use branches for feature development
- Document customizations and changes
9.5 Keep Updated
Update management:
- Apply UNA updates (core & modules) via Studio > Apps Market
- Security fixes often come with new releases
- Test updates in staging before production
- Maintain compatibility with core updates
10. Conclusion
UNA's architecture is designed with the following principles in mind:
-
Modular & MVC-Driven: The clean separation of concerns and modular design create an extensible codebase that's easier to maintain and customize.
-
Deeply Customizable: Service calls, alerts, hooks, and template overrides provide multiple ways to integrate and extend functionality without modifying core code.
-
Enterprise-Ready: Scaling capabilities, load balancing support, and robust security features make UNA suitable for large-scale deployments.
-
Integration-Focused: The REST API, storage integrations, OAuth2 support, push notifications, and payment gateway connections allow UNA to connect with virtually any modern ecosystem.
-
Operator-Oriented: Studio provides a no-code/low-code environment for site operators to configure and manage features safely, reducing the need for developer intervention.
Whether building a straightforward community site or a complex, enterprise-level social platform, UNA CMS offers the flexibility, performance, and security to meet evolving requirements.