use namespace

master
Jean-Christian Paul Denis 2023-03-24 23:12:11 +01:00
parent 820ee61f17
commit 8fc262a089
Signed by: JcDenis
GPG Key ID: 1B5B8C5B90B6C951
13 changed files with 1359 additions and 1065 deletions

View File

@ -1,20 +0,0 @@
<?php
/**
* @brief periodical, a plugin for Dotclear 2
*
* @package Dotclear
* @subpackage Plugin
*
* @author Jean-Christian Denis and contributors
*
* @copyright Jean-Christian Denis
* @copyright GPL-2.0 https://www.gnu.org/licenses/gpl-2.0.html
*/
if (!defined('DC_RC_PATH')) {
return null;
}
Clearbricks::lib()->autoload([
'periodical' => __DIR__ . '/inc/class.periodical.php',
'adminPeriodicalList' => __DIR__ . '/inc/lib.index.pager.php',
]);

View File

@ -1,23 +0,0 @@
<?php
/**
* @brief periodical, a plugin for Dotclear 2
*
* @package Dotclear
* @subpackage Plugin
*
* @author Jean-Christian Denis and contributors
*
* @copyright Jean-Christian Denis
* @copyright GPL-2.0 https://www.gnu.org/licenses/gpl-2.0.html
*/
if (!defined('DC_CONTEXT_ADMIN')) {
return null;
}
$part = !empty($_REQUEST['part']) ? $_REQUEST['part'] : 'periods';
if ($part == 'period') {
include __DIR__ . '/inc/index.period.php';
} else {
include __DIR__ . '/inc/index.periods.php';
}

77
src/Backend.php 100644
View File

@ -0,0 +1,77 @@
<?php
/**
* @brief periodical, a plugin for Dotclear 2
*
* @package Dotclear
* @subpackage Plugin
*
* @author Jean-Christian Denis and contributors
*
* @copyright Jean-Christian Denis
* @copyright GPL-2.0 https://www.gnu.org/licenses/gpl-2.0.html
*/
declare(strict_types=1);
namespace Dotclear\Plugin\periodical;
use dcAdmin;
use dcAuth;
use dcCore;
use dcNsProcess;
use dcPage;
class Backend extends dcNsProcess
{
public static function init(): bool
{
static::$init == defined('DC_CONTEXT_ADMIN')
&& My::phpCompliant()
&& dcCore::app()->auth->check(dcCore::app()->auth->makePermissions([
dcAuth::PERMISSION_USAGE,
dcAuth::PERMISSION_CONTENT_ADMIN,
]), dcCore::app()->blog->id);
return static::$init;
}
public static function process(): bool
{
if (!static::$init) {
return false;
}
dcCore::app()->addBehaviors([
'adminBlogPreferencesFormV2' => [BackendBehaviors::class, 'adminBlogPreferencesForm'],
'adminBeforeBlogSettingsUpdate' => [BackendBehaviors::class, 'adminBeforeBlogSettingsUpdate'],
'adminFiltersListsV2' => [BackendBehaviors::class, 'adminFiltersLists'],
'adminColumnsListsV2' => [BackendBehaviors::class, 'adminColumnsLists'],
'adminPostListHeaderV2' => [BackendBehaviors::class, 'adminPostListHeader'],
'adminPostListValueV2' => [BackendBehaviors::class, 'adminPostListValue'],
'adminBeforePostDelete' => [BackendBehaviors::class, 'adminBeforePostDelete'],
]);
if (dcCore::app()->blog->settings->get(My::id())->get('periodical_active')) {
dcCore::app()->menu[dcAdmin::MENU_PLUGINS]->addItem(
My::name(),
dcCore::app()->adminurl->get('admin.plugin.' . My::id()),
dcPage::getPF(My::id() . '/icon.svg'),
preg_match('/' . preg_quote(dcCore::app()->adminurl->get('admin.plugin.' . My::id())) . '(&.*)?$/', $_SERVER['REQUEST_URI']),
dcCore::app()->auth->check(dcCore::app()->auth->makePermissions([
dcAuth::PERMISSION_USAGE,
dcAuth::PERMISSION_CONTENT_ADMIN,
]), dcCore::app()->blog->id)
);
dcCore::app()->addBehaviors([
'adminDashboardFavoritesV2' => [BackendBehaviors::class, 'adminDashboardFavoritesV2'],
'adminPostHeaders' => [BackendBehaviors::class, 'adminPostHeaders'],
'adminPostsActions' => [BackendBehaviors::class, 'adminPostsActions'],
'adminPostFormItems' => [BackendBehaviors::class, 'adminPostFormItems'],
'adminAfterPostUpdate' => [BackendBehaviors::class, 'adminAfterPostSave'],
'adminAfterPostCreate' => [BackendBehaviors::class, 'adminAfterPostSave'],
]);
}
return true;
}
}

View File

@ -10,133 +10,55 @@
* @copyright Jean-Christian Denis * @copyright Jean-Christian Denis
* @copyright GPL-2.0 https://www.gnu.org/licenses/gpl-2.0.html * @copyright GPL-2.0 https://www.gnu.org/licenses/gpl-2.0.html
*/ */
if (!defined('DC_CONTEXT_ADMIN')) { declare(strict_types=1);
return null;
}
dcCore::app()->blog->settings->addNamespace('periodical'); namespace Dotclear\Plugin\periodical;
dcCore::app()->addBehavior( use ArrayObject;
'adminBlogPreferencesFormV2', use cursor;
['adminPeriodical', 'adminBlogPreferencesForm'] use dcAuth;
); use dcCore;
dcCore::app()->addBehavior( use dcFavorites;
'adminBeforeBlogSettingsUpdate', use dcPage;
['adminPeriodical', 'adminBeforeBlogSettingsUpdate'] use dcPostsActions;
); use dcRecord;
dcCore::app()->addBehavior( use dcSettings;
'adminFiltersListsV2', use Exception;
['adminPeriodical', 'adminFiltersLists'] use form;
); use html;
dcCore::app()->addBehavior(
'adminColumnsListsV2',
['adminPeriodical', 'adminColumnsLists']
);
dcCore::app()->addBehavior(
'adminPostListHeaderV2',
['adminPeriodical', 'adminPostListHeader']
);
dcCore::app()->addBehavior(
'adminPostListValueV2',
['adminPeriodical', 'adminPostListValue']
);
if (dcCore::app()->blog->settings->periodical->periodical_active) {
dcCore::app()->menu[dcAdmin::MENU_PLUGINS]->addItem(
__('Periodical'),
dcCore::app()->adminurl->get('admin.plugin.periodical'),
dcPage::getPF('periodical/icon.svg'),
preg_match('/' . preg_quote(dcCore::app()->adminurl->get('admin.plugin.periodical')) . '(&.*)?$/', $_SERVER['REQUEST_URI']),
dcCore::app()->auth->check(dcCore::app()->auth->makePermissions([
dcAuth::PERMISSION_USAGE,
dcAuth::PERMISSION_CONTENT_ADMIN,
]), dcCore::app()->blog->id)
);
dcCore::app()->addBehavior(
'adminDashboardFavoritesV2',
['adminPeriodical', 'adminDashboardFavoritesV2']
);
dcCore::app()->addBehavior(
'adminPostHeaders',
['adminPeriodical', 'adminPostHeaders']
);
dcCore::app()->addBehavior(
'adminPostsActions',
['adminPeriodical', 'adminPostsActions']
);
dcCore::app()->addBehavior(
'adminPostFormItems',
['adminPeriodical', 'adminPostFormItems']
);
dcCore::app()->addBehavior(
'adminAfterPostUpdate',
['adminPeriodical', 'adminAfterPostSave']
);
dcCore::app()->addBehavior(
'adminAfterPostCreate',
['adminPeriodical', 'adminAfterPostSave']
);
}
dcCore::app()->addBehavior(
'adminBeforePostDelete',
['adminPeriodical', 'adminBeforePostDelete']
);
/** /**
* @ingroup DC_PLUGIN_PERIODICAL * @ingroup DC_PLUGIN_PERIODICAL
* @brief Periodical - admin methods. * @brief Periodical - admin methods.
* @since 2.6 * @since 2.6
*/ */
class adminPeriodical class BackendBehaviors
{ {
public static $combo_period = null; private static array $combo_period = [];
protected static $per = null;
public static function sortbyCombo()
{
return [
__('Next update') => 'periodical_curdt',
__('End date') => 'periodical_enddt',
__('Frequence') => 'periodical_pub_int',
];
}
protected static function period()
{
if (self::$per === null) {
self::$per = new periodical();
}
return self::$per;
}
/** /**
* Add settings to blog preference * Add settings to blog preference
* *
* @param dcSettings $blog_settings dcSettings instance * @param dcSettings $blog_settings dcSettings instance
*/ */
public static function adminBlogPreferencesForm(dcSettings $blog_settings) public static function adminBlogPreferencesForm(dcSettings $blog_settings): void
{ {
$s_active = (bool) $blog_settings->periodical->periodical_active; $s = $blog_settings->get('periodical');
$s_upddate = (bool) $blog_settings->periodical->periodical_upddate;
$s_updurl = (bool) $blog_settings->periodical->periodical_updurl;
echo echo
'<div class="fieldset"><h4 id="periodical_params">' . __('Periodical') . '</h4>' . '<div class="fieldset"><h4 id="periodical_params">' . __('Periodical') . '</h4>' .
'<div class="two-cols">' . '<div class="two-cols">' .
'<div class="col">' . '<div class="col">' .
'<p><label class="classic" for="periodical_active">' . '<p><label class="classic" for="periodical_active">' .
form::checkbox('periodical_active', 1, $s_active) . form::checkbox('periodical_active', 1, (bool) $s->get('periodical_active')) .
__('Enable periodical on this blog') . '</label></p>' . __('Enable periodical on this blog') . '</label></p>' .
'</div>' . '</div>' .
'<div class="col">' . '<div class="col">' .
'<p><label for="periodical_upddate">' . '<p><label for="periodical_upddate">' .
form::checkbox('periodical_upddate', 1, $s_upddate) . form::checkbox('periodical_upddate', 1, (bool) $s->get('periodical_upddate')) .
__('Update post date when publishing it') . '</label></p>' . __('Update post date when publishing it') . '</label></p>' .
'<p><label for="periodical_updurl">' . '<p><label for="periodical_updurl">' .
form::checkbox('periodical_updurl', 1, $s_updurl) . form::checkbox('periodical_updurl', 1, (bool) $s->get('periodical_updurl')) .
__('Update post url when publishing it') . '</label></p>' . __('Update post url when publishing it') . '</label></p>' .
'</div>' . '</div>' .
'</div>' . '</div>' .
@ -149,11 +71,11 @@ class adminPeriodical
* *
* @param dcSettings $blog_settings dcSettings instance * @param dcSettings $blog_settings dcSettings instance
*/ */
public static function adminBeforeBlogSettingsUpdate(dcSettings $blog_settings) public static function adminBeforeBlogSettingsUpdate(dcSettings $blog_settings): void
{ {
$blog_settings->periodical->put('periodical_active', !empty($_POST['periodical_active'])); $blog_settings->get('periodical')->put('periodical_active', !empty($_POST['periodical_active']));
$blog_settings->periodical->put('periodical_upddate', !empty($_POST['periodical_upddate'])); $blog_settings->get('periodical')->put('periodical_upddate', !empty($_POST['periodical_upddate']));
$blog_settings->periodical->put('periodical_updurl', !empty($_POST['periodical_updurl'])); $blog_settings->get('periodical')->put('periodical_updurl', !empty($_POST['periodical_updurl']));
} }
/** /**
@ -161,10 +83,10 @@ class adminPeriodical
* *
* @param arrayObject $cols Columns * @param arrayObject $cols Columns
*/ */
public static function adminColumnsLists($cols) public static function adminColumnsLists(ArrayObject $cols): void
{ {
$cols['periodical'] = [ $cols[My::id()] = [
__('Periodical'), My::name(),
[ [
'curdt' => [true, __('Next update')], 'curdt' => [true, __('Next update')],
'pub_int' => [true, __('Frequency')], 'pub_int' => [true, __('Frequency')],
@ -182,11 +104,11 @@ class adminPeriodical
* *
* @param arrayObject $sorts Sort options * @param arrayObject $sorts Sort options
*/ */
public static function adminFiltersLists($sorts) public static function adminFiltersLists(ArrayObject $sorts): void
{ {
$sorts['periodical'] = [ $sorts[My::id()] = [
__('Periodical'), My::name(),
self::sortbyCombo(), My::sortbyCombo(),
'periodical_curdt', 'periodical_curdt',
'desc', 'desc',
[__('periods per page'), 10], [__('periods per page'), 10],
@ -196,12 +118,12 @@ class adminPeriodical
/** /**
* Add columns period to posts list header. * Add columns period to posts list header.
* *
* @param record $rs record instance * @param dcRecord $rs record instance
* @param arrayObject $cols Columns * @param ArrayObject $cols Columns
*/ */
public static function adminPostListHeader($rs, $cols) public static function adminPostListHeader(dcRecord $rs, ArrayObject $cols): void
{ {
if (dcCore::app()->blog->settings->periodical->periodical_active) { if (dcCore::app()->blog->settings->get('periodical')->get('periodical_active')) {
$cols['period'] = '<th scope="col">' . __('Period') . '</th>'; $cols['period'] = '<th scope="col">' . __('Period') . '</th>';
} }
} }
@ -209,37 +131,37 @@ class adminPeriodical
/** /**
* Add columns period to posts list values. * Add columns period to posts list values.
* *
* @param record $rs record instance * @param dcRecord $rs record instance
* @param arrayObject $cols Columns * @param ArrayObject $cols Columns
*/ */
public static function adminPostListValue($rs, $cols) public static function adminPostListValue(dcRecord $rs, ArrayObject $cols): void
{ {
if (!dcCore::app()->blog->settings->periodical->periodical_active) { if (!dcCore::app()->blog->settings->get('periodical')->get('periodical_active')) {
return null; return;
} }
$r = self::period()->getPosts(['post_id' => $rs->post_id]); $r = Utils::getPosts(['post_id' => $rs->f('post_id')]);
if ($r->isEmpty()) { if ($r->isEmpty()) {
$name = '-'; $name = '-';
} else { } else {
$url = dcCore::app()->adminurl->get('admin.plugin.periodical', ['part' => 'period', 'period_id' => $r->periodical_id]); $url = dcCore::app()->adminurl->get('admin.plugin.periodical', ['part' => 'period', 'period_id' => $r->f('periodical_id')]);
$name = '<a href="' . $url . '#period" title="' . __('edit period') . '">' . html::escapeHTML($r->periodical_title) . '</a>'; $name = '<a href="' . $url . '#period" title="' . __('edit period') . '">' . html::escapeHTML($r->f('periodical_title')) . '</a>';
} }
$cols['period'] = '<td class="nowrap">' . $name . '</td>'; $cols['period'] = '<td class="nowrap">' . $name . '</td>';
} }
/** /**
* Favorites. * Dashboard Favorites.
* *
* @param dcFavorites $favs Array of favorites * @param dcFavorites $favs Array of favorites
*/ */
public static function adminDashboardFavoritesV2(dcFavorites $favs) public static function adminDashboardFavoritesV2(dcFavorites $favs): void
{ {
$favs->register('periodical', [ $favs->register(My::id(), [
'title' => __('Periodical'), 'title' => My::name(),
'url' => dcCore::app()->adminurl->get('admin.plugin.periodical'), 'url' => dcCore::app()->adminurl->get('admin.plugin.' . My::id()),
'small-icon' => dcPage::getPF('periodical/icon.svg'), 'small-icon' => dcPage::getPF(My::id() . '/icon.svg'),
'large-icon' => dcPage::getPF('periodical/icon.svg'), 'large-icon' => dcPage::getPF(My::id() . '/icon.svg'),
'permissions' => dcCore::app()->auth->makePermissions([ 'permissions' => dcCore::app()->auth->makePermissions([
dcAuth::PERMISSION_USAGE, dcAuth::PERMISSION_USAGE,
dcAuth::PERMISSION_CONTENT_ADMIN, dcAuth::PERMISSION_CONTENT_ADMIN,
@ -252,9 +174,9 @@ class adminPeriodical
* *
* @return string HTML head * @return string HTML head
*/ */
public static function adminPostHeaders() public static function adminPostHeaders(): string
{ {
return dcPage::jsLoad(dcPage::getPF('periodical/js/toggle.js')); return dcPage::jsModuleLoad(My::id() . '/js/toggle.js');
} }
/** /**
@ -262,7 +184,7 @@ class adminPeriodical
* *
* @param integer $post_id Post id * @param integer $post_id Post id
*/ */
public static function adminBeforePostDelete($post_id) public static function adminBeforePostDelete(int $post_id): void
{ {
self::delPeriod($post_id); self::delPeriod($post_id);
} }
@ -272,24 +194,23 @@ class adminPeriodical
* *
* @param dcPostsActions $pa dcPostsActions instance * @param dcPostsActions $pa dcPostsActions instance
*/ */
public static function adminPostsActions(dcPostsActions $pa) public static function adminPostsActions(dcPostsActions $pa): void
{ {
$pa->addAction( $pa->addAction(
[__('Periodical') => [__('Add to periodical') => 'periodical_add']], [My::name() => [__('Add to periodical') => 'periodical_add']],
['adminPeriodical', 'callbackAdd'] [self::class, 'callbackAdd']
); );
if (!dcCore::app()->auth->check(dcCore::app()->auth->makePermissions([ if (dcCore::app()->auth->check(dcCore::app()->auth->makePermissions([
dcAuth::PERMISSION_DELETE, dcAuth::PERMISSION_DELETE,
dcAuth::PERMISSION_CONTENT_ADMIN, dcAuth::PERMISSION_CONTENT_ADMIN,
]), dcCore::app()->blog->id)) { ]), dcCore::app()->blog->id)) {
return null;
}
$pa->addAction( $pa->addAction(
[__('Periodical') => [__('Remove from periodical') => 'periodical_remove']], [My::name() => [__('Remove from periodical') => 'periodical_remove']],
['adminPeriodical', 'callbackRemove'] [self::class, 'callbackRemove']
); );
} }
}
/** /**
* Posts actions callback to remove period * Posts actions callback to remove period
@ -297,7 +218,7 @@ class adminPeriodical
* @param dcPostsActions $pa dcPostsActions instance * @param dcPostsActions $pa dcPostsActions instance
* @param ArrayObject $post _POST actions * @param ArrayObject $post _POST actions
*/ */
public static function callbackRemove(dcPostsActions $pa, ArrayObject $post) public static function callbackRemove(dcPostsActions $pa, ArrayObject $post): void
{ {
# No entry # No entry
$posts_ids = $pa->getIDs(); $posts_ids = $pa->getIDs();
@ -318,7 +239,7 @@ class adminPeriodical
self::delPeriod($post_id); self::delPeriod($post_id);
} }
dcAdminNotices::addSuccessNotice(__('Posts have been removed from periodical.')); dcPage::addSuccessNotice(__('Posts have been removed from periodical.'));
$pa->redirect(true); $pa->redirect(true);
} }
@ -328,7 +249,7 @@ class adminPeriodical
* @param dcPostsActions $pa dcPostsActions instance * @param dcPostsActions $pa dcPostsActions instance
* @param ArrayObject $post _POST actions * @param ArrayObject $post _POST actions
*/ */
public static function callbackAdd(dcPostsActions $pa, ArrayObject $post) public static function callbackAdd(dcPostsActions $pa, ArrayObject $post): void
{ {
# No entry # No entry
$posts_ids = $pa->getIDs(); $posts_ids = $pa->getIDs();
@ -342,10 +263,10 @@ class adminPeriodical
if (!empty($post['periodical'])) { if (!empty($post['periodical'])) {
foreach ($posts_ids as $post_id) { foreach ($posts_ids as $post_id) {
self::delPeriod($post_id); self::delPeriod($post_id);
self::addPeriod($post_id, $post['periodical']); self::addPeriod($post_id, (int) $post['periodical']);
} }
dcAdminNotices::addSuccessNotice(__('Posts have been added to periodical.')); dcPage::addSuccessNotice(__('Posts have been added to periodical.'));
$pa->redirect(true); $pa->redirect(true);
} }
@ -381,52 +302,52 @@ class adminPeriodical
* *
* @param ArrayObject $main_items Main items * @param ArrayObject $main_items Main items
* @param ArrayObject $sidebar_items Sidebar items * @param ArrayObject $sidebar_items Sidebar items
* @param record $post Post record or null * @param dcRecord $post Post record or null
*/ */
public static function adminPostFormItems(ArrayObject $main_items, ArrayObject $sidebar_items, $post) public static function adminPostFormItems(ArrayObject $main_items, ArrayObject $sidebar_items, ?dcRecord $post): void
{ {
# Get existing linked period # Get existing linked period
$period = ''; $period = '';
if ($post) { if ($post !== null) {
$rs = self::period()->getPosts(['post_id' => $post->post_id]); $rs = Utils::getPosts(['post_id' => $post->f('post_id')]);
$period = $rs->isEmpty() ? '' : $rs->periodical_id; $period = $rs->isEmpty() ? '' : $rs->f('periodical_id');
} }
# Set linked period form items # Set linked period form items
$sidebar_items['options-box']['items']['period'] = self::formPeriod($period); $sidebar_items['options-box']['items']['period'] = self::formPeriod((int) $period);
} }
/** /**
* Save linked period * Save linked period
* *
* @param cursor $cur Current post cursor * @param cursor $cur Current post cursor
* @param integer $post_id Post id * @param null|int $post_id Post id
*/ */
public static function adminAfterPostSave(cursor $cur, $post_id) public static function adminAfterPostSave(cursor $cur, ?int $post_id): void
{ {
if (!isset($_POST['periodical'])) { if (!isset($_POST['periodical']) || $post_id === null) {
return null; return;
} }
# Delete old linked period # Delete old linked period
self::delPeriod($post_id); self::delPeriod($post_id);
# Add new linked period # Add new linked period
self::addPeriod($post_id, $_POST['periodical']); self::addPeriod($post_id, (int) $_POST['periodical']);
} }
/** /**
* Posts period form field * Posts period form field
* *
* @param string $period Period * @param int $period Period
* @return null|string Period form content * @return string Period form content
*/ */
protected static function formPeriod($period = '') private static function formPeriod(int $period = 0): string
{ {
$combo = self::comboPeriod(); $combo = self::comboPeriod();
if (empty($combo)) { if (empty($combo)) {
return null; return '';
} }
return return
@ -441,63 +362,50 @@ class adminPeriodical
* *
* @return array List of period * @return array List of period
*/ */
protected static function comboPeriod() private static function comboPeriod(): array
{ {
if (adminPeriodical::$combo_period === null) { if (empty(self::$combo_period)) {
$periods = self::period()->getPeriods(); $periods = Utils::getPeriods();
adminPeriodical::$combo_period = [];
if (!$periods->isEmpty()) { if (!$periods->isEmpty()) {
$combo = ['-' => '']; $combo = ['-' => ''];
while ($periods->fetch()) { while ($periods->fetch()) {
$combo[html::escapeHTML($periods->periodical_title)] = $periods->periodical_id; $combo[html::escapeHTML($periods->f('periodical_title'))] = $periods->f('periodical_id');
} }
adminPeriodical::$combo_period = $combo; self::$combo_period = $combo;
} }
} }
return adminPeriodical::$combo_period; return self::$combo_period;
} }
/** /**
* Remove period from posts. * Remove period from posts.
* *
* @param integer $post_id Post id * @param int $post_id Post id
*/ */
protected static function delPeriod($post_id) private static function delPeriod(int $post_id): void
{ {
if ($post_id === null) { Utils::delPost((int) $post_id);
return null;
}
$post_id = (int) $post_id;
self::period()->delPost($post_id);
} }
/** /**
* Add period to posts * Add period to posts
* *
* @param integer $post_id Post id * @param int $post_id Post id
* @param array $period Period * @param int $period_id Period
*/ */
protected static function addPeriod($post_id, $period) private static function addPeriod(int $post_id, int $period_id): void
{ {
# Not saved
if ($post_id === null || empty($period)) {
return null;
}
# Get periods # Get periods
$period = self::period()->getPeriods(['periodical_id' => $period]); $period = Utils::getPeriods(['periodical_id' => $period_id]);
# No period # No period
if ($period->isEmpty()) { if ($period->isEmpty()) {
return null; return;
} }
$post_id = (int) $post_id;
# Add relation # Add relation
self::period()->addPost($period->periodical_id, $post_id); Utils::addPost($period_id, $post_id);
} }
} }

102
src/Dater.php 100644
View File

@ -0,0 +1,102 @@
<?php
/**
* @brief periodical, a plugin for Dotclear 2
*
* @package Dotclear
* @subpackage Plugin
*
* @author Jean-Christian Denis and contributors
*
* @copyright Jean-Christian Denis
* @copyright GPL-2.0 https://www.gnu.org/licenses/gpl-2.0.html
*/
declare(strict_types=1);
namespace Dotclear\Plugin\periodical;
use DateTimeZone;
use dcCore;
use Exception;
/**
* Tools to manupilate period date
*/
class Dater
{
/**
* Format a date from UTC to user TZ
*/
public static function fromUser(string $date, string $format = 'Y-m-d H:i:00'): string
{
$d = date_create($date, new DateTimeZone(dcCore::app()->auth->getInfo('user_tz')));
return $d ? date_format($d->setTimezone(new DateTimeZone('UTC')), $format) : '';
}
/**
* Format a date from user TZ to UTC
*/
public static function toUser(string $date, string $format = 'Y-m-d\TH:i'): string
{
$d = date_create($date, new DateTimeZone('UTC'));
return $d ? date_format($d->setTimezone(new DateTimeZone(dcCore::app()->auth->getInfo('user_tz'))), $format) : '';
}
/**
* Format a date to specific TZ (UTC by default) from another format
*/
public static function toDate(int|string $date = 'now', string $format = 'Y-m-d H:i:00', string $to_tz = 'UTC'): string
{
$d = is_int($date) ?
date_create_from_format('U', (string) $date, new DateTimeZone('UTC')) :
date_create($date, new DateTimeZone('UTC'));
return $d ? date_format($d->setTimeZone(new DateTimeZone($to_tz)), $format) : '';
}
/**
* Get next timestamp from a period
*/
public static function getNextTime(int $ts, string $period): int
{
$dt = date_create_from_format('U', (string) $ts);
if ($dt === false) {
return $ts;
}
switch($period) {
case 'hour':
$dt->modify('+1 hour');
break;
case 'halfday':
$dt->modify('+12 hours');
break;
case 'day':
$dt->modify('+1 day');
break;
case 'week':
$dt->modify('+1 week');
break;
case 'month':
$dt->modify('+1 month');
break;
default:
throw new Exception(__('Unknow frequence'));
}
return (int) $dt->format('U');
}
}

View File

@ -10,79 +10,74 @@
* @copyright Jean-Christian Denis * @copyright Jean-Christian Denis
* @copyright GPL-2.0 https://www.gnu.org/licenses/gpl-2.0.html * @copyright GPL-2.0 https://www.gnu.org/licenses/gpl-2.0.html
*/ */
if (!defined('DC_RC_PATH')) { declare(strict_types=1);
return null;
}
if (!in_array(dcCore::app()->url->type, ['default', 'feed'])) { namespace Dotclear\Plugin\periodical;
return null;
}
dcCore::app()->blog->settings->addNamespace('periodical'); use dcBlog;
use dcCore;
dcCore::app()->addBehavior( use dcNsProcess;
'publicBeforeDocumentV2', use Exception;
['publicPeriodical', 'publicBeforeDocument']
);
/** /**
* @ingroup DC_PLUGIN_PERIODICAL * Update posts from periods on frontend
* @brief Periodical - public methods.
* @since 2.6
*/ */
class publicPeriodical class Frontend extends dcNsProcess
{ {
/** public static function init(): bool
* Publish periodical
*/
public static function publicBeforeDocument()
{ {
try { static::$init = defined('DC_RC_PATH')
$per = new periodical(); && in_array(dcCore::app()->url->type, ['default', 'feed']);
$s = dcCore::app()->blog->settings->periodical;
$per->lockUpdate(); return static::$init;
}
public static function process(): bool
{
if (!static::$init) {
return false;
}
dcCore::app()->addBehavior('publicBeforeDocumentV2', function (): void {
try {
$s = dcCore::app()->blog->settings->get(My::id());
Utils::lockUpdate();
# Get periods # Get periods
$periods = dcCore::app()->auth->sudo([$per, 'getPeriods']); $periods = dcCore::app()->auth->sudo([Utils::class, 'getPeriods']);
# No period # No period
if ($periods->isEmpty()) { if ($periods->isEmpty()) {
$per->unlockUpdate(); Utils::unlockUpdate();
return null; return;
} }
$now = dt::toUTC(time()); $now_ts = (int) Dater::toDate('now', 'U');
$posts_order = $s->periodical_pub_order; $posts_order = $s->get('periodical_pub_order');
if (!preg_match('/^(post_dt|post_creadt|post_id) (asc|desc)$/', $posts_order)) { if (!preg_match('/^(post_dt|post_creadt|post_id) (asc|desc)$/', $posts_order)) {
$posts_order = 'post_dt asc'; $posts_order = 'post_dt asc';
} }
$cur_period = dcCore::app()->con->openCursor(dcCore::app()->prefix . initPeriodical::PERIOD_TABLE_NAME); $cur_period = dcCore::app()->con->openCursor(dcCore::app()->prefix . My::TABLE_NAME);
while ($periods->fetch()) { while ($periods->fetch()) {
# Check if period is ongoing # Check if period is ongoing
$cur_tz = strtotime($periods->periodical_curdt); $cur_ts = (int) Dater::toDate($periods->f('periodical_curdt'), 'U');
$end_tz = strtotime($periods->periodical_enddt); $end_ts = (int) Dater::toDate($periods->f('periodical_enddt'), 'U');
$now_tz = $now + dt::getTimeOffset($periods->periodical_tz, $now);
if ($cur_tz < $now_tz && $now_tz < $end_tz) { if ($cur_ts < $now_ts && $now_ts < $end_ts) {
$max_nb = (int) $periods->f('periodical_pub_nb');
$last_nb = 0; $last_nb = 0;
$last_tz = $cur_tz; $last_ts = $loop_ts = $cur_ts;
$max_nb = $periods->periodical_pub_nb;
$max_tz = $end_tz < $now_tz ? $end_tz : $now_tz;
# Calculate nb of posts to get
$loop_tz = $cur_tz;
$limit = 0; $limit = 0;
try { try {
while (1) { while (1) {
if ($loop_tz > $max_tz) { if ($loop_ts > $now_ts) {
break; break;
} }
$loop_tz = $per->getNextTime($loop_tz, $periods->periodical_pub_int); $loop_ts = Dater::getNextTime($loop_ts, $periods->f('periodical_pub_int'));
$limit += 1; $limit += 1;
} }
} catch (Exception $e) { } catch (Exception $e) {
@ -92,12 +87,12 @@ class publicPeriodical
if ($limit > 0) { if ($limit > 0) {
# Get posts to publish related to this period # Get posts to publish related to this period
$posts_params = []; $posts_params = [];
$posts_params['periodical_id'] = $periods->periodical_id; $posts_params['periodical_id'] = $periods->f('periodical_id');
$posts_params['post_status'] = '-2'; $posts_params['post_status'] = dcBlog::POST_PENDING;
$posts_params['order'] = $posts_order; $posts_params['order'] = $posts_order;
$posts_params['limit'] = $limit * $max_nb; $posts_params['limit'] = $limit * $max_nb;
$posts_params['no_content'] = true; $posts_params['no_content'] = true;
$posts = dcCore::app()->auth->sudo([$per, 'getPosts'], $posts_params); $posts = dcCore::app()->auth->sudo([Utils::class, 'getPosts'], $posts_params);
if (!$posts->isEmpty()) { if (!$posts->isEmpty()) {
$cur_post = dcCore::app()->con->openCursor(dcCore::app()->prefix . dcBlog::POST_TABLE_NAME); $cur_post = dcCore::app()->con->openCursor(dcCore::app()->prefix . dcBlog::POST_TABLE_NAME);
@ -105,34 +100,38 @@ class publicPeriodical
while ($posts->fetch()) { while ($posts->fetch()) {
# Publish post with right date # Publish post with right date
$cur_post->clean(); $cur_post->clean();
$cur_post->post_status = 1; $cur_post->setField('post_status', dcBlog::POST_PUBLISHED);
# Update post date with right date # Update post date with right date
if ($s->periodical_upddate) { if ($s->get('periodical_upddate')) {
$cur_post->post_dt = date('Y-m-d H:i:s', $last_tz); $cur_post->setField('post_dt', Dater::toDate($last_ts, 'Y-m-d H:i:00', $posts->post_tz));
$cur_post->post_tz = $periods->periodical_tz;
} else { } else {
$cur_post->post_dt = $posts->post_dt; $cur_post->setField('post_dt', $posts->f('post_dt'));
} }
# Also update post url with right date # Also update post url with right date
if ($s->periodical_updurl) { if ($s->get('periodical_updurl')) {
$cur_post->post_url = dcCore::app()->blog->getPostURL('', $cur_post->post_dt, $posts->post_title, $posts->post_id); $cur_post->setField('post_url', dcCore::app()->blog->getPostURL(
'',
$cur_post->getField('post_dt'),
$posts->f('post_title'),
$posts->f('post_id')
));
} }
$cur_post->update( $cur_post->update(
'WHERE post_id = ' . $posts->post_id . ' ' . 'WHERE post_id = ' . $posts->f('post_id') . ' ' .
"AND blog_id = '" . dcCore::app()->con->escape(dcCore::app()->blog->id) . "' " "AND blog_id = '" . dcCore::app()->con->escapeStr(dcCore::app()->blog->id) . "' "
); );
# Delete post relation to this period # Delete post relation to this period
$per->delPost($posts->post_id); Utils::delPost((int) $posts->f('post_id'));
$last_nb++; $last_nb++;
# Increment upddt if nb of publishing is to the max # Increment upddt if nb of publishing is to the max
if ($last_nb == $max_nb) { if ($last_nb == $max_nb) {
$last_tz = $per->getNextTime($last_tz, $periods->periodical_pub_int); $last_ts = Dater::getNextTime($last_ts, $periods->f('periodical_pub_int'));
$last_nb = 0; $last_nb = 0;
} }
@ -145,20 +144,19 @@ class publicPeriodical
# Update last published date of this period even if there's no post to publish # Update last published date of this period even if there's no post to publish
$cur_period->clean(); $cur_period->clean();
$cur_period->periodical_curdt = date('Y-m-d H:i:s', $loop_tz); $cur_period->setField('periodical_curdt', Dater::toDate($loop_ts, 'Y-m-d H:i:00'));
$cur_period->update( $cur_period->update(
'WHERE periodical_id = ' . $periods->periodical_id . ' ' . 'WHERE periodical_id = ' . $periods->f('periodical_id') . ' ' .
"AND blog_id = '" . dcCore::app()->con->escape(dcCore::app()->blog->id) . "' " "AND blog_id = '" . dcCore::app()->con->escapeStr(dcCore::app()->blog->id) . "' "
); );
} }
} }
$per->unlockUpdate(); Utils::unlockUpdate();
} catch (Exception $e) { } catch (Exception $e) {
if (isset($per)) { Utils::unlockUpdate();
$per->unlockUpdate();
} }
});
return null; return true;
}
} }
} }

View File

@ -10,29 +10,42 @@
* @copyright Jean-Christian Denis * @copyright Jean-Christian Denis
* @copyright GPL-2.0 https://www.gnu.org/licenses/gpl-2.0.html * @copyright GPL-2.0 https://www.gnu.org/licenses/gpl-2.0.html
*/ */
if (!defined('DC_CONTEXT_ADMIN')) { declare(strict_types=1);
return null;
}
try { namespace Dotclear\Plugin\periodical;
# Check installed version
if (!dcCore::app()->newVersion( use dbStruct;
basename(__DIR__), use dcCore;
dcCore::app()->plugins->moduleInfo(basename(__DIR__), 'version') use dcNsProcess;
)) { use Exception;
return null;
class Install extends dcNsProcess
{
public static function init(): bool
{
static::$init = defined('DC_CONTEXT_ADMIN')
&& My::phpCompliant()
&& dcCore::app()->newVersion(My::id(), dcCore::app()->plugins->moduleInfo(My::id(), 'version'));
return static::$init;
} }
public static function process(): bool
{
if (!static::$init) {
return false;
}
try {
# Tables # Tables
$t = new dbStruct(dcCore::app()->con, dcCore::app()->prefix); $t = new dbStruct(dcCore::app()->con, dcCore::app()->prefix);
# Table principale des sondages # Table principale des sondages
$t->{initPeriodical::PERIOD_TABLE_NAME} $t->{My::TABLE_NAME} // @phpstan-ignore-line
->periodical_id('bigint', 0, false) ->periodical_id('bigint', 0, false)
->blog_id('varchar', 32, false) ->blog_id('varchar', 32, false)
->periodical_type('varchar', 32, false, "'post'") ->periodical_type('varchar', 32, false, "'post'")
->periodical_title('varchar', 255, false, "''") ->periodical_title('varchar', 255, false, "''")
->periodical_tz('varchar', 128, false, "'UTC'")
->periodical_curdt('timestamp', 0, false, ' now()') ->periodical_curdt('timestamp', 0, false, ' now()')
->periodical_enddt('timestamp', 0, false, 'now()') ->periodical_enddt('timestamp', 0, false, 'now()')
->periodical_pub_int('varchar', 32, false, "'day'") ->periodical_pub_int('varchar', 32, false, "'day'")
@ -41,20 +54,20 @@ try {
->primary('pk_periodical', 'periodical_id') ->primary('pk_periodical', 'periodical_id')
->index('idx_periodical_type', 'btree', 'periodical_type'); ->index('idx_periodical_type', 'btree', 'periodical_type');
$ti = new dbStruct(dcCore::app()->con, dcCore::app()->prefix); (new dbStruct(dcCore::app()->con, dcCore::app()->prefix))->synchronize($t);
$changes = $ti->synchronize($t);
# Settings # Settings
dcCore::app()->blog->settings->addNamespace(basename(__DIR__)); $s = dcCore::app()->blog->settings->get(My::id());
$s = dcCore::app()->blog->settings->__get(basename(__DIR__));
$s->put('periodical_active', false, 'boolean', 'Enable extension', false, true); $s->put('periodical_active', false, 'boolean', 'Enable extension', false, true);
$s->put('periodical_upddate', true, 'boolean', 'Update post date', false, true); $s->put('periodical_upddate', true, 'boolean', 'Update post date', false, true);
$s->put('periodical_updurl', false, 'boolean', 'Update post url', false, true); $s->put('periodical_updurl', false, 'boolean', 'Update post url', false, true);
$s->put('periodical_pub_order', 'post_dt asc', 'string', 'Order of publication', false, true); $s->put('periodical_pub_order', 'post_dt asc', 'string', 'Order of publication', false, true);
return true; return true;
} catch (Exception $e) { } catch (Exception $e) {
dcCore::app()->error->add($e->getMessage()); dcCore::app()->error->add($e->getMessage());
}
return false; return false;
}
}
}

View File

@ -10,103 +10,150 @@
* @copyright Jean-Christian Denis * @copyright Jean-Christian Denis
* @copyright GPL-2.0 https://www.gnu.org/licenses/gpl-2.0.html * @copyright GPL-2.0 https://www.gnu.org/licenses/gpl-2.0.html
*/ */
if (!defined('DC_CONTEXT_ADMIN')) { declare(strict_types=1);
return null;
}
dcPage::check(dcCore::app()->auth->makePermissions([dcAuth::PERMISSION_USAGE, dcAuth::PERMISSION_CONTENT_ADMIN])); namespace Dotclear\Plugin\periodical;
# Objects use adminGenericFilter;
$per = new periodical(); use dcAuth;
use dcCore;
use dcNsProcess;
use dcPage;
use Exception;
use form;
use http;
# Default values /**
$action = $_POST['action'] ?? ''; * Admin page for periods
*/
class Manage extends dcNsProcess
{
public static function init(): bool
{
static::$init == defined('DC_CONTEXT_ADMIN')
&& My::phpCompliant()
&& dcCore::app()->auth->check(dcCore::app()->auth->makePermissions([
dcAuth::PERMISSION_USAGE,
dcAuth::PERMISSION_CONTENT_ADMIN,
]), dcCore::app()->blog->id);
# Delete periods and related posts links // call period manage page
if ($action == 'deleteperiods' && !empty($_POST['periods'])) { if (($_REQUEST['part'] ?? 'periods') === 'period') {
try { static::$init = ManagePeriod::init();
foreach ($_POST['periods'] as $id) {
$id = (int) $id;
$per->delPeriodPosts($id);
$per->delPeriod($id);
} }
dcAdminNotices::addSuccessNotice( return static::$init;
}
public static function process(): bool
{
if (!static::$init) {
return false;
}
if (($_REQUEST['part'] ?? 'periods') === 'period') {
return ManagePeriod::process();
}
# Default values
$vars = ManageVars::init();
# Delete periods and related posts links
if ($vars->action == 'deleteperiods' && !empty($vars->periods)) {
try {
foreach ($vars->periods as $id) {
Utils::delPeriodPosts($id);
Utils::delPeriod($id);
}
dcPage::addSuccessNotice(
__('Periods removed.') __('Periods removed.')
); );
if (!empty($_POST['redir'])) { if (!empty($vars->redir)) {
http::redirect($_POST['redir']); http::redirect($vars->redir);
} else { } else {
dcCore::app()->adminurl->redirect('admin.plugin.periodical', ['part' => 'periods']); dcCore::app()->adminurl->redirect('admin.plugin.' . My::id(), ['part' => 'periods']);
} }
} catch (Exception $e) { } catch (Exception $e) {
dcCore::app()->error->add($e->getMessage()); dcCore::app()->error->add($e->getMessage());
} }
}
# Delete periods related posts links (without delete periods)
if ($action == 'emptyperiods' && !empty($_POST['periods'])) {
try {
foreach ($_POST['periods'] as $id) {
$id = (int) $id;
$per->delPeriodPosts($id);
} }
dcAdminNotices::addSuccessNotice( # Delete periods related posts links (without delete periods)
if ($vars->action == 'emptyperiods' && !empty($vars->periods)) {
try {
foreach ($vars->periods as $id) {
Utils::delPeriodPosts($id);
}
dcPage::addSuccessNotice(
__('Periods emptied.') __('Periods emptied.')
); );
if (!empty($_POST['redir'])) { if (!empty($vars->redir)) {
http::redirect($_POST['redir']); http::redirect($vars->redir);
} else { } else {
dcCore::app()->adminurl->redirect('admin.plugin.periodical', ['part' => 'periods']); dcCore::app()->adminurl->redirect('admin.plugin.' . My::id(), ['part' => 'periods']);
} }
} catch (Exception $e) { } catch (Exception $e) {
dcCore::app()->error->add($e->getMessage()); dcCore::app()->error->add($e->getMessage());
} }
} }
$combo_action = [ return true;
__('empty periods') => 'emptyperiods', }
__('delete periods') => 'deleteperiods',
];
# Filters /**
$p_filter = new adminGenericFilter(dcCore::app(), 'periodical'); * Renders the page.
$p_filter->add('part', 'periods'); */
public static function render(): void
{
if (!static::$init) {
return;
}
$params = $p_filter->params(); if (($_REQUEST['part'] ?? 'periods') === 'period') {
ManagePeriod::render();
# Get periods return;
try { }
$periods = $per->getPeriods($params);
$counter = $per->getPeriods($params, true);
$period_list = new adminPeriodicalList(dcCore::app(), $periods, $counter->f(0));
} catch (Exception $e) {
dcCore::app()->error->add($e->getMessage());
}
# Display
echo
'<html><head><title>' . __('Periodical') . '</title>' .
dcPage::jsLoad(dcPage::getPF('periodical/js/checkbox.js')) .
$p_filter->js(dcCore::app()->adminurl->get('admin.plugin.periodical', ['part' => 'periods'])) .
'</head>' .
'<body>' .
dcPage::breadcrumb([
__('Plugins') => '',
__('Periodical') => '',
]) .
dcPage::notices() .
'<p class="top-add">
<a class="button add" href="' . dcCore::app()->admin->getPageURL() . '&amp;part=period">' . __('New period') . '</a>
</p>';
if (isset($period_list)) {
# Filters # Filters
$p_filter->display('admin.plugin.periodical', form::hidden('p', 'periodical') . form::hidden('part', 'periods')); $p_filter = new adminGenericFilter(dcCore::app(), My::id());
$p_filter->add('part', 'periods');
$params = $p_filter->params();
# Get periods
try {
$periods = Utils::getPeriods($params);
$counter = Utils::getPeriods($params, true);
$period_list = new ManageList(dcCore::app(), $periods, $counter->f(0));
} catch (Exception $e) {
dcCore::app()->error->add($e->getMessage());
}
# Display
dcPage::openModule(
My::name(),
dcPage::jsModuleLoad(My::id() . '/js/checkbox.js') .
$p_filter->js(dcCore::app()->adminurl->get('admin.plugin.' . My::id(), ['part' => 'periods']))
);
echo dcPage::breadcrumb([
__('Plugins') => '',
My::name() => '',
]) .
dcPage::notices() .
'<p class="top-add">
<a class="button add" href="' . dcCore::app()->admin->getPageURL() . '&amp;part=period">' . __('New period') . '</a>
</p>';
if (isset($period_list)) {
# Filters
$p_filter->display('admin.plugin.' . My::id(), form::hidden('p', My::id()) . form::hidden('part', 'periods'));
# Periods list # Periods list
$period_list->periodDisplay( $period_list->periodDisplay(
@ -119,14 +166,16 @@ if (isset($period_list)) {
'<p class="col checkboxes-helpers"></p>' . '<p class="col checkboxes-helpers"></p>' .
'<p class="col right">' . __('Selected periods action:') . ' ' . '<p class="col right">' . __('Selected periods action:') . ' ' .
form::combo('action', $combo_action) . form::combo('action', My::periodsActionCombo()) .
'<input type="submit" value="' . __('ok') . '" /></p>' . '<input type="submit" value="' . __('ok') . '" /></p>' .
dcCore::app()->adminurl->getHiddenFormFields('admin.plugin.periodical', array_merge(['p' => 'periodical'], $p_filter->values(true))) . dcCore::app()->adminurl->getHiddenFormFields('admin.plugin.' . My::id(), array_merge(['p' => My::id()], $p_filter->values(true))) .
dcCore::app()->formNonce() . dcCore::app()->formNonce() .
'</div>' . '</div>' .
'</form>' '</form>'
); );
} }
dcPage::helpBlock('periodical'); dcPage::helpBlock('periodical');
echo '</body></html>'; dcPage::closeModule();
}
}

View File

@ -10,20 +10,30 @@
* @copyright Jean-Christian Denis * @copyright Jean-Christian Denis
* @copyright GPL-2.0 https://www.gnu.org/licenses/gpl-2.0.html * @copyright GPL-2.0 https://www.gnu.org/licenses/gpl-2.0.html
*/ */
if (!defined('DC_CONTEXT_ADMIN')) { declare(strict_types=1);
return null;
} namespace Dotclear\Plugin\periodical;
use ArrayObject;
use adminGenericFilter;
use adminGenericList;
use adminPostFilter;
use dcAuth;
use dcBlog;
use dcCore;
use dcPager;
use dt;
use html;
use form;
/** /**
* @ingroup DC_PLUGIN_PERIODICAL * @ingroup DC_PLUGIN_PERIODICAL
* @brief Periodical - admin pager methods. * @brief Periodical - admin pager methods.
* @since 2.6 * @since 2.6
*/ */
class adminPeriodicalList extends adminGenericList class ManageList extends adminGenericList
{ {
private $periodical = null; public function periodDisplay(adminGenericFilter $filter, string $enclose_block = ''): void
public function periodDisplay($filter, $enclose_block = '')
{ {
if ($this->rs->isEmpty()) { if ($this->rs->isEmpty()) {
if ($filter->show()) { if ($filter->show()) {
@ -32,8 +42,7 @@ class adminPeriodicalList extends adminGenericList
echo '<p><strong>' . __('No period') . '</strong></p>'; echo '<p><strong>' . __('No period') . '</strong></p>';
} }
} else { } else {
$this->periodical = new periodical(); $pager = new dcPager((int) $filter->value('page'), (int) $this->rs_count, (int) $filter->value('nb'), 10);
$pager = new dcPager((int) $filter->page, $this->rs_count, $filter->nb, 10);
$pager->var_page = 'page'; $pager->var_page = 'page';
$periods = []; $periods = [];
@ -58,7 +67,7 @@ class adminPeriodicalList extends adminGenericList
'enddt' => '<th scope="col" class="nowrap">' . __('End date') . '</th>', 'enddt' => '<th scope="col" class="nowrap">' . __('End date') . '</th>',
]); ]);
$this->userColumns('periodical', $cols); $this->userColumns(My::id(), $cols);
$html_block .= '<tr>' . implode(iterator_to_array($cols)) . '</tr>%s</table>%s</div>'; $html_block .= '<tr>' . implode(iterator_to_array($cols)) . '</tr>%s</table>%s</div>';
if ($enclose_block) { if ($enclose_block) {
@ -69,17 +78,17 @@ class adminPeriodicalList extends adminGenericList
echo $pager->getLinks() . $blocks[0]; echo $pager->getLinks() . $blocks[0];
while ($this->rs->fetch()) { while ($this->rs->fetch()) {
echo $this->periodLine(isset($periods[$this->rs->periodical_id])); echo $this->periodLine(isset($periods[(int) $this->rs->f('periodical_id')]));
} }
echo $blocks[1] . $blocks[2] . $pager->getLinks(); echo $blocks[1] . $blocks[2] . $pager->getLinks();
} }
} }
private function periodLine($checked) private function periodLine(bool $checked): string
{ {
$nb_posts = $this->periodical->getPosts(['periodical_id' => $this->rs->periodical_id], true)->f(0); $nb_posts = Utils::getPosts(['periodical_id' => $this->rs->f('periodical_id')], true)->f(0);
$url = dcCore::app()->adminurl->get('admin.plugin.periodical', ['part' => 'period', 'period_id' => $this->rs->periodical_id]); $url = dcCore::app()->adminurl->get('admin.plugin.periodical', ['part' => 'period', 'period_id' => $this->rs->f('periodical_id')]);
$name = '<a href="' . $url . '#period" title="' . __('edit period') . '">' . html::escapeHTML($this->rs->periodical_title) . '</a>'; $name = '<a href="' . $url . '#period" title="' . __('edit period') . '">' . html::escapeHTML($this->rs->periodical_title) . '</a>';
@ -87,28 +96,28 @@ class adminPeriodicalList extends adminGenericList
'<a href="' . $url . '#posts" title="' . __('view related entries') . '">' . $nb_posts . '</a>' : '<a href="' . $url . '#posts" title="' . __('view related entries') . '">' . $nb_posts . '</a>' :
'0'; '0';
$interval = in_array($this->rs->periodical_pub_int, $this->periodical->getTimesCombo()) ? $interval = in_array($this->rs->f('periodical_pub_int'), My::periodCombo()) ?
__(array_search($this->rs->periodical_pub_int, $this->periodical->getTimesCombo())) : __('Unknow frequence'); __((string) array_search($this->rs->f('periodical_pub_int'), My::periodCombo())) : __('Unknow frequence');
$cols = new ArrayObject([ $cols = new ArrayObject([
'check' => '<td class="nowrap">' . form::checkbox(['periods[]'], $this->rs->periodical_id, ['checked' => $checked]) . '</td>', 'check' => '<td class="nowrap">' . form::checkbox(['periods[]'], $this->rs->f('periodical_id'), ['checked' => $checked]) . '</td>',
'name' => '<td class="maximal">' . $name . '</td>', 'name' => '<td class="maximal">' . $name . '</td>',
'curdt' => '<td class="nowrap count">' . dt::dt2str(__('%Y-%m-%d %H:%M'), $this->rs->periodical_curdt) . '</td>', 'curdt' => '<td class="nowrap count">' . dt::dt2str(__('%Y-%m-%d %H:%M'), $this->rs->f('periodical_curdt'), dcCore::app()->auth->getInfo('user_tz')) . '</td>',
'pub_int' => '<td class="nowrap">' . $interval . '</td>', 'pub_int' => '<td class="nowrap">' . $interval . '</td>',
'pub_nb' => '<td class="nowrap count">' . $this->rs->periodical_pub_nb . '</td>', 'pub_nb' => '<td class="nowrap count">' . $this->rs->f('periodical_pub_nb') . '</td>',
'nbposts' => '<td class="nowrap count">' . $posts . '</td>', 'nbposts' => '<td class="nowrap count">' . $posts . '</td>',
'enddt' => '<td class="nowrap count">' . dt::dt2str(__('%Y-%m-%d %H:%M'), $this->rs->periodical_enddt) . '</td>', 'enddt' => '<td class="nowrap count">' . dt::dt2str(__('%Y-%m-%d %H:%M'), $this->rs->f('periodical_enddt'), dcCore::app()->auth->getInfo('user_tz')) . '</td>',
]); ]);
$this->userColumns('periodical', $cols); $this->userColumns(My::id(), $cols);
return return
'<tr class="line ' . ($nb_posts ? '' : ' offline') . '" id="p' . $this->rs->periodical_id . '">' . '<tr class="line ' . ($nb_posts ? '' : ' offline') . '" id="p' . $this->rs->f('periodical_id') . '">' .
implode(iterator_to_array($cols)) . implode(iterator_to_array($cols)) .
'</tr>'; '</tr>';
} }
public function postDisplay($filter, $base_url, $enclose_block = '') public function postDisplay(adminPostFilter $filter, string $base_url, string $enclose_block = ''): void
{ {
$echo = ''; $echo = '';
if ($this->rs->isEmpty()) { if ($this->rs->isEmpty()) {
@ -118,7 +127,7 @@ class adminPeriodicalList extends adminGenericList
echo '<p><strong>' . __('No entry') . '</strong></p>'; echo '<p><strong>' . __('No entry') . '</strong></p>';
} }
} else { } else {
$pager = new dcPager($filter->page, $this->rs_count, $filter->nb, 10); $pager = new dcPager((int) $filter->value('page'), (int) $this->rs_count, (int) $filter->value('nb'), 10);
$pager->base_url = $base_url; $pager->base_url = $base_url;
$pager->var_page = 'page'; $pager->var_page = 'page';
@ -153,7 +162,7 @@ class adminPeriodicalList extends adminGenericList
echo $pager->getLinks() . $blocks[0]; echo $pager->getLinks() . $blocks[0];
while ($this->rs->fetch()) { while ($this->rs->fetch()) {
echo $this->postLine(isset($periodical_entries[$this->rs->post_id])); echo $this->postLine(isset($periodical_entries[(int) $this->rs->f('post_id')]));
} }
$img = '<img alt="%1$s" title="%1$s" src="images/%2$s" /> %1$s'; $img = '<img alt="%1$s" title="%1$s" src="images/%2$s" /> %1$s';
@ -170,7 +179,7 @@ class adminPeriodicalList extends adminGenericList
} }
} }
private function postLine($checked) private function postLine(bool $checked): string
{ {
if (dcCore::app()->auth->check(dcCore::app()->auth->makePermissions([dcAuth::PERMISSION_CATEGORIES]), dcCore::app()->blog->id)) { if (dcCore::app()->auth->check(dcCore::app()->auth->makePermissions([dcAuth::PERMISSION_CATEGORIES]), dcCore::app()->blog->id)) {
$cat_link = '<a href="category.php?id=%s">%s</a>'; $cat_link = '<a href="category.php?id=%s">%s</a>';
@ -178,11 +187,11 @@ class adminPeriodicalList extends adminGenericList
$cat_link = '%2$s'; $cat_link = '%2$s';
} }
if ($this->rs->cat_title) { if ($this->rs->f('cat_title')) {
$cat_title = sprintf( $cat_title = sprintf(
$cat_link, $cat_link,
$this->rs->cat_id, $this->rs->f('cat_id'),
html::escapeHTML($this->rs->cat_title) html::escapeHTML($this->rs->f('cat_title'))
); );
} else { } else {
$cat_title = __('None'); $cat_title = __('None');
@ -190,35 +199,35 @@ class adminPeriodicalList extends adminGenericList
$img_status = ''; $img_status = '';
$img = '<img alt="%1$s" title="%1$s" src="images/%2$s" />'; $img = '<img alt="%1$s" title="%1$s" src="images/%2$s" />';
switch ($this->rs->post_status) { switch ((int) $this->rs->f('post_status')) {
case 1: case dcBlog::POST_PUBLISHED:
$img_status = sprintf($img, __('published'), 'check-on.png'); $img_status = sprintf($img, __('published'), 'check-on.png');
break; break;
case 0: case dcBlog::POST_UNPUBLISHED:
$img_status = sprintf($img, __('unpublished'), 'check-off.png'); $img_status = sprintf($img, __('unpublished'), 'check-off.png');
break; break;
case -1: case dcBlog::POST_SCHEDULED:
$img_status = sprintf($img, __('scheduled'), 'scheduled.png'); $img_status = sprintf($img, __('scheduled'), 'scheduled.png');
break; break;
case -2: case dcBlog::POST_PENDING:
$img_status = sprintf($img, __('pending'), 'check-wrn.png'); $img_status = sprintf($img, __('pending'), 'check-wrn.png');
break; break;
} }
$protected = ''; $protected = '';
if ($this->rs->post_password) { if ($this->rs->f('post_password')) {
$protected = sprintf($img, __('protected'), 'locker.png'); $protected = sprintf($img, __('protected'), 'locker.png');
} }
$selected = ''; $selected = '';
if ($this->rs->post_selected) { if ($this->rs->f('post_selected')) {
$selected = sprintf($img, __('selected'), 'selected.png'); $selected = sprintf($img, __('selected'), 'selected.png');
} }
@ -230,14 +239,14 @@ class adminPeriodicalList extends adminGenericList
} }
$cols = [ $cols = [
'check' => '<td class="minimal">' . form::checkbox(['periodical_entries[]'], $this->rs->post_id, ['checked' => $checked]) . '</td>', 'check' => '<td class="minimal">' . form::checkbox(['periodical_entries[]'], $this->rs->f('post_id'), ['checked' => $checked]) . '</td>',
'title' => '<td class="maximal"><a href="' . dcCore::app()->getPostAdminURL($this->rs->post_type, $this->rs->post_id) . '" ' . 'title' => '<td class="maximal"><a href="' . dcCore::app()->getPostAdminURL($this->rs->f('post_type'), $this->rs->f('post_id')) . '" ' .
'title="' . html::escapeHTML($this->rs->getURL()) . '">' . html::escapeHTML($this->rs->post_title) . '</a></td>', 'title="' . html::escapeHTML($this->rs->getURL()) . '">' . html::escapeHTML($this->rs->post_title) . '</a></td>',
'date' => '<td class="nowrap">' . dt::dt2str(__('%Y-%m-%d %H:%M'), $this->rs->post_dt) . '</td>', 'date' => '<td class="nowrap">' . dt::dt2str(__('%Y-%m-%d %H:%M'), $this->rs->f('post_dt')) . '</td>',
'category' => '<td class="nowrap">' . $cat_title . '</td>', 'category' => '<td class="nowrap">' . $cat_title . '</td>',
'author' => '<td class="nowrap">' . $this->rs->user_id . '</td>', 'author' => '<td class="nowrap">' . $this->rs->f('user_id') . '</td>',
'status' => '<td class="nowrap status">' . $img_status . ' ' . $selected . ' ' . $protected . ' ' . $attach . '</td>', 'status' => '<td class="nowrap status">' . $img_status . ' ' . $selected . ' ' . $protected . ' ' . $attach . '</td>',
'create' => '<td class="nowrap">' . dt::dt2str(__('%Y-%m-%d %H:%M'), $this->rs->post_creadt, dcCore::app()->auth->getInfo('user_tz')) . '</td>', 'create' => '<td class="nowrap">' . dt::dt2str(__('%Y-%m-%d %H:%M'), $this->rs->f('post_creadt'), dcCore::app()->auth->getInfo('user_tz')) . '</td>',
]; ];
return '<tr class="line">' . implode($cols) . '</tr>'; return '<tr class="line">' . implode($cols) . '</tr>';

View File

@ -10,315 +10,257 @@
* @copyright Jean-Christian Denis * @copyright Jean-Christian Denis
* @copyright GPL-2.0 https://www.gnu.org/licenses/gpl-2.0.html * @copyright GPL-2.0 https://www.gnu.org/licenses/gpl-2.0.html
*/ */
if (!defined('DC_CONTEXT_ADMIN')) { declare(strict_types=1);
return null;
}
dcPage::check(dcCore::app()->auth->makePermissions([dcAuth::PERMISSION_USAGE, dcAuth::PERMISSION_CONTENT_ADMIN])); namespace Dotclear\Plugin\periodical;
# Objects use adminPostFilter;
$per = new periodical(); use dcAuth;
use dcCore;
use dcNsProcess;
use dcPage;
use Exception;
use form;
use html;
use http;
# Default values /**
$action = $_POST['action'] ?? ''; * Admin page for a period
*/
class ManagePeriod extends dcNsProcess
{
public static function init(): bool
{
static::$init == defined('DC_CONTEXT_ADMIN')
&& My::phpCompliant()
&& dcCore::app()->auth->check(dcCore::app()->auth->makePermissions([
dcAuth::PERMISSION_USAGE,
dcAuth::PERMISSION_CONTENT_ADMIN,
]), dcCore::app()->blog->id)
&& ($_REQUEST['part'] ?? 'periods') === 'period';
$starting_script = ''; return static::$init;
}
# Default value for period public static function process(): bool
$period_id = null; {
$period_title = __('One post per day'); if (!static::$init) {
$period_pub_nb = 1; return false;
$period_pub_int = 'day'; }
$period_curdt = date('Y-m-d H:i', time());
$period_enddt = date('Y-m-d H:i', time() + 31536000); //one year
$bad_period_curdt = false;
$bad_period_enddt = false;
# Get period # Default values
if (!empty($_REQUEST['period_id'])) { $vars = ManageVars::init();
$rs = $per->getPeriods([
'periodical_id' => $_REQUEST['period_id'], # Get period
]); if ($vars->bad_period_id) {
if ($rs->isEmpty()) {
dcCore::app()->error->add(__('This period does not exist.')); dcCore::app()->error->add(__('This period does not exist.'));
$period_id = null;
} else {
$period_id = $rs->periodical_id;
$period_title = $rs->periodical_title;
$period_pub_nb = $rs->periodical_pub_nb;
$period_pub_int = $rs->periodical_pub_int;
$period_curdt = date('Y-m-d H:i', strtotime($rs->periodical_curdt));
$period_enddt = date('Y-m-d H:i', strtotime($rs->periodical_enddt));
} }
}
# Set period # Set period
if ($action == 'setperiod') { if ($vars->action == 'setperiod') {
# Get POST values if ($vars->bad_period_curdt || $vars->bad_period_enddt) {
if (!empty($_POST['period_title'])) { dcCore::app()->error->add(__('Invalid date'));
$period_title = $_POST['period_title'];
}
if (!empty($_POST['period_pub_nb'])) {
$period_pub_nb = abs((int) $_POST['period_pub_nb']);
}
if (!empty($_POST['period_pub_int'])
&& in_array($_POST['period_pub_int'], $per->getTimesCombo())
) {
$period_pub_int = $_POST['period_pub_int'];
}
if (!empty($_POST['period_curdt'])) {
try {
$period_curdt = strtotime($_POST['period_curdt']);
if ($period_curdt == false || $period_curdt == -1) {
$bad_period_curdt = true;
throw new Exception(__('Invalid date'));
}
$period_curdt = date('Y-m-d H:i', $period_curdt);
} catch (Exception $e) {
dcCore::app()->error->add($e->getMessage());
}
}
if (!empty($_POST['period_enddt'])) {
try {
$period_enddt = strtotime($_POST['period_enddt']);
if ($period_enddt == false || $period_enddt == -1) {
$bad_period_enddt = true;
throw new Exception(__('Invalid date'));
}
$period_enddt = date('Y-m-d H:i', $period_enddt);
} catch (Exception $e) {
dcCore::app()->error->add($e->getMessage());
}
} }
# Check period title and dates # Check period title and dates
$old_titles = $per->getPeriods([ $old_titles = Utils::getPeriods([
'periodical_title' => $period_title, 'periodical_title' => $vars->period_title,
]); ]);
if (!$old_titles->isEmpty()) { if (!$old_titles->isEmpty()) {
while ($old_titles->fetch()) { while ($old_titles->fetch()) {
if (!$period_id || $old_titles->periodical_id != $period_id) { if (!$vars->period_id || $old_titles->f('periodical_id') != $vars->period_id) {
dcCore::app()->error->add(__('Period title is already taken')); dcCore::app()->error->add(__('Period title is already taken'));
} }
} }
} }
if (empty($period_title)) { if (empty($vars->period_title)) {
dcCore::app()->error->add(__('Period title is required')); dcCore::app()->error->add(__('Period title is required'));
} }
if (strtotime($period_curdt) > strtotime($period_enddt)) { if (strtotime($vars->period_curdt) > strtotime($vars->period_enddt)) {
dcCore::app()->error->add(__('Start date must be older than end date')); dcCore::app()->error->add(__('Start date must be older than end date'));
} }
# If no error, set period # If no error, set period
if (!dcCore::app()->error->flag()) { if (!dcCore::app()->error->flag()) {
$cur = $per->openCursor(); $cur = Utils::openCursor();
$cur->periodical_title = $period_title; $cur->setField('periodical_title', $vars->period_title);
$cur->periodical_curdt = $period_curdt; $cur->setField('periodical_curdt', $vars->period_curdt);
$cur->periodical_enddt = $period_enddt; $cur->setField('periodical_enddt', $vars->period_enddt);
$cur->periodical_pub_int = $period_pub_int; $cur->setField('periodical_pub_int', $vars->period_pub_int);
$cur->periodical_pub_nb = $period_pub_nb; $cur->setField('periodical_pub_nb', $vars->period_pub_nb);
# Update period # Update period
if ($period_id) { if ($vars->period_id) {
$per->updPeriod($period_id, $cur); Utils::updPeriod($vars->period_id, $cur);
dcAdminNotices::addSuccessNotice( self::redirect($vars->redir, $vars->period_id, '#period', __('Period successfully updated.'));
__('Period successfully updated.')
);
# Create period # Create period
} else { } else {
$period_id = $per->addPeriod($cur); $period_id = Utils::addPeriod($cur);
dcAdminNotices::addSuccessNotice( self::redirect($vars->redir, $period_id, '#period', __('Period successfully created.'));
__('Period successfully created.') }
);
}
if (!empty($_POST['redir'])) {
http::redirect($_POST['redir']);
} else {
dcCore::app()->adminurl->redirect('admin.plugin.periodical', ['part' => 'period', 'period_id' => $period_id], '#period');
} }
} }
}
# Actions on related posts # Actions on related posts
if (!dcCore::app()->error->flag() && $period_id && $action && !empty($_POST['periodical_entries'])) { if (!dcCore::app()->error->flag() && $vars->period_id && $vars->action && !empty($vars->entries)) {
# Publish posts # Publish posts
if ($action == 'publish') { if ($vars->action == 'publish') {
try { try {
foreach ($_POST['periodical_entries'] as $id) { foreach ($vars->entries as $id) {
$id = (int) $id;
dcCore::app()->blog->updPostStatus($id, 1); dcCore::app()->blog->updPostStatus($id, 1);
$per->delPost($id); Utils::delPost($id);
} }
dcAdminNotices::addSuccessNotice( self::redirect($vars->redir, $vars->period_id, '#posts', __('Entries successfully published.'));
__('Entries successfully published.')
);
if (!empty($_POST['redir'])) {
http::redirect($_POST['redir']);
} else {
dcCore::app()->adminurl->redirect('admin.plugin.periodical', ['part' => 'period', 'period_id' => $period_id], '#posts');
}
} catch (Exception $e) { } catch (Exception $e) {
dcCore::app()->error->add($e->getMessage()); dcCore::app()->error->add($e->getMessage());
} }
} }
# Unpublish posts # Unpublish posts
if ($action == 'unpublish') { if ($vars->action == 'unpublish') {
try { try {
foreach ($_POST['periodical_entries'] as $id) { foreach ($vars->entries as $id) {
$id = (int) $id;
dcCore::app()->blog->updPostStatus($id, 0); dcCore::app()->blog->updPostStatus($id, 0);
$per->delPost($id); Utils::delPost($id);
} }
dcAdminNotices::addSuccessNotice( self::redirect($vars->redir, $vars->period_id, '#posts', __('Entries successfully unpublished.'));
__('Entries successfully unpublished.')
);
if (!empty($_POST['redir'])) {
http::redirect($_POST['redir']);
} else {
dcCore::app()->adminurl->redirect('admin.plugin.periodical', ['part' => 'period', 'period_id' => $period_id], '#posts');
}
} catch (Exception $e) { } catch (Exception $e) {
dcCore::app()->error->add($e->getMessage()); dcCore::app()->error->add($e->getMessage());
} }
} }
# Remove posts from periodical # Remove posts from periodical
if ($action == 'remove_post_periodical') { if ($vars->action == 'remove_post_periodical') {
try { try {
foreach ($_POST['periodical_entries'] as $id) { foreach ($vars->entries as $id) {
$id = (int) $id; Utils::delPost($id);
$per->delPost($id);
} }
dcAdminNotices::addSuccessNotice( self::redirect($vars->redir, $vars->period_id, '#posts', __('Entries successfully removed.'));
__('Entries successfully removed.')
);
if (!empty($_POST['redir'])) {
http::redirect($_POST['redir']);
} else {
dcCore::app()->adminurl->redirect('admin.plugin.periodical', ['part' => 'period', 'period_id' => $period_id], '#posts');
}
} catch (Exception $e) { } catch (Exception $e) {
dcCore::app()->error->add($e->getMessage()); dcCore::app()->error->add($e->getMessage());
} }
} }
} }
# Prepare combos for posts list return true;
if ($period_id) { }
/**
* Renders the page.
*/
public static function render(): void
{
if (!static::$init) {
return;
}
# Default values
$vars = ManageVars::init();
$starting_script = '';
# Prepare combos for posts list
if ($vars->period_id > 0) {
# Filters # Filters
$post_filter = new adminPostFilter(); $post_filter = new adminPostFilter();
$post_filter->add('part', 'period'); $post_filter->add('part', 'period');
$params = $post_filter->params(); $params = $post_filter->params();
$params['periodical_id'] = $period_id; $params['periodical_id'] = $vars->period_id;
$params['no_content'] = true; $params['no_content'] = true;
# Get posts # Get posts
try { try {
$posts = $per->getPosts($params); $posts = Utils::getPosts($params);
$counter = $per->getPosts($params, true); $counter = Utils::getPosts($params, true);
$post_list = new adminPeriodicalList(dcCore::app(), $posts, $counter->f(0)); $post_list = new ManageList(dcCore::app(), $posts, $counter->f(0));
} catch (Exception $e) { } catch (Exception $e) {
dcCore::app()->error->add($e->getMessage()); dcCore::app()->error->add($e->getMessage());
} }
$starting_script = dcPage::jsLoad(dcPage::getPF('periodical/js/checkbox.js')) . $starting_script = dcPage::jsModuleLoad(My::id() . '/js/checkbox.js') .
$post_filter->js(dcCore::app()->adminurl->get('admin.plugin.periodical', ['part' => 'period', 'period_id' => $period_id], '&') . '#posts'); $post_filter->js(dcCore::app()->adminurl->get('admin.plugin.' . My::id(), ['part' => 'period', 'period_id' => $vars->period_id], '&') . '#posts');
} }
# Display # Display
echo ' dcPage::openModule(
<html><head><title>' . __('Periodical') . '</title>' . My::name(),
dcPage::jsLoad(dcPage::getPF('periodical/js/dates.js')) . dcPage::jsModuleLoad(My::id() . '/js/dates.js') .
$starting_script . $starting_script .
dcPage::jsDatePicker() . dcPage::jsDatePicker() .
dcPage::jsPageTabs() . dcPage::jsPageTabs()
'</head> );
<body>';
echo echo
dcPage::breadcrumb([ dcPage::breadcrumb([
__('Plugins') => '', __('Plugins') => '',
__('Periodical') => dcCore::app()->admin->getPageURL() . '&amp;part=periods', My::name() => dcCore::app()->admin->getPageURL() . '&amp;part=periods',
(null === $period_id ? __('New period') : __('Edit period')) => '', (null === $vars->period_id ? __('New period') : __('Edit period')) => '',
]) . ]) .
dcPage::notices(); dcPage::notices();
# Period form # Period form
echo ' echo '
<div id="period"><h3>' . (null === $period_id ? __('New period') : __('Edit period')) . '</h3> <div id="period"><h3>' . (null === $vars->period_id ? __('New period') : __('Edit period')) . '</h3>
<form method="post" action="' . dcCore::app()->admin->getPageURL() . '"> <form method="post" action="' . dcCore::app()->admin->getPageURL() . '">
<p><label for="period_title">' . __('Title:') . '</label>' . <p><label for="period_title">' . __('Title:') . '</label>' .
form::field('period_title', 60, 255, html::escapeHTML($period_title), 'maximal') . '</p> form::field('period_title', 60, 255, html::escapeHTML($vars->period_title), 'maximal') . '</p>
<div class="two-boxes"> <div class="two-boxes">
<p><label for="period_curdt">' . __('Next update:') . '</label>' . <p><label for="period_curdt">' . __('Next update:') . '</label>' .
form::datetime('period_curdt', [ form::datetime('period_curdt', [
'default' => html::escapeHTML(dt::str('%Y-%m-%dT%H:%M', strtotime($period_curdt))), 'default' => html::escapeHTML(Dater::toUser($vars->period_curdt)),
'class' => ($bad_period_curdt ? 'invalid' : ''), 'class' => ($vars->bad_period_curdt ? 'invalid' : ''),
]) . '</p> ]) . '</p>
<p><label for="period_enddt">' . __('End date:') . '</label>' . <p><label for="period_enddt">' . __('End date:') . '</label>' .
form::datetime('period_enddt', [ form::datetime('period_enddt', [
'default' => html::escapeHTML(dt::str('%Y-%m-%dT%H:%M', strtotime($period_enddt))), 'default' => html::escapeHTML(Dater::toUser($vars->period_enddt)),
'class' => ($bad_period_enddt ? 'invalid' : ''), 'class' => ($vars->bad_period_enddt ? 'invalid' : ''),
]) . '</p> ]) . '</p>
</div><div class="two-boxes"> </div><div class="two-boxes">
<p><label for="period_pub_int">' . __('Publication frequency:') . '</label>' . <p><label for="period_pub_int">' . __('Publication frequency:') . '</label>' .
form::combo('period_pub_int', $per->getTimesCombo(), $period_pub_int) . '</p> form::combo('period_pub_int', My::periodCombo(), $vars->period_pub_int) . '</p>
<p><label for="period_pub_nb">' . __('Number of entries to publish every time:') . '</label>' . <p><label for="period_pub_nb">' . __('Number of entries to publish every time:') . '</label>' .
form::number('period_pub_nb', ['min' => 1, 'max' => 20, 'default' => $period_pub_nb]) . '</p> form::number('period_pub_nb', ['min' => 1, 'max' => 20, 'default' => $vars->period_pub_nb]) . '</p>
</div> </div>
<div class="clear"> <div class="clear">
<p><input type="submit" name="save" value="' . __('Save') . '" />' . <p><input type="submit" name="save" value="' . __('Save') . '" />' .
dcCore::app()->formNonce() . dcCore::app()->formNonce() .
form::hidden(['action'], 'setperiod') . form::hidden(['action'], 'setperiod') .
form::hidden(['period_id'], $period_id) . form::hidden(['period_id'], $vars->period_id) .
form::hidden(['part'], 'period') . ' form::hidden(['part'], 'period') . '
</p> </p>
</div> </div>
</form> </form>
</div>'; </div>';
if ($period_id && isset($post_filter) && isset($post_list) && !dcCore::app()->error->flag()) {
# Actions combo box
$combo_action = [];
$combo_action[__('Entries')][__('Publish')] = 'publish';
$combo_action[__('Entries')][__('Unpublish')] = 'unpublish';
$combo_action[__('Periodical')][__('Remove from periodical')] = 'remove_post_periodical';
if ($vars->period_id && isset($post_filter) && isset($post_list) && !dcCore::app()->error->flag()) {
$base_url = dcCore::app()->admin->getPageURL() . $base_url = dcCore::app()->admin->getPageURL() .
'&amp;period_id=' . $period_id . '&amp;period_id=' . $vars->period_id .
'&amp;part=period' . '&amp;part=period' .
'&amp;user_id=' . $post_filter->user_id . '&amp;user_id=' . $post_filter->value('user_id', '') .
'&amp;cat_id=' . $post_filter->cat_id . '&amp;cat_id=' . $post_filter->value('cat_id', '') .
'&amp;status=' . $post_filter->status . '&amp;status=' . $post_filter->value('status', '') .
'&amp;selected=' . $post_filter->selected . '&amp;selected=' . $post_filter->value('selected', '') .
'&amp;attachment=' . $post_filter->attachment . '&amp;attachment=' . $post_filter->value('attachment', '') .
'&amp;month=' . $post_filter->month . '&amp;month=' . $post_filter->value('month', '') .
'&amp;lang=' . $post_filter->lang . '&amp;lang=' . $post_filter->value('lang', '') .
'&amp;sortby=' . $post_filter->sortby . '&amp;sortby=' . $post_filter->value('sortby', '') .
'&amp;order=' . $post_filter->order . '&amp;order=' . $post_filter->value('order', '') .
'&amp;nb=' . $post_filter->nb . '&amp;nb=' . $post_filter->value('nb', '') .
'&amp;page=%s' . '&amp;page=%s' .
'#posts'; '#posts';
@ -329,7 +271,7 @@ if ($period_id && isset($post_filter) && isset($post_list) && !dcCore::app()->er
$post_filter->display( $post_filter->display(
['admin.plugin.periodical', '#posts'], ['admin.plugin.periodical', '#posts'],
dcCore::app()->adminurl->getHiddenFormFields('admin.plugin.periodical', [ dcCore::app()->adminurl->getHiddenFormFields('admin.plugin.periodical', [
'period_id' => $period_id, 'period_id' => $vars->period_id,
'part' => 'period', 'part' => 'period',
]) ])
); );
@ -346,11 +288,11 @@ if ($period_id && isset($post_filter) && isset($post_list) && !dcCore::app()->er
'<p class="col checkboxes-helpers"></p>' . '<p class="col checkboxes-helpers"></p>' .
'<p class="col right">' . __('Selected entries action:') . ' ' . '<p class="col right">' . __('Selected entries action:') . ' ' .
form::combo('action', $combo_action) . form::combo('action', My::entriesActionsCombo()) .
'<input type="submit" value="' . __('ok') . '" /></p>' . '<input type="submit" value="' . __('ok') . '" /></p>' .
dcCore::app()->adminurl->getHiddenFormFields('admin.plugin.periodical', array_merge($post_filter->values(), [ dcCore::app()->adminurl->getHiddenFormFields('admin.plugin.periodical', array_merge($post_filter->values(), [
'period_id' => $period_id, 'period_id' => $vars->period_id,
'redir' => sprintf($base_url, $post_filter->page), 'redir' => sprintf($base_url, $post_filter->value('page', '')),
])) . ])) .
dcCore::app()->formNonce() . dcCore::app()->formNonce() .
'</div>' . '</div>' .
@ -359,8 +301,21 @@ if ($period_id && isset($post_filter) && isset($post_list) && !dcCore::app()->er
echo echo
'</div>'; '</div>';
}
dcPage::helpBlock('periodical');
dcPage::closeModule();
}
private static function redirect(string $redir, int $id, string $tab, string $msg): void
{
dcPage::addSuccessNotice($msg);
if (!empty($redir)) {
http::redirect($redir);
} else {
dcCore::app()->adminurl->redirect('admin.plugin.' . My::id(), ['part' => 'period', 'period_id' => $id], $tab);
}
}
} }
dcPage::helpBlock('periodical');
echo '</body></html>';

140
src/ManageVars.php 100644
View File

@ -0,0 +1,140 @@
<?php
/**
* @brief periodical, a plugin for Dotclear 2
*
* @package Dotclear
* @subpackage Plugin
*
* @author Jean-Christian Denis and contributors
*
* @copyright Jean-Christian Denis
* @copyright GPL-2.0 https://www.gnu.org/licenses/gpl-2.0.html
*/
declare(strict_types=1);
namespace Dotclear\Plugin\periodical;
/**
* Admin page vars
*/
class ManageVars
{
/**
* @var ManageVars self instance
*/
private static $container;
public readonly string $action;
public readonly string $redir;
public readonly array $periods;
public readonly array $entries;
public readonly ?int $period_id;
public readonly string $period_title;
public readonly int $period_pub_nb;
public readonly string $period_pub_int;
public readonly string $period_curdt;
public readonly string $period_enddt;
public readonly bool $bad_period_id;
public readonly bool $bad_period_curdt;
public readonly bool $bad_period_enddt;
protected function __construct()
{
$this->action = $_POST['action'] ?? '';
$this->redir = $_POST['redir'] ?? '';
// periods
$periods = $_POST['periods'] ?? [];
$periods = is_array($periods) ? $periods : [];
array_walk($periods, function (&$v) { if ($v !== null) { $v = (int) $v; } });
$this->periods = $periods;
// entries
$entries = $_POST['periodical_entries'] ?? [];
$entries = is_array($entries) ? $entries : [];
array_walk($entries, function (&$v) {
if ($v !== null) {
$v = (int) $v;
}
});
$this->entries = $entries;
// period values from default
$period_id = null;
$period_title = __('One post per day');
$period_pub_nb = 1;
$period_pub_int = 'day';
$period_curdt = Dater::toDate('now', 'Y-m-d H:i:00');
$period_enddt = Dater::toDate('+1 year', 'Y-m-d H:i:00');
$bad_period_id = false;
$bad_period_curdt = false;
$bad_period_enddt = false;
# period values from record
if (!empty($_REQUEST['period_id'])) {
$rs = Utils::getPeriods([
'periodical_id' => $_REQUEST['period_id'],
]);
if (!$rs->isEmpty()) {
$period_id = (int) $rs->f('periodical_id');
$period_title = $rs->f('periodical_title');
$period_pub_nb = (int) $rs->f('periodical_pub_nb');
$period_pub_int = $rs->f('periodical_pub_int');
$period_curdt = Dater::toDate($rs->f('periodical_curdt'), 'Y-m-d H:i:00');
$period_enddt = Dater::toDate($rs->f('periodical_enddt'), 'Y-m-d H:i:00');
} else {
$bad_period_id = true;
}
}
# period values from POST
if (!empty($_POST['period_title'])) {
$period_title = $_POST['period_title'];
}
if (!empty($_POST['period_pub_nb'])) {
$period_pub_nb = abs((int) $_POST['period_pub_nb']);
}
if (!empty($_POST['period_pub_int'])
&& in_array($_POST['period_pub_int'], My::periodCombo())
) {
$period_pub_int = $_POST['period_pub_int'];
}
if (!empty($_POST['period_curdt'])) {
$tmp_period_curdt = Dater::fromUser($_POST['period_curdt'], 'Y-m-d H:i:00');
if (empty($tmp_period_curdt)) {
$bad_period_curdt = true;
} else {
$period_curdt = $tmp_period_curdt;
}
}
if (!empty($_POST['period_enddt'])) {
$tmp_period_enddt = Dater::fromUser($_POST['period_enddt'], 'Y-m-d H:i:00');
if (empty($tmp_period_enddt)) {
$bad_period_enddt = true;
} else {
$period_enddt = $tmp_period_enddt;
}
}
// set period values
$this->period_id = $period_id;
$this->period_title = $period_title;
$this->period_pub_nb = $period_pub_nb;
$this->period_pub_int = $period_pub_int;
$this->period_curdt = $period_curdt;
$this->period_enddt = $period_enddt;
$this->bad_period_id = $bad_period_id;
$this->bad_period_curdt = $bad_period_curdt;
$this->bad_period_enddt = $bad_period_enddt;
}
public static function init(): ManageVars
{
if (!(self::$container instanceof self)) {
self::$container = new self();
}
return self::$container;
}
}

109
src/My.php 100644
View File

@ -0,0 +1,109 @@
<?php
/**
* @brief periodical, a plugin for Dotclear 2
*
* @package Dotclear
* @subpackage Plugin
*
* @author Jean-Christian Denis and contributors
*
* @copyright Jean-Christian Denis
* @copyright GPL-2.0 https://www.gnu.org/licenses/gpl-2.0.html
*/
declare(strict_types=1);
namespace Dotclear\Plugin\periodical;
use dcCore;
/**
* Plugin def
*/
class My
{
/** @var string Required php version */
public const PHP_MIN = '8.1';
/** @var string This plugin table name */
public const TABLE_NAME = 'periodical';
/** @var string This plugin meta type */
public const META_TYPE = 'periodical';
/**
* This module id
*/
public static function id(): string
{
return basename(dirname(__DIR__));
}
/**
* This module name
*/
public static function name(): string
{
return __((string) dcCore::app()->plugins->moduleInfo(self::id(), 'name'));
}
/**
* Check php version
*/
public static function phpCompliant(): bool
{
return version_compare(phpversion(), self::PHP_MIN, '>=');
}
/**
* Periods action combo
*/
public static function periodsActionCombo(): array
{
return [
__('empty periods') => 'emptyperiods',
__('delete periods') => 'deleteperiods',
];
}
/**
* Period entries action combo
*/
public static function entriesActionsCombo(): array
{
return [
__('Entries') => [
__('Publish') => 'publish',
__('Unpublish') => 'unpublish',
],
__('Periodical') => [
__('Remove from periodical') => 'remove_post_periodical',
],
];
}
/**
* Periods sortby combo
*/
public static function sortbyCombo(): array
{
return [
__('Next update') => 'periodical_curdt',
__('End date') => 'periodical_enddt',
__('Frequence') => 'periodical_pub_int',
];
}
/**
* Period combo
*/
public static function periodCombo(): array
{
return [
__('Hourly') => 'hour',
__('twice a day') => 'halfday',
__('Daily') => 'day',
__('Weekly') => 'week',
__('Monthly') => 'month',
];
}
}

View File

@ -10,32 +10,56 @@
* @copyright Jean-Christian Denis * @copyright Jean-Christian Denis
* @copyright GPL-2.0 https://www.gnu.org/licenses/gpl-2.0.html * @copyright GPL-2.0 https://www.gnu.org/licenses/gpl-2.0.html
*/ */
if (!defined('DC_RC_PATH')) { declare(strict_types=1);
return;
}
class periodical namespace Dotclear\Plugin\periodical;
use cursor;
use dcAuth;
use dcBlog;
use dcCore;
use dcMeta;
use dcRecord;
use Exception;
use files;
use path;
/**
* Manage records
*/
class Utils
{ {
public $con; /** @var null|resource Lock update process */
private static $lock = null;
protected $table; /**
protected $blog; * Get escaped blog id
private $lock = null; */
private static function blog(): string
public function __construct()
{ {
$this->con = dcCore::app()->con; return dcCore::app()->con->escapeStr(dcCore::app()->blog->id);
$this->table = dcCore::app()->con->escape(dcCore::app()->prefix . initPeriodical::PERIOD_TABLE_NAME);
$this->blog = dcCore::app()->con->escape(dcCore::app()->blog->id);
} }
public function openCursor() /**
* Get escaped periodical full table name
*/
private static function table(): string
{ {
return $this->con->openCursor($this->table); return dcCore::app()->con->escapeStr(dcCore::app()->prefix . My::TABLE_NAME);
} }
# Get periods /**
public function getPeriods($params = [], $count_only = false) * Get periodical table cursor
*/
public static function openCursor(): cursor
{
return dcCore::app()->con->openCursor(dcCore::app()->prefix . My::TABLE_NAME);
}
/**
* Get periods
*/
public static function getPeriods(array $params = [], bool $count_only = false): dcRecord
{ {
if ($count_only) { if ($count_only) {
$q = 'SELECT count(T.periodical_id) '; $q = 'SELECT count(T.periodical_id) ';
@ -45,125 +69,123 @@ class periodical
if (!empty($params['columns']) && is_array($params['columns'])) { if (!empty($params['columns']) && is_array($params['columns'])) {
$q .= implode(', ', $params['columns']) . ', '; $q .= implode(', ', $params['columns']) . ', ';
} }
$q .= 'T.periodical_title, T.periodical_tz, ' . $q .= 'T.periodical_title, ' .
'T.periodical_curdt, T.periodical_enddt, ' . 'T.periodical_curdt, T.periodical_enddt, ' .
'T.periodical_pub_int, T.periodical_pub_nb '; 'T.periodical_pub_int, T.periodical_pub_nb ';
} }
$q .= 'FROM ' . $this->table . ' T '; $q .= 'FROM ' . self::table() . ' T ';
if (!empty($params['from'])) { if (!empty($params['from'])) {
$q .= $params['from'] . ' '; $q .= $params['from'] . ' ';
} }
$q .= "WHERE T.blog_id = '" . $this->blog . "' "; $q .= "WHERE T.blog_id = '" . self::blog() . "' ";
if (isset($params['periodical_type'])) { if (isset($params['periodical_type'])) {
if (is_array($params['periodical_type']) && !empty($params['periodical_type'])) { if (is_array($params['periodical_type']) && !empty($params['periodical_type'])) {
$q .= 'AND T.periodical_type ' . $this->con->in($params['periodical_type']); $q .= 'AND T.periodical_type ' . dcCore::app()->con->in($params['periodical_type']);
} elseif ($params['periodical_type'] != '') { } elseif ($params['periodical_type'] != '') {
$q .= "AND T.periodical_type = '" . $this->con->escape($params['periodical_type']) . "' "; $q .= "AND T.periodical_type = '" . dcCore::app()->con->escapeStr($params['periodical_type']) . "' ";
} }
} else { } else {
$q .= "AND T.periodical_type = 'post' "; $q .= "AND T.periodical_type = 'post' ";
} }
if (!empty($params['periodical_id'])) { if (!empty($params['periodical_id'])) {
if (is_array($params['periodical_id'])) { if (is_array($params['periodical_id'])) {
array_walk($params['periodical_id'], create_function('&$v,$k', 'if($v!==null){$v=(integer)$v;}')); array_walk($params['periodical_id'], function ($v) { if ($v !== null) { $v = (int) $v; } });
} else { } else {
$params['periodical_id'] = [(int) $params['periodical_id']]; $params['periodical_id'] = [(int) $params['periodical_id']];
} }
$q .= 'AND T.periodical_id ' . $this->con->in($params['periodical_id']); $q .= 'AND T.periodical_id ' . dcCore::app()->con->in($params['periodical_id']);
} }
if (!empty($params['periodical_title'])) { if (!empty($params['periodical_title'])) {
$q .= "AND T.periodical_title = '" . $this->con->escape($params['periodical_title']) . "' "; $q .= "AND T.periodical_title = '" . dcCore::app()->con->escapeStr($params['periodical_title']) . "' ";
} }
if (!empty($params['sql'])) { if (!empty($params['sql'])) {
$q .= $params['sql'] . ' '; $q .= $params['sql'] . ' ';
} }
if (!$count_only) { if (!$count_only) {
if (!empty($params['order'])) { if (!empty($params['order'])) {
$q .= 'ORDER BY ' . $this->con->escape($params['order']) . ' '; $q .= 'ORDER BY ' . dcCore::app()->con->escapeStr($params['order']) . ' ';
} else { } else {
$q .= 'ORDER BY T.periodical_id ASC '; $q .= 'ORDER BY T.periodical_id ASC ';
} }
} }
if (!$count_only && !empty($params['limit'])) { if (!$count_only && !empty($params['limit'])) {
$q .= $this->con->limit($params['limit']); $q .= dcCore::app()->con->limit($params['limit']);
}
$rs = $this->con->select($q);
//$rs->core = dcCore::app();
//$rs->periodical = $this;
return $rs;
} }
public function addPeriod($cur) return new dcRecord(dcCore::app()->con->select($q));
}
/**
* Add a period
*/
public static function addPeriod(cursor $cur): int
{ {
$this->con->writeLock($this->table); dcCore::app()->con->writeLock(self::table());
try { try {
$id = $this->con->select( $id = dcCore::app()->con->select(
'SELECT MAX(periodical_id) FROM ' . $this->table 'SELECT MAX(periodical_id) FROM ' . self::table()
)->f(0) + 1; )->f(0) + 1;
$cur->periodical_id = $id; $cur->setField('periodical_id', $id);
$cur->blog_id = $this->blog; $cur->setField('blog_id', self::blog());
$cur->periodical_type = 'post'; $cur->setField('periodical_type', 'post');
$cur->periodical_tz = dcCore::app()->auth->getInfo('user_tz');
$cur->insert(); $cur->insert();
$this->con->unlock(); dcCore::app()->con->unlock();
} catch (Exception $e) { } catch (Exception $e) {
$this->con->unlock(); dcCore::app()->con->unlock();
throw $e; throw $e;
} }
return $cur->periodical_id; return (int) $cur->getField('periodical_id');
} }
public function updPeriod($period_id, $cur) /**
* Update a period
*/
public static function updPeriod(int $period_id, cursor $cur): void
{ {
$period_id = (int) $period_id;
if ($cur->periodical_tz == ''
&& ($cur->periodical_curdt != '' || $cur->periodical_enddt != '')) {
$cur->periodical_tz = dcCore::app()->auth->getInfo('user_tz');
}
$cur->update( $cur->update(
"WHERE blog_id = '" . $this->blog . "' " . "WHERE blog_id = '" . self::blog() . "' " .
'AND periodical_id = ' . $period_id . ' ' 'AND periodical_id = ' . $period_id . ' '
); );
} }
# Delete a period /**
public function delPeriod($period_id) * Delete a period
*/
public static function delPeriod(int $period_id): void
{ {
$period_id = (int) $period_id;
$params = []; $params = [];
$params['periodical_id'] = $period_id; $params['periodical_id'] = $period_id;
$params['post_status'] = ''; $params['post_status'] = '';
$rs = $this->getPosts($params); $rs = self::getPosts($params);
if (!$rs->isEmpty()) { if (!$rs->isEmpty()) {
throw new Exception('Periodical is not empty'); throw new Exception('Periodical is not empty');
} }
$this->con->execute( dcCore::app()->con->execute(
'DELETE FROM ' . $this->table . ' ' . 'DELETE FROM ' . self::table() . ' ' .
"WHERE blog_id = '" . $this->blog . "' " . "WHERE blog_id = '" . self::blog() . "' " .
'AND periodical_id = ' . $period_id . ' ' 'AND periodical_id = ' . $period_id . ' '
); );
} }
# Remove all posts related to a period /**
public function delPeriodPosts($period_id) * Remove all posts related to a period
*/
public static function delPeriodPosts(int $period_id): void
{ {
$params = []; $params = [];
$params['post_status'] = ''; $params['post_status'] = '';
$params['periodical_id'] = (int) $period_id; $params['periodical_id'] = $period_id;
$rs = $this->getPosts($params); $rs = self::getPosts($params);
if ($rs->isEmpty()) { if ($rs->isEmpty()) {
return; return;
@ -171,22 +193,24 @@ class periodical
$ids = []; $ids = [];
while ($rs->fetch()) { while ($rs->fetch()) {
$ids[] = $rs->post_id; $ids[] = $rs->f('post_id');
} }
if (empty($ids)) { if (empty($ids)) {
return; return;
} }
$this->con->execute( dcCore::app()->con->execute(
'DELETE FROM ' . dcCore::app()->prefix . dcMeta::META_TABLE_NAME . ' ' . 'DELETE FROM ' . dcCore::app()->prefix . dcMeta::META_TABLE_NAME . ' ' .
"WHERE meta_type = 'periodical' " . "WHERE meta_type = '" . My::META_TYPE . "' " .
'AND post_id ' . $this->con->in($ids) 'AND post_id ' . dcCore::app()->con->in($ids)
); );
} }
# Get posts related to periods /**
public function getPosts($params = [], $count_only = false) * Get posts related to periods
*/
public static function getPosts(array $params = [], bool $count_only = false): dcRecord
{ {
if (!isset($params['columns'])) { if (!isset($params['columns'])) {
$params['columns'] = []; $params['columns'] = [];
@ -204,25 +228,28 @@ class periodical
$params['columns'][] = 'T.periodical_id'; $params['columns'][] = 'T.periodical_id';
$params['columns'][] = 'T.periodical_title'; $params['columns'][] = 'T.periodical_title';
$params['columns'][] = 'T.periodical_type'; $params['columns'][] = 'T.periodical_type';
$params['columns'][] = 'T.periodical_tz';
$params['columns'][] = 'T.periodical_curdt'; $params['columns'][] = 'T.periodical_curdt';
$params['columns'][] = 'T.periodical_enddt'; $params['columns'][] = 'T.periodical_enddt';
$params['columns'][] = 'T.periodical_pub_int'; $params['columns'][] = 'T.periodical_pub_int';
$params['columns'][] = 'T.periodical_pub_nb'; $params['columns'][] = 'T.periodical_pub_nb';
$params['join'] .= 'LEFT JOIN ' . dcCore::app()->prefix . dcMeta::META_TABLE_NAME . ' R ON P.post_id = R.post_id '; $params['join'] .= 'LEFT JOIN ' . dcCore::app()->prefix . dcMeta::META_TABLE_NAME . ' R ON P.post_id = R.post_id ';
$params['join'] .= 'LEFT JOIN ' . $this->table . ' T ON CAST(T.periodical_id as char) = CAST(R.meta_id as char) '; $params['join'] .= 'LEFT JOIN ' . self::table() . ' T ON CAST(T.periodical_id as char) = CAST(R.meta_id as char) ';
$params['sql'] .= "AND R.meta_type = 'periodical' "; $params['sql'] .= "AND R.meta_type = '" . My::META_TYPE . "' ";
$params['sql'] .= "AND T.periodical_type = 'post' "; $params['sql'] .= "AND T.periodical_type = 'post' ";
if (!empty($params['periodical_id'])) { if (!empty($params['periodical_id'])) {
if (is_array($params['periodical_id'])) { if (is_array($params['periodical_id'])) {
array_walk($params['periodical_id'], function ($v) { if ($v !== null) { $v = (int) $v; } }); array_walk($params['periodical_id'], function ($v) {
if ($v !== null) {
$v = (int) $v;
}
});
} else { } else {
$params['periodical_id'] = [(int) $params['periodical_id']]; $params['periodical_id'] = [(int) $params['periodical_id']];
} }
$params['sql'] .= 'AND T.periodical_id ' . $this->con->in($params['periodical_id']); $params['sql'] .= 'AND T.periodical_id ' . dcCore::app()->con->in($params['periodical_id']);
unset($params['periodical_id']); unset($params['periodical_id']);
} }
if (dcCore::app()->auth->check(dcCore::app()->auth->makePermissions([dcAuth::PERMISSION_ADMIN]), dcCore::app()->blog->id)) { if (dcCore::app()->auth->check(dcCore::app()->auth->makePermissions([dcAuth::PERMISSION_ADMIN]), dcCore::app()->blog->id)) {
@ -233,67 +260,63 @@ class periodical
unset($params['post_status']); unset($params['post_status']);
} }
} else { } else {
$params['sql'] .= 'AND P.post_status = -2 '; $params['sql'] .= 'AND P.post_status = ' . dcBlog::POST_PENDING . ' ';
} }
$rs = dcCore::app()->blog->getPosts($params, $count_only); return dcCore::app()->blog->getPosts($params, $count_only);
$rs->periodical = $this;
return $rs;
} }
# Add post to periodical /**
public function addPost($period_id, $post_id) * Add post to a period
*/
public static function addPost(int $period_id, int $post_id): void
{ {
$period_id = (int) $period_id;
$post_id = (int) $post_id;
# Check if exists # Check if exists
$rs = $this->getPosts(['post_id' => $post_id, 'periodical_id' => $period_id]); $rs = self::getPosts(['post_id' => $post_id, 'periodical_id' => $period_id]);
if (!$rs->isEmpty()) { if (!$rs->isEmpty()) {
return; return;
} }
$cur = $this->con->openCursor(dcCore::app()->prefix . dcMeta::META_TABLE_NAME); $cur = dcCore::app()->con->openCursor(dcCore::app()->prefix . dcMeta::META_TABLE_NAME);
$this->con->writeLock(dcCore::app()->prefix . dcMeta::META_TABLE_NAME); dcCore::app()->con->writeLock(dcCore::app()->prefix . dcMeta::META_TABLE_NAME);
try { try {
$cur->post_id = $post_id; $cur->setField('post_id', $post_id);
$cur->meta_id = $period_id; $cur->setField('meta_id', $period_id);
$cur->meta_type = 'periodical'; $cur->setField('meta_type', My::META_TYPE);
$cur->insert(); $cur->insert();
$this->con->unlock(); dcCore::app()->con->unlock();
} catch (Exception $e) { } catch (Exception $e) {
$this->con->unlock(); dcCore::app()->con->unlock();
throw $e; throw $e;
} }
} }
# Delete post from periodical /**
public function delPost($post_id) * Remove a post from periods
*/
public static function delPost(int $post_id): void
{ {
$post_id = (int) $post_id; dcCore::app()->con->execute(
$this->con->execute(
'DELETE FROM ' . dcCore::app()->prefix . dcMeta::META_TABLE_NAME . ' ' . 'DELETE FROM ' . dcCore::app()->prefix . dcMeta::META_TABLE_NAME . ' ' .
"WHERE meta_type = 'periodical' " . "WHERE meta_type = '" . My::META_TYPE . "' " .
"AND post_id = '" . $post_id . "' " "AND post_id = '" . $post_id . "' "
); );
return true;
} }
# Remove all posts without pending status from periodical /**
public function cleanPosts($period_id = null) * Remove all posts without pending status from periodical
*/
public static function cleanPosts(?int $period_id = null): void
{ {
$params = []; $params = [];
$params['post_status'] = ''; $params['post_status'] = '';
$params['sql'] = 'AND post_status != -2 '; $params['sql'] = 'AND post_status != ' . dcBlog::POST_PENDING . ' ';
if ($period_id !== null) { if ($period_id !== null) {
$params['periodical_id'] = (int) $period_id; $params['periodical_id'] = $period_id;
} }
$rs = $this->getPosts($params); $rs = self::getPosts($params);
if ($rs->isEmpty()) { if ($rs->isEmpty()) {
return; return;
@ -301,74 +324,24 @@ class periodical
$ids = []; $ids = [];
while ($rs->fetch()) { while ($rs->fetch()) {
$ids[] = $rs->post_id; $ids[] = (int) $rs->f('post_id');
} }
if (empty($ids)) { if (empty($ids)) {
return; return;
} }
$this->con->execute( dcCore::app()->con->execute(
'DELETE FROM ' . dcCore::app()->prefix . dcMeta::META_TABLE_NAME . ' ' . 'DELETE FROM ' . dcCore::app()->prefix . dcMeta::META_TABLE_NAME . ' ' .
"WHERE meta_type = 'periodical' " . "WHERE meta_type = '" . My::META_TYPE . "' " .
'AND post_id ' . $this->con->in($ids) 'AND post_id ' . dcCore::app()->con->in($ids)
); );
} }
public static function getTimesCombo() /**
{ * Lock a file to see if an update is ongoing
return [ */
__('Hourly') => 'hour', public static function lockUpdate(): bool
__('twice a day') => 'halfday',
__('Daily') => 'day',
__('Weekly') => 'week',
__('Monthly') => 'month',
];
}
public static function getNextTime($ts, $period)
{
$ts = (int) $ts;
$e = explode(',', date('H,i,s,n,j,Y', $ts));
switch($period) {
case 'hour':
$new_ts = mktime($e[0] + 1, $e[1], $e[2], $e[3], $e[4], $e[5]);
break;
case 'halfday':
$new_ts = mktime($e[0] + 12, $e[1], $e[2], $e[3], $e[4], $e[5]);
break;
case 'day':
$new_ts = mktime($e[0], $e[1], $e[2], $e[3], $e[4] + 1, $e[5]);
break;
case 'week':
$new_ts = mktime($e[0], $e[1], $e[2], $e[3], $e[4] + 7, $e[5]);
break;
case 'month':
$new_ts = mktime($e[0], $e[1], $e[2], $e[3] + 1, $e[4], $e[5]);
break;
default:
$new_ts = 0;
throw new Exception(__('Unknow frequence'));
break;
}
return $new_ts;
}
# Lock a file to see if an update is ongoing
public function lockUpdate()
{ {
try { try {
# Need flock function # Need flock function
@ -380,7 +353,7 @@ class periodical
throw new Exception("Can't write in cache fodler"); throw new Exception("Can't write in cache fodler");
} }
# Set file path # Set file path
$f_md5 = md5($this->blog); $f_md5 = md5(self::blog());
$cached_file = sprintf( $cached_file = sprintf(
'%s/%s/%s/%s/%s.txt', '%s/%s/%s/%s/%s.txt',
DC_TPL_CACHE, DC_TPL_CACHE,
@ -391,6 +364,9 @@ class periodical
); );
# Real path # Real path
$cached_file = path::real($cached_file, false); $cached_file = path::real($cached_file, false);
if (is_bool($cached_file)) {
throw new Exception("Can't write in cache fodler");
}
# Make dir # Make dir
if (!is_dir(dirname($cached_file))) { if (!is_dir(dirname($cached_file))) {
files::makeDir(dirname($cached_file), true); files::makeDir(dirname($cached_file), true);
@ -412,19 +388,20 @@ class periodical
if (!flock($fp, LOCK_EX)) { if (!flock($fp, LOCK_EX)) {
throw new Exception("Can't lock file"); throw new Exception("Can't lock file");
} }
$this->lock = $fp; self::$lock = $fp;
return true; return true;
} catch (Exception $e) { } catch (Exception $e) {
throw $e; throw $e;
} }
return false;
} }
public function unlockUpdate() /**
* Unlock update process
*/
public static function unlockUpdate(): void
{ {
@fclose($this->lock); @fclose(self::$lock);
$this->lock = null; self::$lock = null;
} }
} }