Files
MokoJoomHero/src/mod_mokojoomhero.php
T
Jonathan Miller ea9ea5c3a7
Generic: Repo Health / Site Health (push) Has been cancelled
Generic: Repo Health / Access control (push) Has been cancelled
Universal: PR Check / Branch Policy (pull_request) Has been cancelled
Universal: Build & Release / Build & Release Pipeline (pull_request) Has been cancelled
Joomla: Extension CI / Release Readiness Check (pull_request) Has been cancelled
Universal: Secret Scanning / Gitleaks Secret Scan (pull_request) Has been cancelled
Joomla: Extension CI / Lint & Validate (pull_request) Has been cancelled
Universal: Build & Release / Promote to RC (pull_request) Has been cancelled
Universal: PR Check / Validate PR (pull_request) Has been cancelled
Generic: Repo Health / Scripts governance (push) Has been cancelled
Generic: Repo Health / Repository health (push) Has been cancelled
Generic: Repo Health / Report Issues (push) Has been cancelled
Joomla: Extension CI / Tests (PHP 8.2) (pull_request) Has been cancelled
Joomla: Extension CI / Tests (PHP 8.3) (pull_request) Has been cancelled
Joomla: Extension CI / PHPStan Analysis (pull_request) Has been cancelled
Joomla: Extension CI / Build RC Pre-Release (pull_request) Has been cancelled
Universal: PR Check / Build RC Package (pull_request) Has been cancelled
Universal: PR Check / Report Issues (pull_request) Has been cancelled
refactor: restructure from package back to standalone module
Remove plg_system_mokojoomhero and package wrapper. Move module files
from src/packages/mod_mokojoomhero/ back to src/. Update Makefile
build target for module ZIP. Update CLAUDE.md and file PATH headers.

Authored-by: Moko Consulting
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-06-04 11:07:42 -05:00

315 lines
9.6 KiB
PHP

<?php
/**
* @package Joomla.Site
* @subpackage mod_mokojoomhero
*
* @copyright Copyright (C) 2026 Moko Consulting. All rights reserved.
* @license GPL-3.0-or-later
* SPDX-License-Identifier: GPL-3.0-or-later
*/
defined('_JEXEC') or die;
use Joomla\CMS\Helper\ModuleHelper;
use Joomla\CMS\Uri\Uri;
/** @var \Joomla\CMS\Application\SiteApplication $app */
/** @var \stdClass $module */
/** @var \Joomla\Registry\Registry $params */
// Load module assets via Web Asset Manager (registry in media/mod_mokojoomhero/)
$wa = $app->getDocument()->getWebAssetManager();
$wa->getRegistry()->addExtensionRegistryFile('mod_mokojoomhero');
$wa->usePreset('mod_mokojoomhero');
// Schedule check — skip rendering if outside the configured date range
$scheduleEnabled = (bool) $params->get('scheduleEnabled', 0);
if ($scheduleEnabled) {
$now = new \DateTime('now', new \DateTimeZone($app->get('offset', 'UTC')));
$scheduleStart = $params->get('scheduleStart', '');
$scheduleEnd = $params->get('scheduleEnd', '');
if ($scheduleStart) {
$start = new \DateTime($scheduleStart, new \DateTimeZone($app->get('offset', 'UTC')));
if ($now < $start) {
return;
}
}
if ($scheduleEnd) {
$end = new \DateTime($scheduleEnd, new \DateTimeZone($app->get('offset', 'UTC')));
if ($now > $end) {
return;
}
}
}
// A/B testing — weighted random variation, session-sticky per module instance
$abEnabled = (bool) $params->get('abEnabled', 0);
$abVariationContent = '';
if ($abEnabled) {
$abVariations = $params->get('abVariations', '');
$abData = is_string($abVariations) ? json_decode($abVariations, true) : (array) $abVariations;
if (is_array($abData) && count($abData) > 0) {
$session = \Joomla\CMS\Factory::getSession();
$sessionKey = 'mokojoomhero.ab.' . $module->id;
$picked = $session->get($sessionKey, null);
if ($picked === null || !isset($abData[$picked])) {
// Weighted random selection
$totalWeight = 0;
foreach ($abData as $v) {
$totalWeight += (int) (((array) $v)['weight'] ?? 50);
}
$rand = mt_rand(1, max($totalWeight, 1));
$cumulative = 0;
$picked = 0;
foreach ($abData as $i => $v) {
$cumulative += (int) (((array) $v)['weight'] ?? 50);
if ($rand <= $cumulative) {
$picked = $i;
break;
}
}
$session->set($sessionKey, $picked);
}
$variation = (array) ($abData[$picked] ?? []);
$abVariationContent = $variation['content'] ?? '';
}
}
// Module parameters
$heroMode = $params->get('heroMode', 'images');
$imageFolder = $params->get('imageFolder', 'images/heroes');
$imageCount = (int) $params->get('imageCount', 5);
$slideInterval = (int) $params->get('slideInterval', 5000);
$fadeType = $params->get('fadeType', 'crossfade');
$videoFile = $params->get('videoFile', '');
$heroHeight = $params->get('heroHeight', '60vh');
$heroHeightMobile = $params->get('heroHeightMobile', '');
$overlayColor = $params->get('overlayColor', '#000000');
$overlayType = $params->get('overlayType', 'solid');
$overlayOpacity = (float) $params->get('overlayOpacity', 0.5);
$textAlign = $params->get('textAlign', 'center');
$verticalAlign = $params->get('verticalAlign', 'center');
$textColor = $params->get('textColor', '#ffffff');
$contentSource = $params->get('contentSource', 'manual');
$articleId = (int) $params->get('articleId', 0);
$useArticleTitle = (bool) $params->get('useArticleTitle', 0);
$heroContent = $params->get('heroContent', '');
$slideContent = $params->get('slideContent', '');
$showCard = (bool) $params->get('showCard', 1);
$cardDelay = (int) $params->get('cardDelay', 0);
$contentAnimation = $params->get('contentAnimation', 'none');
$contentAnimationDelay = (int) $params->get('contentAnimationDelay', 0);
$parallaxEnabled = (bool) $params->get('parallaxEnabled', 0);
$parallaxSpeed = (float) $params->get('parallaxSpeed', 0.5);
$showMuteToggle = (bool) $params->get('showMuteToggle', 0);
$videoPoster = $params->get('videoPoster', '');
$showScrollIndicator = (bool) $params->get('showScrollIndicator', 0);
$localVideoFile = $params->get('localVideoFile', '');
$bgColor = $params->get('bgColor', '#003366');
$gradientStart = $params->get('gradientStart', '#003366');
$gradientEnd = $params->get('gradientEnd', '#006699');
$gradientAngle = (int) $params->get('gradientAngle', 135);
// Validate CSS height values to prevent injection
if (!preg_match('/^\d+(\.\d+)?(px|vh|vw|em|rem|%)$/', $heroHeight)) {
$heroHeight = '60vh';
}
if ($heroHeightMobile && !preg_match('/^\d+(\.\d+)?(px|vh|vw|em|rem|%)$/', $heroHeightMobile)) {
$heroHeightMobile = '';
}
// Validate hex colour values
$hexColorPattern = '/^#[0-9a-fA-F]{6}$/';
if (!preg_match($hexColorPattern, $overlayColor)) {
$overlayColor = '#000000';
}
if (!preg_match($hexColorPattern, $textColor)) {
$textColor = '#ffffff';
}
if (!preg_match($hexColorPattern, $bgColor)) {
$bgColor = '#003366';
}
if (!preg_match($hexColorPattern, $gradientStart)) {
$gradientStart = '#003366';
}
if (!preg_match($hexColorPattern, $gradientEnd)) {
$gradientEnd = '#006699';
}
// Validate allowlist values
$allowedTextAlign = ['left', 'center', 'right'];
if (!in_array($textAlign, $allowedTextAlign, true)) {
$textAlign = 'center';
}
$allowedFadeTypes = ['crossfade', 'slide', 'fade-black', 'zoom'];
if (!in_array($fadeType, $allowedFadeTypes, true)) {
$fadeType = 'crossfade';
}
$allowedOverlayTypes = ['solid', 'gradient-bottom', 'gradient-top', 'gradient-left', 'gradient-right'];
if (!in_array($overlayType, $allowedOverlayTypes, true)) {
$overlayType = 'solid';
}
$allowedContentAnimations = ['none', 'fade-in', 'slide-up', 'slide-left', 'slide-right'];
if (!in_array($contentAnimation, $allowedContentAnimations, true)) {
$contentAnimation = 'none';
}
$parallaxSpeed = max(0.1, min(0.9, $parallaxSpeed));
$gradientAngle = max(0, min(360, $gradientAngle));
// Apply A/B variation content if active
if ($abEnabled && $abVariationContent) {
$heroContent = $abVariationContent;
}
// Collect hero images
$heroImages = [];
if ($heroMode === 'images') {
$folderPath = JPATH_ROOT . '/' . ltrim($imageFolder, '/');
if (is_dir($folderPath)) {
try {
$allowed = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'avif', 'svg'];
$all = [];
foreach (new DirectoryIterator($folderPath) as $file) {
if ($file->isFile() && in_array(strtolower($file->getExtension()), $allowed, true)) {
$all[] = $file->getFilename();
}
}
if ($all) {
shuffle($all);
$picked = array_slice($all, 0, min($imageCount, 5));
foreach ($picked as $filename) {
$heroImages[] = Uri::root() . $imageFolder . '/' . $filename;
}
}
} catch (\UnexpectedValueException $e) {
\Joomla\CMS\Log\Log::add(
'MokoJoomHero: Cannot read image folder "' . $folderPath . '": ' . $e->getMessage(),
\Joomla\CMS\Log\Log::WARNING,
'mod_mokojoomhero'
);
}
}
}
// Build video URL — smartly detect YouTube, Vimeo, or local/direct file
$videoUrl = '';
$youtubeId = '';
$vimeoId = '';
if ($heroMode === 'localvideo' && $localVideoFile) {
$videoUrl = Uri::root() . ltrim($localVideoFile, '/');
} elseif ($heroMode === 'video' && $videoFile) {
// YouTube: watch, embed, shorts, youtu.be, with optional timestamps/params
if (preg_match('/(?:youtube\.com\/(?:watch\?.*v=|embed\/|shorts\/|v\/)|youtu\.be\/)([\w-]{11})/', $videoFile, $m)) {
$youtubeId = $m[1];
// Vimeo: vimeo.com/123456 or player.vimeo.com/video/123456
} elseif (preg_match('/vimeo\.com\/(?:video\/)?(\d+)/', $videoFile, $m)) {
$vimeoId = $m[1];
} else {
// Direct URL or local file path
$videoUrl = (strpos($videoFile, '://') !== false)
? $videoFile
: Uri::root() . ltrim($videoFile, '/');
}
}
// Load content from article if configured
$articleTitle = '';
if ($contentSource === 'article' && $articleId > 0) {
try {
$db = \Joomla\CMS\Factory::getDbo();
$query = $db->getQuery(true)
->select($db->quoteName(['title', 'introtext', 'fulltext']))
->from($db->quoteName('#__content'))
->where($db->quoteName('id') . ' = ' . $articleId)
->where($db->quoteName('state') . ' = 1');
$db->setQuery($query);
$article = $db->loadObject();
if ($article) {
$rawContent = $article->introtext ?: $article->fulltext;
$heroContent = \Joomla\CMS\HTML\HTMLHelper::_('content.prepare', $rawContent);
$articleTitle = $article->title;
}
} catch (\RuntimeException $e) {
\Joomla\CMS\Log\Log::add(
'MokoJoomHero: Failed to load article ID ' . $articleId . ': ' . $e->getMessage(),
\Joomla\CMS\Log\Log::WARNING,
'mod_mokojoomhero'
);
}
}
// Process per-slide content — overrides folder-based images when populated
$slides = [];
if ($heroMode === 'images' && !empty($slideContent)) {
$slideData = is_string($slideContent) ? json_decode($slideContent, true) : (array) $slideContent;
if ($slideData === null && json_last_error() !== JSON_ERROR_NONE) {
\Joomla\CMS\Log\Log::add(
'MokoJoomHero: Failed to decode slideContent JSON: ' . json_last_error_msg(),
\Joomla\CMS\Log\Log::WARNING,
'mod_mokojoomhero'
);
}
if (is_array($slideData)) {
foreach ($slideData as $item) {
$item = (array) $item;
if (!empty($item['image'])) {
$slides[] = [
'image' => Uri::root() . ltrim($item['image'], '/'),
'heading' => $item['heading'] ?? '',
'body' => $item['body'] ?? '',
'link' => $item['link'] ?? '',
'linkText' => $item['linkText'] ?? 'Learn More',
];
}
}
}
// Per-slide content overrides folder-based random images
if ($slides) {
$heroImages = array_column($slides, 'image');
}
}
require ModuleHelper::getLayoutPath('mod_mokojoomhero', $params->get('layout', 'default'));