' . __('Not only link started with this blog URL could be shortened.') . '
-
-
' . __('If this extension is disabled and the passive mode is enabled, "kutrl" tags (like EntryKurl) will display long urls instead of nothing on templates.') . '
-
-
' . __('If the active mode is enabled, all know default template tags (like EntryURL) will display short urls instead of long ones on templates.') . ' ' .
-__('You can disable URL shortening for a specific template tag by adding attribute disable_kutrl="1" to it . ') . '
-
' . __('We strongly discourage using active mode as it crashes public post form and complex url if theme is not customize for kUtRL.') . '
-
-
' . __('This can be changed on page of creation/edition of an entry.') . '
', $img_chk) . $o->error->toHTML()));
+ }
+
+ if ($o->home != '') {
+ $s_items[] = (new Para())
+ ->items([
+ (new Link())
+ ->href($o->home)
+ ->title(__('homepage'))
+ ->text(sprintf(__('Learn more about %s.'), $o->name)),
+ ]);
+ }
+
+ $i_config[] = (new Text('hr'));
+ $i_config[] = (new Div('settings-' . $service_id))
+ ->items([
+ (new Text('h5', $o->name)),
+ ... $s_items,
+ $o->settingsForm(),
+ ]);
+ }
+
+ echo (new Div())
+ ->class('fieldset')
+ ->items([
+ (new text('h4', __('Settings'))),
+ (new Div('setting-plugin'))
+ ->items([
+ (new Text('h5', __('Activation'))),
+ (new Para())
+ ->items([
+ (new Checkbox('s_active', $s_active))
+ ->value(1),
+ (new Label(__('Enable plugin'), Label::OUTSIDE_LABEL_AFTER))
+ ->class('classic')
+ ->for('s_active'),
+ ]),
+ ]),
+ (new Text('hr')),
+
+ (new Div('setting-option'))
+ ->items([
+ (new Text('h5', __('Behaviors'))),
+ (new Para())
+ ->items([
+ (new Checkbox('s_allow_external_url', $s_allow_external_url))
+ ->value(1),
+ (new Label(__('Allow short link for external URL'), Label::OUTSIDE_LABEL_AFTER))
+ ->class('classic')
+ ->for('s_allow_external_url'),
+ ]),
+ (new Note())
+ ->class('form-note')
+ ->text(__('Not only link started with this blog URL could be shortened.')),
+ (new Para())
+ ->items([
+ (new Checkbox('s_tpl_passive', $s_tpl_passive))
+ ->value(1),
+ (new Label(__('Passive mode'), Label::OUTSIDE_LABEL_AFTER))
+ ->class('classic')
+ ->for('s_tpl_passive'),
+ ]),
+ (new Note())
+ ->class('form-note')
+ ->text(__('If this extension is disabled and the passive mode is enabled, "kutrl" tags (like EntryKurl) will display long urls instead of nothing on templates.')),
+ (new Para())
+ ->items([
+ (new Checkbox('s_tpl_active', $s_tpl_active))
+ ->value(1),
+ (new Label(__('Active mode'), Label::OUTSIDE_LABEL_AFTER))
+ ->class('classic')
+ ->for('s_tpl_active'),
+ ]),
+ (new Note())
+ ->class('form-note')
+ ->text(__('If the active mode is enabled, all know default template tags (like EntryURL) will display short urls instead of long ones on templates.')),
+ (new Note())
+ ->class('form-note')
+ ->text(__('You can disable URL shortening for a specific template tag by adding attribute disable_kutrl="1" to it . ')),
+ (new Note())
+ ->class('warning')
+ ->text(__('We strongly discourage using active mode as it crashes public post form and complex url if theme is not customize for kUtRL.')),
+ (new Para())
+ ->items([
+ (new Checkbox('s_admin_entry_default', $s_admin_entry_default))
+ ->value(1),
+ (new Label(__('Create short link for new entries'), Label::OUTSIDE_LABEL_AFTER))
+ ->class('classic')
+ ->for('s_admin_entry_default'),
+ ]),
+ (new Note())
+ ->class('form-note')
+ ->text(__('This can be changed on page of creation/edition of an entry.')),
+ ]),
+ (new Text('hr')),
+
+ (new Div('setting-service'))
+ ->items([
+ (new Text('h5', __('Default services'))),
+ (new Para())
+ ->items([
+ (new Label($chk_admin_service . __('Administration:'), Label::OUTSIDE_LABEL_BEFORE))
+ ->for('s_admin_service'),
+ (new Select('s_admin_service'))
+ ->items(Combo::servicesCombo())
+ ->default($s_admin_service),
+ ]),
+ (new Note())
+ ->class('form-note')
+ ->text(__('Service to use in this admin page and on edit page of an entry.')),
+ (new Para())
+ ->items([
+ (new Label($chk_plugin_service . __('Extensions:'), Label::OUTSIDE_LABEL_BEFORE))
+ ->for('s_plugin_service'),
+ (new Select('s_plugin_service'))
+ ->items(Combo::servicesCombo())
+ ->default($s_plugin_service),
+ ]),
+ (new Note())
+ ->class('form-note')
+ ->text(__('Service to use on third part plugins.')),
+ (new Para())
+ ->items([
+ (new Label($chk_tpl_service . __('Templates:'), Label::OUTSIDE_LABEL_BEFORE))
+ ->for('s_tpl_service'),
+ (new Select('s_tpl_service'))
+ ->items(Combo::servicesCombo())
+ ->default($s_tpl_service),
+ ]),
+ (new Note())
+ ->class('form-note')
+ ->text(__('Shorten links automatically when using template value like "EntryKutrl".')),
+ (new Para())
+ ->items([
+ (new Label($chk_wiki_service . __('Contents:'), Label::OUTSIDE_LABEL_BEFORE))
+ ->for('s_wiki_service'),
+ (new Select('s_wiki_service'))
+ ->items(Combo::servicesCombo())
+ ->default($s_wiki_service),
+ ]),
+ (new Note())
+ ->class('form-note')
+ ->text(__('Shorten links automatically found in contents using wiki synthax.')),
+ ]),
+ ])
+ ->render() .
+
+ (new Div())
+ ->class('fieldset')
+ ->items([
+ (new text('h4', __('Settings'))),
+ (new Note())
+ ->class('info')
+ ->text(__('List of services you can use to shorten links with pkugin kUtRL.')),
+ ... $i_config,
+ ])
+ ->render();
+ }
}
-
-echo'
';
diff --git a/src/Frontend.php b/src/Frontend.php
index 8748e86..1f610f0 100644
--- a/src/Frontend.php
+++ b/src/Frontend.php
@@ -10,567 +10,66 @@
* @copyright Jean-Christian Denis
* @copyright GPL-2.0 https://www.gnu.org/licenses/gpl-2.0.html
*/
-if (!defined('DC_RC_PATH')) {
- return null;
-}
+declare(strict_types=1);
-require_once __DIR__ . '/_widgets.php';
+namespace Dotclear\Plugin\kUtRL;
-dcCore::app()->tpl->setPath(dcCore::app()->tpl->getPath(), __DIR__ . '/default-templates');
+use dcCore;
-dcCore::app()->addBehavior('publicBeforeDocumentV2', ['pubKutrl', 'publicBeforeDocumentV2']);
-dcCore::app()->addBehavior('publicHeadContent', ['pubKutrl', 'publicHeadContent']);
-dcCore::app()->addBehavior('publicBeforeContentFilterV2', ['pubKutrl', 'publicBeforeContentFilterV2']);
-dcCore::app()->addBehavior('templateBeforeValueV2', ['pubKutrl', 'templateBeforeValueV2']);
-dcCore::app()->addBehavior('templateAfterValueV2', ['pubKutrl', 'templateAfterValueV2']);
+use Dotclear\Core\Process;
-dcCore::app()->tpl->addBlock('kutrlPageIf', ['tplKutrl', 'pageIf']);
-dcCore::app()->tpl->addBlock('kutrlMsgIf', ['tplKutrl', 'pageMsgIf']);
-
-dcCore::app()->tpl->addValue('kutrlPageURL', ['tplKutrl', 'pageURL']);
-dcCore::app()->tpl->addValue('kutrlMsg', ['tplKutrl', 'pageMsg']);
-dcCore::app()->tpl->addValue('kutrlHumanField', ['tplKutrl', 'humanField']);
-dcCore::app()->tpl->addValue('kutrlHumanFieldProtect', ['tplKutrl', 'humanFieldProtect']);
-
-dcCore::app()->tpl->addBlock('AttachmentKutrlIf', ['tplKutrl', 'AttachmentKutrlIf']);
-dcCore::app()->tpl->addValue('AttachmentKutrl', ['tplKutrl', 'AttachmentKutrl']);
-dcCore::app()->tpl->addBlock('MediaKutrlIf', ['tplKutrl', 'MediaKutrlIf']);
-dcCore::app()->tpl->addValue('MediaKutrl', ['tplKutrl', 'MediaKutrl']);
-dcCore::app()->tpl->addBlock('EntryAuthorKutrlIf', ['tplKutrl', 'EntryAuthorKutrlIf']);
-dcCore::app()->tpl->addValue('EntryAuthorKutrl', ['tplKutrl', 'EntryAuthorKutrl']);
-dcCore::app()->tpl->addBlock('EntryKutrlIf', ['tplKutrl', 'EntryKutrlIf']);
-dcCore::app()->tpl->addValue('EntryKutrl', ['tplKutrl', 'EntryKutrl']);
-dcCore::app()->tpl->addBlock('CommentAuthorKutrlIf', ['tplKutrl', 'CommentAuthorKutrlIf']);
-dcCore::app()->tpl->addValue('CommentAuthorKutrl', ['tplKutrl', 'CommentAuthorKutrl']);
-dcCore::app()->tpl->addBlock('CommentPostKutrlIf', ['tplKutrl', 'CommentPostKutrlIf']);
-dcCore::app()->tpl->addValue('CommentPostKutrl', ['tplKutrl', 'CommentPostKutrl']);
-
-class urlKutrl extends dcUrlHandlers
+/**
+ * Frontend prepend.
+ */
+class Frontend extends Process
{
- # Redirect !!! local !!! service only
- public static function redirectUrl($args)
+ public static function init(): bool
{
- # Not active, go to default 404
- if (!dcCore::app()->blog->settings->get(basename(__DIR__))->get('active')) {
- self::p404();
-
- return null;
- }
- # Not a valid url, go to kutrl 404
- if (!preg_match('#^(|(/(.*?)))$#', $args, $m)) {
- self::kutrl404();
-
- return null;
- }
-
- $args = $m[3] ?? '';
- dcCore::app()->ctx->kutrl_msg = '';
- dcCore::app()->ctx->kutrl_hmf = hmfKutrl::create();
- dcCore::app()->ctx->kutrl_hmfp = hmfKutrl::protect(dcCore::app()->ctx->kutrl_hmf);
-
- $kut = new localKutrlService();
-
- # Nothing on url
- if ($m[1] == '/') {
- dcCore::app()->ctx->kutrl_msg = 'No link given.';
- }
- # find suffix on redirect url
- $suffix = '';
- if (preg_match('@^([^?/#]+)(.*?)$@', $args, $more)) {
- $args = $more[1];
- $suffix = $more[2];
- }
- # No arg, go to kurtl page
- if ($args == '') {
- self::pageKutrl($kut);
-
- return null;
- }
- # Not find, go to kutrl 404
- if (false === ($url = $kut->getUrl($args))) {
- //dcCore::app()->ctx->kutrl_msg = 'Failed to find short link.';
- //self::pageKutrl($kut);
- self::kutrl404();
-
- return null;
- }
- # Removed (empty url), go to kutrl 404
- if (!$url) {
- self::kutrl404();
-
- return null;
- }
-
- dcCore::app()->blog->triggerBlog();
- http::redirect($url . $suffix);
-
- return null;
+ return self::status(My::checkContext(My::FRONTEND));
}
- private static function pageKutrl($kut)
+ public static function process(): bool
{
- $s = dcCore::app()->blog->settings->get(basename(__DIR__));
-
- # Not active, go to default 404
- if (!$s->get('active')) {
- self::p404();
-
- return null;
- }
- # Public page not active, go to kutrl 404
- if (!$s->get('srv_local_public')) {
- self::kutrl404();
-
- return null;
- }
- # Validation form
- $url = !empty($_POST['longurl']) ? trim(dcCore::app()->con->escape($_POST['longurl'])) : '';
- if (!empty($url)) {
- $hmf = !empty($_POST['hmf']) ? $_POST['hmf'] : '!';
- $hmfu = !empty($_POST['hmfp']) ? hmfKutrl::unprotect($_POST['hmfp']) : '?';
-
- $err = false;
- if (!$err) {
- if ($hmf != $hmfu) {
- $err = true;
- dcCore::app()->ctx->kutrl_msg = __('Failed to verify protected field.');
- }
- }
- if (!$err) {
- if (!$kut->testService()) {
- $err = true;
- dcCore::app()->ctx->kutrl_msg = __('Service is not well configured.');
- }
- }
- if (!$err) {
- if (!$kut->isValidUrl($url)) {
- $err = true;
- dcCore::app()->ctx->kutrl_msg = __('This string is not a valid URL.');
- }
- }
- if (!$err) {
- if (!$kut->isLongerUrl($url)) {
- $err = true;
- dcCore::app()->ctx->kutrl_msg = __('This link is too short.');
- }
- }
- if (!$err) {
- if (!$kut->isProtocolUrl($url)) {
- $err = true;
- dcCore::app()->ctx->kutrl_msg = __('This type of link is not allowed.');
- }
- }
-
- if (!$err) {
- if (!$kut->allow_external_url && !$kut->isBlogUrl($url)) {
- $err = true;
- dcCore::app()->ctx->kutrl_msg = __('Short links are limited to this blog URL.');
- }
- }
- if (!$err) {
- if ($kut->isServiceUrl($url)) {
- $err = true;
- dcCore::app()->ctx->kutrl_msg = __('This link is already a short link.');
- }
- }
- if (!$err) {
- if (false !== ($rs = $kut->isKnowUrl($url))) {
- $err = true;
-
- $url = $rs->url;
- $new_url = $kut->url_base . $rs->hash;
-
- dcCore::app()->ctx->kutrl_msg = sprintf(
- __('Short link for %s is %s'),
- html::escapeHTML($url),
- '' . $new_url . ''
- );
- }
- }
- if (!$err) {
- if (false === ($rs = $kut->hash($url))) {
- $err = true;
- dcCore::app()->ctx->kutrl_msg = __('Failed to create short link.');
- } else {
- $url = $rs->url;
- $new_url = $kut->url_base . $rs->hash;
-
- dcCore::app()->ctx->kutrl_msg = sprintf(
- __('Short link for %s is %s'),
- html::escapeHTML($url),
- '' . $new_url . ''
- );
- dcCore::app()->blog->triggerBlog();
-
- # ex: Send new url to messengers
- if (!empty($rs)) {
- dcCore::app()->callBehavior('publicAfterKutrlCreate', $rs, __('New public short URL'));
- }
- }
- }
+ if (!self::status()) {
+ return false;
}
- dcCore::app()->tpl->setPath(dcCore::app()->tpl->getPath(), __DIR__ . '/default-templates');
- self::serveDocument('kutrl.html');
+ dcCore::app()->tpl->setPath(
+ dcCore::app()->tpl->getPath(),
+ My::path() . DIRECTORY_SEPARATOR . 'default-templates'
+ );
+ dcCore::app()->addBehavior('initWidgets', [Widgets::class, 'initShorten']);
+ dcCore::app()->addBehavior('initWidgets', [Widgets::class, 'initRank']);
- return null;
- }
+ dcCore::app()->addBehaviors([
+ 'publicBeforeDocumentV2' => [FrontendBehaviors::class, 'publicBeforeDocumentV2'],
+ 'publicHeadContent' => [FrontendBehaviors::class, 'publicHeadContent'],
+ 'publicBeforeContentFilterV2' => [FrontendBehaviors::class, 'publicBeforeContentFilterV2'],
+ 'templateBeforeValueV2' => [FrontendBehaviors::class, 'templateBeforeValueV2'],
+ 'templateAfterValueV2' => [FrontendBehaviors::class, 'templateAfterValueV2'],
+ ]);
- protected static function kutrl404()
- {
- if (!dcCore::app()->blog->settings->get(basename(__DIR__))->get('srv_local_404_active')) {
- self::p404();
+ dcCore::app()->tpl->addBlock('kutrlPageIf', [FrontendTemplate::class, 'pageIf']);
+ dcCore::app()->tpl->addBlock('kutrlMsgIf', [FrontendTemplate::class, 'pageMsgIf']);
- return null;
- }
+ dcCore::app()->tpl->addValue('kutrlPageURL', [FrontendTemplate::class, 'pageURL']);
+ dcCore::app()->tpl->addValue('kutrlMsg', [FrontendTemplate::class, 'pageMsg']);
+ dcCore::app()->tpl->addValue('kutrlHumanField', [FrontendTemplate::class, 'humanField']);
+ dcCore::app()->tpl->addValue('kutrlHumanFieldProtect', [FrontendTemplate::class, 'humanFieldProtect']);
- dcCore::app()->tpl->setPath(dcCore::app()->tpl->getPath(), __DIR__ . '/default-templates');
+ dcCore::app()->tpl->addBlock('AttachmentKutrlIf', [FrontendTemplate::class, 'AttachmentKutrlIf']);
+ dcCore::app()->tpl->addValue('AttachmentKutrl', [FrontendTemplate::class, 'AttachmentKutrl']);
+ dcCore::app()->tpl->addBlock('MediaKutrlIf', [FrontendTemplate::class, 'MediaKutrlIf']);
+ dcCore::app()->tpl->addValue('MediaKutrl', [FrontendTemplate::class, 'MediaKutrl']);
+ dcCore::app()->tpl->addBlock('EntryAuthorKutrlIf', [FrontendTemplate::class, 'EntryAuthorKutrlIf']);
+ dcCore::app()->tpl->addValue('EntryAuthorKutrl', [FrontendTemplate::class, 'EntryAuthorKutrl']);
+ dcCore::app()->tpl->addBlock('EntryKutrlIf', [FrontendTemplate::class, 'EntryKutrlIf']);
+ dcCore::app()->tpl->addValue('EntryKutrl', [FrontendTemplate::class, 'EntryKutrl']);
+ dcCore::app()->tpl->addBlock('CommentAuthorKutrlIf', [FrontendTemplate::class, 'CommentAuthorKutrlIf']);
+ dcCore::app()->tpl->addValue('CommentAuthorKutrl', [FrontendTemplate::class, 'CommentAuthorKutrl']);
+ dcCore::app()->tpl->addBlock('CommentPostKutrlIf', [FrontendTemplate::class, 'CommentPostKutrlIf']);
+ dcCore::app()->tpl->addValue('CommentPostKutrl', [FrontendTemplate::class, 'CommentPostKutrl']);
- header('Content-Type: text/html; charset=UTF-8');
- http::head(404, 'Not Found');
- dcCore::app()->url->type = '404';
- dcCore::app()->ctx->current_tpl = 'kutrl404.html';
- dcCore::app()->ctx->content_type = 'text/html';
-
- echo dcCore::app()->tpl->getData(dcCore::app()->ctx->current_tpl);
-
- # --BEHAVIOR-- publicAfterDocument
- dcCore::app()->callBehavior('publicAfterDocumentV2');
- exit;
- }
-}
-
-class pubKutrl
-{
- # List of template tag which content URL that can be shortenn
- public static $know_tags = [
- 'AttachmentURL',
- 'CategoryURL',
- 'MediaURL',
- 'EntryAuthorURL',
- 'EntryURL',
- 'EntryCategoryURL',
- 'CommentAuthorURL',
- 'CommentPostURL',
- ];
-
- # Disable URL shoretning on filtered tag
- public static function templateBeforeValueV2($tag, $attr)
- {
- if (!empty($attr['disable_kutrl']) && in_array($tag, pubKutrl::$know_tags)) {
- return 'ctx->__set("disable_kutrl", true); ?>';
- }
-
- return null;
- }
-
- # Re unable it after tag
- public static function templateAfterValueV2($tag, $attr)
- {
- if (!empty($attr['disable_kutrl']) && in_array($tag, pubKutrl::$know_tags)) {
- return 'ctx->__set("disable_kutrl", false); ?>';
- }
-
- return null;
- }
-
- # Replace long urls on the fly (on filter) for default tags
- public static function publicBeforeContentFilterV2($tag, $args)
- {
- # Unknow tag
- if (!in_array($tag, pubKutrl::$know_tags)) {
- return null;
- }
- # URL shortening is disabled by tag attribute
- if (true !== dcCore::app()->ctx->__get('disable_kutrl')) {
- # kUtRL is not activated
- if (!dcCore::app()->blog->settings->get(basename(__DIR__))->get('active')
- || !dcCore::app()->blog->settings->get(basename(__DIR__))->get('tpl_active')
- ) {
- return null;
- }
-
- # Oups
- if (!dcCore::app()->ctx->exists('kutrl')) {
- return null;
- }
- # Existing
- if (false !== ($kutrl_rs = dcCore::app()->ctx->kutrl->isKnowUrl($args[0]))) {
- $args[0] = dcCore::app()->ctx->kutrl->url_base . $kutrl_rs->hash;
- # New
- } elseif (false !== ($kutrl_rs = dcCore::app()->ctx->kutrl->hash($args[0]))) {
- $args[0] = dcCore::app()->ctx->kutrl->url_base . $kutrl_rs->hash;
-
- # ex: Send new url to messengers
- if (!empty($kutrl_rs)) {
- dcCore::app()->callBehavior('publicAfterKutrlCreate', $kutrl_rs, __('New public short URL'));
- }
- }
- }
- }
-
- public static function publicBeforeDocumentV2()
- {
- $s = dcCore::app()->blog->settings->get(basename(__DIR__));
-
- # Passive : all kutrl tag return long url
- dcCore::app()->ctx->kutrl_passive = (bool) $s->get('tpl_passive');
-
- if (!$s->get('active') || !$s->get('tpl_service')) {
- return null;
- }
- if (null === ($kut = kUtRL::quickPlace('tpl'))) {
- return null;
- }
- dcCore::app()->ctx->kutrl = $kut;
- }
-
- public static function publicHeadContent($_)
- {
- $css = dcCore::app()->blog->settings->get(basename(__DIR__))->get('srv_local_css');
- if ($css) {
- echo
- "\n \n" .
- "\n";
- }
- }
-}
-
-class tplKutrl
-{
- public static function pageURL($attr)
- {
- $f = dcCore::app()->tpl->getFilters($attr);
-
- return 'blog->url.dcCore::app()->url->getBase("kutrl")') . '; ?>';
- }
-
- public static function pageIf($attr, $content)
- {
- $operator = isset($attr['operator']) ? self::getOperator($attr['operator']) : '&&';
-
- if (isset($attr['is_active'])) {
- $sign = (bool) $attr['is_active'] ? '' : '!';
- $if[] = $sign . 'dcCore::app()->blog->settings->get("' . basename(__DIR__) . '")->get("srv_local_public")';
- }
- if (empty($if)) {
- return $content;
- }
-
- return
- '\n" .
- $content .
- "\n";
- }
-
- public static function pageMsgIf($attr, $content)
- {
- $operator = isset($attr['operator']) ? self::getOperator($attr['operator']) : '&&';
-
- if (isset($attr['has_message'])) {
- $sign = (bool) $attr['has_message'] ? '!' : '=';
- $if[] = '"" ' . $sign . '= dcCore::app()->ctx->kutrl_msg';
- }
- if (empty($if)) {
- return $content;
- }
-
- return
- '\n" .
- $content .
- "\n";
- }
-
- public static function pageMsg($attr)
- {
- return 'ctx->kutrl_msg; ?>';
- }
-
- public static function humanField($attr)
- {
- return "ctx->kutrl_hmf); ?>";
- }
-
- public static function humanFieldProtect($attr)
- {
- return
- '' .
- 'formNonce(); ?>';
- }
-
- public static function AttachmentKutrlIf($attr, $content)
- {
- return self::genericKutrlIf('$attach_f->file_url', $attr, $content);
- }
-
- public static function AttachmentKutrl($attr)
- {
- return self::genericKutrl('$attach_f->file_url', $attr);
- }
-
- public static function MediaKutrlIf($attr, $content)
- {
- return self::genericKutrlIf('dcCore::app()->ctx->file_url', $attr, $content);
- }
-
- public static function MediaKutrl($attr)
- {
- return self::genericKutrl('dcCore::app()->ctx->file_url', $attr);
- }
-
- public static function EntryAuthorKutrlIf($attr, $content)
- {
- return self::genericKutrlIf('dcCore::app()->ctx->posts->user_url', $attr, $content);
- }
-
- public static function EntryAuthorKutrl($attr)
- {
- return self::genericKutrl('dcCore::app()->ctx->posts->user_url', $attr);
- }
-
- public static function EntryKutrlIf($attr, $content)
- {
- return self::genericKutrlIf('dcCore::app()->ctx->posts->getURL()', $attr, $content);
- }
-
- public static function EntryKutrl($attr)
- {
- return self::genericKutrl('dcCore::app()->ctx->posts->getURL()', $attr);
- }
-
- public static function CommentAuthorKutrlIf($attr, $content)
- {
- return self::genericKutrlIf('dcCore::app()->ctx->comments->getAuthorURL()', $attr, $content);
- }
-
- public static function CommentAuthorKutrl($attr)
- {
- return self::genericKutrl('dcCore::app()->ctx->comments->getAuthorURL()', $attr);
- }
-
- public static function CommentPostKutrlIf($attr, $content)
- {
- return self::genericKutrlIf('dcCore::app()->ctx->comments->getPostURL()', $attr, $content);
- }
-
- public static function CommentPostKutrl($attr)
- {
- return self::genericKutrl('dcCore::app()->ctx->comments->getPostURL()', $attr);
- }
-
- protected static function genericKutrlIf($str, $attr, $content)
- {
- $operator = isset($attr['operator']) ? self::getOperator($attr['operator']) : '&&';
-
- if (isset($attr['is_active'])) {
- $sign = (bool) $attr['is_active'] ? '' : '!';
- $if[] = $sign . 'dcCore::app()->ctx->exists("kutrl")';
- }
- if (isset($attr['passive_mode'])) {
- $sign = (bool) $attr['passive_mode'] ? '' : '!';
- $if[] = $sign . 'dcCore::app()->ctx->kutrl_passive';
- }
- if (isset($attr['has_kutrl'])) {
- $sign = (bool) $attr['has_kutrl'] ? '!' : '=';
- $if[] = '(dcCore::app()->ctx->exists("kutrl") && false ' . $sign . '== dcCore::app()->ctx->kutrl->select(' . $str . ',null,null,"kutrl"))';
- }
- if (empty($if)) {
- return $content;
- }
-
- return
- '\n" .
- $content .
- "\n";
- }
-
- protected static function genericKutrl($str, $attr)
- {
- $f = dcCore::app()->tpl->getFilters($attr);
-
- return
- "ctx->preview) { \n" .
- ' echo ' . sprintf($f, $str) . '; ' .
- "} else { \n" .
- # Disable
- "if (!dcCore::app()->ctx->exists('kutrl')) { \n" .
- # Passive mode
- ' if (dcCore::app()->ctx->kutrl_passive) { ' .
- ' echo ' . sprintf($f, $str) . '; ' .
- " } \n" .
- "} else { \n" .
- # Existing
- ' if (false !== ($kutrl_rs = dcCore::app()->ctx->kutrl->isKnowUrl(' . $str . '))) { ' .
- ' echo ' . sprintf($f, 'dcCore::app()->ctx->kutrl->url_base.$kutrl_rs->hash') . '; ' .
- " } \n" .
- # New
- ' elseif (false !== ($kutrl_rs = dcCore::app()->ctx->kutrl->hash(' . $str . '))) { ' .
- ' echo ' . sprintf($f, 'dcCore::app()->ctx->kutrl->url_base.$kutrl_rs->hash') . '; ' .
-
- # ex: Send new url to messengers
- ' if (!empty($kutrl_rs)) { ' .
- " dcCore::app()->callBehavior('publicAfterKutrlCreate',\$kutrl_rs,__('New public short URL')); " .
- " } \n" .
-
- " } \n" .
- " unset(\$kutrl_rs); \n" .
- "} \n" .
- "} \n" .
- "?>\n";
- }
-
- protected static function getOperator($op)
- {
- switch (strtolower($op)) {
- case 'or':
- case '||':
- return '||';
- case 'and':
- case '&&':
- default:
- return '&&';
- }
- }
-}
-
-class hmfKutrl
-{
- public static $chars = 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
-
- public static function create($len = 6)
- {
- $res = '';
- $chars = self::$chars;
- for ($i = 0; $i < $len; $i++) {
- $res .= $chars[rand(0, strlen($chars) - 1)];
- }
-
- return $res;
- }
-
- public static function protect($str)
- {
- $res = '';
- $chars = self::$chars;
- for ($i = 0; $i < strlen($str); $i++) {
- $res .= $chars[rand(0, strlen($chars) - 1)] . $str[$i];
- }
-
- return $res;
- }
-
- public static function unprotect($str)
- {
- $res = '';
- for ($i = 0; $i < strlen($str); $i++) {
- $i++;
- $res .= $str[$i];
- }
-
- return $res;
+ return true;
}
}
diff --git a/src/FrontendBehaviors.php b/src/FrontendBehaviors.php
new file mode 100644
index 0000000..d10d404
--- /dev/null
+++ b/src/FrontendBehaviors.php
@@ -0,0 +1,102 @@
+ctx->__set("disable_kutrl", true); ?>';
+ }
+
+ return null;
+ }
+
+ # Re unable it after tag
+ public static function templateAfterValueV2(string $tag, ArrayObject $attr): ?string
+ {
+ if (!empty($attr['disable_kutrl']) && in_array($tag, My::USED_TAGS)) {
+ return 'ctx->__set("disable_kutrl", false); ?>';
+ }
+
+ return null;
+ }
+
+ # Replace long urls on the fly (on filter) for default tags
+ public static function publicBeforeContentFilterV2(string $tag, array $args): ?string
+ {
+ # Unknow tag
+ if (!in_array($tag, My::USED_TAGS)) {
+ return null;
+ }
+ # URL shortening is disabled by tag attribute
+ if (true !== dcCore::app()->ctx->__get('disable_kutrl')) {
+ # plugin is not activated
+ if (!My::settings()->get('active')
+ || !My::settings()->get('tpl_active')
+ || !dcCore::app()->ctx->exists('kutrl')
+ ) {
+ return null;
+ }
+ # Existing
+ if (false !== ($kutrl_rs = dcCore::app()->ctx->kutrl->isKnowUrl($args[0]))) {
+ $args[0] = dcCore::app()->ctx->kutrl->url_base . $kutrl_rs->hash;
+ # New
+ } elseif (false !== ($kutrl_rs = dcCore::app()->ctx->kutrl->hash($args[0]))) {
+ $args[0] = dcCore::app()->ctx->kutrl->url_base . $kutrl_rs->hash;
+
+ # ex: Send new url to messengers
+ if (!empty($kutrl_rs)) {
+ dcCore::app()->callBehavior('publicAfterKutrlCreate', $kutrl_rs, __('New public short URL'));
+ }
+ }
+ }
+ }
+
+ public static function publicBeforeDocumentV2(): void
+ {
+ $s = My::settings();
+
+ # Passive : all kutrl tag return long url
+ dcCore::app()->ctx->kutrl_passive = (bool) $s->get('tpl_passive');
+
+ if (!$s->get('active')
+ || !$s->get('tpl_service')
+ || null === ($kut = Utils::quickPlace('tpl'))
+ ) {
+ return;
+ }
+
+ dcCore::app()->ctx->kutrl = $kut;
+ }
+
+ public static function publicHeadContent($_): void
+ {
+ $css = My::settings()->get('srv_local_css');
+ if (!empty($css)) {
+ echo
+ "\n \n" .
+ "\n";
+ }
+ }
+}
diff --git a/src/FrontendTemplate.php b/src/FrontendTemplate.php
new file mode 100644
index 0000000..b864f0c
--- /dev/null
+++ b/src/FrontendTemplate.php
@@ -0,0 +1,205 @@
+tpl->getFilters($attr);
+
+ return 'blog->url.dcCore::app()->url->getBase("kutrl")') . '; ?>';
+ }
+
+ public static function pageIf(ArrayObject $attr, string $content): string
+ {
+ $operator = isset($attr['operator']) ? dcTemplate::getOperator($attr['operator']) : '&&';
+
+ if (isset($attr['is_active'])) {
+ $sign = (bool) $attr['is_active'] ? '' : '!';
+ $if[] = $sign . 'dcCore::app()->blog->settings->get("' . My::id() . '")->get("srv_local_public")';
+ }
+ if (empty($if)) {
+ return $content;
+ }
+
+ return
+ '\n" .
+ $content .
+ "\n";
+ }
+
+ public static function pageMsgIf(ArrayObject$attr, string $content): string
+ {
+ $operator = isset($attr['operator']) ? dcTemplate::getOperator($attr['operator']) : '&&';
+
+ if (isset($attr['has_message'])) {
+ $sign = (bool) $attr['has_message'] ? '!' : '=';
+ $if[] = '"" ' . $sign . '= dcCore::app()->ctx->kutrl_msg';
+ }
+ if (empty($if)) {
+ return $content;
+ }
+
+ return
+ '\n" .
+ $content .
+ "\n";
+ }
+
+ public static function pageMsg(ArrayObject$attr): string
+ {
+ return 'ctx->kutrl_msg; ?>';
+ }
+
+ public static function humanField(ArrayObject $attr): string
+ {
+ return "ctx->kutrl_hmf); ?>";
+ }
+
+ public static function humanFieldProtect(ArrayObject $attr): string
+ {
+ return
+ '' .
+ 'formNonce(); ?>';
+ }
+
+ public static function AttachmentKutrlIf(ArrayObject$attr, string $content): string
+ {
+ return self::genericKutrlIf('$attach_f->file_url', $attr, $content);
+ }
+
+ public static function AttachmentKutrl(ArrayObject $attr): string
+ {
+ return self::genericKutrl('$attach_f->file_url', $attr);
+ }
+
+ public static function MediaKutrlIf(ArrayObject$attr, string $content): string
+ {
+ return self::genericKutrlIf('dcCore::app()->ctx->file_url', $attr, $content);
+ }
+
+ public static function MediaKutrl(ArrayObject $attr): string
+ {
+ return self::genericKutrl('dcCore::app()->ctx->file_url', $attr);
+ }
+
+ public static function EntryAuthorKutrlIf(ArrayObject$attr, string $content): string
+ {
+ return self::genericKutrlIf('dcCore::app()->ctx->posts->user_url', $attr, $content);
+ }
+
+ public static function EntryAuthorKutrl(ArrayObject $attr): string
+ {
+ return self::genericKutrl('dcCore::app()->ctx->posts->user_url', $attr);
+ }
+
+ public static function EntryKutrlIf(ArrayObject $attr, string $content): string
+ {
+ return self::genericKutrlIf('dcCore::app()->ctx->posts->getURL()', $attr, $content);
+ }
+
+ public static function EntryKutrl(ArrayObject $attr): string
+ {
+ return self::genericKutrl('dcCore::app()->ctx->posts->getURL()', $attr);
+ }
+
+ public static function CommentAuthorKutrlIf(ArrayObject $attr, string $content): string
+ {
+ return self::genericKutrlIf('dcCore::app()->ctx->comments->getAuthorURL()', $attr, $content);
+ }
+
+ public static function CommentAuthorKutrl(ArrayObject $attr): string
+ {
+ return self::genericKutrl('dcCore::app()->ctx->comments->getAuthorURL()', $attr);
+ }
+
+ public static function CommentPostKutrlIf(ArrayObject $attr, string $content): string
+ {
+ return self::genericKutrlIf('dcCore::app()->ctx->comments->getPostURL()', $attr, $content);
+ }
+
+ public static function CommentPostKutrl(ArrayObject $attr): string
+ {
+ return self::genericKutrl('dcCore::app()->ctx->comments->getPostURL()', $attr);
+ }
+
+ protected static function genericKutrlIf(string $str, ArrayObject $attr, string $content): string
+ {
+ $operator = isset($attr['operator']) ? dcTemplate::getOperator($attr['operator']) : '&&';
+
+ if (isset($attr['is_active'])) {
+ $sign = (bool) $attr['is_active'] ? '' : '!';
+ $if[] = $sign . 'dcCore::app()->ctx->exists("kutrl")';
+ }
+ if (isset($attr['passive_mode'])) {
+ $sign = (bool) $attr['passive_mode'] ? '' : '!';
+ $if[] = $sign . 'dcCore::app()->ctx->kutrl_passive';
+ }
+ if (isset($attr['has_kutrl'])) {
+ $sign = (bool) $attr['has_kutrl'] ? '!' : '=';
+ $if[] = '(dcCore::app()->ctx->exists("kutrl") && false ' . $sign . '== dcCore::app()->ctx->kutrl->select(' . $str . ',null,null,"kutrl"))';
+ }
+ if (empty($if)) {
+ return $content;
+ }
+
+ return
+ '\n" .
+ $content .
+ "\n";
+ }
+
+ protected static function genericKutrl(string $str, ArrayObject $attr): string
+ {
+ $f = dcCore::app()->tpl->getFilters($attr);
+
+ return
+ "ctx->preview) { \n" .
+ ' echo ' . sprintf($f, $str) . '; ' .
+ "} else { \n" .
+ # Disable
+ "if (!dcCore::app()->ctx->exists('kutrl')) { \n" .
+ # Passive mode
+ ' if (dcCore::app()->ctx->kutrl_passive) { ' .
+ ' echo ' . sprintf($f, $str) . '; ' .
+ " } \n" .
+ "} else { \n" .
+ # Existing
+ ' if (false !== ($kutrl_rs = dcCore::app()->ctx->kutrl->isKnowUrl(' . $str . '))) { ' .
+ ' echo ' . sprintf($f, 'dcCore::app()->ctx->kutrl->url_base.$kutrl_rs->hash') . '; ' .
+ " } \n" .
+ # New
+ ' elseif (false !== ($kutrl_rs = dcCore::app()->ctx->kutrl->hash(' . $str . '))) { ' .
+ ' echo ' . sprintf($f, 'dcCore::app()->ctx->kutrl->url_base.$kutrl_rs->hash') . '; ' .
+
+ # ex: Send new url to messengers
+ ' if (!empty($kutrl_rs)) { ' .
+ " dcCore::app()->callBehavior('publicAfterKutrlCreate',\$kutrl_rs,__('New public short URL')); " .
+ " } \n" .
+
+ " } \n" .
+ " unset(\$kutrl_rs); \n" .
+ "} \n" .
+ "} \n" .
+ "?>\n";
+ }
+}
diff --git a/src/FrontendUrl.php b/src/FrontendUrl.php
new file mode 100644
index 0000000..c2a4de8
--- /dev/null
+++ b/src/FrontendUrl.php
@@ -0,0 +1,211 @@
+get('active')) {
+ self::p404();
+
+ return;
+ }
+ # Not a valid url, go to kutrl 404
+ if (!preg_match('#^(|(/(.*?)))$#', $args, $m)) {
+ self::kutrl404();
+
+ return;
+ }
+
+ $args = $m[3] ?? '';
+ dcCore::app()->ctx->kutrl_msg = '';
+ dcCore::app()->ctx->kutrl_hmf = FrontendUtils::create();
+ dcCore::app()->ctx->kutrl_hmfp = FrontendUtils::protect(dcCore::app()->ctx->kutrl_hmf);
+
+ $kut = new Service\ServiceLocal();
+
+ # Nothing on url
+ if ($m[1] == '/') {
+ dcCore::app()->ctx->kutrl_msg = 'No link given.';
+ }
+ # find suffix on redirect url
+ $suffix = '';
+ if (preg_match('@^([^?/#]+)(.*?)$@', $args, $more)) {
+ $args = $more[1];
+ $suffix = $more[2];
+ }
+ # No arg, go to kurtl page
+ if ($args == '') {
+ self::pageKutrl($kut);
+
+ return;
+ }
+ # Not find, go to kutrl 404
+ if (false === ($url = $kut->getUrl($args))) {
+ //dcCore::app()->ctx->kutrl_msg = 'Failed to find short link.';
+ //self::pageKutrl($kut);
+ self::kutrl404();
+
+ return;
+ }
+ # Removed (empty url), go to kutrl 404
+ if (!$url) {
+ self::kutrl404();
+
+ return;
+ }
+
+ dcCore::app()->blog->triggerBlog();
+ Http::redirect($url . $suffix);
+ }
+
+ private static function pageKutrl(Service $kut): void
+ {
+ $s = My::settings();
+
+ # Not active, go to default 404
+ if (!$s->get('active')) {
+ self::p404();
+
+ return;
+ }
+ # Public page not active, go to kutrl 404
+ if (!$s->get('srv_local_public')) {
+ self::kutrl404();
+
+ return;
+ }
+ # Validation form
+ $url = !empty($_POST['longurl']) ? trim(dcCore::app()->con->escapeStr((string) $_POST['longurl'])) : '';
+ if (!empty($url)) {
+ $hmf = !empty($_POST['hmf']) ? $_POST['hmf'] : '!';
+ $hmfu = !empty($_POST['hmfp']) ? FrontendUtils::unprotect($_POST['hmfp']) : '?';
+
+ $err = false;
+ if (!$err) {
+ if ($hmf != $hmfu) {
+ $err = true;
+ dcCore::app()->ctx->kutrl_msg = __('Failed to verify protected field.');
+ }
+ }
+ if (!$err) {
+ if (!$kut->testService()) {
+ $err = true;
+ dcCore::app()->ctx->kutrl_msg = __('Service is not well configured.');
+ }
+ }
+ if (!$err) {
+ if (!$kut->isValidUrl($url)) {
+ $err = true;
+ dcCore::app()->ctx->kutrl_msg = __('This string is not a valid URL.');
+ }
+ }
+ if (!$err) {
+ if (!$kut->isLongerUrl($url)) {
+ $err = true;
+ dcCore::app()->ctx->kutrl_msg = __('This link is too short.');
+ }
+ }
+ if (!$err) {
+ if (!$kut->isProtocolUrl($url)) {
+ $err = true;
+ dcCore::app()->ctx->kutrl_msg = __('This type of link is not allowed.');
+ }
+ }
+
+ if (!$err) {
+ if (!$kut->allow_external_url && !$kut->isBlogUrl($url)) {
+ $err = true;
+ dcCore::app()->ctx->kutrl_msg = __('Short links are limited to this blog URL.');
+ }
+ }
+ if (!$err) {
+ if ($kut->isServiceUrl($url)) {
+ $err = true;
+ dcCore::app()->ctx->kutrl_msg = __('This link is already a short link.');
+ }
+ }
+ if (!$err) {
+ if (false !== ($rs = $kut->isKnowUrl($url))) {
+ $err = true;
+
+ $url = $rs->url;
+ $new_url = $kut->url_base . $rs->hash;
+
+ dcCore::app()->ctx->kutrl_msg = sprintf(
+ __('Short link for %s is %s'),
+ Html::escapeHTML($url),
+ '' . $new_url . ''
+ );
+ }
+ }
+ if (!$err) {
+ if (false === ($rs = $kut->hash($url))) {
+ $err = true;
+ dcCore::app()->ctx->kutrl_msg = __('Failed to create short link.');
+ } else {
+ $url = $rs->url;
+ $new_url = $kut->url_base . $rs->hash;
+
+ dcCore::app()->ctx->kutrl_msg = sprintf(
+ __('Short link for %s is %s'),
+ Html::escapeHTML($url),
+ '' . $new_url . ''
+ );
+ dcCore::app()->blog->triggerBlog();
+
+ # ex: Send new url to messengers
+ if (!empty($rs)) {
+ dcCore::app()->callBehavior('publicAfterKutrlCreate', $rs, __('New public short URL'));
+ }
+ }
+ }
+ }
+
+ dcCore::app()->tpl->setPath(dcCore::app()->tpl->getPath(), My::path() . '/default-templates');
+ self::serveDocument('kutrl.html');
+ }
+
+ protected static function kutrl404(): void
+ {
+ if (!My::settigns()->get('srv_local_404_active')) {
+ self::p404();
+
+ return;
+ }
+
+ dcCore::app()->tpl->setPath(dcCore::app()->tpl->getPath(), My::path() . '/default-templates');
+
+ header('Content-Type: text/html; charset=UTF-8');
+ Http::head(404, 'Not Found');
+ dcCore::app()->url->type = '404';
+ dcCore::app()->ctx->current_tpl = 'kutrl404.html';
+ dcCore::app()->ctx->content_type = 'text/html';
+
+ echo dcCore::app()->tpl->getData(dcCore::app()->ctx->current_tpl);
+
+ # --BEHAVIOR-- publicAfterDocumentV2
+ dcCore::app()->callBehavior('publicAfterDocumentV2');
+ exit;
+ }
+}
diff --git a/src/FrontendUtils.php b/src/FrontendUtils.php
new file mode 100644
index 0000000..6593064
--- /dev/null
+++ b/src/FrontendUtils.php
@@ -0,0 +1,53 @@
+export(
+ My::TABLE_NAME,
+ 'SELECT kut_id, blog_id, kut_service, kut_type, ' .
+ 'kut_hash, kut_url, kut_dt, kut_password, kut_counter ' .
+ 'FROM ' . dcCore::app()->prefix . My::TABLE_NAME . ' ' .
+ "WHERE blog_id = '" . $blog_id . "' "
+ );
+ }
+
+ public static function exportFullV2($exp)
+ {
+ $exp->exportTable(My::TABLE_NAME);
+ }
+
+ public static function importInitV2($bk)
+ {
+ $bk->cur_kutrl = dcCore::app()->con->openCursor(dcCore::app()->prefix . My::TABLE_NAME);
+ $bk->kutrl = new Logs();
+ }
+
+ public static function importSingleV2($line, $bk)
+ {
+ if ($line->__name == My::TABLE_NAME) {
+ # Do nothing if str/type exists !
+ if (false === $bk->kutrl->select($line->kut_url, $line->kut_hash, $line->kut_type, $line->kut_service)) {
+ $bk->kutrl->insert($line->kut_url, $line->kut_hash, $line->kut_type, $line->kut_service);
+ }
+ }
+ }
+
+ public static function importFullV2($line, $bk)
+ {
+ if ($line->__name == My::TABLE_NAME) {
+ $bk->cur_kutrl->clean();
+ $bk->cur_kutrl->kut_id = (int) $line->kut_id;
+ $bk->cur_kutrl->blog_id = (string) $line->blog_id;
+ $bk->cur_kutrl->kut_service = (string) $line->kut_service;
+ $bk->cur_kutrl->kut_type = (string) $line->kut_type;
+ $bk->cur_kutrl->kut_hash = (string) $line->kut_hash;
+ $bk->cur_kutrl->kut_url = (string) $line->kut_url;
+ $bk->cur_kutrl->kut_dt = (string) $line->miniurl_dt;
+ $bk->cur_kutrl->kut_counter = (int) $line->kut_counter;
+ $bk->cur_kutrl->kut_password = (string) $line->kut_password;
+ $bk->cur_kutrl->insert();
+ }
+ }
+}
diff --git a/src/Install.php b/src/Install.php
index b2892e2..dab7c48 100644
--- a/src/Install.php
+++ b/src/Install.php
@@ -10,94 +10,109 @@
* @copyright Jean-Christian Denis
* @copyright GPL-2.0 https://www.gnu.org/licenses/gpl-2.0.html
*/
-if (!defined('DC_CONTEXT_ADMIN')) {
- return;
-}
+declare(strict_types=1);
-try {
- // Compare versions
- if (!dcCore::app()->newVersion(
- basename(__DIR__),
- dcCore::app()->plugins->moduleInfo(basename(__DIR__), 'version')
- )) {
- return null;
+namespace Dotclear\Plugin\kUtRL;
+
+use dcCore;
+use dcNamespace;
+use Dotclear\Core\Process;
+use Dotclear\Database\Structure;
+use Exception;
+
+/**
+ * Module installation.
+ */
+class Install extends Process
+{
+ public static function init(): bool
+ {
+ return self::status(My::checkContext(My::INSTALL));
}
- // Table
- $t = new dbStruct(dcCore::app()->con, dcCore::app()->prefix);
- $t->{initkUtRL::KURL_TABLE_NAME}
- ->kut_id('bigint', 0, false)
- ->blog_id('varchar', 32, false)
- ->kut_service('varchar', 32, false, "'kUtRL'")
- ->kut_type('varchar', 32, false)
- ->kut_hash('varchar', 32, false)
- ->kut_url('text', 0, false)
- ->kut_dt('timestamp', 0, false, 'now()')
- ->kut_password('varchar', 32, true)
- ->kut_counter('bigint', 0, false, 0)
-
- ->primary('pk_kutrl', 'kut_id')
- ->index('idx_kut_blog_id', 'btree', 'blog_id')
- ->index('idx_kut_hash', 'btree', 'kut_hash')
- ->index('idx_kut_service', 'btree', 'kut_service')
- ->index('idx_kut_type', 'btree', 'kut_type');
-
- $ti = new dbStruct(dcCore::app()->con, dcCore::app()->prefix);
- $changes = $ti->synchronize($t);
-
- // upgrade version < 2022.12.22 : upgrade settings id and ns and array
- $current = dcCore::app()->getVersion(basename(__DIR__));
- if ($current && version_compare($current, '2022.12.22', '<')) {
- $record = dcCore::app()->con->select(
- 'SELECT * FROM ' . dcCore::app()->prefix . dcNamespace::NS_TABLE_NAME . ' ' .
- "WHERE setting_ns = 'kUtRL' "
- );
- while ($record->fetch()) {
- if (preg_match('/^kutrl_(.*?)$/', $record->setting_id, $match)) {
- $cur = dcCore::app()->con->openCursor(dcCore::app()->prefix . dcNamespace::NS_TABLE_NAME);
- // avoid the use of serialize function
- if (in_array($record->setting_id, ['kutrl_srv_custom'])) {
- $cur->setting_value = json_encode(@unserialize(base64_decode((string) $record->setting_value)));
- }
- $cur->setting_id = $match[1];
- $cur->setting_ns = basename(__DIR__);
- $cur->update(
- "WHERE setting_id = '" . $record->setting_id . "' and setting_ns = 'kUtRL' " .
- 'AND blog_id ' . (null === $record->blog_id ? 'IS NULL ' : ("= '" . dcCore::app()->con->escape($record->blog_id) . "' "))
- );
- }
+ public static function process(): bool
+ {
+ if (!self::status()) {
+ return false;
}
- } else {
- // Settings
- $s = dcCore::app()->blog->settings->addNamespace(basename(__DIR__));
- $s->put('active', false, 'boolean', 'Enabled kutrl plugin', false, true);
- $s->put('plugin_service', 'default', 'string', 'Service to use to shorten links on third part plugins', false, true);
- $s->put('admin_service', 'local', 'string', 'Service to use to shorten links on admin', false, true);
- $s->put('tpl_service', 'local', 'string', 'Service to use to shorten links on template', false, true);
- $s->put('wiki_service', 'local', 'string', 'Service to use to shorten links on contents', false, true);
- $s->put('allow_external_url', true, 'boolean', 'Limited short url to current blog\'s url', false, true);
- $s->put('tpl_passive', true, 'boolean', 'Return long url on kutrl tags if kutrl is unactivate', false, true);
- $s->put('tpl_active', false, 'boolean', 'Return short url on dotclear tags if kutrl is active', false, true);
- $s->put('admin_entry_default', true, 'boolean', 'Create short link on new entry by default', false, true);
- # Settings for "local" service
- $local_css = ".shortenkutrlwidget input { border: 1px solid #CCCCCC; }\n" .
- '.dc-kutrl input { border: 1px solid #CCCCCC; margin: 10px; }';
- $s->put('srv_local_protocols', 'http:,https:,ftp:,ftps:,irc:', 'string', 'Allowed kutrl local service protocols', false, true);
- $s->put('srv_local_public', false, 'boolean', 'Enabled local service public page', false, true);
- $s->put('srv_local_css', $local_css, 'string', 'Special CSS for kutrl local service', false, true);
- $s->put('srv_local_404_active', false, 'boolean', 'Use special 404 page on unknow urls', false, true);
- # Settings for "bilbolinks" service
- $s->put('srv_bilbolinks_base', 'http://tux-pla.net/', 'string', 'URL of bilbolinks service', false, true);
- # Settings for "YOURLS" service
- $s->put('srv_yourls_base', '', 'string', 'URL of YOURLS service', false, true);
- $s->put('srv_yourls_username', '', 'string', 'User name to YOURLS service', false, true);
- $s->put('srv_yourls_password', '', 'string', 'User password to YOURLS service', false, true);
+ try {
+ // Table
+ $t = new Structure(dcCore::app()->con, dcCore::app()->prefix);
+ $t->{My::TABLE_NAME}
+ ->kut_id('bigint', 0, false)
+ ->blog_id('varchar', 32, false)
+ ->kut_service('varchar', 32, false, "'kUtRL'")
+ ->kut_type('varchar', 32, false)
+ ->kut_hash('varchar', 32, false)
+ ->kut_url('text', 0, false)
+ ->kut_dt('timestamp', 0, false, 'now()')
+ ->kut_password('varchar', 32, true)
+ ->kut_counter('bigint', 0, false, 0)
+
+ ->primary('pk_kutrl', 'kut_id')
+ ->index('idx_kut_blog_id', 'btree', 'blog_id')
+ ->index('idx_kut_hash', 'btree', 'kut_hash')
+ ->index('idx_kut_service', 'btree', 'kut_service')
+ ->index('idx_kut_type', 'btree', 'kut_type');
+
+ (new Structure(dcCore::app()->con, dcCore::app()->prefix))->synchronize($t);
+
+ // upgrade version < 2022.12.22 : upgrade settings id and ns and array
+ $current = dcCore::app()->getVersion(My::id());
+ if ($current && version_compare($current, '2022.12.22', '<')) {
+ $record = dcCore::app()->con->select(
+ 'SELECT * FROM ' . dcCore::app()->prefix . dcNamespace::NS_TABLE_NAME . ' ' .
+ "WHERE setting_ns = 'kUtRL' "
+ );
+ while ($record->fetch()) {
+ if (preg_match('/^kutrl_(.*?)$/', $record->setting_id, $match)) {
+ $cur = dcCore::app()->con->openCursor(dcCore::app()->prefix . dcNamespace::NS_TABLE_NAME);
+ // avoid the use of serialize function
+ if (in_array($record->setting_id, ['kutrl_srv_custom'])) {
+ $cur->setting_value = json_encode(@unserialize(base64_decode((string) $record->setting_value)));
+ }
+ $cur->setting_id = $match[1];
+ $cur->setting_ns = basename(__DIR__);
+ $cur->update(
+ "WHERE setting_id = '" . $record->setting_id . "' and setting_ns = 'kUtRL' " .
+ 'AND blog_id ' . (null === $record->blog_id ? 'IS NULL ' : ("= '" . dcCore::app()->con->escapeStr((string) $record->blog_id) . "' "))
+ );
+ }
+ }
+ } else {
+ // Settings
+ $s = My::settings();
+
+ $s->put('active', false, 'boolean', 'Enabled kutrl plugin', false, true);
+ $s->put('plugin_service', 'default', 'string', 'Service to use to shorten links on third part plugins', false, true);
+ $s->put('admin_service', 'local', 'string', 'Service to use to shorten links on admin', false, true);
+ $s->put('tpl_service', 'local', 'string', 'Service to use to shorten links on template', false, true);
+ $s->put('wiki_service', 'local', 'string', 'Service to use to shorten links on contents', false, true);
+ $s->put('allow_external_url', true, 'boolean', 'Limited short url to current blog\'s url', false, true);
+ $s->put('tpl_passive', true, 'boolean', 'Return long url on kutrl tags if kutrl is unactivate', false, true);
+ $s->put('tpl_active', false, 'boolean', 'Return short url on dotclear tags if kutrl is active', false, true);
+ $s->put('admin_entry_default', true, 'boolean', 'Create short link on new entry by default', false, true);
+ # Settings for "local" service
+ $local_css = ".shortenkutrlwidget input { border: 1px solid #CCCCCC; }\n" .
+ '.dc-kutrl input { border: 1px solid #CCCCCC; margin: 10px; }';
+ $s->put('srv_local_protocols', 'http:,https:,ftp:,ftps:,irc:', 'string', 'Allowed kutrl local service protocols', false, true);
+ $s->put('srv_local_public', false, 'boolean', 'Enabled local service public page', false, true);
+ $s->put('srv_local_css', $local_css, 'string', 'Special CSS for kutrl local service', false, true);
+ $s->put('srv_local_404_active', false, 'boolean', 'Use special 404 page on unknow urls', false, true);
+ # Settings for "bilbolinks" service
+ $s->put('srv_bilbolinks_base', 'http://tux-pla.net/', 'string', 'URL of bilbolinks service', false, true);
+ # Settings for "YOURLS" service
+ $s->put('srv_yourls_base', '', 'string', 'URL of YOURLS service', false, true);
+ $s->put('srv_yourls_username', '', 'string', 'User name to YOURLS service', false, true);
+ $s->put('srv_yourls_password', '', 'string', 'User password to YOURLS service', false, true);
+ }
+
+ return true;
+ } catch (Exception $e) {
+ dcCore::app()->error->add($e->getMessage());
+
+ return false;
+ }
}
-
- return true;
-} catch (Exception $e) {
- dcCore::app()->error->add($e->getMessage());
}
-
-return false;
diff --git a/src/LinksListing.php b/src/LinksListing.php
index 9ffda50..3b65b76 100644
--- a/src/LinksListing.php
+++ b/src/LinksListing.php
@@ -10,121 +10,141 @@
* @copyright Jean-Christian Denis
* @copyright GPL-2.0 https://www.gnu.org/licenses/gpl-2.0.html
*/
-class kutrlLinkslist
+declare(strict_types=1);
+
+namespace Dotclear\Plugin\kUtRL;
+
+use ArrayObject;
+use dcCore;
+use Dotclear\Core\Backend\Filter\Filters;
+use Dotclear\Core\Backend\Listing\{
+ Listing,
+ Pager
+};
+use Dotclear\Helper\Date;
+use Dotclear\Helper\Html\Form\{
+ Checkbox,
+ Div,
+ Link,
+ Note,
+ Para,
+ Text,
+};
+use Dotclear\Helper\Html\Html;
+
+class LinksListing extends Listing
{
- protected $rs;
- protected $rs_count;
- protected $html_prev;
- protected $html_next;
-
- public function __construct($rs, $rs_count)
- {
- $this->rs = &$rs;
- $this->rs_count = $rs_count;
- $this->html_prev = __('« prev.');
- $this->html_next = __('next »');
- }
-
- public function userColumns($type, $cols)
- {
- $cols_user = @dcCore::app()->auth->user_prefs->interface->cols;
- if (is_array($cols_user) || $cols_user instanceof ArrayObject) {
- if (isset($cols_user[$type])) {
- foreach ($cols_user[$type] as $cn => $cd) {
- if (!$cd && isset($cols[$cn])) {
- unset($cols[$cn]);
- }
- }
- }
- }
- }
-
- public function display($page, $nb_per_page, $enclose_block, $filter = false)
+ public function display(Filters $filter, string $enclose_block): void
{
if ($this->rs->isEmpty()) {
- if ($filter) {
- echo '
' . __('No short link matches the filter') . '
';
- } else {
- echo '
' . __('No short link') . '
';
- }
- } else {
- $pager = new dcPager($page, $this->rs_count, $nb_per_page, 10);
- $links = [];
- if (isset($_REQUEST['entries'])) {
- foreach ($_REQUEST['entries'] as $v) {
- $links[(int) $v] = true;
- }
- }
+ echo (new Note())
+ ->class('info')
+ ->text($filter->show() ? __('No short link matches the filter') : __('No short link'))
+ ->render();
- $cols = [
- 'kut_url' => '
' .
- __('There is nothing to configure for this service.') .
- '
';
+ return (new Div())
+ ->items([
+ (new Note())
+ ->class('form-note')
+ ->text(__('There is nothing to configure for this service.')),
+ ]);
}
# Test if service is well configured
- public function testService()
+ public function testService(): bool
{
- return null;
+ return true;
}
# Test if an url is valid
- public function isValidUrl($url)
+ public function isValidUrl(string $url): bool
{
return (bool) filter_var($url, FILTER_VALIDATE_URL);
}
# Test if an url contents know prefix
- public function isServiceUrl($url)
+ public function isServiceUrl(string $url): bool
{
return strpos($url, $this->url_base) === 0;
}
# Test if an url is long enoutgh
- public function isLongerUrl($url)
+ public function isLongerUrl(string $url): bool
{
return (strlen($url) >= (int) $this->url_min_len);
}
# Test if an url protocol (eg: http://) is allowed
- public function isProtocolUrl($url)
+ public function isProtocolUrl(string $url): bool
{
foreach ($this->allow_protocols as $protocol) {
if (empty($protocol)) {
@@ -126,7 +142,7 @@ class kutrlService
}
# Test if an url is from current blog
- public function isBlogUrl($url)
+ public function isBlogUrl(string $url): bool
{
$base = dcCore::app()->blog->url;
$url = substr($url, 0, strlen($base));
@@ -134,22 +150,34 @@ class kutrlService
return $url == $base;
}
- # Test if an url is know
- public function isKnowUrl($url)
+ /**
+ * Test if an url is know.
+ *
+ * @return false|MetaRecord
+ */
+ public function isKnowUrl(string $url)
{
return $this->log->select($url, null, $this->id, 'kutrl');
}
- # Test if an custom short url is know
- public function isKnowHash($hash)
+ /**
+ * Test if an custom short url is know.
+ *
+ * @return false|MetaRecord
+ */
+ public function isKnowHash(string $hash)
{
return $this->log->select(null, $hash, $this->id, 'kutrl');
}
- # Create hash from url
- public function hash($url, $hash = null)
+ /**
+ * Create hash from url.
+ *
+ * @return false|MetaRecord
+ */
+ public function hash(string $url, ?string $hash = null)
{
- $url = trim(dcCore::app()->con->escape($url));
+ $url = trim(dcCore::app()->con->escapeStr((string) $url));
if ('undefined' === $this->id) {
return false;
}
@@ -183,41 +211,54 @@ class kutrlService
return $rs;
}
- # Create a hash for a given url (and its custom hash)
- public function createHash($url, $hash = null)
+ /**
+ * Create a hash for a given url (and its custom hash).
+ *
+ * @return false|ArrayObject
+ */
+ public function createHash(string $url, ?string $hash = null)
{
return false;
}
- # Remove an url from list of know urls
- public function remove($url)
+ /**
+ * Remove an url from list of know urls.
+ */
+ public function remove(string $url): bool
{
if (!($rs = $this->isKnowUrl($url))) {
return false;
}
$this->deleteUrl($url);
- $this->log->delete($rs->id);
+ $this->log->delete((int) $rs->id);
return true;
}
- # Delete url on service (second argument really delete urls)
- public function deleteUrl($url, $delete = false)
- {
- return null;
- }
-
- # Retrieve long url from hash
- public function getUrl($hash)
+ /**
+ * Delete url on service (second argument really delete urls).
+ */
+ public function deleteUrl(string $url, bool $delete = false): bool
{
return false;
}
- # Post request
- public static function post($server, $data, $verbose = true, $get = false, $headers = [])
+ /**
+ * Retrieve long url from hash.
+ *
+ * @return false|string
+ */
+ public function getUrl(string $hash)
{
- $url = (string) $server;
- $client = netHttp::initClient($url, $url);
+ return false;
+ }
+
+ /**
+ * Post request.
+ */
+ public static function post(string $url, $data, bool $verbose = true, bool $get = false, $headers = [])
+ {
+ $client = HttpClient::initClient($url, $url);
$client->setUserAgent('kUtRL - https://github.com/JcDenis/kUtRL');
$client->setPersistReferers(false);
diff --git a/src/Service/ServiceBilbolinks.php b/src/Service/ServiceBilbolinks.php
index 572f413..7eb56ed 100644
--- a/src/Service/ServiceBilbolinks.php
+++ b/src/Service/ServiceBilbolinks.php
@@ -10,11 +10,21 @@
* @copyright Jean-Christian Denis
* @copyright GPL-2.0 https://www.gnu.org/licenses/gpl-2.0.html
*/
-if (!defined('DC_RC_PATH')) {
- return null;
-}
+declare(strict_types=1);
-class bilbolinksKutrlService extends kutrlService
+namespace Dotclear\Plugin\kUtRL\Service;
+
+use ArrayObject;
+use Dotclear\Helper\Html\Form\{
+ Div,
+ Input,
+ label,
+ Note,
+ Para
+};
+use Dotclear\Plugin\kUtRL\Service;
+
+class ServiceBilbolinks extends Service
{
protected $config = [
'id' => 'bilbolinks',
@@ -22,7 +32,7 @@ class bilbolinksKutrlService extends kutrlService
'home' => 'http://www.tux-planet.fr/bilbobox/',
];
- protected function init()
+ protected function init(): void
{
$base = (string) $this->settings->get('srv_bilbolinks_base');
if (!empty($base) && substr($base, -1, 1) != '/') {
@@ -33,7 +43,7 @@ class bilbolinksKutrlService extends kutrlService
$this->config['url_min_len'] = 25;
}
- public function saveSettings()
+ public function saveSettings(): void
{
$base = '';
if (!empty($_POST['kutrl_srv_bilbolinks_base'])) {
@@ -45,19 +55,26 @@ class bilbolinksKutrlService extends kutrlService
$this->settings->put('srv_bilbolinks_base', $base);
}
- public function settingsForm()
+ public function settingsForm(): Div
{
- echo
- '' .
- '
' .
- __('This is the root URL of the "bilbolinks" service you want to use. Ex: "http://tux-pla.net/".') .
- '
';
+ return (new Div())
+ ->items([
+ (new Para())
+ ->items([
+ (new Label(__('Url of the service:'), Label::OUTSIDE_LABEL_BEFORE))
+ ->for('kutrl_srv_bilbolinks_base'),
+ (new Input('kutrl_srv_bilbolinks_base'))
+ ->size(50)
+ ->maxlenght(255)
+ ->value((string) $this->settings->get('srv_bilbolinks_base')),
+ ]),
+ (new Note())
+ ->class('form-note')
+ ->text(__('This is the root URL of the "bilbolinks" service you want to use. Ex: "http://tux-pla.net/".')),
+ ]);
}
- public function testService()
+ public function testService(): bool
{
if (empty($this->url_base)) {
$this->error->add(__('Service is not well configured.'));
@@ -75,7 +92,7 @@ class bilbolinksKutrlService extends kutrlService
return true;
}
- public function createHash($url, $hash = null)
+ public function createHash(string $url, ?string $hash = null)
{
$arg = ['longurl' => $url];
diff --git a/src/Service/ServiceBitly.php b/src/Service/ServiceBitly.php
index a08b83a..bf4383d 100644
--- a/src/Service/ServiceBitly.php
+++ b/src/Service/ServiceBitly.php
@@ -10,20 +10,30 @@
* @copyright Jean-Christian Denis
* @copyright GPL-2.0 https://www.gnu.org/licenses/gpl-2.0.html
*/
-if (!defined('DC_RC_PATH')) {
- return null;
-}
+declare(strict_types=1);
-class bitlyKutrlService extends kutrlService
+namespace Dotclear\Plugin\kUtRL\Service;
+
+use ArrayObject;
+use Dotclear\Helper\Html\Form\{
+ Div,
+ Input,
+ label,
+ Note,
+ Para
+};
+use Dotclear\Plugin\kUtRL\Service;
+
+class ServiceBitly extends Service
{
protected $config = [
- 'id' => 'bitly',
- 'name' => 'bit.ly',
- 'home' => 'https://bit.ly',
+ 'id' => 'bitly',
+ 'name' => 'bit.ly',
+ 'home' => 'https://bit.ly',
- 'url_api' => 'https://api-ssl.bitly.com/v4/',
- 'url_base' => 'https://bit.ly/',
- 'url_min_len' => 25,
+ 'url_api' => 'https://api-ssl.bitly.com/v4/',
+ 'url_base' => 'https://bit.ly/',
+ 'url_min_len' => 25,
'allow_protocols' => ['http://', 'https://'],
];
@@ -32,28 +42,36 @@ class bitlyKutrlService extends kutrlService
'apiKey' => '',
];
- protected function init()
+ protected function init(): void
{
$this->args['apiKey'] = $this->settings->get('srv_bitly_apikey');
}
- public function saveSettings()
+ public function saveSettings(): void
{
$this->settings->put('srv_bitly_apikey', $_POST['kutrl_srv_bitly_apikey']);
}
- public function settingsForm()
+ public function settingsForm(): Div
{
- echo
- '' .
- '
' .
- sprintf(__('This is your personnal %s API key. You can find it on your account page.'), $this->config['name']) .
- '
';
+ return (new Div())
+ ->items([
+ (new Para())
+ ->items([
+ (new Label(__('API Key:'), Label::OUTSIDE_LABEL_BEFORE))
+ ->for('kutrl_srv_bitly_apikey'),
+ (new Input('kutrl_srv_bitly_apikey'))
+ ->size(50)
+ ->maxlenght(255)
+ ->value((string) $this->settings->get('srv_bitly_apikey')),
+ ]),
+ (new Note())
+ ->class('form-note')
+ ->text(sprintf(__('This is your personnal %s API key. You can find it on your account page.'), $this->config['name'])),
+ ]);
}
- public function testService()
+ public function testService(): bool
{
if (empty($this->args['apiKey'])) {
$this->error->add(__('Service is not well configured.'));
@@ -71,7 +89,7 @@ class bitlyKutrlService extends kutrlService
return true;
}
- public function createHash($url, $hash = null)
+ public function createHash(string $url, ?string $hash = null)
{
$args = json_encode(['domain' => 'bit.ly', 'long_url' => $url]);
diff --git a/src/Service/ServiceCustom.php b/src/Service/ServiceCustom.php
index 6df5b3f..4a98645 100644
--- a/src/Service/ServiceCustom.php
+++ b/src/Service/ServiceCustom.php
@@ -10,18 +10,29 @@
* @copyright Jean-Christian Denis
* @copyright GPL-2.0 https://www.gnu.org/licenses/gpl-2.0.html
*/
-if (!defined('DC_RC_PATH')) {
- return null;
-}
+declare(strict_types=1);
-class customKutrlService extends kutrlService
+namespace Dotclear\Plugin\kUtRL\Service;
+
+use ArrayObject;
+use Dotclear\Helper\Html\Form\{
+ Checkbox,
+ Div,
+ Input,
+ Label,
+ Note,
+ Para
+};
+use Dotclear\Plugin\kUtRL\Service;
+
+class ServiceCustom extends Service
{
protected $config = [
'id' => 'custom',
'name' => 'Custom',
];
- protected function init()
+ protected function init(): void
{
$config = json_decode((string) $this->settings->get('srv_custom'), true);
if (!is_array($config)) {
@@ -36,7 +47,7 @@ class customKutrlService extends kutrlService
$this->config['url_min_length'] = strlen($this->url_base) + 2;
}
- public function saveSettings()
+ public function saveSettings(): void
{
$config = [
'url_api' => $_POST['kutrl_srv_custom_url_api'],
@@ -47,7 +58,7 @@ class customKutrlService extends kutrlService
$this->settings->put('srv_custom', json_encode($config));
}
- public function settingsForm()
+ public function settingsForm(): Div
{
$default = [
'url_api' => '',
@@ -61,30 +72,63 @@ class customKutrlService extends kutrlService
}
$config = array_merge($default, $config);
- echo
- '
' . __('You can set a configurable service.') . ' ' .
- __('It consists on a simple query to an URL with only one param.') . ' ' .
- __('It must respond with a http code 200 on success.') . ' ' .
- __('It must returned the short URL (or only hash) in clear text.') . '
' .
- '' .
- '
' . __('Full path to API of the URL shortener. ex: "http://is.gd/api.php"') . '
' .
- '' .
- '
' . __('Common part of the short URL. ex: "http://is.gd/"') . '
' .
- '' .
- '
' . __('Param of the query. ex: "longurl"') . '
' .
- '';
+ return (new Div())
+ ->items([
+ (new Para())
+ ->text(
+ __('You can set a configurable service.') . ' ' .
+ __('It consists on a simple query to an URL with only one param.') . ' ' .
+ __('It must respond with a http code 200 on success.') . ' ' .
+ __('It must returned the short URL (or only hash) in clear text.')
+ ),
+ (new Para())
+ ->items([
+ (new Label(__('API URL:'), Label::OUTSIDE_LABEL_BEFORE))
+ ->for('kutrl_srv_custom_url_api'),
+ (new Input('kutrl_srv_custom_url_api'))
+ ->size(50)
+ ->maxlenght(255)
+ ->value((string) $config['url_api']),
+ ]),
+ (new Note())
+ ->class('form-note')
+ ->text(__('Full path to API of the URL shortener. ex: "http://is.gd/api.php"')),
+ (new Para())
+ ->items([
+ (new Label(__('Short URL domain:'), Label::OUTSIDE_LABEL_BEFORE))
+ ->for('kutrl_srv_custom_url_base'),
+ (new Input('kutrl_srv_custom_url_base'))
+ ->size(50)
+ ->maxlenght(255)
+ ->value((string) $config['url_base']),
+ ]),
+ (new Note())
+ ->class('form-note')
+ ->text(__('Common part of the short URL. ex: "http://is.gd/"')),
+ (new Para())
+ ->items([
+ (new Label(__('API URL param:'), Label::OUTSIDE_LABEL_BEFORE))
+ ->for('kutrl_srv_custom_url_param'),
+ (new Input('kutrl_srv_custom_url_param'))
+ ->size(50)
+ ->maxlenght(255)
+ ->value((string) $config['url_param']),
+ ]),
+ (new Note())
+ ->class('form-note')
+ ->text(__('Param of the query. ex: "longurl"')),
+ (new Para())
+ ->items([
+ (new Checkbox('kutrl_srv_custom_url_encode', (bool) $config['url_encode']))
+ ->value(1),
+ (new Label(__('Encode URL'), Label::OUTSIDE_LABEL_AFTER))
+ ->class('classic')
+ ->for('kutrl_srv_custom_url_encode'),
+ ]),
+ ]);
}
- public function testService()
+ public function testService(): bool
{
if (empty($this->url_api)) {
return false;
@@ -100,7 +144,7 @@ class customKutrlService extends kutrlService
return true;
}
- public function createHash($url, $hash = null)
+ public function createHash(string $url, ?string $hash = null)
{
$enc = $this->url_encode ? urlencode($url) : $url;
$arg = [$this->url_param => $enc];
diff --git a/src/Service/ServiceDefault.php b/src/Service/ServiceDefault.php
index 9214825..72422bb 100644
--- a/src/Service/ServiceDefault.php
+++ b/src/Service/ServiceDefault.php
@@ -10,55 +10,70 @@
* @copyright Jean-Christian Denis
* @copyright GPL-2.0 https://www.gnu.org/licenses/gpl-2.0.html
*/
-if (!defined('DC_RC_PATH')) {
- return null;
-}
+declare(strict_types=1);
+
+namespace Dotclear\Plugin\kUtRL\Service;
+
+use ArrayObject;
+use Dotclear\Helper\Html\Form\{
+ Div,
+ Note,
+ Para,
+ Text
+};
+use Dotclear\Plugin\kUtRL\Service;
# nb: "default" ne veut pas dire service par défaut
# mais service simple et rapide configuré par des constantes
# cela permet de configurer ces constantes dans le fichier
# config de Dotclear pour une plateforme complète.
-class defaultKutrlService extends kutrlService
+class ServiceDefault extends Service
{
- protected function init()
+ protected function init(): void
{
$this->config = [
- 'id' => 'default',
- 'name' => 'Default',
- 'home' => '',
+ 'id' => 'default',
+ 'name' => 'Default',
+ 'home' => '',
'url_api' => SHORTEN_SERVICE_API,
'url_base' => SHORTEN_SERVICE_BASE,
'url_min_len' => strlen(SHORTEN_SERVICE_BASE) + 2,
- 'url_param' => SHORTEN_SERVICE_PARAM,
- 'url_encode' => SHORTEN_SERVICE_ENCODE,
+ 'url_param' => SHORTEN_SERVICE_PARAM,
+ 'url_encode' => SHORTEN_SERVICE_ENCODE,
];
}
- public function settingsForm()
+ public function settingsForm(): Div
{
- echo
- '
' .
- __('There is nothing to configure for this service.') .
- '
';
+ return (new Div())
+ ->items([
+ (new Note())
+ ->class('form-note')
+ ->text(__('There is nothing to configure for this service.')),
+ (new Para())
+ ->text(__('There is nothing to configure for this service.')),
+ (new Text(
+ '',
+ '
' .
+ return (new Div())
+ ->items([
+ (new Div())
+ ->class('two-cols')
+ ->items([
+ (new Div())
+ ->class('col')
+ ->items([
+ (new Text('b', __('Settings:'))),
+ (new Para())
+ ->items([
+ (new Label(__('Allowed protocols:'), Label::OUTSIDE_LABEL_BEFORE))
+ ->for('kutrl_srv_local_protocols'),
+ (new Input('kutrl_srv_local_protocols'))
+ ->size(50)
+ ->maxlenght(255)
+ ->value((string) $this->settings->get('srv_local_protocols')),
+ ]),
+ (new Note())
+ ->class('form-note')
+ ->text(__('Use comma seperated list like: "http:,https:,ftp:"')),
+ (new Para())
+ ->items([
+ (new Checkbox('kutrl_srv_local_public', (bool) $this->settings->get('srv_local_public')))
+ ->value(1),
+ (new Label(__('Enable public page for visitors to shorten links'), Label::OUTSIDE_LABEL_AFTER))
+ ->class('classic')
+ ->for('kutrl_srv_local_public'),
+ ]),
+ (new Para('style-area'))
+ ->class('area')
+ ->items([
+ (new Label(__('CSS:'), Label::OUTSIDE_LABEL_BEFORE))
+ ->for('kutrl_srv_local_css'),
+ (new Textarea('kutrl_srv_local_css', Html::escapeHTML($this->settings->get('srv_local_css'))))
+ ->cols(50)
+ ->rows(3),
+ ]),
+ (new Note())
+ ->class('form-note')
+ ->text(__('You can add here special cascading style sheet. Body of page has class "dc-kutrl" and widgets have class "shortenkutrlwidget" and "rankkutrlwidget".')),
+ (new Para())
+ ->items([
+ (new Checkbox('kutrl_srv_local_404_active', (bool) $this->settings->get('srv_local_404_active')))
+ ->value(1),
+ (new Label(__('Enable special 404 error public page for unknow urls'), Label::OUTSIDE_LABEL_AFTER))
+ ->class('classic')
+ ->for('kutrl_srv_local_404_active'),
+ ]),
+ (new Note())
+ ->class('form-note')
+ ->text(__('If this is not activated, the default 404 page of the theme will be display.')),
+ ]),
- '
' . __('You can add here special cascading style sheet. Body of page has class "dc-kutrl" and widgets have class "shortenkutrlwidget" and "rankkutrlwidget".') . '
' .
-
- '' .
- '
' . __('If this is not activated, the default 404 page of the theme will be display.') . '
' .
-
- '
' .
-
- '
' . __('Note:') . '
' .
- '
' .
- __('This service use your own Blog to shorten and serve URL.') . ' ' .
- sprintf(__('This means that with this service short links start with "%s".'), $this->url_base) .
- '
' .
- '
' .
- __("You can use Dotclear's plugin called myUrlHandlers to change short links prefix on your blog.");
-
- if (preg_match('/index\.php/', $this->url_base)) {
- echo
- '
' . __('There are two templates delivered with kUtRL, if you do not use default theme, you may adapt them to yours.') . ' ' .
- __('Files are in plugin directory /default-templates, just copy them into your theme and edit them.') . '
' .
-
- '
';
+ (new Div())
+ ->class('col')
+ ->items([
+ (new Text('b', __('Note:'))),
+ (new Text(
+ 'p',
+ __('This service use your own Blog to shorten and serve URL.') . ' ' .
+ sprintf(__('This means that with this service short links start with "%s".'), $this->url_base)
+ )),
+ (new Text(
+ 'p',
+ __("You can use Dotclear's plugin called myUrlHandlers to change short links prefix on your blog.") .
+ (
+ preg_match('/index\.php/', $this->url_base) ?
+ ' ' .
+ __("We recommand that you use a rewrite engine in order to remove 'index.php' from your blog's URL.") .
+ ' ' .
+ __("You can find more about this on the Dotclear's documentation.") .
+ ''
+ : ''
+ )
+ )),
+ (new Text(
+ 'p',
+ __('There are two templates delivered with kUtRL, if you do not use default theme, you may adapt them to yours.') . ' ' .
+ __('Files are in plugin directory /default-templates, just copy them into your theme and edit them.')
+ )),
+ ]),
+ ]),
+ (new Text('br', ''))->class('clear'),
+ ]);
}
- public function testService()
+ public function testService(): bool
{
$ap = $this->allow_protocols;
if (!empty($ap)) {
@@ -109,7 +156,7 @@ class localKutrlService extends kutrlService
return false;
}
- public function createHash($url, $hash = null)
+ public function createHash(string $url, ?string $hash = null)
{
# Create response object
$rs = new ArrayObject();
@@ -121,12 +168,12 @@ class localKutrlService extends kutrlService
$type = 'localnormal';
$rs->hash = $this->next($this->last('localnormal'));
- # Mixed custom link
+ # Mixed custom link
} elseif (preg_match('/^([A-Za-z0-9]{2,})\!\!$/', $hash, $m)) {
$type = 'localmix';
$rs->hash = $m[1] . $this->next(-1, $m[1]);
- # Custom link
+ # Custom link
} elseif (preg_match('/^[A-Za-z0-9\.\-\_]{2,}$/', $hash)) {
if (false !== $this->log->select(null, $hash, null, 'local')) {
$this->error->add(__('Custom short link is already taken.'));
@@ -136,7 +183,7 @@ class localKutrlService extends kutrlService
$type = 'localcustom';
$rs->hash = $hash;
- # Wrong char in custom hash
+ # Wrong char in custom hash
} else {
$this->error->add(__('Custom short link is not valid.'));
@@ -215,7 +262,7 @@ class localKutrlService extends kutrlService
return implode($id);
}
- public function getUrl($hash)
+ public function getUrl(string $hash)
{
if (false === ($rs = $this->log->select(null, $hash, null, 'local'))) {
return false;
@@ -223,20 +270,20 @@ class localKutrlService extends kutrlService
if (!$rs->url) { //previously removed url
return false;
}
- $this->log->counter($rs->id, 'up');
+ $this->log->counter((int) $rs->id, 'up');
return $rs->url;
}
- public function deleteUrl($url, $delete = false)
+ public function deleteUrl(string $url, bool $delete = false): bool
{
if (false === ($rs = $this->log->select($url, null, null, 'local'))) {
return false;
}
if ($delete) {
- $this->log->delete($rs->id);
+ $this->log->delete((int) $rs->id);
} else {
- $this->log->clear($rs->id, '');
+ $this->log->clear((int) $rs->id);
}
return true;
diff --git a/src/Service/ServiceYourls.php b/src/Service/ServiceYourls.php
index d354557..e5f5071 100644
--- a/src/Service/ServiceYourls.php
+++ b/src/Service/ServiceYourls.php
@@ -10,11 +10,21 @@
* @copyright Jean-Christian Denis
* @copyright GPL-2.0 https://www.gnu.org/licenses/gpl-2.0.html
*/
-if (!defined('DC_RC_PATH')) {
- return null;
-}
+declare(strict_types=1);
-class yourlsKutrlService extends kutrlService
+namespace Dotclear\Plugin\kUtRL\Service;
+
+use ArrayObject;
+use Dotclear\Helper\Html\Form\{
+ Div,
+ Input,
+ Label,
+ Note,
+ Para
+};
+use Dotclear\Plugin\kUtRL\Service;
+
+class ServiceYourls extends Service
{
protected $config = [
'id' => 'yourls',
@@ -29,7 +39,7 @@ class yourlsKutrlService extends kutrlService
'action' => 'shorturl',
];
- protected function init()
+ protected function init(): void
{
$this->args['username'] = $this->settings->get('srv_yourls_username');
$this->args['password'] = $this->settings->get('srv_yourls_password');
@@ -42,38 +52,58 @@ class yourlsKutrlService extends kutrlService
$this->config['url_min_len'] = strlen($base) + 3;
}
- public function saveSettings()
+ public function saveSettings(): void
{
$this->settings->put('srv_yourls_username', $_POST['kutrl_srv_yourls_username']);
$this->settings->put('srv_yourls_password', $_POST['kutrl_srv_yourls_password']);
$this->settings->put('srv_yourls_base', $_POST['kutrl_srv_yourls_base']);
}
- public function settingsForm()
+ public function settingsForm(): Div
{
- echo
- '' .
- '
' .
- __('This is the URL of the YOURLS service you want to use. Ex: "http://www.smaller.org/api.php".') .
- '
' .
- '' .
- '
' .
- __('This is your user name to sign up to this YOURLS service.') .
- '
' .
- '' .
- '
' .
- __('This is your password to sign up to this YOURLS service.') .
- '
';
+ return (new Div())
+ ->items([
+ (new Para())
+ ->items([
+ (new Label(__('Url of the service:'), Label::OUTSIDE_LABEL_BEFORE))
+ ->for('kutrl_srv_yourls_base'),
+ (new Input('kutrl_srv_yourls_base'))
+ ->size(50)
+ ->maxlenght(255)
+ ->value((string) $this->settings->get('srv_yourls_base')),
+ (new Note())
+ ->class('form-note')
+ ->text(__('This is the URL of the YOURLS service you want to use. Ex: "http://www.smaller.org/api.php".')),
+ ]),
+ (new Para())
+ ->items([
+ (new Label(__('Login:'), Label::OUTSIDE_LABEL_BEFORE))
+ ->for('kutrl_srv_yourls_username'),
+ (new Input('kutrl_srv_yourls_username'))
+ ->size(50)
+ ->maxlenght(255)
+ ->value((string) $this->settings->get('srv_yourls_username')),
+ (new Note())
+ ->class('form-note')
+ ->text(__('This is your user name to sign up to this YOURLS service.')),
+ ]),
+ (new Para())
+ ->items([
+ (new Label(__('Password:'), Label::OUTSIDE_LABEL_BEFORE))
+ ->for('kutrl_srv_yourls_password'),
+ (new Input('kutrl_srv_yourls_password'))
+ ->size(50)
+ ->maxlenght(255)
+ ->value((string) $this->settings->get('srv_yourls_password')),
+ (new Note())
+ ->class('form-note')
+ ->text(__('This is your password to sign up to this YOURLS service.')),
+ ]),
+
+ ]);
}
- public function testService()
+ public function testService(): bool
{
if (empty($this->url_api)) {
$this->error->add(__('Service is not well configured.'));
@@ -99,7 +129,7 @@ class yourlsKutrlService extends kutrlService
return false;
}
- public function createHash($url, $hash = null)
+ public function createHash(string $url, ?string $hash = null)
{
$args = array_merge($this->args, ['url' => $url]);
diff --git a/src/Services/ServiceGoogl.php b/src/Services/ServiceGoogl.php
deleted file mode 100644
index ba787d7..0000000
--- a/src/Services/ServiceGoogl.php
+++ /dev/null
@@ -1,84 +0,0 @@
- '',
- ];
- private $headers = ['Content-Type: application/json'];
-
- protected function init()
- {
- $this->url_base = 'http://goo.gl/';
- $this->url_min_length = 20;
- }
-
- public function testService()
- {
- $args = $this->args;
- $args['shortUrl'] = $this->url_base . 'PLovn';
- if (!($response = self::post($this->url_api, $args, true, true, $this->headers))) {
- $this->error->add(__('Failed to call service.'));
-
- return false;
- }
-
- $rsp = json_decode($response);
-
- if (empty($rsp->status)) {
- $this->error->add(__('An error occured'));
-
- return false;
- }
-
- return true;
- }
-
- public function createHash($url, $hash = null)
- {
- $args = $this->args;
- $args['longUrl'] = $url;
- $args = json_encode($args);
-
- if (!($response = self::post($this->url_api, $args, true, false, $this->headers))) {
- $this->error->add(__('Failed to call service.'));
-
- return false;
- }
-
- $rsp = json_decode($response);
-
- if (empty($rsp->id)) {
- $this->error->add(__('An error occured'));
-
- return false;
- }
-
- $rs = new ArrayObject();
- $rs->hash = str_replace($this->url_base, '', $rsp->id);
- $rs->url = $rsp->longUrl;
- $rs->type = $this->id;
-
- return $rs;
- }
-}
diff --git a/src/Services/ServiceShortto.php b/src/Services/ServiceShortto.php
deleted file mode 100644
index 3cd7f60..0000000
--- a/src/Services/ServiceShortto.php
+++ /dev/null
@@ -1,58 +0,0 @@
- 'shortto',
- 'name' => 'short.to',
- 'home' => 'http://short.to',
-
- 'url_api' => 'http://short.to/s.txt',
- 'url_base' => 'http://short.to/',
- 'url_min_len' => 25,
- ];
-
- public function testService()
- {
- $arg = ['url' => urlencode($this->url_test)];
- if (!self::post($this->url_api, $arg, true, true)) {
- $this->error->add(__('Service is unavailable.'));
-
- return false;
- }
-
- return true;
- }
-
- public function createHash($url, $hash = null)
- {
- $arg = ['url' => $url];
-
- if (!($response = self::post($this->url_api, $arg, true, true))) {
- $this->error->add(__('Service is unavailable.'));
-
- return false;
- }
-
- $rs = new ArrayObject();
- $rs->hash = str_replace($this->url_base, '', $response);
- $rs->url = $url;
- $rs->type = $this->id;
-
- return $rs;
- }
-}
diff --git a/src/Services/ServiceSupr.php b/src/Services/ServiceSupr.php
deleted file mode 100644
index c0f000d..0000000
--- a/src/Services/ServiceSupr.php
+++ /dev/null
@@ -1,124 +0,0 @@
- 'supr',
- 'name' => 'su.pr StumbleUpon',
- 'home' => 'http://su.pr',
-
- 'url_api' => 'http://su.pr/api/',
- 'url_base' => 'http://su.pr/',
- 'url_min_len' => 23,
- ];
-
- private $args = [
- 'version' => '1.0',
- 'format' => 'xml',
- 'login' => '',
- 'apiKey' => '',
- ];
-
- protected function init()
- {
- $this->args['login'] = $this->settings->get('srv_supr_login');
- $this->args['apiKey'] = $this->settings->get('srv_supr_apikey');
- }
-
- public function saveSettings()
- {
- $this->settings->put('srv_supr_login', $_POST['kutrl_srv_supr_login']);
- $this->settings->put('srv_supr_apikey', $_POST['kutrl_srv_supr_apikey']);
- }
-
- public function settingsForm()
- {
- echo
- '' .
- '
' .
- sprintf(__('This is your login to sign up to %s'), $this->config['name']) .
- '
' .
- '' .
- '
' .
- sprintf(__('This is your personnal %s API key. You can find it on your account page.'), $this->config['name']) .
- '