<?php
namespace App\Twig\Extension;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
use Pimcore\Model\Document;
use Pimcore\Model\Document as PimcoreDocument;
use Pimcore\Model\Document\Page;
use Pimcore\Tool\Transliteration;
use Pimcore\Model\WebsiteSetting;
class Apik extends AbstractExtension
{
/** Listing des fonctions reprises en dessous de ce block */
public function getFunctions(): array
{
return [
new TwigFunction('build_data_object_url', [$this, 'buildDataObjectUrl']),
new TwigFunction('build_data_tag_url', [$this, 'buildDataTagUrl']),
new TwigFunction('build_data_tag_array_url', [$this, 'buildDataTagArrayUrl']),
new TwigFunction('get_localized_page_url', [$this, 'getLocalizedPageUrl']),
new TwigFunction('get_language_switcher', [$this, 'getLanguageSwitcher']),
new TwigFunction('get_language_switcher_html', [$this, 'getLanguageSwitcherHtml']),
new TwigFunction('email_obfuscator', [$this, 'emailObfuscator']),
new TwigFunction('email_obfuscator_svg', [$this, 'emailObfuscatorSvg']),
new TwigFunction('email_obfuscator_svg_only', [$this, 'emailObfuscatorSvgOnly']),
new TwigFunction('convert_phone_to_url', [$this, 'convertPhoneToPhoneUrl']),
new TwigFunction('get_body_class', [$this, 'getBodyClass']),
new TwigFunction('get_robots_index', [$this, 'getRobotsIndex']),
new TwigFunction('get_links_alternate', [$this, 'getLinksAlternate']),
new TwigFunction('website_config_advanced', [$this, 'websiteConfigAdvanced']),
new TwigFunction('to_url', [$this, 'toUrl']),
new TwigFunction('convert_date', [$this, 'convertDate']),
new TwigFunction('metadatas_image', [$this, 'metadatasImage']),
new TwigFunction('add_slashes', [$this, 'apk_addslashes']),
new TwigFunction('set_seo', [$this, 'setSeo']),
new TwigFunction('base_64', [$this, 'base64'])
];
}
/**
* Construit l'URL d'un Data Object
* @param $staticRouteNameNotLocalized Le nom de la Static Route non localisée (ex pour 'recette_fr', alors la valeur sera 'recette')
* @param $language La langue à retourner
* @param $dataObject Le Data Object
* @return $string
*
* Exemple:
* <?php
* $dataObjectUrl = buildDataObjectUrl('recette', $this->getLocale(), $monDataObject);
*
* Remarque:
* - Le code actuel ne prend en charge que les Static Route construite de la sorte: %lang/%prefix/%slug-%id
* - Le Data Object doit obligatoirement posséder un champ 'Slug'
* - Le champ slug doit être automatiquement généré via l'EventListener SaveDataObjectListener
*/
function buildDataObjectUrl($staticRouteNameNotLocalized, $language, $dataObject)
{
//$staticRouteLocalized = \Pimcore\Model\Staticroute::getByName($staticRouteNameNotLocalized . '_' . $language);
$staticRouteLocalized = \Pimcore\Model\Staticroute::getByName($staticRouteNameNotLocalized);
if ($staticRouteLocalized) {
$link = $staticRouteLocalized->getReverse(); // %lang/%prefix/%slug-%id
$link = str_replace('%lang', $language, $link);
$link = str_replace('%prefix', $staticRouteLocalized->getDefaults(), $link);
if(strpos($link, '%slug') !== false):
$link = str_replace('%slug', $dataObject->getSlug($language), $link);
endif;
if(strpos($link, '%name') !== false):
$link = str_replace('%name', self::toUrl($dataObject->getName($language)), $link);
endif;
if(strpos($link, '%title') !== false):
$link = str_replace('%title', self::toUrl($dataObject->getTitle($language)), $link);
endif;
$link = str_replace('%id', 'id'.$dataObject->getId(), $link);
}
return '/' . $link;
}
/**
* Construit l'URL pour un tag
* @param $staticRouteNameNotLocalized Le nom de la Static Route non localisée (ex pour 'recette_fr', alors la valeur sera 'recette')
* @param $language La langue à retourner
* @param $dataObject Le Data Object
* @return $string
*
*/
function buildDataTagUrl($staticRouteNameNotLocalized, $language, $dataObject)
{
$staticRouteLocalized = \Pimcore\Model\Staticroute::getByName($staticRouteNameNotLocalized . '_' . $language);
if ($staticRouteLocalized) {
$link = $staticRouteLocalized->getReverse(); // %lang/%prefix/%slug-%id
$link = str_replace('%lang', $language, $link);
$link = str_replace('%prefix', $staticRouteLocalized->getDefaults(), $link);
$link = str_replace('%name', self::toUrl($dataObject->getName($language)), $link);
$link = str_replace('%id', 'id'.$dataObject->getId(), $link);
}
return '/' . $link;
}
function buildDataTagArrayUrl($staticRouteNameNotLocalized, $language, $dataArray)
{
$staticRouteLocalized = \Pimcore\Model\Staticroute::getByName($staticRouteNameNotLocalized . '_' . $language);
if ($staticRouteLocalized) {
$link = $staticRouteLocalized->getReverse(); // %lang/%prefix/%slug-%id
$link = str_replace('%lang', $language, $link);
$link = str_replace('%prefix', $staticRouteLocalized->getDefaults(), $link);
$link = str_replace('%name', self::toUrl($dataArray['name']), $link);
$link = str_replace('%id', 'id'.$dataArray['id'], $link);
}
return '/' . $link;
}
/**
* Localise une Page (Document) dans la langue courante à partir de son ID et retourne son URL (string)
* @param $objectThis L'objet $this appelée depuis la vue
* @param $pageId L'ID de la Page (Document)
* @return null|PimcoreDocument
*
* Exemple:
* echo Apik::getLocalizedPageUrl($this, 123);
*/
public static function getLocalizedPageUrl($pageId)
{
$localizedPage = self::getLocalizedPage($pageId);
if ($localizedPage) {
return $localizedPage->getFullPath();
}
return '';
}
/**
* Localise une Page (Document) dans la langue courante à partir de son ID et retourne son document (objet)
* @param $objectThis L'objet $this appelée depuis la vue
* @param $pageId L'ID de la Page (Document)
* @return null|PimcoreDocument
*
* Exemple:
* $localizedPage = Apik::getLocalizedPage($this, 123);
* if ($localizedPage) {
* echo $localizedPage->getFullPath();
* }
*/
public static function getLocalizedPage($pageId)
{
$document = Document::getById($pageId);
if ($document instanceof Document) {
if ($document instanceof Document\Page) {
/** @var Document\Service $service */
$service = new Document\Service();
$linkedDocuments = $service->getTranslations($document);
if (count($linkedDocuments) == 0) {
return $document;
} else {
foreach ($linkedDocuments as $docLanguage => $docId) {
if ($docLanguage == $this->getLocale()) {
/** @var Document $doc */
$doc = Document::getById($docId);
if ($doc instanceof Document\Page) {
return $doc;
}
}
}
}
}
}
return null;
}
/**
* Retourne le sélecteur de langues sous forme de tableau
* @param $objectThis L'objet $this appelée depuis la vue
* @return array
*
* Exemple:
* $languageSwitcher = Apik::getLanguageSwitcher($this);
* print_r($languageSwitcher);
*/
public static function getLanguageSwitcher($objectThis)
{
$CurrentLanguageCode = $objectThis->getProperty("language");
$service = new PimcoreDocument\Service;
/** @var \App\Templating\Helper\LanguageSwitcher $languageSwitcher */
$languageSwitcher = new \App\Templating\Helper\LanguageSwitcher($service);
$switcher = [];
$switcher['current'] = [];
$switcher['current_id'] = $objectThis->getId();
$switcher['other'] = [];
$switcher['all'] = [];
foreach ($languageSwitcher->getLocalizedLinks($objectThis) as $link => $language):
$host = parse_url($link, PHP_URL_HOST);
// Si domaine courant, alors $link ne contiendra que le chemin de la page (ex: /exemple) sans l'host
// On va donc rajouter le protoctol et l'host.
if (empty($host)) {
$link = \Pimcore\Tool::getHostUrl() .'/'. $link;
}
if ($language['code'] == $CurrentLanguageCode) {
$switcher['current'] = array_merge(['url' => $link], $language);
} else {
$switcher['other'][] = array_merge(['url' => $link], $language);
}
$switcher['all'][] = array_merge(['current' => $language['code'] == $CurrentLanguageCode, 'url' => $link], $language);
endforeach;
$_switcher = $switcher;
$_switcher['current'] = $switcher['current'];
$_switcher['other'] = $switcher['other'];
$_switcher['all'] = $switcher['all'];
$switcher = $_switcher;
return $switcher;
}
/**
* Retourne le sélecteur de langues en HTML
* @param $objectThis (Obligatoire) L'objet $this appelée depuis la vue
* @param string $render (Obligatoire) Le format de retour : 'inline' ou 'dropdown'
* @param string $show (Obligatoire) Ce qu'il faut montrer : 'label' (Français,...), 'code' (FR,...) ou $replace pour un libellé personnalisé
* @param string $options (Facultatif) Options pour personnaliser le sélecteur de langue
*
* $replace est permet remplacer le libellé code/label par un libellé personnalisé.
*
* Exemple:
* echo getLanguageSwitcherHtml($this, 'dropdown', 'label');
*
* Exemple d'utilisation de $replace pour le paramètre $show:
* $replace = [
* 'fr_FR' => $this->translate('FR (France)'), // Affichera 'FR (France)' si le code de langue est fr_FR
* 'fr_BE' => $this->translate('FR (Belgique)'), // Affichera 'FR (Belgique)' si le code de langue est fr_BE
* 'nl_BE' => $this->translate('NL'), // Affichera 'NL' si le code de langue est nl_BE
* ];e
*
* Exemple d'utilisation de $options:
* Pour utiliser $options, copier/coller du tableau $options ci-dessous et le passer en paramètre à la fonction getLanguageSwitcherHtml(). La documentation de chaque option y est indiquée.
*
* @return string
*/
public static function getLanguageSwitcherHtml($document, $render, $show, $options = [])
{
$custom_options = $options;
$switcher = self::getLanguageSwitcher($document);
$options = [
'classes' => [
'current' => 'uk-active', // Classe à ajouter sur la langue courante
'other' => '' // Classe à ajouter sur les autres langues
],
'dropdown' => [
'properties' => 'pos: bottom-center' // Propriété du dropdown
]
];
// Fusionne les options
$options = array_merge($options, $custom_options);
$html = '';
if ($render == 'inline') {
$html .= '<nav class="apk-language-switcher">';
$html .= '<ul class="uk-subnav uk-subnav-divider">';
foreach ($switcher['all'] as $language):
$html .= '<li';
if ($language['current']) {
$html .= ' class="uk-active"';
}
$html .= '>';
$html .= '<a href="' . $language['url'] . '"';
if ($language['current'] && array_key_exists('current', $options['classes']) && !empty($options['classes']['current'])) {
$html .= ' class="' . $options['classes']['current'] . '"';
} elseif (!$language['current'] && array_key_exists('other', $options['classes']) && !empty($options['classes']['other'])) {
$html .= ' class="' . $options['classes']['other'] . '"';
}
$html .= '>';
if ($show == 'label') {
$html .= ucfirst($language['label']);
} elseif ($show == 'code') {
$html .= strtoupper($language['code']);
} elseif (is_array($show)) {
if (array_key_exists($language['code'], $show)) {
$html .= $show[$language['code']];
} else {
$html .= strtoupper($language['code']);
}
}
$html .= '</a>';
$html .= '</li>';
endforeach;
$html .= '</ul>';
$html .= '</nav>';
} elseif ($render == 'dropdown') {
$html .= '<nav class="apk-language-switcher uk-display-inline-block">';
$html .= '<div class="uk-active';
if (array_key_exists('current', $options['classes']) && !empty($options['classes']['current'])) {
$html .= ' ' . $options['classes']['current'];
}
$html .= '">';
if ($show == 'label') {
$html .= ucfirst($switcher['current']['label']);
} elseif ($show == 'code') {
$html .= '<span>'.strtoupper($switcher['current']['code']).'</span>';
} elseif (is_array($show)) {
if (array_key_exists($switcher['current']['code'], $show)) {
$html .= $show[$switcher['current']['code']];
} else {
$html .= strtoupper($switcher['current']['code']);
}
}
$html .= '<svg class="uk-margin-small-left" xmlns="http://www.w3.org/2000/svg" width="11" height="7" viewBox="0 0 11 7"><g><g><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="20" stroke-width="2" d="M1.24 1.5v0l4.374 4.374v0L9.988 1.5v0"/></g></g></svg>';
$html .= '</div>';
$html .= '<div uk-dropdown="' . $options['dropdown']['properties'] . '">';
$html .= '<ul class="uk-nav uk-dropdown-nav uk-text-left">';
foreach ($switcher['other'] as $language):
$html .= '<li>';
$html .= '<a href="' . $language['url'] . '"';
if (array_key_exists('other', $options['classes']) && !empty($options['classes']['other'])) {
$html .= ' class="' . $options['classes']['other'] . '"';
}
$html .= '>';
if ($show == 'label') {
$html .= ucfirst($language['label']);
} elseif ($show == 'code') {
$html .= strtoupper($language['code']);
} elseif (is_array($show)) {
if (array_key_exists($language['code'], $show)) {
$html .= $show[$language['code']];
} else {
$html .= strtoupper($language['code']);
}
}
$html .= '</a>';
$html .= '</li>';
endforeach;
$html .= '</ul>';
$html .= '</div>';
$html .= '</nav>';
}
return $html;
}
/**
* Retourne un lien mailto en cryptant l'adresse email ( OBFUSCATOR )
* Basé sur le script 2.1 de Andrew Moulden ( https://www.jottings.com/obfuscator/ )
* @param $email
* @return string
*
* @Author : Bastien Heynderickx <info@hachbe.be> updated by Grégory Lemmens
* @Version : 1.1
* @Description :
* permet de générer un lien mailto en protégeant l'adresse email (Obfuscator)
* ex : {{ email_obfuscator(+32 478 60 52 47)|raw }}
* /!\ le filtre row permet de convertir le code en html
* - https://www.jottings.com/obfuscator/
*/
public function emailObfuscator($address)
{
$address = strtolower($address);
$coded = "";
$unmixedkey = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.@";
$inprogresskey = $unmixedkey;
$mixedkey = "";
$unshuffled = strlen($unmixedkey);
for ($i = 0; $i < strlen($unmixedkey); $i++) {
$ranpos = rand(0, $unshuffled - 1);
$nextchar = $inprogresskey[$ranpos];
$mixedkey .= $nextchar;
$before = substr($inprogresskey, 0, $ranpos);
$after = substr($inprogresskey, $ranpos + 1, $unshuffled - ($ranpos + 1));
$inprogresskey = $before . '' . $after;
$unshuffled -= 1;
}
$cipher = $mixedkey;
$shift = strlen($address);
$txt = "<script type=\"text/javascript\" language=\"javascript\">\n" .
"<!-" . "-\n" .
"// Email obfuscator script 2.1 by Tim Williams, University of Arizona\n" .
"// Random encryption key feature by Andrew Moulden, Site Engineering Ltd\n" .
"// PHP version coded by Ross Killen, Celtic Productions Ltd\n" .
"// This code is freeware provided these six comment lines remain intact\n" .
"// A wizard to generate this code is at http://www.jottings.com/obfuscator/\n" .
"// The PHP code may be obtained from http://www.celticproductions.net/\n\n";
for ($j = 0; $j < strlen($address); $j++) {
if (strpos($cipher, $address[$j]) == -1) {
$chr = $address[$j];
$coded .= $address[$j];
} else {
$chr = (strpos($cipher, $address[$j]) + $shift) % strlen($cipher);
$coded .= $cipher[$chr];
}
}
$txt .= "\ncoded = \"" . $coded . "\"\n" .
" key = \"" . $cipher . "\"\n" .
" shift=coded.length\n" .
" link=\"\"\n" .
" for (i=0; i<coded.length; i++) {\n" .
" if (key.indexOf(coded.charAt(i))==-1) {\n" .
" ltr = coded.charAt(i)\n" .
" link += (ltr)\n" .
" }\n" .
" else { \n" .
" ltr = (key.indexOf(coded.charAt(i))-
shift+key.length) % key.length\n" .
" link += (key.charAt(ltr))\n" .
" }\n" .
" }\n" .
"document.write(\"<a href='mailto:\"+link+\"'>\"+link+\"</a>\")\n" .
"\n" .
"//-" . "->\n" .
"<" . "/script><noscript>Sorry, you need Javascript on to email us." .
"<" . "/noscript>";
return $txt;
}
/**
* Retourne un lien mailto en cryptant l'adresse email ( OBFUSCATOR )
* Basé sur le script 2.1 de Andrew Moulden ( https://www.jottings.com/obfuscator/ )
* @param $email
* @return string
*
* @Author : Bastien Heynderickx <info@hachbe.be> updated by Grégory Lemmens
* @Version : 1.1
* @Description :
* permet de générer un lien mailto en protégeant l'adresse email (Obfuscator)
* ex : {{ email_obfuscator(+32 478 60 52 47)|raw }}
* /!\ le filtre row permet de convertir le code en html
* - https://www.jottings.com/obfuscator/
*/
public function emailObfuscatorSvg($address)
{
$address = strtolower($address);
$coded = "";
$unmixedkey = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.@";
$inprogresskey = $unmixedkey;
$mixedkey = "";
$svg = "<img uk-svg width='29' height='29' src='/static/img/icons/email.svg' alt='Tel' />";
$unshuffled = strlen($unmixedkey);
for ($i = 0; $i < strlen($unmixedkey); $i++) {
$ranpos = rand(0, $unshuffled - 1);
$nextchar = $inprogresskey[$ranpos];
$mixedkey .= $nextchar;
$before = substr($inprogresskey, 0, $ranpos);
$after = substr($inprogresskey, $ranpos + 1, $unshuffled - ($ranpos + 1));
$inprogresskey = $before . '' . $after;
$unshuffled -= 1;
}
$cipher = $mixedkey;
$shift = strlen($address);
$txt = "<script type=\"text/javascript\" language=\"javascript\">\n" .
"<!-" . "-\n" .
"// Email obfuscator script 2.1 by Tim Williams, University of Arizona\n" .
"// Random encryption key feature by Andrew Moulden, Site Engineering Ltd\n" .
"// PHP version coded by Ross Killen, Celtic Productions Ltd\n" .
"// This code is freeware provided these six comment lines remain intact\n" .
"// A wizard to generate this code is at http://www.jottings.com/obfuscator/\n" .
"// The PHP code may be obtained from http://www.celticproductions.net/\n\n";
for ($j = 0; $j < strlen($address); $j++) {
if (strpos($cipher, $address[$j]) == -1) {
$chr = $address[$j];
$coded .= $address[$j];
} else {
$chr = (strpos($cipher, $address[$j]) + $shift) % strlen($cipher);
$coded .= $cipher[$chr];
}
}
$txt .= "\ncoded = \"" . $coded . "\"\n" .
" key = \"" . $cipher . "\"\n" .
" svg = \"" . $svg . "\"\n" .
" shift=coded.length\n" .
" link=\"\"\n" .
" for (i=0; i<coded.length; i++) {\n" .
" if (key.indexOf(coded.charAt(i))==-1) {\n" .
" ltr = coded.charAt(i)\n" .
" link += (ltr)\n" .
" }\n" .
" else { \n" .
" ltr = (key.indexOf(coded.charAt(i))-
shift+key.length) % key.length\n" .
" link += (key.charAt(ltr))\n" .
" }\n" .
" }\n" .
"document.write(\"<a href='mailto:\"+link+\"'>\"+svg+link+\"</a>\")\n" .
"\n" .
"//-" . "->\n" .
"<" . "/script><noscript>Sorry, you need Javascript on to email us." .
"<" . "/noscript>";
return $txt;
}
/**
* Retourne un lien mailto en cryptant l'adresse email ( OBFUSCATOR )
* Basé sur le script 2.1 de Andrew Moulden ( https://www.jottings.com/obfuscator/ )
* @param $email
* @return string
*
* @Author : Bastien Heynderickx <info@hachbe.be> updated by Grégory Lemmens
* @Version : 1.1
* @Description :
* permet de générer un lien mailto en protégeant l'adresse email (Obfuscator)
* ex : {{ email_obfuscator(+32 478 60 52 47)|raw }}
* /!\ le filtre row permet de convertir le code en html
* - https://www.jottings.com/obfuscator/
*/
public function emailObfuscatorSvgOnly($address)
{
$address = strtolower($address);
$coded = "";
$unmixedkey = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.@";
$inprogresskey = $unmixedkey;
$mixedkey = "";
$svg = "<img uk-svg width='29' height='29' src='/static/img/icons/email.svg' alt='Tel' />";
$unshuffled = strlen($unmixedkey);
for ($i = 0; $i < strlen($unmixedkey); $i++) {
$ranpos = rand(0, $unshuffled - 1);
$nextchar = $inprogresskey[$ranpos];
$mixedkey .= $nextchar;
$before = substr($inprogresskey, 0, $ranpos);
$after = substr($inprogresskey, $ranpos + 1, $unshuffled - ($ranpos + 1));
$inprogresskey = $before . '' . $after;
$unshuffled -= 1;
}
$cipher = $mixedkey;
$shift = strlen($address);
$txt = "<script type=\"text/javascript\" language=\"javascript\">\n" .
"<!-" . "-\n" .
"// Email obfuscator script 2.1 by Tim Williams, University of Arizona\n" .
"// Random encryption key feature by Andrew Moulden, Site Engineering Ltd\n" .
"// PHP version coded by Ross Killen, Celtic Productions Ltd\n" .
"// This code is freeware provided these six comment lines remain intact\n" .
"// A wizard to generate this code is at http://www.jottings.com/obfuscator/\n" .
"// The PHP code may be obtained from http://www.celticproductions.net/\n\n";
for ($j = 0; $j < strlen($address); $j++) {
if (strpos($cipher, $address[$j]) == -1) {
$chr = $address[$j];
$coded .= $address[$j];
} else {
$chr = (strpos($cipher, $address[$j]) + $shift) % strlen($cipher);
$coded .= $cipher[$chr];
}
}
$txt .= "\ncoded = \"" . $coded . "\"\n" .
" key = \"" . $cipher . "\"\n" .
" svg = \"" . $svg . "\"\n" .
" shift=coded.length\n" .
" link=\"\"\n" .
" for (i=0; i<coded.length; i++) {\n" .
" if (key.indexOf(coded.charAt(i))==-1) {\n" .
" ltr = coded.charAt(i)\n" .
" link += (ltr)\n" .
" }\n" .
" else { \n" .
" ltr = (key.indexOf(coded.charAt(i))-
shift+key.length) % key.length\n" .
" link += (key.charAt(ltr))\n" .
" }\n" .
" }\n" .
"document.write(\"<a href='mailto:\"+link+\"'>\"+svg+\"</a>\")\n" .
"\n" .
"//-" . "->\n" .
"<" . "/script><noscript>Sorry, you need Javascript on to email us." .
"<" . "/noscript>";
return $txt;
}
/**
* Convertit un numéro de téléphone au format lien "tel:"
* Exemple: // +32 2 357 33 00 -> +3223573300
* @param $phone
* @return string
*
* @Author : Bastien Heynderickx <info@hachbe.be> basé sur la version WordPress de Jérôme De Boysère
* @Version : 1.0
* @Description :
* permet de convertir un numéro de téléphone au format url | lien "tel:"
*/
public static function convertPhoneToPhoneUrl($phone)
{
if (!empty($phone)) {
$phone = trim($phone);
$phone = preg_replace('/\s/', '', $phone); // +32 2 357 33 00 -> +3223573300
}
return $phone;
}
/**
* Génère des classes CSS pour facilité l'intégration web (à utiliser pour le <body> depuis le layout).
* @param $objectThis L'objet $this appelé depuis layout
* @param $__FILE__ La variable __FILE__ appelée depuis le layout
* @return string
*
* Exemple:
* echo Apik::getBodyClass($this, __FILE__);
*/
/* ToDO: To refactoring for twig */
public static function getBodyClass($objectThis, $__FILE__)
{
// - Ajoute le CMS utilisé
// - Ajoute 'editmode' si on est en mode édition
$bodyClasses = array();
$bodyClasses[] = 'apk-cms-pimcore';
if ($objectThis->editmode) {
$bodyClasses[] = 'editmode';
}
// - CXréation d'une classe en fonction du controller + action + (template) + vue
$class = pathinfo($__FILE__, PATHINFO_BASENAME);
//$class = strtr($class, array('.html.php' => '-html', '.' => '-', '/' => '_'));
$class = str_replace('.html.php', '', strtolower($class));
$class = strtolower($class);
$bodyClasses[] = 'pimcore-layout-' . $class;
// Template : Default/home.html.php => gs-template_default_home-html
/*if ($objectThis->document->getTemplate()) {
$class = $objectThis->document->getTemplate();
$class = strtr($class, array('.html.php' => '-html', '.' => '-', '/' => '_'));
$class = strtolower($class);
$bodyClasses[] = 'gs-template_' . $class;
$hasTemplate = true;
} elseif ($objectThis->document->getController() == 'default' && $objectThis->document->getAction() == 'default') {
$bodyClasses[] = 'gs-template-by-default';
}*/
$controller = '';
if ($objectThis->document->getController()) {
$class = $objectThis->document->getController();
$class = strtolower($class);
$class = explode('\\', $class);
//$class = end($class);
$class = str_replace('controller', '', end($class));
$controller = $class;
//$bodyClasses[] = 'gs-controller_' . $class;
}
$action = '';
if ($objectThis->document->getAction()) {
$class = $objectThis->document->getAction();
$class = strtolower($class);
$action = $class;
//$bodyClasses[] = 'gs-action_' . $class;
}
if ($controller && $action) {
$bodyClasses[] = 'pimcore-' . $controller . '-' . $action;
}
return implode(' ', $bodyClasses);
}
/**
* Retourne le tag concernant l'indexation pour les robots
* @return string
*
* Exemple:
* echo Apik::getRobotsIndex();
*/
public static function getRobotsIndex()
{
$return = '';
$return .= "\n" . '<!-- Robots indexation -->' . "\n";
//if (getenv('PIMCORE_ENVIRONMENT') == "prod") {
if (strpos($_SERVER['HTTP_HOST'], "apik-pp") === FALSE && strpos($_SERVER['HTTP_HOST'], "atypic-pp") === FALSE) {
$return .= '<meta name="robots" content="INDEX, FOLLOW" />';
} else {
$return .= '<meta name="robots" content="NOINDEX, NOFOLLOW" />';
}
return $return;
}
/**
* Retourne tous les <link rel="alternate" href="..." hreflang="..." />
* @param $document
* @return string
*
* @Author : Cédric Moriot <cedric@atypic.be>, Jérôme De Boysère <jerome@atypic.be>
* @Version : 2.0
* @Description :
* Permet d'ajouter les balises hreflang, conformément à la doc Google :
* - https://support.google.com/webmasters/answer/189077?hl=fr
*/
public static function getLinksAlternate($document)
{
$return = '';
$links = [];
$languageSwitcher = self::getLanguageSwitcher($document);
foreach ($languageSwitcher['all'] as $k => $lang) {
$links[$lang['code']] = '<link rel="alternate" hreflang="' . str_replace('_', '-', $lang['code']) . '" href="' . $lang['url'] . '" />';
}
$return .= "\n" . '<!-- Link alternate -->' . "\n";
$return .= count($links) > 0 ? implode("\n", $links) : '<!-- Nothing to do because there is only 1 language configured on this website. -->';
return $return;
/*$links = [];
$service = new PimcoreDocument\Service;
$validLanguages = \Pimcore\Tool::getValidLanguages();
$languageSwitcher = $objectThis->languageSwitcher();
$arrayUrlForHrefLang = $languageSwitcher->getLocalizedLinks($objectThis->document);
if (is_array($arrayUrlForHrefLang)) {
foreach ($arrayUrlForHrefLang as $link => $text) {
if (in_array($text['code'], $validLanguages)) {
$translations = $service->getTranslations($objectThis->document);
$tempLink = \Pimcore\Model\Document::getById($translations[$text['code']]);
$finalLink = '';
if ($text['code'] == $objectThis->getLocale()) {
//Active Page
$finalLink = $objectThis->document->getFullPath();
} else if (is_object($tempLink) && !empty($tempLink->getPrettyUrl())) {
$finalLink = $tempLink->getPrettyUrl();
} elseif (is_object($tempLink)) {
//Alternate Page W/O Pretty URL
$finalLink = $tempLink->getPath() . $tempLink->getKey();
}
if (!empty($finalLink)) {
$links[$text['code']] = '<link rel="alternate" href="' . \Pimcore\Tool::getHostUrl() . $finalLink . '" hreflang="' . $text['code'] . '" />';
} else {
$links[$text['code']] = '<!-- Link alternate - No page found for the language : ' . $text['label'] . ' (' . $text['code'] . ') -->';
}
}
}
}
return count($validLanguages) > 1 ? implode("\n", $links) : '<!-- Link alternate - Nothing to do because there is only 1 language configured on this website. -->';
*/
}
/**
* Retourne la valeur du website setting localisé
* @param $objectThis
* @return string
*
* @Author : Bastien Heynderickx <info@hachbe.be>
* @Version : 1.0
* @Description :
* permet de récupérer la valeur d'un website setting sur base la localisation
* - https://support.google.com/webmasters/answer/189077?hl=fr
*/
public static function websiteConfigAdvanced($name, $siteId = null, $language = null, $fallbackLanguage = null)
{
return WebsiteSetting::getByName($name, $siteId, $language)->getData();
}
/**
* Create a web friendly URL slug from a string.
*
* Although supported, transliteration is discouraged because
* 1) most web browsers support UTF-8 characters in URLs
* 2) transliteration causes a loss of information
*
* @author Sean Murphy <sean@iamseanmurphy.com>
* @copyright Copyright 2012 Sean Murphy. All rights reserved.
* @license http://creativecommons.org/publicdomain/zero/1.0/
*
* @param string $str
* @param array $options
* @return string
*/
public static function toUrl($str, $options = array())
{
// Make sure string is in UTF-8 and strip invalid UTF-8 characters
$str = mb_convert_encoding((string)$str, 'UTF-8', mb_list_encodings());
$defaults = array(
'delimiter' => '-',
'limit' => null,
'lowercase' => true,
'replacements' => array(),
'transliterate' => true,
);
// Merge options
$options = array_merge($defaults, $options);
$char_map = array(
// Latin
'À' => 'A', 'Á' => 'A', 'Â' => 'A', 'Ã' => 'A', 'Ä' => 'A', 'Å' => 'A', 'Æ' => 'AE', 'Ç' => 'C',
'È' => 'E', 'É' => 'E', 'Ê' => 'E', 'Ë' => 'E', 'Ì' => 'I', 'Í' => 'I', 'Î' => 'I', 'Ï' => 'I',
'Ð' => 'D', 'Ñ' => 'N', 'Ò' => 'O', 'Ó' => 'O', 'Ô' => 'O', 'Õ' => 'O', 'Ö' => 'O', 'Ő' => 'O',
'Ø' => 'O', 'Ù' => 'U', 'Ú' => 'U', 'Û' => 'U', 'Ü' => 'U', 'Ű' => 'U', 'Ý' => 'Y', 'Þ' => 'TH',
'ß' => 'ss',
'à' => 'a', 'á' => 'a', 'â' => 'a', 'ã' => 'a', 'ä' => 'a', 'å' => 'a', 'æ' => 'ae', 'ç' => 'c',
'è' => 'e', 'é' => 'e', 'ê' => 'e', 'ë' => 'e', 'ì' => 'i', 'í' => 'i', 'î' => 'i', 'ï' => 'i',
'ð' => 'd', 'ñ' => 'n', 'ò' => 'o', 'ó' => 'o', 'ô' => 'o', 'õ' => 'o', 'ö' => 'o', 'ő' => 'o',
'ø' => 'o', 'ù' => 'u', 'ú' => 'u', 'û' => 'u', 'ü' => 'u', 'ű' => 'u', 'ý' => 'y', 'þ' => 'th',
'ÿ' => 'y',
// Latin symbols
'©' => '(c)',
// Greek
'Α' => 'A', 'Β' => 'B', 'Γ' => 'G', 'Δ' => 'D', 'Ε' => 'E', 'Ζ' => 'Z', 'Η' => 'H', 'Θ' => '8',
'Ι' => 'I', 'Κ' => 'K', 'Λ' => 'L', 'Μ' => 'M', 'Ν' => 'N', 'Ξ' => '3', 'Ο' => 'O', 'Π' => 'P',
'Ρ' => 'R', 'Σ' => 'S', 'Τ' => 'T', 'Υ' => 'Y', 'Φ' => 'F', 'Χ' => 'X', 'Ψ' => 'PS', 'Ω' => 'W',
'Ά' => 'A', 'Έ' => 'E', 'Ί' => 'I', 'Ό' => 'O', 'Ύ' => 'Y', 'Ή' => 'H', 'Ώ' => 'W', 'Ϊ' => 'I',
'Ϋ' => 'Y',
'α' => 'a', 'β' => 'b', 'γ' => 'g', 'δ' => 'd', 'ε' => 'e', 'ζ' => 'z', 'η' => 'h', 'θ' => '8',
'ι' => 'i', 'κ' => 'k', 'λ' => 'l', 'μ' => 'm', 'ν' => 'n', 'ξ' => '3', 'ο' => 'o', 'π' => 'p',
'ρ' => 'r', 'σ' => 's', 'τ' => 't', 'υ' => 'y', 'φ' => 'f', 'χ' => 'x', 'ψ' => 'ps', 'ω' => 'w',
'ά' => 'a', 'έ' => 'e', 'ί' => 'i', 'ό' => 'o', 'ύ' => 'y', 'ή' => 'h', 'ώ' => 'w', 'ς' => 's',
'ϊ' => 'i', 'ΰ' => 'y', 'ϋ' => 'y', 'ΐ' => 'i',
// Turkish
'Ş' => 'S', 'İ' => 'I', 'Ç' => 'C', 'Ü' => 'U', 'Ö' => 'O', 'Ğ' => 'G',
'ş' => 's', 'ı' => 'i', 'ç' => 'c', 'ü' => 'u', 'ö' => 'o', 'ğ' => 'g',
// Russian
'А' => 'A', 'Б' => 'B', 'В' => 'V', 'Г' => 'G', 'Д' => 'D', 'Е' => 'E', 'Ё' => 'Yo', 'Ж' => 'Zh',
'З' => 'Z', 'И' => 'I', 'Й' => 'J', 'К' => 'K', 'Л' => 'L', 'М' => 'M', 'Н' => 'N', 'О' => 'O',
'П' => 'P', 'Р' => 'R', 'С' => 'S', 'Т' => 'T', 'У' => 'U', 'Ф' => 'F', 'Х' => 'H', 'Ц' => 'C',
'Ч' => 'Ch', 'Ш' => 'Sh', 'Щ' => 'Sh', 'Ъ' => '', 'Ы' => 'Y', 'Ь' => '', 'Э' => 'E', 'Ю' => 'Yu',
'Я' => 'Ya',
'а' => 'a', 'б' => 'b', 'в' => 'v', 'г' => 'g', 'д' => 'd', 'е' => 'e', 'ё' => 'yo', 'ж' => 'zh',
'з' => 'z', 'и' => 'i', 'й' => 'j', 'к' => 'k', 'л' => 'l', 'м' => 'm', 'н' => 'n', 'о' => 'o',
'п' => 'p', 'р' => 'r', 'с' => 's', 'т' => 't', 'у' => 'u', 'ф' => 'f', 'х' => 'h', 'ц' => 'c',
'ч' => 'ch', 'ш' => 'sh', 'щ' => 'sh', 'ъ' => '', 'ы' => 'y', 'ь' => '', 'э' => 'e', 'ю' => 'yu',
'я' => 'ya',
// Ukrainian
'Є' => 'Ye', 'І' => 'I', 'Ї' => 'Yi', 'Ґ' => 'G',
'є' => 'ye', 'і' => 'i', 'ї' => 'yi', 'ґ' => 'g',
// Czech
'Č' => 'C', 'Ď' => 'D', 'Ě' => 'E', 'Ň' => 'N', 'Ř' => 'R', 'Š' => 'S', 'Ť' => 'T', 'Ů' => 'U',
'Ž' => 'Z',
'č' => 'c', 'ď' => 'd', 'ě' => 'e', 'ň' => 'n', 'ř' => 'r', 'š' => 's', 'ť' => 't', 'ů' => 'u',
'ž' => 'z',
// Polish
'Ą' => 'A', 'Ć' => 'C', 'Ę' => 'e', 'Ł' => 'L', 'Ń' => 'N', 'Ó' => 'o', 'Ś' => 'S', 'Ź' => 'Z',
'Ż' => 'Z',
'ą' => 'a', 'ć' => 'c', 'ę' => 'e', 'ł' => 'l', 'ń' => 'n', 'ó' => 'o', 'ś' => 's', 'ź' => 'z',
'ż' => 'z',
// Latvian
'Ā' => 'A', 'Č' => 'C', 'Ē' => 'E', 'Ģ' => 'G', 'Ī' => 'i', 'Ķ' => 'k', 'Ļ' => 'L', 'Ņ' => 'N',
'Š' => 'S', 'Ū' => 'u', 'Ž' => 'Z',
'ā' => 'a', 'č' => 'c', 'ē' => 'e', 'ģ' => 'g', 'ī' => 'i', 'ķ' => 'k', 'ļ' => 'l', 'ņ' => 'n',
'š' => 's', 'ū' => 'u', 'ž' => 'z'
);
// Make custom replacements
$str = preg_replace(array_keys($options['replacements']), $options['replacements'], $str);
// Transliterate characters to ASCII
if ($options['transliterate']) {
$str = str_replace(array_keys($char_map), $char_map, $str);
}
// Replace non-alphanumeric characters with our delimiter
$str = preg_replace('/[^\p{L}\p{Nd}]+/u', $options['delimiter'], $str);
// Remove duplicate delimiters
$str = preg_replace('/(' . preg_quote($options['delimiter'], '/') . '){2,}/', '$1', $str);
// Truncate slug to max. characters
$str = mb_substr($str, 0, ($options['limit'] ? $options['limit'] : mb_strlen($str, 'UTF-8')), 'UTF-8');
// Remove delimiter from ends
$str = trim($str, $options['delimiter']);
return $options['lowercase'] ? mb_strtolower($str, 'UTF-8') : $str;
}
/**
* Convertit la date YYYY/MM/DD dans un autre format
* @param $date La date au format YYYY/MM/DD
* @param $outputFormat (Facultatif) Le format de sortie (d/m/Y, \O\n j F, Y,...)
* @return string
*
* Exemple:
* echo Apik::convertDate('2019/12/24', 'd/m/Y');
*/
public static function convertDate($yyyy_mm_dd, $outputFormat = 'd/m/Y', $lang = null)
{
$date = new \DateTime($yyyy_mm_dd);
if($lang!=null && $lang!='en'):
$date = $date->format($outputFormat);
$english_days = array('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday');
$french_days = array('Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi', 'Dimanche');
$dutch_days = array('Maandag', 'Dinsdag', 'Woensdag', 'Donderdag', 'Vrijdag', 'Zaterdag', 'Zondag');
$english_months = array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
$french_months = array('Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre');
$dutch_months = array('Januari', 'Februari', 'Maart', 'April', 'Mei', 'Juni', 'Juli', 'Augustus', 'September', 'Oktober', 'November', 'December');
switch($lang):
case 'fr': $date_localized = str_replace($english_months, $french_months, str_replace($english_days, $french_days, $date ));
break;
case 'nl': $date_localized = str_replace($english_months, $dutch_months, str_replace($english_days, $dutch_days, $date ));
break;
endswitch;
return $date_localized;
else:
return $date->format($outputFormat);
endif;
}
/**
*
* @param string $image
* @param string $defaultAlt
* @param string $language
*
* @return string
*
* @Author : Grégory Lemmens
* @Version : 1.0
* @Description :
* permet de créer les attributs titres et alt et copyright pour les images
*
*/
public static function metadatasImage($image, $defaultAlt, $language){
if($image->getMetadata('alt')){
if($image->getMetadata('copyright')){
$imageAlt = ' alt="' . $image->getMetadata('alt') . ' | © '. $image->getMetadata('copyright') .'"';
}elseif($image->getMetadata('copyright', $language)){
$imageAlt = ' alt="' . $image->getMetadata('alt') . ' | © '. $image->getMetadata('copyright', $language) .'"';
}else{
$imageAlt = ' alt="' . $image->getMetadata('alt') . '"';
}
}elseif($image->getMetadata('alt', $language)){
if($image->getMetadata('copyright')){
$imageAlt = ' alt="' . $image->getMetadata('alt', $language) . ' | © '. $image->getMetadata('copyright') .'"';
}elseif($image->getMetadata('copyright', $language)){
$imageAlt = ' alt="' . $image->getMetadata('alt', $language) . ' | © '. $image->getMetadata('copyright', $language) .'"';
}else{
$imageAlt = ' alt="' . $image->getMetadata('alt', $language) . '"';
}
}else{
if($image->getMetadata('copyright')){
$imageAlt = ' alt="' . $defaultAlt . ' | © '. $image->getMetadata('copyright') .'"';
}elseif($image->getMetadata('copyright', $language)){
$imageAlt = ' alt="' . $defaultAlt . ' | © '. $image->getMetadata('copyright', $language) .'"';
}else{
$imageAlt = ' alt="' . $defaultAlt . '"';
}
}
if($image->getMetadata('title')){
if($image->getMetadata('copyright')){
$imageTitle = ' title="' . $image->getMetadata('title') . ' | © '. $image->getMetadata('copyright') .'"';
}elseif($image->getMetadata('copyright', $language)){
$imageTitle = ' title="' . $image->getMetadata('title') . ' | © '. $image->getMetadata('copyright', $language) .'"';
}else{
$imageTitle = ' title="' . $image->getMetadata('title') . '"';
}
}elseif($image->getMetadata('title', $language)){
if($image->getMetadata('copyright')){
$imageTitle = ' title="' . $image->getMetadata('title', $language) . ' | © '. $image->getMetadata('copyright') .'"';
}elseif($image->getMetadata('copyright', $language)){
$imageTitle = ' title="' . $image->getMetadata('title', $language) . ' | © '. $image->getMetadata('copyright', $language) .'"';
}else{
$imageTitle = ' title="' . $image->getMetadata('title', $language) . '"';
}
}else{
$imageTitle = '';
}
$metaDatas = $imageAlt . $imageTitle;
return $metaDatas;
}
function setSeo($headTitle, $headMeta ,$title, $description, $image, $overwriteTitle = null, $overwriteDescription = null){
if($overwriteTitle !== null && !empty($overwriteTitle)){
$headTitle->set($overwriteTitle);
}else{
$headTitle->set($title);
}
if($overwriteDescription !== null && !empty($overwriteDescription)){
$headMeta->setDescription(strip_tags($overwriteDescription));
}else{
$headMeta->setDescription(strip_tags($description));
}
$headMeta->setProperty('og:type', 'website');
$headMeta->setProperty('og:url', HighlightStudio::getCurrentUrl());
if($overwriteTitle !== null && !empty($overwriteTitle)){
$headMeta->setProperty('og:title', $overwriteTitle);
}else{
$headMeta->setProperty('og:title', $title);
}
if($overwriteDescription !== null && !empty($overwriteDescription)){
$headMeta->setProperty('og:description', strip_tags($overwriteDescription));
}else{
$headMeta->setProperty('og:description', strip_tags($description));
};
if($image){
$headMeta->setProperty('og:image', \Pimcore\Tool::getHostUrl() . $image);
}
return $seo;
}
/**
*
* @param string $text
*
* @return string
*
* @Author : Grégory Lemmens
* @Version : 1.0
* @Description :
* permet d'appliquer la fonction addslashes de php
*
*/
function apk_addslashes($text) {
return addslashes($text);
}
/**
*
* @param string $image
*
* @return string
*
* @Author : Grégory Lemmens
* @Version : 1.0
* @Description :
* transformer une image en base64
*
*/
function base64($fullpath, $image) {
//php file_get_contents disable ssl check
$arrContextOptions=array(
"ssl"=>array(
"verify_peer"=>false,
"verify_peer_name"=>false,
),
);
// Get the image and convert into string
$img = file_get_contents($fullpath.$image, false, stream_context_create($arrContextOptions) );
// Encode the image string data into base64
$data = base64_encode($img);
// Display the output
return $data;
}
}