feat(batch): batch OG tag generation (#1) #16

Merged
jmiller merged 1 commits from feature/1-batch-processing into dev 2026-05-23 23:04:18 +00:00
5 changed files with 272 additions and 0 deletions
@@ -39,3 +39,12 @@ COM_MOKOOG_HEADING_OG_TITLE_ASC="OG Title ascending"
COM_MOKOOG_HEADING_OG_TITLE_DESC="OG Title descending"
COM_MOKOOG_HEADING_MODIFIED_ASC="Modified ascending"
COM_MOKOOG_HEADING_MODIFIED_DESC="Modified descending"
COM_MOKOOG_TOOLBAR_BATCH_GENERATE="Batch Generate"
COM_MOKOOG_BATCH_TITLE="Batch OG Tag Generation"
COM_MOKOOG_BATCH_COUNTING="Counting articles without OG tags..."
COM_MOKOOG_BATCH_NONE="All articles already have OG tags."
COM_MOKOOG_BATCH_FOUND="articles found without OG tags."
COM_MOKOOG_BATCH_PROCESSED="processed"
COM_MOKOOG_BATCH_COMPLETE="Batch generation complete!"
COM_MOKOOG_BATCH_ERROR="Error:"
@@ -39,3 +39,12 @@ COM_MOKOOG_HEADING_OG_TITLE_ASC="OG Title ascending"
COM_MOKOOG_HEADING_OG_TITLE_DESC="OG Title descending"
COM_MOKOOG_HEADING_MODIFIED_ASC="Modified ascending"
COM_MOKOOG_HEADING_MODIFIED_DESC="Modified descending"
COM_MOKOOG_TOOLBAR_BATCH_GENERATE="Batch Generate"
COM_MOKOOG_BATCH_TITLE="Batch OG Tag Generation"
COM_MOKOOG_BATCH_COUNTING="Counting articles without OG tags..."
COM_MOKOOG_BATCH_NONE="All articles already have OG tags."
COM_MOKOOG_BATCH_FOUND="articles found without OG tags."
COM_MOKOOG_BATCH_PROCESSED="processed"
COM_MOKOOG_BATCH_COMPLETE="Batch generation complete!"
COM_MOKOOG_BATCH_ERROR="Error:"
@@ -0,0 +1,169 @@
<?php
/**
* @package MokoOpenGraph
* @subpackage com_mokoog
* @author Moko Consulting <hello@mokoconsulting.tech>
* @copyright Copyright (C) 2026 Moko Consulting. All rights reserved.
* @license GNU General Public License version 3 or later; see LICENSE
*/
namespace Joomla\Component\MokoOG\Administrator\Controller;
defined('_JEXEC') or die;
use Joomla\CMS\Factory;
use Joomla\CMS\Language\Text;
use Joomla\CMS\MVC\Controller\BaseController;
use Joomla\CMS\Response\JsonResponse;
use Joomla\CMS\Session\Session;
class BatchController extends BaseController
{
/**
* Count the total articles eligible for batch generation.
*
* @return void
*/
public function count(): void
{
Session::checkToken('get') || jexit(Text::_('JINVALID_TOKEN'));
$db = Factory::getDbo();
$query = $db->getQuery(true)
->select('COUNT(*)')
->from($db->quoteName('#__content', 'c'))
->leftJoin(
$db->quoteName('#__mokoog_tags', 't')
. ' ON ' . $db->quoteName('t.content_type') . ' = ' . $db->quote('com_content')
. ' AND ' . $db->quoteName('t.content_id') . ' = ' . $db->quoteName('c.id')
)
->where($db->quoteName('c.state') . ' = 1')
->where($db->quoteName('t.id') . ' IS NULL');
$db->setQuery($query);
$total = (int) $db->loadResult();
echo new JsonResponse(['total' => $total]);
Factory::getApplication()->close();
}
/**
* Process a chunk of articles for batch OG generation.
*
* @return void
*/
public function process(): void
{
Session::checkToken('get') || jexit(Text::_('JINVALID_TOKEN'));
$app = Factory::getApplication();
$offset = $app->getInput()->getInt('offset', 0);
$limit = $app->getInput()->getInt('limit', 50);
$db = Factory::getDbo();
$query = $db->getQuery(true)
->select($db->quoteName([
'c.id', 'c.title', 'c.metadesc', 'c.introtext', 'c.fulltext', 'c.images',
]))
->from($db->quoteName('#__content', 'c'))
->leftJoin(
$db->quoteName('#__mokoog_tags', 't')
. ' ON ' . $db->quoteName('t.content_type') . ' = ' . $db->quote('com_content')
. ' AND ' . $db->quoteName('t.content_id') . ' = ' . $db->quoteName('c.id')
)
->where($db->quoteName('c.state') . ' = 1')
->where($db->quoteName('t.id') . ' IS NULL')
->order($db->quoteName('c.id') . ' ASC');
$db->setQuery($query, $offset, $limit);
$articles = $db->loadObjectList();
$created = 0;
$now = Factory::getDate()->toSql();
foreach ($articles as $article) {
$ogTitle = $article->title;
$ogDescription = $this->extractDescription($article);
$ogImage = $this->extractImage($article);
$record = (object) [
'content_type' => 'com_content',
'content_id' => (int) $article->id,
'og_title' => $ogTitle,
'og_description' => $ogDescription,
'og_image' => $ogImage,
'og_type' => 'article',
'seo_title' => '',
'meta_description' => $article->metadesc ?: '',
'robots' => '',
'canonical_url' => '',
'published' => 1,
'created' => $now,
'modified' => $now,
];
$db->insertObject('#__mokoog_tags', $record);
$created++;
}
echo new JsonResponse([
'created' => $created,
'offset' => $offset,
'processed' => $offset + $created,
]);
$app->close();
}
/**
* Extract a description from article content.
*
* @param object $article Article record
*
* @return string
*/
private function extractDescription(object $article): string
{
// Prefer meta description if set
if (!empty($article->metadesc)) {
return $article->metadesc;
}
// Fall back to intro text
$text = $article->introtext ?: $article->fulltext;
$text = strip_tags($text);
$text = trim(preg_replace('/\s+/', ' ', $text));
if (\strlen($text) > 160) {
$text = mb_substr($text, 0, 157) . '...';
}
return $text;
}
/**
* Extract the best image from article data.
*
* @param object $article Article record
*
* @return string
*/
private function extractImage(object $article): string
{
if (!empty($article->images)) {
$images = json_decode($article->images, true);
if (!empty($images['image_fulltext'])) {
return $images['image_fulltext'];
}
if (!empty($images['image_intro'])) {
return $images['image_intro'];
}
}
return '';
}
}
@@ -65,6 +65,7 @@ class HtmlView extends BaseHtmlView
protected function addToolbar(): void
{
ToolbarHelper::title(Text::_('COM_MOKOOG_TAGS_TITLE'), 'bookmark');
ToolbarHelper::custom('batch.generate', 'refresh', '', 'COM_MOKOOG_TOOLBAR_BATCH_GENERATE', false);
ToolbarHelper::deleteList('JGLOBAL_CONFIRM_DELETE', 'tags.delete');
ToolbarHelper::preferences('com_mokoog');
}
@@ -14,9 +14,11 @@ use Joomla\CMS\HTML\HTMLHelper;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Layout\LayoutHelper;
use Joomla\CMS\Router\Route;
use Joomla\CMS\Session\Session;
/** @var \Joomla\Component\MokoOG\Administrator\View\Tags\HtmlView $this */
$token = Session::getFormToken();
?>
<form action="<?php echo Route::_('index.php?option=com_mokoog&view=tags'); ?>" method="post" name="adminForm" id="adminForm">
<div class="row">
@@ -134,3 +136,85 @@ use Joomla\CMS\Router\Route;
</div>
</div>
</form>
<!-- Batch Generation Progress -->
<div id="mokoog-batch-panel" style="display:none;" class="card mt-3">
<div class="card-body">
<h4><?php echo Text::_('COM_MOKOOG_BATCH_TITLE'); ?></h4>
<div class="progress mb-2">
<div id="mokoog-batch-bar" class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" style="width: 0%">0%</div>
</div>
<p id="mokoog-batch-status"></p>
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
// Intercept the batch.generate toolbar button
var origSubmitbutton = Joomla.submitbutton;
Joomla.submitbutton = function(task) {
if (task === 'batch.generate') {
mokoogBatchGenerate();
return;
}
if (origSubmitbutton) {
origSubmitbutton(task);
}
};
function mokoogBatchGenerate() {
var panel = document.getElementById('mokoog-batch-panel');
var bar = document.getElementById('mokoog-batch-bar');
var status = document.getElementById('mokoog-batch-status');
var token = '<?php echo $token; ?>';
var chunkSize = 50;
panel.style.display = 'block';
status.textContent = '<?php echo Text::_('COM_MOKOOG_BATCH_COUNTING', true); ?>';
// Step 1: Count eligible articles
fetch('index.php?option=com_mokoog&task=batch.count&format=json&' + token + '=1')
.then(function(r) { return r.json(); })
.then(function(resp) {
var total = resp.data.total;
if (total === 0) {
bar.style.width = '100%';
bar.textContent = '100%';
bar.classList.remove('progress-bar-animated');
bar.classList.add('bg-success');
status.textContent = '<?php echo Text::_('COM_MOKOOG_BATCH_NONE', true); ?>';
return;
}
status.textContent = total + ' <?php echo Text::_('COM_MOKOOG_BATCH_FOUND', true); ?>';
processChunk(0, total, chunkSize, token, bar, status);
})
.catch(function(err) {
status.textContent = '<?php echo Text::_('COM_MOKOOG_BATCH_ERROR', true); ?> ' + err.message;
});
}
function processChunk(offset, total, chunkSize, token, bar, status) {
fetch('index.php?option=com_mokoog&task=batch.process&format=json&offset=' + offset + '&limit=' + chunkSize + '&' + token + '=1')
.then(function(r) { return r.json(); })
.then(function(resp) {
var processed = resp.data.processed;
var pct = Math.min(100, Math.round((processed / total) * 100));
bar.style.width = pct + '%';
bar.textContent = pct + '%';
status.textContent = processed + ' / ' + total + ' <?php echo Text::_('COM_MOKOOG_BATCH_PROCESSED', true); ?>';
if (processed < total) {
processChunk(processed, total, chunkSize, token, bar, status);
} else {
bar.classList.remove('progress-bar-animated');
bar.classList.add('bg-success');
status.textContent = '<?php echo Text::_('COM_MOKOOG_BATCH_COMPLETE', true); ?> ' + total + ' articles.';
setTimeout(function() { location.reload(); }, 2000);
}
})
.catch(function(err) {
status.textContent = '<?php echo Text::_('COM_MOKOOG_BATCH_ERROR', true); ?> ' + err.message;
});
}
});
</script>