Snippets

Heiko Bihlmaier TYPO3 Frontend Editing: Repair links when saving

Created by Heiko Bihlmaier
<?php

namespace SCW\Extkey\Hooks;

class PreProcess implements \TYPO3\CMS\FrontendEditing\RequestPreProcess\RequestPreProcessInterface
{
    public function preProcess(string $table, array $record, string &$fieldName, string $content, bool &$isFinished): string {

        $content = preg_replace_callback('/<a\s[^>]*href=\"([^\"]*)\"[^>]*>(.*)<\/a>/siU', function($matches) {
            $wrong = $matches[1];

            if(!preg_match('/^(t3|http|https|tel):\/\//', $wrong)) {
                if (substr($wrong, strlen($wrong)-1 ) == "/") {
                    $wrong = substr($wrong, 0, strlen($wrong) - 1);
                }

                $queryBuilder = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Core\Database\ConnectionPool::class)->getQueryBuilderForTable('tx_realurl_pathdata');
                $page = $queryBuilder
                    ->select('page_id')
                    ->from('tx_realurl_pathdata')
                    ->where(
                        $queryBuilder->expr()->eq('pagepath', $queryBuilder->createNamedParameter($wrong))
                    )
                    ->execute()
                    ->fetchColumn(0);

                if($page) {
                    $replace = "t3://page?uid=" . $page;
                } else {
                    $protocol = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') ||
                        $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
                    $domainName = $_SERVER['HTTP_HOST'];
                    $replace = $protocol.$domainName . '/' . $wrong . '/';
                }

                $return = str_replace($matches[1], $replace, $matches[0]);

                return $return;
            } else {
                return  $matches[0];
            }
        }, $content);
        $isFinished = true;
        return $content;
    }
}
1
2
3
4
5
<?php

// ......

$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['FrontendEditing']['requestPreProcess'][] = \SCW\Origo\Hooks\PreProcess::class;

Comments (1)

  1. Heiko Bihlmaier

    The idea behind this is that when you save the broken link is repaired. When the frontend editing is called again, the link is not selected correctly, but no error message is displayed when saving

    Requires realurl - extension.

    Feel free, to change this in your own project.

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.